8

I am trying to map Ctrl+s to save my file however it does not work.

My mappings:

map <C-s> :w <CR> :echo "Saved" <CR>
imap <C-s> <Esc> :w <CR> :echo "Saved" <CR> i

When in insert mode I see /:echo "Saved" in the bottom corner instead of saved and when I am in normal mode I see the same thing. What am I doing wrong?

This is at the very top of my vimrc so my other code should not be causing a issue. I am running Vim inside the OSX Terminal.

  • Are you using Vim from a terminal? Control+S is also a special keybind picked up by the terminal which means "stop output"... When I try the above 2 keybinds from gVim, it seems to work. – Martin Tournoij Mar 7 '15 at 18:45
  • 'I am also running vim inside the Mac terminal.' Yes I am running vim via terminal. Would it be better using Alt instead of Ctrl or Cmd? – iProgram Mar 7 '15 at 18:50
  • This question has been asked many times, by the way ;-) I don't have time to write an answer, but that link should help you... – Martin Tournoij Mar 7 '15 at 18:54
  • To bind save to Cmd-S on OSX you could try mapping from <D-s> although I'm not sure if that works in terminal Vim, and it is already a default in MacVim anyway! – joeytwiddle Mar 8 '15 at 10:41
6

To ensure that this workaround runs even when Vim is started by a separate tool (such as git), I have this in my ~/.vimrc:

" Allow us to use Ctrl-s and Ctrl-q as keybinds
silent !stty -ixon

" Restore default behaviour when leaving Vim.
autocmd VimLeave * silent !stty ixon

This has been working for me on Linux, GVim, Mac OS X and MacVim.

Caveats:

  • On Windows, or any other OS lacking the stty command, the above will likely throw up errors every time Vim starts! (silent! might mute that.)

  • If your shell already had this TTY setting disabled, of course the VimLeave autocommand will turn it back on again! Detecting and restoring the current settings is an advantage with @aPyDeveloper's approach.


A combination of this and @aPyDeveloper's solution, which handles compatibility concerns under OS X and Windows, would be great to post up here and/or on the Wiki!

To avoid choosing between stty -g and stty --save, you could try the following test for just the ix option.

call system("stty -a | grep '\( \|^\)ixon\>' >/dev/null")
let g:ix_at_startup = (v:shell_error == 0)
2

Thanks to @Carpetsmoker for the links.

Adding this script into bash_profile worked for me.

vim()
{
    # osx users, use stty -g
    local STTYOPTS="$(stty --save)"
    stty stop '' -ixoff
    command vim "$@"
    stty "$STTYOPTS"
}

Here is a link to it. http://vim.wikia.com/wiki/Map_Ctrl-S_to_save_current_or_new_files

I also had to remove the space before the :

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.