Subject: bug#78587: [PATCH] TeX-find-macro-end

From: "Paul D. Nelson" <[email-masked]>
Date: Sun, 25 May 2025 17:14:44 +0200

Hi all,

I noticed that TeX-find-macro-end doesn't work as expected way on, e.g.,

  \begin{enumerate}[a)]

The issue arose organically when folding such macros.

To see the basic issue, evaluate the following in scratch:

--8<---------------cut here---------------start------------->8---
(mapcar
 (lambda (str)
   (with-temp-buffer
     (LaTeX-mode)
     (insert str)
     (char-to-string (char-before (TeX-find-macro-end-helper (point-min))))))
 '("\begin{enumerate}[a]"
   "\begin{enumerate}[(a)]"
   "\begin{enumerate}[a)]"))
--8<---------------cut here---------------end--------------->8---

This returns ("]" "]" ")") but should return ("]" "]" "]").

The attached patch seems to address the issue by using a stripped syntax
table, which seems like a standard approach in tex.el.  Any feedback
would be welcome.

Paul

>From c523eeedf567499d98d46c3dd6f04629f96799aa Mon Sep 17 00:00:00 2001
From: Paul Nelson <[email-masked]>
Date: Sun, 25 May 2025 17:11:49 +0200
Subject: [PATCH] Fix TeX macro end detection in some edge cases

* tex.el (TeX-find-macro-end-helper): Use
TeX-search-syntax-table with square brackets when calling
forward-sexp.  This fixes parsing of optional arguments
containing other unmatched delimiters, such as
\begin{enumerate}[a)], where the search would stop at ')'
instead of ']'.
---
 tex.el | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/tex.el b/tex.el
index e90252d8..d65599be 100644
--- a/tex.el
+++ b/tex.el
@@ -5867,7 +5867,8 @@ those will be considered part of it."
                        (looking-at "[ \t]*\\(\\[\\)"))))
             (goto-char (match-beginning 1))
             (condition-case nil
-                (forward-sexp)
+                (with-syntax-table (TeX-search-syntax-table ?\[ ?\])
+                  (forward-sexp))
               (scan-error (throw 'found (point)))))
            ;; Skip over pairs of curly braces
            ((or (looking-at "[ \t]*\n?[ \t]*{") ; Be conservative: Consider
-- 
2.39.3 (Apple Git-145)