Use of ! in VIM

When you make no changes to the actual content of the file, you can simply quit with :q. However if you make edits, vim will not allow a simple quit because you may not want to abandon those changes (especially if you've been in vim for a long time editing and use :q by accident). The :q! in this case is a force the quit operation (override the warning). You can issue a forced quit to all opened windows (such as those opened with Ctrlwn) with :qa!.

You can write changes out and quit with :wq (or :x), and this sometimes will fail (the file has been opened as readonly (-R on the command line, or vim was invoked with the view command), in which case you can force the write operation with :wq!.

As an aside, you can also use ZQ to do the same operation as :q! and ZZ to do the same as :wq, which can be easier on the hands for typing :)

Vim also has a built-in help which you can access via :help; exiting has it's own quick topic page: :help Q_wq.


There is no "general use" of !, it's just a modifier. Each command gets to chose what an extra ! will do to it.

In many cases commands are programmed so that ! forces them. Examples include q that you mention, but also save: save! will overwrite the file if it already exists, while save would return an error and suggest to use save! if you are sure of what you're doing.

Finally ! used on its own is used for shell commands, for instance :!ls or :!mkdir foo.

In the case of read (from your comment), the command read! <something> is interpreted by Vim as "execute <something> and read (meaning, in Vim, write to buffer) its output". So here it is as if the ! behaves not as a modifier of the read command but as the stand-alone command !. It could be that the read command does not declare a variant with ! so Vim just interprets the rest independently (so it reads a "! used alone" after read), or that read declares a variant with ! that has this particular behavior ("execute the rest as shell") that happens to mimic what the "! used alone" does.

I guess the take-away is: there is not rule, each command defines what ! will do, and while there is an attempt to have some sort of consistency in the effect of modifiers, not having super-strict rules (like "! will always be for forcing") allow to have more useful behaviors with less keystrokes, which is a plus too.

Tags:

Vi

Vim