12

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.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
iProgram
  • 1,589
  • 2
  • 15
  • 25

3 Answers3

10

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! iProgram's approach manages that by detecting the settings at startup.


A combination of this and iProgram'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)
joeytwiddle
  • 3,622
  • 19
  • 28
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 :

iProgram
  • 1,589
  • 2
  • 15
  • 25
1

It should work out of the box if you have these patches:

Although, I would rewrite the mappings:

nnoremap <c-s> :<c-u>w <bar>echo 'Saved'<cr>
inoremap <c-s> <c-\><c-o>:w <bar>echo 'Saved'<cr>
user938271
  • 5,947
  • 1
  • 15
  • 24