vim Exiting Vim


Example

In order to exit Vim, first make sure you are in Normal mode by pressing Esc.

  • :q Enter (will prevent you from exiting if you have unsaved changes - short for :quit)

To discard changes and exit Vim:

  • :q! Enter to force exit and discard changes (short for :quit!, not to be confused with :!q),
  • ZQ is a shortcut that does the same as :q!,
  • :cq Enter quit and return error (discard all changes so the compiler will not recompile this file)

To save changes and exit Vim:

  • :wq Enter (shorthand for :write and :quit),
  • :x Enter (same as :wq, but will not write if the file was not changed),
  • ZZ is a shortcut that does the same as :x (Save workspace and quit the editor),
  • :[range]wq! Enter (write the lines in [range])

To close multiple buffers at once (even in multiple windows and/or tabs), append the letter a to any of the Commands above (the ones starting with :). For example, to write and quit all windows you can use:

  • :wqa Enter or
  • :xa Enter — Write all changed buffers and exit Vim. If there are buffers without a file name, which are readonly or which cannot be written for another reason, Vim will not quit
  • :xa! Enter — Write all changed buffers, even the ones that are readonly, and exit Vim. If there are buffers without a file name or which cannot be written for another reason, Vim will not quit
  • :qa Enter — try to quit, but stop if there are any unsaved files;
  • :qa! Enter — quit without saving (discard changes in any unsaved files)

If you have opened Vim without specifying a file and you want to save that file before exiting, you will receive E32: No file name message. You can save your file and quit using:

  • :wq filename Enter or;
  • :x filename Enter

Explanation:

The : keystroke actually opens Command mode. The command q is an abbreviation of quit, w, of write and x, of exit (you can also type :quit, :write and :exit if you want). Shortcuts not starting with : such as ZZ and ZQ refer to Normal mode key mappings. You can think of them as shortcuts.

The ! keystroke is sometimes used at the end of a command to force its execution, which allows to discard changes in the case of :q!. Placing the ! at the beginning of the command has a different meaning. For example, one can mistype :!q instead of :q! and vim would terminate with a 127 error.

An easy way to remember this is to think of ! as a way of insisting on executing something. Just like when you write: "I want to quit!"