Subject: Improving `TeX-electric-math' behavior

From: Arash Esbati <[email-masked]>
Date: Wed, 23 Apr 2025 09:25:25 +0200

Hi all,

currently, we have this in AUCTeX manual[1]:

  User Option: TeX-electric-math

  In addition, when the variable is non-nil and there is an active
  region outside math mode, typing $ will put around the active region
  symbols for opening and closing inline equation and keep the region
  active, leaving point after the closing symbol.  By pressing
  repeatedly $ while the region is active you can toggle between an
  inline equation, a display equation, and no equation.  To be precise,
  ‘$...$’ is replaced by ‘$$...$$’, whereas ‘\(...\)’ is replaced by
  ‘\[...\]’.

Using $$...$$ in LaTeX is discouraged, so I think AUCTeX shouldn't
promote this as well, so I suggest this change to
`TeX-insert-dollar-electric-region':

--8<---------------cut here---------------start------------->8---
diff --git a/tex.el b/tex.el
index 3d28b2c6..5d184942 100644
--- a/tex.el
+++ b/tex.el
@@ -6188,10 +6188,13 @@ See `TeX-electric-math'."
              (re-search-forward "\\=\\$\\$\\([^z-a]*\\)\\$\\$" (mark) t)))
     (replace-match "\\1" t)
     (set-mark (match-beginning 0)))
-   ;; $...$ to $$...$$
+   ;; $...$ to $$...$$ or \[...\] dep. on mode:
    ((and (eq last-command #'TeX-insert-dollar)
          (re-search-forward "\\=\\$\\([^z-a]*\\)\\$" (mark) t))
-    (replace-match "$$\\1$$" t)
+    (replace-match (if (memq major-mode '(LaTeX-mode docTeX-mode))
+                       "\\\\[\\1\\\\]"
+                     "$$\\1$$")
+                   t)
     (set-mark (match-beginning 0)))
    ;; \(...\) to \[...\]
    ((and (eq last-command #'TeX-insert-dollar)
--8<---------------cut here---------------end--------------->8---

I think this needs some more massaging in order to make it work for
ConTeXt users as well, but this should get us going for other modes.

What do people think?  If Ok, I would install it and update the manual
accordingly.

Best, Arash

Footnotes:
[1]  https://elpa.gnu.org/packages/doc/auctex.html#index-TeX_002delectric_002dmath