What's the use of the exclamation mark ('!') in Vim's command line after certain commands like ":w!"?
Basically I would like to know the difference between: :w
and :w!
or :wq
and :wq!
Solution 1:
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.
Solution 2:
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!