Editor that replaces only text inside math environments

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.


My solution using emacs (>=24) and auctex:

(defun latex-replace-in-math ()
"Call `query-replace-regexp' with `isearch-filter-predicate' set to filter out matches outside LaTeX math environments."
(interactive)
(let ((isearch-filter-predicate
(lambda (BEG END)
(save-excursion (save-match-data (goto-char BEG) (texmathp)))))
(case-fold-search nil))
(call-interactively 'query-replace-regexp)))

Instead of manually listing math environments, this uses texmathp to detect them. Undefining case-fold-search has the effect of making the search case sensitive; this usually makes sense for variable symbols.

Usual regular expressions can be used, e.g. searching for \<i\> instead of just i avoids changing \sin to \sxn.


WinEdt is enough:

  1. In the "Replace" dialog box, choose the check box "Whole words only" and "Regular expressions".

  2. Search for i\E{isMath} and Replace with x.

Then, it works. However, for expression like _i, it will also change to _x which maybe not that you want.

You can also replace text not in math environment by using i\e{isMath}.

I find this trick by searching "Regular Expressions" in the diaglog "WinEdt help". Maybe you find more useful tricks in the help.

Tags:

Editors