Question

I often surround some code/text with some other lines of text. For the sake of a concrete example, say I have some text:

this is 
some text

I then have macro that lets me convert that (after highlighting the lines) to

if false then
    this is
    some text
end;

the macros I use to do this are:

nmap <space>i ccif false then<CR><c-r>"end;<esc>
vmap <space>i cif false then<CR><c-r>"end;<esc>

However I would like to be able to create macro to then remove the surrounding text. That is, if the cursor is surrounded by lines "if false then" and "end;" then those lines should be removed.

Any ideas how I would create a macro like that?

Let me note that I have looked at surround.vim, but have not found a way to do it using that package.

Was it helpful?

Solution

Try following dirty function and check if can help to solve your issue. From cursor position it looks forward and backwards for those strings. Delete them only when both match:

function! RemoveSurrondingIfCondition()
    let s:current_line = line('.')
    "" Look backwards for the key string.
    let s:beginif = search( '\v^if\s+false\s+then\s*$', 'bWn' )
    if s:beginif == 0 || s:current_line <= s:beginif
        return
    endif
    "" Set a mark where the _if_ begins
    execute s:beginif 'mark b'
    "" Look forward for the end of the _if_
    let s:endif = search( '\v^end;\s*$', 'Wn' )
    if s:endif == 0 || s:endif <= s:beginif || s:current_line >= s:endif
        return
    endif
    "" Delete both end points if searches succeed.
    execute s:endif . 'delete'
    'b delete
endfunction

noremap <space>d :call RemoveSurrondingIfCondition()<CR>

OTHER TIPS

I threw together an answer that'll do this in one line – you and I both know that can only spell "regex." Anyways, this will work on the closest set of if false then and end;. If you're not in the "scope" of such a pair, it will delete the nearest two, maybe in a weird way! Feel free to call this "undefined behavior."

:?^\s*if\ false\ then?,/^\s*end;/ g/^\s*if\ false\ then\|^\s*end;/d

You can dig around in there and find the actual strings, and change them to what actually suits you. And, if you're willing to get down and dirty with the regex, you could, for example, make it match both if false thens and if true thens and really if <something> thens, and all sorts of fun stuff.

If you'd like a less cursory (read: nonexistent) explanation of how this works, feel free to say so. I'm assuming here you're at least as knowledgeable about :g as I am.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top