[Tex/LaTex] Editor that replaces only text inside math environments

editors

I'm writing a document where I had to change all instances of the variable i to x and the document is already considerably long. Is there a editor that will allow me to do this, or in general, replace text inside math environments?

Best Answer

emacs can do this sort of thing fairly easily

(defun change-mathvar (a b)
  (interactive "sfrom: \nsto: ")
  (beginning-of-buffer)
  (while (re-search-forward
      "\\(\\\\(\\|\\\\\\[\\|[^\\\\]\$\$?\\|\\\\begin{equation}\\|\\\\begin{align}\\)" nil 1)
    (query-replace-regexp a  b t  (point) 
              (progn (re-search-forward 
                  "\\(\\\\)\\|\\\\\\]\\|[^\\\\]\$\$?\\|\\\\end{equation}\\|\\\\end{align}\\)" nil 1) (point)))))

this looks for $ \( \[ \begin{equation} \begin{align} as math-start. Other environments can be added.

Starting from a document such as

\documentclass{article}

\begin{document}


i   i   aib  


\[i   i   aib  \]


i   i   aib  


\begin{equation}
i   i   aib
\end{equation}


\end{document}

then executing M-x change-mathvar the editor will prompt for the old and new names then do a query-replace of the variable names to produce:

\documentclass{article}

\begin{document}


i   i   aib  


\[x   x   aib  \]


i   i   aib  


\begin{equation}
x   x   aib
\end{equation}


\end{document}

Note it hasn't changed anything out of math and it only changes i where it appears as a complete word, not aib. If you want aib to change as well change the t in the code to nil to make a non-delimited match.