2017-03-18 Deleting all instances of a LaTeX environment

Today, someone asked on the AUCTeX-devel mailing list about a way to delete (or comment out) all the instances of certain environment. Here’s my solution. It’s not 100% robust (it can be fooled by a partially commented out environment, for instance – but that shouldn’t happen anyway), but for a “normal” file it should work well enough. (If you want to comment out environments instead of deleting them, you might use comment-region instead of delete-region. In the case of deletion, consider using diff-buffer-with-file, just to make sure nothing important got deleted.)

Notice the use of save-mark-and-excursion. Also, LaTeX-environment-list-filtered is used to get the list of environments for completion.

(defun LaTeX-delete-environment (env)
  "Delete all instances of environment ENV in the buffer."
  (interactive (list (completing-read "Environment to delete: "
	(goto-char (point-min))
	(while (search-forward (format "\\begin{%s}" env) nil t)
	  (unless (nth 4 (syntax-ppss))
	(delete-region (region-beginning) (region-end))))))

CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryLaTeX