In my LaTeX
code I want to replace one-line eqnarray
environments with the equation
environment. To do that I need to "count" the new-line (\\
) strings in a region and I also need to ignore some new-line strings that may occur in some math sub-enviroments like array
, matrix
etc.
If I have, e.g.:
\begin{eqnarray}
x+y&=& 1
\begin{array}{ccc}
a & b & c\\
d & e & f\\
\end{array}
\end{eqnarray}
I need to ignore the \\
strings inside the array environment.
To do that I can, temporarily replace these strings with arbitrary strings but I have the downside of the reappearing of them (the arbitrary strings) when i undo
some changes.
So I tried to use the with-silent-modification
macro:
(defun latex-one-line-eqnarray-to-equation ()
(interactive)
(save-excursion
(let* ((a (copy-marker (point-min)))
(z (copy-marker (point-max))))
(goto-char a)
(unwind-protect
(while (search-forward-regexp "\\\\begin{eqnarray}" nil t)
(save-excursion
(let ((b (copy-marker (match-beginning 0)))
(e (copy-marker (search-forward-regexp
"\\\\end{eqnarray}" nil t))))
;; *LaTeX sub environment line break occultation:*
(save-restriction
(narrow-to-region b e)
(goto-char b)
(while (search-forward-regexp "\\\\begin{array}" nil t)
(save-excursion
(let ((i (copy-marker (match-beginning 0)))
(f (copy-marker (search-forward-regexp
"\\\\end{array}" nil t))))
(with-silent-modifications
(perform-replace "\\\\" "❤❤" nil nil nil 1 nil i f)))))
(when (= 0 (how-many "\\\\\\\\" b e))
(perform-replace "{eqnarray}"
"{equation}" t nil nil 1 nil b e))))))
;; *UNWINDFORMS*
(with-silent-modifications
(perform-replace "❤❤" "\\\\" nil nil nil 1 nil a z))))))
In this case the trick seems to work because I (temporarily) replace my target string with one of the same length (\\
with ❤❤
).
Is it a coincidence? Is it safe to operate this way?
Note. I'd prefer to use some "tex property" to hide my target string to the how-many
function but I've not been able to find the way to do it.
Note 2. I red the with-silent-modifications
docstring:
If BODY performs real modifications to the buffer’s text, other than cosmetic ones, undo data may become corrupted.
C-h f perform-replace
says: "Don't use this in your own program"docstring
says: Don’t use this in your own program unless you want to query and set the mark just as ‘query-replace’ does.