"$^"
probably1 won't be matching anything, so no lines will ever be flushed.
That has nothing to do with using it in a script -- the same thing will be evident if you attempted that interactively.
Perhaps you want something more like this?
(defun delete-empty-lines-in-bibliography ()
"Delete empty lines in bibliography."
(interactive)
(save-excursion
(goto-char (point-min))
(save-match-data
(while (search-forward "\\begin{thebibliography}" nil t)
(let ((start (match-beginning 0)))
(when (search-forward "\\end{thebibliography}" nil t)
(save-excursion
(flush-lines "^$" start (point)))))))))
Note how I am using let
to remember the start position, without any need to use markers. A marker would be needed if there was any chance that the position could change before it was used, but that is not the case here, so we can safely (and sensibly) use a simpler approach.
Note also that if you do need to use markers for any valid reason, you should set them to nil
when you are finished with them, otherwise they will continue to be tracked in the buffer (and hence consuming resources) after the function has finished. That is more of an issue with your code on account of your use of global variables -- m1
and m2
will continue to exist, and so garbage collection will never clean those markers up.
1 The regexp $^
matches that same two-character sequence literally, so you would only flush lines containing the text $^
.
C-hig (elisp)Regexp Special
explains that, "For historical compatibility, special characters are treated as ordinary ones if they are in contexts where their special meanings make no sense." and so ^
and $
are only special in certain positions:
^
can be used only at the beginning of the regular expression, or after \(
, \(?:
or \|
.
$
can be used only at the end of the regular expression, or before \)
or \|
.
Outside of those positions (as in your scenario), ^
and $
just match literally, as if they had been escaped.