1

I am trying to implement autosave in vim.

I managed to put together these lines using this article - Understand Vim Mappings and Create Your Own Shortcuts! and added them to .vimrc

" auto save on esc
noremap <silent> <esc> <esc>:w<CR>
inoremap <silent> <esc> <esc>:w<CR>

On pressing <esc>, vim returns to normal mode and executes the write command with <enter>. Nothing outputs to command area with the silent argument.

The first line add non recursive mapping in normal, visual and select mode. The second line does the same but in insert mode.

I'm assuming normal, visual and insert are the only modes that allow text editing.

I have two problems:

  1. The silent option isn't working.
  2. Every time i open a file in vim, the first character of the file is replaced with g. And the command area contains the following text
:a8a8/a4a4/9d9d^G

When I comment out the two lines in .vimrc, the problem is resolved.

  • 2
    Never, ever, remap Esc - too many things depends on this key – Jorengarenar Jul 11 at 13:38
  • I'm quite new to vim, any specific key you would recommend? esc seems very intuitive. Would recursive mapping solve the issue. – Benny Thadikaran Jul 11 at 13:47
  • 1
    About those weird characters ... Why does this <Esc> normal mode mapping affect startup? – B Layer Jul 11 at 14:27
  • @BennyThadikaran as B Layer and Jordngarenar point out, even a recursive mapping wont work—changing escape effectively breaks all the terminal codes used to manipulate the screen. PS we prefer one question per post so I’ve deleted the question about recursive mappings (they allow sequences in the right-hand side to trigger other mappings). – D. Ben Knoble Jul 12 at 13:14
  • PPS there are other modes, it’s not clear what’s not working with silent. You may prefer to read vim’s builtin help; it’s how I learned vim, and it very instructive. – D. Ben Knoble Jul 12 at 13:18
3

You should not use mapping to do it. For such purpose are autocommands.

If you want to save after exiting insert mode (InsertLeave event), after text change (TextChanged event) or after Vim losing focus (FocusLost event):

augroup AUTOSAVE
  au!
  autocmd InsertLeave,TextChanged,FocusLost * silent! write
augroup END

silent! for ignoring warnings from untitled buffers. w is shortcut from write

There is also autowrite option, you may be interested in (:h 'autowrite').

| improve this answer | |

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.