Ctrl+s to save changes in VIM Editor

In Vim editor if we want to save changes, typically we have to get into command mode by typing ":" and type "w" to save changes to file from current buffer but I always wanted to save my changes with ctrl+s.
So, I have mapped writing operation of "w" with ctrl+s with following commands,


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

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

If you want to map a key for only one Vim session temporarily, then you don't need to save the map command in a file. When you quit that Vim instance, the temporary map definition will be lost.

If you want to restore the key maps across Vim instances, you need to save the map definition command in a .vimrc file normally present in $HOME.



That's it !!!
Let me give you brief what these mean,
The general syntax of map command is (from vim.fandom.com),
{cmd} {attr} {lhs} {rhs}

where
{cmd}  is one of ':map', ':map!', ':nmap', ':vmap', ':imap',
       ':cmap', ':smap', ':xmap', ':omap', ':lmap', etc.
{attr} is optional and one or more of the following: <buffer>, <silent>,
       <expr> <script>, <unique> and <special>.
       More than one attribute can be specified to a map.
{lhs}  left hand side, is a sequence of one or more keys that you will use
       in your new shortcut.
{rhs}  right hand side, is the sequence of keys that the {lhs} shortcut keys
       will execute when entered.

so whenever <C-s>(lhs) is pressed, vim executes <Esc>:w<CR>(rhs) which means vim first get into normal mode because of Esc, run the command ":w" and press enter(CR) to execute the command.

Vim supports several editing modes - normal, insert, replace, visual, select, command-line and operator-pending. I have mapped it in normal, visual and insert mode but you can map a key to work in all or some of these modes.

Notes,
  • First letter indicates the mode in which this command should execute
    • nnoremap - normal mode
    • vnoremap - visual mode
  • "nore" indicates non-recursive mapping (for more info - non-recursive mapping)
  • Add below line to your .bashrc. This is needed because for most terminals ctrl+s is already used for something, so these alias vim so that before we run vim we turn off that mapping.
    • alias vim="stty stop '' -ixoff; vim"
    • alias vi="stty stop '' -ixoff; vi"

Comments

Popular posts from this blog

MBR partitioning with 'parted' utility

Replace default splash screen in Yocto

Disk Partitioning: MBR vs GPT