M-x all-things-emacs

Indent Whole Buffer

January 17th, 2007 by Rob Christie · 5 Comments

I use this function almost daily. Why? Well, it’s because too many developers use editors that muck the alignment of the source.

1
2
3
4
5
6
(defun iwb ()
  "indent whole buffer"
  (interactive)
  (delete-trailing-whitespace)
  (indent-region (point-min) (point-max) nil)
  (untabify (point-min) (point-max)))

Open a file, M-x iwb, save, commit, and edit happily.

I can’t take credit for it, but it seems like it should be passed along. I think I originally copied it from another co-worker’s .emacs file when I started using emacs.

Tags: elisp · tips

5 responses so far ↓

  • 1 Jake // Nov 15, 2007 at 10:33 pm

    that’s cool.
    i’ve tried to write one,but with no luck.

    and here you iwb() is.

    thanks~

  • 2 Doug // Sep 25, 2008 at 9:59 pm

    This is great, thanks very much for sharing this. I’ve wanted a function like this for quite some time now, and haven’t had great luck writing my own. Thanks!

  • 3 vedang // Oct 8, 2008 at 7:16 am

    Thanks a lot! I don’t know Lisp, I mostly work with C/C++. Much of the code I come across is poorly indented, and I have to sit indenting the code myself / using the indent-region feature (which, though it makes the job easier, still involves me selecting the region!).
    So, this is going to be a big help to me!

  • 4 konsty // Feb 5, 2009 at 8:35 pm

    Thanks.
    Simply useful :)

  • 5 Steve // Mar 31, 2009 at 5:22 pm

    I took your awesome definition and made it even awesomer by adding the following to the end:

    (global-set-key [f12] ‘iwb)

    Woot! This was exactly what I wanted.

Leave a Comment