2

Is there a command to exit insert mode and perform :w or :wq in the same command?

I am tired of pressing esc + :w every time I need to write to a file after making edits.

Alternatively, is there an autosave function?

3
  • 4
    You can create an insert-mode mapping, but I caution against it: in time, :write will be natural. Not all edits are done in insert mode, so <esc> is not always necessary. If you find yourself spending a lot of time in insert mode (especially in insert mode but not actually inserting text, such as moving around, or deleting things), it may be worthwhile to try spending more time in normal mode. twitter.com/nelstrom/status/1354367205010530314?s=20
    – D. Ben Knoble
    Jan 9, 2022 at 15:22
  • 3
    Adding my voice to the above comment and the answer as this can't be overstated: the only time you should be in Insert mode is when you're actively typing content. If you're navigating the buffer...heck, even if you're just thinking...you should be in Normal mode. A fair number of beginners seem to make the mistake of being in Insert mode most of the time and it really can stand in the way of getting the most out of Vim.
    – B Layer
    Jan 10, 2022 at 0:21
  • 1
    (Probably unnecessary to point out but despite those "you should"s this is just advice. Use Vim however you'd like. Note, though, the reputation of myself and Matt and DBK...there's a lot of experience backing that advice.)
    – B Layer
    Jan 10, 2022 at 1:28

3 Answers 3

5

It is pretty straightforward to create a mapping, e.g.

inoremap <C-S> <cmd>update<CR>

But the point is that you shouldn't stay in Insert mode for too long. That is, always press "esc" immediately after you've finished typing. Use "J", "d", "o", "<<" and other Normal mode keys to reduce the time spent in Insert mode as much as possible. Ideally, you shouldn't need any Insert-mode keys except for typing regular characters and spaces. And if you still don't like pressing :w<CR> then create a Normal-mode mapping instead.

1

The command is CTRL-OZZ.

  • In insert mode CTRL-O will change to normal mode for one command and then return to insert mode: :help i_CTRL-O. In this case it doesn't return because the following command is an exit command, but the return behaviour is useful for much more than this particular situation.

  • ZZ is the command to write the current file if modified and then close the current window: :help ZZ. You can use any of the quit commands (:help write-quit) here as well, of course.

0

It's an old question, but I find interesting to answer in order to suggest the autosave option. I'd also advise to not spent all your life in text input mode.

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.