What's the use of the exclamation mark ('!') in Vim's command line after certain commands like ":w!"?

The ! qualifier tells Vim to force the operation. For example, if the file was read-only you would use :w! to write it anyway. If the file was modified and you wanted to quit without saving, you would use :q!. :wq! just means force write and quit in one command.


Besides the situations where the exclamation point forces things, like writes, it will turn a command into a toggle command. So if I do:

:set cursorline

the line my cursor is on will be highlighted. I can turn it off with:

:set nocursorline

Or I could do:

:set cursorline!

That command flips between the two settings, off and on.

I turn cursor line highlighting off and on frequently, and the toggle command lets me do it with a simple function key mapping. Without the toggle, I would need either two mappings: one to turn it on, and a second to turn it off. Or I would have to write a function to determine whether the cursorline setting was on or off, and then turn on the opposite setting.

This works with, as far as I know, all command line settings that have on and off settings, like hlsearch, paste, cursorcolumn, number, insearch, etc.

Note also that the exclamation point will toggle the no version of the command. For example, you could also toggle the cursor line setting with:

:set nocursorline!

The exclamation point usually means to force some action. However, there are many other uses, e.g.

  • ! followed by some command executes that command directly from the editor, e.g. :! ls /etc
  • :w !cmd pipes the contents of the current buffer to the command cmd, e.g. :w !sudo tee % (a.k.a. the write with sudo trick).

Tags:

Vim