Emacs: Clean Empty Lines

By Xah Lee. Date: . Last updated: .

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

Clean White Space

(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)

Clean Empty Lines

(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")))))))

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. Clean Empty Lines
  2. Delete Trailing Whitespace
  3. Delete Whitespace around Cursor
  4. Tabs, Space, Indentation Setup
  5. Make Whitespaces Visible
  6. Newline Representation ^M ^J ^L
  7. Batch Convert Line Ending in Dired
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.