# How can I find corresponding balanced parentheses?

I have this LaTeX code:

\caption{Lorem ipsum dolor sit amet: foo), bar), baz) and qux) consectetuer adipiscing elit.}


I want to put a marker immediately before the first { and one immediately after its corresponding }.

forward-list is my usual choice in order to find balanced parentheses, but in this case it is not suitable because it moves cursor immediately after the first ) (as its standard behaviour).

How can I do this?

;; my standard way
(while (re-search-forward "\\\\\\<caption\\>" nil t)
(setq pos1 (point-marker))
(set-marker-insertion-type pos1 t)
(forward-list)
(setq pos2 (point-marker))
(set-marker-insertion-type pos2 t)
(save-excursion
(save-restriction
(narrow-to-region pos1 pos2)
(goto-char (point-min))
;; do something
)))


I have found an answer here:

Strict parenthesis matching

Function forward-pexp does the trick.

• (search-forward "}") perhaps? – NickD May 21 '20 at 15:12
• @NickD The problem with (search-forward "}") is that \caption{...} can contain many other { } as in \ref{ } or \cite{ } or in math expression like ^{-1} and so on. – Onner Irotsab May 21 '20 at 15:58
• (forward-sexp) does not work in this case, but (sp-forward-sexp) from the smartparens package works. – gregoryg May 21 '20 at 16:12

Use forward-sexp, bound to C-M-f.
• You're right, with that text. Sounds like a bug, to me. The delimiter paired with { should be }, not ), no? – Drew May 21 '20 at 17:10
• @Drew Please, could you be more clear abount "bound to C-M-f"? – Onner Irotsab May 21 '20 at 17:43
• @Drew - I thought so, but maybe I'm missing something. Part of the problem I think is the unbalanced parens in the OP's example, e.g. in cc-mode, C-M-f goes from { to } but only if the other paren-like things in-between balance. – NickD May 21 '20 at 18:50
• @NickD: Yeah, I can see an argument for that as the proper behavior. But it doesn't sound correct to me, in a mode such as LaTeX. I'd think that it should just look for a closing }. – Drew May 21 '20 at 20:34