Mac Vim Save And Exit

Posted on  by admin

It may sometimes happen that you open a system file for edition, forgetting (or not seeing the warning) that the file is actually read-only. Then you make a couple of changes, then try to write the file.
A nice message then pops up:

Press Esc key: This is very important, because you must exit the edit mode first before typing the exit command(s). Next, you can type one of the following commands: 2.:q (yes, the colon is included in the command) – This will quit the editor. – Quit Vim without saving the data file. If you want to save and exit the current file in vi or vim text editor, and you need to press Esc key to back to normal mode, and type:wq command, then press Enter key in your keyboard. Save/Exit the file in vim editor We need to follow the below steps to save and exit the file. Press Esc key to go back to command mode. Once it is done, the string — INSERT—- will be disappeared at the bottom of the editor. This fails when changes have been made.:quit! Quit without writing.:cquit Quit always, without writing.:wq. Write the current file and exit.:wq! Write the current file and exit always.:wq. Exit if not editing the last:wq! Write to and exit always.:rangewq! file Same as above, but only write the lines in range. 9) Type escape to return to command mode and then type ZZ (shift key down) to save and exit vifs (or some other method to save and exit if you are using something other than vim). 10) Type the following and press enter to reset the auto mounter: sudo automount -vc. 11) Quit Terminal.

Can't open file for writing

How To Exit Vim

Mac vim save and exit program

Rather than being tempted to exit (ESC :q!), lose your changes, reopen the file with sudo (sudo vim /path/to/my/system/file) and editing it again, you can use the following interactive command right in Vi/Vim to write your changes:


This command will ask for your password, then you will be able to acknowledge the buffer changes or reload the file to its initial state.

Vim exit search

Mac Vim Save And Exit Download

At this stage, you will be presented with the content of the file and a prompt to press ENTER or type another command.
Then type the letter O to simply save the file and move on.
Note that pressing L seems to do pretty much the same thing. The file will be saved but remains opened in Vi/Vim for more editing or reading. We can now exit normally by typing ESC :q! since the file is still opened as read-only.

For reference, below is what those commands actually mean and do:

  • :w : Write
  • !sudo : Invoke a shell with the sudo command
  • tee : the output of the write command above
  • % : the current file path

Vim Exit Recording

That's it for this quite short first post. I hope this trick proves useful, as it saved my day earlier today :) Any comment is obviously more than welcome.