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