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)
  (setq pos2 (point-marker))
  (set-marker-insertion-type pos2 t)
      (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 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 at 15:58
  • 1
    (forward-sexp) does not work in this case, but (sp-forward-sexp) from the smartparens package works. – gregoryg May 21 at 16:12

Use forward-sexp, bound to C-M-f.

See these nodes of the Emacs and Elisp manuals:

| improve this answer | |
  • In my experiments, that did not work on the OP's example. – NickD May 21 at 16:04
  • You're right, with that text. Sounds like a bug, to me. The delimiter paired with { should be }, not ), no? – Drew May 21 at 17:10
  • @Drew Please, could you be more clear abount "bound to C-M-f"? – Onner Irotsab May 21 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 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 at 20:34

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.