2

I have this test code:

foo

\begin{equation}
  foo
\end{equation}

foo

$foo$

foo

I want to replace "foo" with "bar" everywhere but LaTeX math, so I have written these functions:

(defun test-a ()
  (interactive)
  (let ((isearch-filter-predicate 'skip-equation-env))

    (query-replace-regexp "foo"
                          "bar" nil (point-min) (point-max))))

(defun skip-equation-env (beg end)
  (catch 'skip-region
    (save-excursion
      (save-match-data
        (when (and (looking-back "\\\\begin{equation}\\([[:graph:] \n]+\\)")
                   (looking-at "\\([[:graph:] \n]+\\)\\\\end{equation}"))
          (throw 'skip-region nil)))
      t)))

(defun test-b ()
  (interactive)
  (let ((isearch-filter-predicate 'skip-inline-math))

    (query-replace-regexp "foo"
                          "bar" nil (point-min) (point-max))))

(defun skip-inline-math (beg end)
  (catch 'skip-region
    (save-excursion
      (save-match-data
        (when (face-at-point beg 'tex-math)
          (throw 'skip-region nil)))
      t)))

I have adapted skip-equation-env and skip-inline-math from another code to be fit to my case, so I'm not sure of all their lines.

I have tested these functions successfully, but I would like to know if there is a more suitable way to write them using isearch-filter-predicate. I am new to isearch.

I am not allowed to use auctex.

1 Answer 1

1

If you don't need to discriminate between in-line mathematics and mathematical environments, you can simply use texmathp. You don't need to install AUCTeX, but you can retrieve the texmathp.el file from GitHub: https://github.com/emacsmirror/auctex/blob/master/texmathp.el.

(require 'texmathp)

(defun omit-maths (beg end)
  "Return nil if some text BEG to END is in a LaTeX maths environment or in in-line
maths."
  (catch 'skip-region
    (let ((pos beg))
      (save-excursion
        (save-match-data
          (goto-char pos)
          (while (< pos end)
            (when (texmathp) (throw 'skip-region nil))
            (goto-char (setq pos (1+ pos)))))
        t))))

(defun hold-maths (beg end)
  "Return t if some text BEG to END is NOT in a LaTeX maths environment or in
in-line maths."
  (catch 'skip-region
    (let ((pos beg))
      (save-excursion
        (save-match-data
          (goto-char pos)
          (while (< pos end)
            (unless (texmathp) (throw 'skip-region nil))
            (goto-char (setq pos (1+ pos)))))
        t))))

You can also install AUCTeX without automatic activation for LaTeX (.tex) files: https://emacs.stackexchange.com/a/80263/15606

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.