In vim, search backwards for matching braces/parens

keyboard shortcutsvim

As most of you probably know, you can use % to search forwards on the line to find the next paired brace/bracket/paren and move to its matched partner:

|a|rray[index] = value;
" |e| is the cursor; hit %:
array[index|]| = value;

I am hoping there is a similar key that searches backwards on the line, e.g.:

array[index] = value|;|
" |;| is the cursor again, hit the key I'm looking for:
array|[|index] = value;

Most vim commands have both a backwards and forwards, so it seems this should to. Does it not have a partner? If so, is that because once it's on a paired character they would act the same?

Best Answer

If you really want to search backwards for common matching characters, you can use one of these vim-specific commands:

  • [( ...(go to previous unmatched ( character)
  • [{ ...(go to previous unmatched { character)

These two commands have matching forwards partners:

  • ]) ...(go to next unmatched ) character)
  • ]} ...(go to next unmatched } character)

There are other similar commands for #ifdef and for C comments.

You can find more when in vim by using the command :help %.

Related Question