Subject: bug#73302: TeX-find-closing-brace and verbatim macros

From: Paul Nelson <[email-masked]>
Date: Fri, 27 Sep 2024 20:36:10 +0200

Hi Arash,

> How does your code work on this example:
>
>   \verb|}|
>
> ?  I admit, this is a mess, but maybe we can come up with a solution
> within AUCTeX; I have to think about it, though.
>
> Best, Arash

That example motivated me to take a proper look at the verbatim
functions in AUCTeX, which is indeed relevant.  The following modified
code passes all tests mentioned thus far in this thread, although the
way the verbatim argument is found might be a bit brittle -- I guess
you could have a commented "{" in the middle of a multi-line
\Verb{...}, but multi-line \Verb{...} seems like illegal latex anyway,
so maybe it's all OK?

(defun czm-tex-fold--verb-data (&rest _args)
  "Return data for a verbatim macro.
Returns a list of the form (START END CONTENT)."
  (when-let* ((boundaries (LaTeX-verbatim-macro-boundaries))
              (bound-start (car boundaries))
              (bound-end (cdr boundaries))
              (end-delim-char (char-before bound-end))
              (start-delim-char
               (cond
                ((eq end-delim-char ?}) ?{)
                ((eq end-delim-char ?|) ?|)))
              (start-delim (char-to-string start-delim-char)))
    (goto-char (1- bound-end))
    (when (search-backward start-delim bound-start t)
      (let* ((verb-arg-start (1+ (point)))
             (verb-arg-end (1- bound-end)))
        (list
         bound-start
         bound-end
         (buffer-substring verb-arg-start verb-arg-end))))))

(defun czm-tex-fold-verbs (start end)
  "Fold verbatim macros between START and END."
  (save-excursion
    (goto-char start)
    (let ((re (concat "\\\\" (regexp-opt
                              (append
                               (LaTeX-verbatim-macros-with-braces)
                               (LaTeX-verbatim-macros-with-delims))))))
      (while (re-search-forward re end t)
        (when-let* ((data (czm-tex-fold--verb-data))
                    (verb-start (nth 0 data))
                    (verb-end (nth 1 data))
                    (content (nth 2 data))
                    (spec (lambda (&rest _args)
                            (nth 2 (czm-tex-fold--verb-content)))))
          (czm-tex-fold--create-misc-overlay verb-start verb-end
content spec))))))