# Query-replace in multiple LaTeX environments, narrowing each in turn

I am trying to come up with a Elisp function that narrows a buffer to a certain LaTeX enviroment (table, figures, ...), does some query-replace-regexp inside the narrowing, then searches for the next occurrence of the environment and does the same, until the last occurrence of the environment.

I have come up with this:

(defun narrowtable ()
"narrowing on table environment"
(interactive)
(beginning-of-buffer)
(save-excursion
(search-forward "begin{table}")
(LaTeX-narrow-to-environment)
(goto-char (point-min))
(query-replace "X" "B"); Just some query-replace
(widen)))


which works for fine the first occurence of {table}, but only for that.

I guess I misplaced save-excursion for this to work properly, or there is something other to improve?

I suggest you try something like this:

(defun narrowtable ()
"Narrowing on table or figure environments."
(interactive)
(save-excursion
(goto-char (point-min))
(while (search-forward-regexp
"\\\\begin{\$$?:table\\|figure\$$}\$$?:\$[^]]*\$\$$?" nil t)
(LaTeX-narrow-to-environment)
(query-replace "X" "B"); Just some query-replace
(widen))))


1. Do not use beginning-of-buffer in Lisp code, use (goto-char (point-min)) instead
3. I used search-forward-regexp in order to match the environments table and figure incl. an optional argument