Search code examples
emacsauctex

Emacs/Auctex: Automatically enabling/disabling LaTeX-Math-mode


I'm using Emacs in conjunction with AucTeX (running Ubuntu 10.04, if that matters).

Does anyone know if there is a way to automatically enable LaTeX-math-mode (a minor mode of AucTeX) if the point is in any maths environment (i.e. in a $...$, a $$...$$, begin{equation}...\end{equation}, and so on)?

I suppose there is a relatively easy answer, since syntax highlighting uses the same criterion for coloring math stuff, but I could not find anything.


Solution

  • If andre-r's answer doesn't satisfy you, here's some code that sets up ` to self-insert in text mode and act as a math mode prefix in math mode. LaTeX-math-mode must be off.

    (defun LaTeX-maybe-math ()
      "If in math mode, act as a prefix key for `LaTeX-math-keymap'.
    Otherwise act as `self-insert-command'."
      (interactive)
      (if (texmathp)
          (let* ((events (let ((overriding-local-map LaTeX-math-keymap))
                           (read-key-sequence "math: ")))
                 (binding (lookup-key LaTeX-math-keymap events)))
            (call-interactively binding))
        (call-interactively 'self-insert-command)))
    (define-key LaTeX-mode-map "`" 'LaTeX-maybe-math)
    

    The following improvements are left as exercises:

    • Make it a minor mode.

    • Make it more robust towards unexpected input (I've only tested basic operation).

    • Show a better error message if the user presses an unbound key sequence.

    • Show help if the user presses C-h or f1.