0

I want to do the following:

autocmd changeFromItoN * if &readonly == 0 && filereadable(bufname('%'))
                        \ | silent update | endif

That is: I want to implement the auto-save, so when I exit the insert mode and back to normal mode it will run :w automately. So what is the real command for changeItoN?

Note: This sounds like a little problem but actually there is a similar problem on SO that the accepted answer on that thread won't work with an important plugin which is used by a lot of people --- The CoC.nvim, and so I want to accomplish this feature myself :)


Conclusion: The command should be:

autocmd InsertLeave,TextChanged * if &readonly == 0 && filereadable(bufname('%'))
                                 \ | silent update | endif

Notice that the TextChanged is also needed so autosave will also work with daily-commands, e.g. after you delete a line by dd.

7
  • 2
    Have a look at InsertLeave. – Jürgen Krämer May 3 at 14:01
  • @JürgenKrämer: I works :) If you're willing you might put it into an answer. – job_start May 3 at 14:06
  • 1
    The way you broke your command into two lines is not correct. You need to put the backslash at the start of the second line. I guess when you tested your command you had everything in one line; otherwise Vim would have printed an error message. – Jürgen Krämer May 3 at 14:15
  • @JürgenKrämer: Good catch! I think that's because I was writing python! – job_start May 3 at 14:17
  • FYI :h autocmd-events lists the available events it might be useful next time you have a similar question. Also rather than using an autocommand you could go with a mapping like this: inoremap <silent> jk <Esc>:update<CR> You'd use jk to switch from insert mode to normal mode and it would save each time you switch mode. I've been using this for years and I'm perfectly happy with it. – statox May 3 at 15:30
2

There is an autocommand event InsertLeave. It is triggered when you leave Insert mode permanently with ESC or temporarily with Ctrl+O, but not if you leave Insert mode with Ctrl+C.

1
  • If you identity any problem on the command I provided in OP, you might also point it out :) Thank you so much! – job_start May 3 at 14:11

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.