Emacs: Clean Empty Lines

By Xah Lee. Date: . Last updated: .

Here's 2 commands that remove repeated blank lines and delete trailing white space.

(defun xah-clean-empty-lines ()
  "Replace repeated blank lines to just 1.
Works on whole buffer or text selection, respects `narrow-to-region'.

URL `http://ergoemacs.org/emacs/elisp_compact_empty_lines.html'
Version 2017-09-22"
  (interactive)
  (let ($begin $end)
    (if (region-active-p)
        (setq $begin (region-beginning) $end (region-end))
      (setq $begin (point-min) $end (point-max)))
    (save-excursion
      (save-restriction
        (narrow-to-region $begin $end)
        (progn
          (goto-char (point-min))
          (while (re-search-forward "\n\n\n+" nil "move")
            (replace-match "\n\n")))))))
(defun xah-clean-whitespace ()
  "Delete trailing whitespace, and replace repeated blank lines to just 1.
Only space and tab is considered whitespace here.
Works on whole buffer or text selection, respects `narrow-to-region'.

URL `http://ergoemacs.org/emacs/elisp_compact_empty_lines.html'
Version 2017-09-22"
  (interactive)
  (let ($begin $end)
    (if (region-active-p)
        (setq $begin (region-beginning) $end (region-end))
      (setq $begin (point-min) $end (point-max)))
    (save-excursion
      (save-restriction
        (narrow-to-region $begin $end)
        (progn
          (goto-char (point-min))
          (while (re-search-forward "[ \t]+\n" nil "move")
            (replace-match "\n")))
        (progn
          (goto-char (point-min))
          (while (re-search-forward "\n\n\n+" nil "move")
            (replace-match "\n\n")))
        (progn
          (goto-char (point-max))
          (while (equal (char-before) 32) ; char 32 is space
            (delete-char -1))))
      (message "white space cleaned"))))

You can make this automatic. Every time the file is saved, whitespaces are cleaned.

(add-hook 'before-save-hook 'xah-clean-whitespace)

Whitespace Sensitive Files

Be careful on whitespace sensitive language or file format.

If you work with these languages, you probably want to add a check in your function. Try to modify the code. Hint: check on the variable major-mode, or check file name extension.

Whitespace Topic

  1. Emacs: Clean Empty Lines
  2. Emacs: Delete Trailing Whitespace
  3. Emacs: Delete Whitespace around Cursor
  4. Emacs: Tabs, Space, Indentation Setup
  5. Emacs: Make Whitespaces Visible
  6. Emacs: Newline Representation ^M ^J ^L
  7. Emacs: Batch Convert Line Ending in Dired
Liket it? Put $1 at patreon. Or Buy Xah Emacs Tutorial. Thanks.