M-x all-things-emacs

Indent Whole Buffer

January 17th, 2007 by Rob Christie · 216 Comments

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

(defun iwb ()
  "indent whole buffer"
  (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

216 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.


  • 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

    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.

  • 6 Deniz Dogan // Dec 9, 2010 at 1:24 pm

    I prefer binding these sorts of things to mnemonics. I have this bound to “C-c i b”.

  • 7 Yichao Yu // Jul 5, 2012 at 4:56 pm

    Thanks for the function
    One minor problem: u might want to disable the untabify for Makefile…

  • 8 Luis Villegas // Oct 10, 2012 at 12:55 am

    Awesome!, thanks for sharing! I really love this function, I was tired of hitting TAB and TAB as an asshole. Thanks again!

  • 9 Derek V // Feb 8, 2013 at 5:15 pm

    Funny, I was looking something up to write this exact function.

  • 10 Amanda // Aug 15, 2013 at 6:22 pm

    Cool! Thanks! Exactly what I was looking for. And I hadn’t heard of a .emacs file. Guess I can add the meta-x butterflies command.