I would like to write a elisp function that corrects a few formatting issues in my LaTeX code. Precisely, I would like to transform the following text
Some useless text
\begin{equation}
some math stuff
\end{equation}
Further text.
into
Some useless text
%
\begin{equation}
some math stuff
\end{equation}
%
Further text.
i.e. I want that equation environments that are not surrounded by comments get an empty comment line before and after the environment. My idea was to write a small elisp function that replaces all such occurences with some regex. With lots of trial and error I found the following regex that seems to find the \begin{equations} that are not preceeded by % in the line before.
^[[:space:]]*[^%].*\n[[:space:]]*\\\\begin{equation}
I also found the following snippet on the internet to do search an replace:
(defun foo ()
(interactive)
(save-excursion
(beginning-of-buffer)
(while (re-search-forward "foo\nbar" nil t)
(replace-match "bar\nfoo" nil nil))))
My guess is the a clever combination of these things will give me my result, but so far all my attempts have failed. Can anybody give me some hints on how I achieve the sought substitution?
Update:
After reading: Emacs regexp groups in regex-replace I came up with the following:
(defun foo ()
(interactive)
(save-excursion
(beginning-of-buffer)
(while (re-search-forward "\\(^[[:space:]]*[^%].*\n\\)\\([[:space:]]*\\)\\(\\\\begin{equation}\\)" nil t)
(replace-match "\\1\\2%\n\\2\\3" nil nil))))
which seems to work for the few test cases that I tried so far. It fails when \begin{equation} terms are nested immediately after each other, but since this is not allowed in LaTeX anyway its not a critical issue.
begin
/end
macros and than look at the line before or after and maybe insert a comment.