Indent/Format the whole buffer in Emacs
Monday, February 8th, 2010I have had an indent-buffer command like this for some time, which formats the whole current buffer. I used it for java, c++, css, html, xml and lisp.
(defun indent-buffer ()
"Indent the current buffer"
(interactive)
(save-excursion (indent-region (point-min) (point-max) nil))
)
I found the above function at http://www.emacswiki.org/cgi-bin/wiki/ReformatBuffer
Recently I noticed that it was leaving tabs in (which I hate) and trailing spaces. It was simply just indenting the buffer.
After some more searching today I found the untabify
command and I created the following commands. Mainly because I expected the command to be called something like tab-???
(defun untabify-buffer ()
"Untabify current buffer"
(interactive)
(save-excursion (untabify (point-min) (point-max)))
)
(defun tab-to-spaces ()
"Convert tab to spaces"
(interactive)
(save-excursion (untabify (point-min) (point-max)))
)
I then found this page, http://emacsblog.org/2007/01/17/indent-whole-buffer/ which has the best indent/format buffer function.
(defun indent-buffer-2 ()
"Indent the buffer 2"
(interactive)
(save-excursion
(delete-trailing-whitespace)
(indent-region (point-min) (point-max) nil)
(untabify (point-min) (point-max))
)
)