How to invert the selection in vim?
Solution 1:
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.
Solution 2:
- select your text
-
"*yggdG"*p
which means ..."*y " yank it to the selection register ggdG " delete everything "*p " and paste the selection again
Solution 3:
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.