I want to define <C-s> to save current editing file in any mode.
map <C-s> :call StripWhitespace()<CR> works fine in normal mode. But if I'm in insert mode, always need to Esc before saving.

Tried below methods, but failed.
imap <C-s> :call StripWhitespace()<CR>

function! My_Force_Save()
   if mode() != 'n'
      exe "normal! \<esc>"
   call StripWhitespace()

function! StripWhitespace ()
    let save_cursor = getpos(".")
    let old_query = getreg('/')
    call setpos('.', save_cursor)
    call setreg('/', old_query)
    exe ":w!"

1 Answer 1


The :map command you tried works in normal, visual, and operator pending modes, and the :imap command works in insert mode, so you're going to need both, but you're also going to need to make a few changes.

Firstly, you should always use the non-recursive nore forms of the various map commands unless you have a specific reason not to.

Next, note that the map commands work as though you are typing out the things you map to. When you type a colon in visual mode, the command-line is pre-populated with a :'<,'> range. We don't want to pass this range to the :call command, so we need to clear it first with Ctrl-U:

noremap <C-S> :<C-U>call StripWhitespace()<CR>

Similarly, to call a function from an insert mode map, you need to include the Esc in your mapping:

inoremap <C-S> <Esc>:call StripWhitespace()<CR>

Even better, use Ctrl-O to perform a single command and remain in insert mode:

inoremap <C-S> <C-O>:call StripWhitespace()<CR>

See :help i_CTRL-O

  • vi.stackexchange.com/users/343/rich @Rich, Found an issue: In normal mode, 'dd' delete a line, after this 'C-s' is not working.
    – Fisher
    Commented Mar 29, 2018 at 16:20
  • Not sure why inoremap is not working. Need to use map <C-S> <Esc>:call StripWhitespace()<CR>
    – Fisher
    Commented Mar 30, 2018 at 0:10
  • @Fisher You need both! See my updated answer.
    – Rich
    Commented Mar 30, 2018 at 7:39
  • Thanks a lot for the details. Now I understand the difference. Why I can't @Rich in the beginning?
    – Fisher
    Commented Mar 31, 2018 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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