3

While writing code it often happens that adding one parenthesis leaves another one orphaned somewhere. Many syntax color scheme color the parenthesis differently to signal it.

For example, while writing LaTeX code

$\mathbb{E} something }$

the second } will be marked in red in my vim. If I want to remove it I would have to do

f}x

assuming my cursor is located past the first }, otherwise I need to do some repositiong to reach it.

Since the syntax highlights picks up on it, is there a way to bind a command to something like 'go to the next unmatched parens and delete it'? Bonus point if the cursor is left in its place and left in normal mode.

1

If you use vim-surround you can just delete both the { and } with ds{ or ds} ("delete surrounding {"), so you won't have these dangling }s in the first place!

Finding "unmatched" parens in a 100% generic way is difficult, as that would require a reasonably deep understanding of the language.

However, finding the next syntax group and deleting that is not so hard:

" Find next error on the current line and remove it.
" 
" There's no "match syntax group atom", so move cursor forward one character
" at the time, check for the syntax name, and repeat until we're at the end
" of the time.
fun! RemoveError()
    " Remove this group
    let l:rm = 'texMathError'

    " Save cursor position, folds, etc.
    let l:save = winsaveview()

    while 1
        if synIDattr(synID(line('.'), col('.'), 1), 'name') == l:rm
            normal! x
        else
            normal! l
        endif

        " End of line
        if col('.') == col('$') - 1
            break
        endif
    endwhile

    call winrestview(l:save)
endfun
nnoremap <Leader>x :call RemoveError()<Cr>

If you want to remove multiple syntax groups you could make l:rm a list or check against a regexp.

I would have to do f}x assuming my cursor is located past the first }, otherwise I need to do some repositiong to reach it.

Note that you can use 2f}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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