Delete blank lines and shrink whitespace

We looked previously at deleting spaces between words, and a related task is to delete one or more blank lines at the position of the cursor.

Emacs has a built-in command for this, delete-blank-lines, which is bound to C-x C-o. From the help for the function

On blank line, delete all surrounding blank lines, leaving just one. On isolated blank line, delete that one. On nonblank line, delete any immediately following blank lines.

However, the best solution to deleting both blank lines and spaces between words is to install the package shrink-whitespace which gives you the best of both worlds. As illustrated in this animation, if the cursor is between words it will delete spaces leaving one space, and calling it again will remove that space too (similar to cycle-spacing). If the cursor is between lines it will delete blank lines leaving one blank line, and calling it again will remove that line too.

delete-blank-lines.gif

I have bound this to M=SPACE in my emacs config file using

;; delete blank lines and whitespace
(global-set-key (kbd "M-SPC") 'shrink-whitespace)

Leave a comment