up vote 4 down vote favorite
1
share [g+] share [fb]

After selecting a range of lines with the V command, I would like to delete every line of the file that is NOT selected.

Edit: What I would really like to know, is if there is a way to invert the selection -- select every line that is not selected. Like how

:g!/FOO/d`

deletes every line which does NOT contain FOO. The inverse of

'a,'b

would be the two ranges:

1,'a-1 and 'b+1,$

I suspect that this cannot be done in one step -- but it would be nice!

link|improve this question
so you want a "crop"-style operation? – quack quixote Nov 19 '09 at 16:10
feedback

3 Answers

up vote 0 down vote accepted

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.
link|improve this answer
1  
just to explain it: 1,'< - 1 is the range from line 1 upto the start of the selection. '> + 1,$ is the range from 1 line after the selection upto the end... – akira Nov 19 '09 at 17:13
Is there some way to do that with only one "delete" command? – Kevin Panko Nov 19 '09 at 18:34
@Kevin Panko: you'd need to combine the ranges into a single expression. i've looked at the docs and i don't think the range syntax supports such a thing. vimdoc.sourceforge.net/htmldoc/cmdline.html#cmdline-ranges ,,, vim.wikia.com/wiki/Ranges – quack quixote Nov 19 '09 at 22:05
feedback
  1. select your text
  2. "*yggdG"*p which means ...

    "*y    " yank it to the selection register
    ggdG   " delete everything
    "*p    " and paste the selection again
    
link|improve this answer
5  
ygg"_dGP is the same but shorter. – Kevin Panko Nov 19 '09 at 17:56
in the end you get the same text, true :) – akira Nov 19 '09 at 18:20
... or :m0<CR>jdG or y:%d_<CR>P or ... :) – peth May 16 '11 at 15:21
feedback

since 'inverting' means basically to create 'multiselections' (the area before and after the original selection) i searched the vimscripts again http://www.vim.org/scripts/script.php?script_id=953. try this.

 There are a number of operations to very
 easily manipulate selections such as modifying 
 the regions (add/delete/inverte/clear), hiding, 
 refreshing, saving and restoring etc."
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.