I make a lot of mistakes when I write prose, because I usually write down everything that comes to mind and then edit sentences and paragraphs over and over again until I get what I want. This is a recipe for all sort of errors, of course.
Although I have been a happy user of Flyspell and proselint
, in order not to
get distracted by warnings and errors nowadays I like to avoid automatic
spell-checkers or linters and rely on ispell-buffer
.
There is however a specific category of errors for which ispell-buffer
cannot
help: duplicate words. When quickly rephrasing a sentence or adjusting a
paragraph it could happen that I do not pay enough attention to the words I
remove and so I keep typing with no care whatsoever.
Much in the spirit of my occasional use of ispell-buffer
, I want a command
that scans the buffer, finds consecutive occurrences of the same word, and
removes all but one of them. Emacs already has a built-in solution for this:
C-M-%
(query-replace-regexp
).
Nevertheless, laziness prevails. Why typing the necessary regular expression every time when a simple command can do it for me?
(defun mu-delete-duplicate-words ()
"Delete duplicate words via `query-replace-regexp'."
(interactive nil text-mode)
(save-excursion
(goto-char (point-min))
(query-replace-regexp "\\(\\b\\w+\\b\\)\\W+\\1\\b" "\\1")))