Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs regex: replacing a string inside a latex equation

Tags:

regex

emacs

latex

I'd like to replace all occurrences of the letter 'n' that occur inside any LaTeX equation, with the letter 'N'. It can be assumed that the LaTeX equations in the document are of the form $...$

Will accept also solutions in perl or any other language/tool/application readily available on ubuntu or Windows.

like image 627
Evan Aad Avatar asked Dec 12 '22 10:12

Evan Aad


1 Answers

My solution is inspired by Tobias but uses isearch-filter-predicate for filtering instead of modifying the internals of query-replace-regexp. This needs at least Emacs 24.

Also, I only use case-sensitive search and replace for math, so I have set (case-fold-search nil) in the function below.

(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)))
like image 102
pavel Avatar answered Jan 22 '23 16:01

pavel