Emacs: Clean Empty Lines

By Xah Lee. Date: . Last updated: .

Here's 2 commands.

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

*N is the number of newline chars to use in replacement.
If 0, it means lines will be joined.
By befault, *N is 2. It means, 1 visible blank line.

URL `http://ergoemacs.org/emacs/elisp_compact_empty_lines.html'
Version 2017-01-27"
  (interactive
   (if (region-active-p)
       (list (region-beginning) (region-end))
     (list (point-min) (point-max))))
  (when (not *begin)
    (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 "NOERROR")
          (replace-match (make-string (if *n *n 2) 10)))))))
(defun xah-clean-whitespace (&optional *begin *end)
  "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 2016-10-15"
  (interactive
   (if (region-active-p)
       (list (region-beginning) (region-end))
     (list (point-min) (point-max))))
  (when (not *begin)
    (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 "NOERROR")
          (replace-match "\n")))
      (xah-clean-empty-lines (point-min) (point-max))
      (progn
        (goto-char (point-max))
        (while (equal (char-before) 32) ; char 32 is space
          (delete-char -1))))))

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
Like it? Buy Xah Emacs Tutorial. Thanks.