1

If I want to remap <C-s> to :w<CR> I'd have to do something like this

nnoremap <C-s> :w<CR>
inoremap <C-s> <Esc>:w<CR>

since insert mode would requre escaping to normal mode before entering the command (sure, another <Esc> wouldn't kill anything, but it's ugly, my terminal bell goes off and with all the other modes available [n, i, v, s, x, c and o] there are plenty of cases where extra <Esc> wouldn't cut it).

Is there an easy way to map a command "for all modes" in Vim?

lindhe
  • 806
  • 2
  • 14
  • 32
  • Did you already took a look at http://stackoverflow.com/questions/3446320/in-vim-how-to-map-save-to-ctrl-s ? You can cover it all with 3 cases, and no `` – Maximiliano Padulo May 11 '15 at 21:04
  • No, I didn't. And honestly I knew that I only need three of the modes (v, i, and n), but it's still bothersome if there are many lines to be mapped. Oh, it's smart enough to handle escaping properly? Interesting. Does anyone know more on what exactly that it's "smart enough" to handle? – lindhe May 11 '15 at 21:16
  • 1
    Note: There is a [dedicated site for vi & vim](http://vi.stackexchange.com/). – Shahbaz May 12 '15 at 13:12
  • Wow, I didn't know that. I guess it's new? Guess I'll hang there quite a bit. :) Edit: Yup, it's definitly new. "Beta". – lindhe May 13 '15 at 23:38

2 Answers2

2

You can get quite close by taking advantage of the CTRL-\ CTRL-N command. CTRL-\ CTRL-N goes to Normal mode from any mode.

We can define just two mappings with identical right-hand side to cover Normal, Visual, Select, Operator-pending, Insert, and Command-line mode.

noremap  <C-S> <C-\><C-N>:write<CR>
noremap! <C-S> <C-\><C-N>:write<CR>

See :h CTRL-\_CTRL-N.

glts
  • 21,808
  • 12
  • 73
  • 94
0

There is no easy "One mapping to rule them all" way to do such a thing. On the plus side when you do make all your mappings you put them in your ~/.vimrc and forget about it.

However I must say it is the Vim Way to do a save from normal mode (as a matter a fact do most thing from normal mode). If you did it form insert mode for example you would be breaking up your undo block if you wanted to exit from insert mode, save, and then reinsert insert mode (See :h i_Ctrl-o). Not to mention such a mapping may affect the . command which is super handy.

You may also want to avoid the <c-s> key on the terminal because it will often trigger terminal's software flow control (XON/XOFF). You can disable this for your terminal by using stty -ixon.

Peter Rincker
  • 43,539
  • 9
  • 74
  • 101
  • 1
    Mapping `` to write the buffer was just meant as an example. I'm looking for a general solution. – lindhe May 11 '15 at 21:20
  • But the problem still remains. You are trying to create a mapping that works the "same" in every mode. Doesn't that sound un-vim like to you? I know it does to me. – Peter Rincker May 11 '15 at 21:56