Clean up buffer or region in Emacs

sure indentation is correct and delete trailing whitespace.

Here’s a function that does just that (inspired by cleanup-buffer from Emacs starter kit).

(defun clean-up-buffer-or-region ()
  "Untabifies, indents and deletes trailing whitespace from buffer or region."
  (interactive)
  (save-excursion
    (unless (region-active-p)
      (mark-whole-buffer))
    (untabify (region-beginning) (region-end))
    (indent-region (region-beginning) (region-end))
    (save-restriction
      (narrow-to-region (region-beginning) (region-end))
      (delete-trailing-whitespace))))

The function either operates on a region (if any region is selected) or the whole buffer.

My binding:

(global-set-key (kbd "C-c n") 'clean-up-buffer-or-region)

blog comments powered by Disqus Back to Top

Fork me on GitHub