Reply to message «Re: Delete lines matching hits», 
sent 02:48:53 06 February 2011, Sunday
by Tim Chase:

> If it is, it should be fairly possible to do it with a :s
> command, something like
> 
>    :%s/^abc\ndef\n//
It should be
    :%s/.*{pattern}.*\n//
or, in this particular case:
    :%s/.*abc\ndef.*\n//
because we are going to delete the whole lines that contain match, but nobody 
said that they contain only match. Both solutions does not work for patterns 
with \zs and \ze, maybe it is better to do the following:

    function! s:MarkToDel(todelete, sline, submatch)
        let lnum=len(substitute(a:submatch, '\n\@!.', '', 'g'))
        call add(a:todelete, [a:sline, lnum])
        return a:submatch
    endfunction
    function! DeleteMatchingLines(pattern)
        let todelete=[]
        let savedgdefault=&gdefault
        set nogdefault
        try
            execute '%s/'.escape(a:pattern, '/').
                        \'/\=s:MarkToDel(todelete, line("."), submatch(0))'
        finally
            let &gdefault=savedgdefault
        endtry
        let deleted=0
        for [sline, lnum] in todelete
            let sline-=deleted
            let deleted+=lnum+1
            let range=sline.','.(sline+lnum)
            execute range.'delete _'
        endfor
    endfunction

By the way, with some trivial modifications this code can be used in 
CopyMatchingLines because it has the following advantages:
1. For each match only one search is done.
2. Pattern is compiled only once.
3. No «The 'normal! $' attempts to avoid copying the same line more than
once.»: vim does this for you when you omit /g flag (this is why 'gdefault' 
option is saved and restored).

Original message:
> On 02/05/2011 05:02 PM, Ben Fritz wrote:
> >>> I wonder if there's a way to do the same but instead of copying them
> >>> to the clipboard, delete them.
> >>> 
> >> :g/pattern/d
> > 
> > I think this will not work for the second part claimed by the comment
> > in the code posted: "The pattern may extend over multiple lines."
> > 
> > For example,
> > 
> > abc
> > def
> > ghi
> > 
> > :g/abcc\ndef/d
> > 
> > will delete only "abc", it will not delete "def".
> > 
> > I'm not sure how important this is to the OP...
> 
> If it is, it should be fairly possible to do it with a :s
> command, something like
> 
>    :%s/^abc\ndef\n//
> 
> -tim

Attachment: signature.asc
Description: This is a digitally signed message part.

Reply via email to