0

I am working with LaTeX files in Emacs and need a strategy to test whether a parenthesis (e.g., (, [) starts a balanced expression in latex-mode. I tried using the sexp-at-point function, but it does not seem to be suitable for this purpose (Make sexp-at-point ignore ";" in LaTeX mode).

Example:

Given the following LaTeX content:

\documentclass{article}
\begin{document}
Here is some math with balanced parentheses: $ (a + b) $ and balanced brackets: $ [x, y] $.
Here is an unbalanced expression: $ (a + b] $
\end{document}

Goal:

  • For $ (a + b) $, I want to confirm that here ( starts a balanced expression.
  • For $ [x, y] $, I want to confirm that here [ starts a balanced expression.
  • For $ (a + b] $, I want to detect that here ( does not start a balanced expression.

When the point is on an opening parenthesis (, [, etc., the function should return t if the parenthesis starts a balanced expression; otherwise, it should return nil.

Considerations. I found that forward-sexp and similar functions works fine and I can customize their behaviour setting the syntax-table.

Question:

Is there a built-in function or a recommended strategy to accurately determine (t or nil) if a parenthesis starts a balanced expression in latex-mode? If not, how could I implement such functionality, considering the peculiarities of LaTeX syntax?

Any help or suggestions would be greatly appreciated. Thank you!

1 Answer 1

0

Here's a function to do that:

(defun ndk/paren-match-p ()
   (let ((mismatch (nth 4 (show-paren--default))))
      (not mismatch)))

It'll say t or nil reliably if your cursor is on an opening paren or after a closing paren. It will not work reliably if your cursor is somewhere else, but you can check if you are on one of the two "reliable" places and error out if you are not.

show-paren-default returns a list of five elements: the first four are starting and ending positions of the starting and ending delimiters and the fifth is a mismatch indication. The show-paren code uses that to create overlays and make the match (or mismatch) visible.

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.