Home » Questions » Computers [ Ask a new question ]

How to invert the selection in vim?

How to invert the selection in vim?

After selecting a range of lines with the V command, I would like to delete every line of the file that is NOT selected, so is a way to invert the selection -- select every line that is not selected?

Asked by: Guest | Views: 381
Total answers/comments: 2
bert [Entry]

"First create the following mapping (for example bound to the <F4> key)

map <F4> :<C-U>1,'<-1:delete<CR>:'>+1,$:delete<CR>

then, after selecting a range in visual mode, just press <F4> to trigger the associated command. The command can be easily explained in parts:

"":"" Enter command line mode.
""<C-U>"" Remove all characters between the cursor position and the beginning of the line.
""1,'<-1"" Specifiy the range from the first line of the file to the line before the start of current selection.
"":delete<CR>"" Delete (the previously specified range of lines).
"":'>+1,$:delete<CR>"" Delete the lines in the range ""'>+1,$"", i.e. from the line after the end of the selection to the end of the file."
bert [Entry]

"Just for posterity:

:v/\%V/d

That does an inverse global on lines that are not part of the selection. Note that :v is a line-based construct, so any line that contains any of the selection, be it line, stream, or block selection will be spared deletion."