lindhe
lindhe

Reputation: 889

Create a command in vim for all modes

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?

Upvotes: 1

Views: 655

Answers (2)

Peter Rincker
Peter Rincker

Reputation: 45177

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.

Upvotes: 0

glts
glts

Reputation: 22734

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.

Upvotes: 2

Related Questions