Is there a way to cycle through \( x=1 \), \[ x=1\] and \begin{equation} x=1 \end{equation}
in any latex package? I find this function practical but I didn't know how to implement using elisp or maybe someone has already done that?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityThis function will do what you want:
(defun cycle-texmath ()
(if (texmathp)
(save-excursion
(setq env (car texmathp-why))
(if (string= env "equation") (progn
(search-backward "\\begin{equation}") (replace-match "\\[" t t)
(search-forward "\\end{equation}") (replace-match "\\]" t t)))
(if (string= env "\\[") (progn
(search-backward "\\[") (replace-match "\\(" t t)
(search-forward "\\]") (replace-match "\\)" t t)))
(if (string= env "\\(") (progn
(search-backward "\\(") (replace-match "\\begin{equation}" t t)
(search-forward "\\)") (replace-match "\\end{equation}" t t)))
)))
(eval-after-load "latex"
'(progn
(define-key LaTeX-mode-map (kbd "C-c t") (lambda () (interactive) (cycle-texmath)))
))
It relies on the texmathp
and texmathp-why
functions which are built into AucTeX
to determine if the point is within a math mode and which indicators are used to invoke it. I've bound it to C-c t
, but feel free to replace that with whatever you'd like.
After posing this as another question to handle the edge case of being within a text{}
environment, the updated version of the code is here:
(defun cycle-texmath ()
(save-excursion
(while (member (TeX-current-macro) '("text"))
(backward-char))
(when (texmathp)
(let ((env (car texmathp-why)))
(cond
((string= env "equation")
(search-backward "\\begin{equation}")
(replace-match "\\[" t t)
(search-forward "\\end{equation}")
(replace-match "\\]" t t))
((string= env "\\[")
(search-backward "\\[")
(replace-match "\\(" t t)
(search-forward "\\]")
(replace-match "\\)" t t))
((string= env "\\(")
(search-backward "\\(")
(replace-match "\\begin{equation}" t t)
(search-forward "\\)")
(replace-match "\\end{equation}" t t)))))))
AucTeX
? If not, I'd recommend it. If so, there are some built in commands which would help out here.