Thursday, October 6, 2011

Make vim save files with Ctrl-s like Windows

SkyHi @ Thursday, October 06, 2011

Have you ever been working in vim over ssh and hit Ctrl-s by accident? This happens to folks who also work on Windows all the time, because Ctrl-s is the standard Windows keyboard shortcut for saving a file. What happens over ssh is that you issue a terminal stop command, and your ssh session appears to lock up.
The good news is, it’s not lost — just frozen. You can “unstop” the terminal by hitting Ctrl-q. Good as new! But we can do more…
If you’re a Windows user who ssh’s into *nix boxes frequently, we can actually make Ctrl-s in vim save the file like you’re intending. First, add the following to your .bashrc file to disable terminal stopping:
stty stop ''  // works on Ubuntu
stty ixany  //works on Centos
You’ll notice that now the Ctrl-s doesn’t lock up vim anymore, but it doesn’t do anything yet. Let’s add that functionality now with two mappings in our .vimrc file.
map <C-s> :w<CR>
imap <C-s> <Esc>:w<CR>i
Boom, done! Now when you hit Ctrl-s in vim, rather than locking up your terminal, it saves the file. In command mode, it just executes the traditional :wcommand, and in insert mode, it hits escape (to get to command mode), does the :w, and then hits “i” to get you back into insert mode where you left off.
I’m not a vim expert by any means, so if anyone has a better way to do it, I’m all ears.