What is a reliable way to find the matching balanced bracket (eg: {}, [], () in C or Python), which doesn't get confused by brackets in strings, or escaped brackets for e.g.


["Foo]" ?\] 0 [1 2]]
^                  ^
Input point.      Return point.

Something like how show-paren-mode works, except as an elisp-function where you can pass in a point and get a matching point or nil when not found.

1 Answer 1


Generally forward-sexp should know what to do in any given mode, so you could perhaps base it on this:

(save-excursion (ignore-errors (forward-sexp) (1- (point))))


Something like how show-paren-mode works

You could use that exact same code. Look at M-x find-function RET show-paren-function and how it uses the results of (funcall show-paren-data-function), and adapt to your purposes.

show-paren-data-function is a variable defined in `paren.el'.
Its value is `show-paren--default'

  This variable may be risky if used as a file-local variable.

Function to find the opener/closer "near" point and its match.
The function is called with no argument and should return either nil
if there's no opener/closer near point, or a list of the form
Where HERE-BEG..HERE-END is expected to be near point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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