# query-replace within LaTeX/Math

The answer below was taken from https://stackoverflow.com/a/44913296. This is the most upvoted answer there.

Unfortunately, after running the code (for example by replacing q with \theta) one encounters the following error:

match-substitute-replacement: Invalid use of ‘\’ in replacement text

Moreover, if I use \\theta instead of \theta, query-replace does not work properly, it looks outside LaTeX formula as well.

Is there a way to correct the code?

  (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)))

• This works as expected for me: if I replace q with \\theta, only q characters inside math environments get replaced, and are replaced by \theta. This is with Emacs 28.0.50 – Tyler Mar 17 at 14:16
• @Tyler Can you test also with a document with q outside math environments? – Name Mar 17 at 15:42
• Works also for me with Emacs 27.1 and AUCTeX 13.0.4 with the following example document \documentclass{article} \begin{document} q $$q$$ \end{document} – matteol Mar 17 at 18:13
• @name I did, and it worked. q replaced inside math environment, but not outside. – Tyler Mar 17 at 18:29