I use $ ... $ for inline math and \[ ... \] for display math. I'd like to be able to toggle between the two by selecting the text and calling TeX-insert-dollar.

However, as I understand it, this function only allows the cycles

$ ... $ <-> $$ ... $$ <-> ...


\( ... \) <-> \[ ... \] <-> ...

(this behaviour is controlled by setting the variable TeX-electric-math).

Is there any way to customize this behaviour to my needs (it would also be useful to extend it to other equation enviroments such as equation, align, gather, etc.)?


I finally managed to do this like so

(defun begin-end-regexps (env)
  (list env
        (replace-regexp-in-string "{\\([a-zA-Z]+\\)\\*}" "{\\1\\\\*}" (concat "\\\\begin{" env "}\\([^\0]*?\\)\\\\end{" env "}"))
        (concat "\\\\begin{" env "}\\1\\\\end{" env "}")))

(defun loop-math-modes (step)
  (if (texmathp)
          ((math-modes (list '("$" "\\$\\([^$\0]+?\\)\\$" "$\\1$")
                             '("\\[" "\\\\\\[\\([^\0]*?\\)\\\\\\]" "\\\\[\\1\\\\]")
                             (begin-end-regexps "equation")
                             (begin-end-regexps "equation*")
                             (begin-end-regexps "align")
                             (begin-end-regexps "align*")
                             (begin-end-regexps "gather")
                             (begin-end-regexps "gather*")))

        (dolist (element math-modes) ;; get list of cars
          (setq commands
                (append commands (list (car element)))))
            ((math-mode-index (cl-position (car texmathp-why) commands :test 'equal))
             (current-pos (point)))
            (goto-char (cdr texmathp-why)) ;; for some reason save-excursion is not working
            (re-search-forward (nth 1 (nth math-mode-index math-modes)))
            (replace-match (nth 2 (nth (mod (+ math-mode-index step) (length math-modes)) math-modes)))
            (goto-char current-pos)))
    (message "Not inside math environment")))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.