Re-indent things sanely

Suppose you have, oh, a few jillion lines of code.

Now, suppose that this code was keyed in by cruel people, and its indentation is all kinds of messed-up.

Shocking, right?

Maybe half of it uses 10-column tabs, and half of it uses 3-space indents. Maybe it’s Lisp code written by folks who had no idea that there are rules about these things. Maybe big chunks of it were wrapped in “if… ” blocks and never indented to reflect that.

Step 1. Make sure your Emacs is set up to indent things the way you want.

Add this to your init.el and eval it:

(defun indent-buffer ()
  "Indent an entire buffer using the current syntax settings."
   (goto-char (point-min))
   (while (re-search-forward "\t" nil t)
          (replace-match " " t t)))
  (indent-region (point-min) (point-max)))

This, you will notice, trims trailing whitespace, replaces every TAB with a space, and then re-indents the entire file.

Test by opening any one file, and type M-x indent-buffer RET.

OK, now you have one theoretically-legible file, right?

Step 2. Repeat for every other file.

But, we’re not going to do that manually, that would be masochism.

find . -name \*.c -exec emacsclient -e \
  '(with-current-buffer (find-file "{}") (indent-buffer))' \;

Repeat with each appropriate file-extension.

Step 3. Save!

The emacsclient invocation above intentionally doesn’t save any files. Hit C-x b and you’ll see all the dirty buffers it just changed. C-x s to save-some-buffers … and if you’re confident they’re all good enough, hit ! to “yes to all” it.

Step 4. Double-check with git

Now, you’re doing this on source, so you surely have it under version control, right? And before mass-re-indenting the whole codebase, you had a clean checkout, right?

git diff -w should show you no changes, because all that changed was whitespace.

So you can git commit -am ‘Re-indented’ without shame.

Unless it was Python code. If it was Python, you’re just screwed.

Bobby Newberry Jr liked this post

One thought on “Re-indent things sanely

  1. […] I’ve been using this for some time, as I mentioned a few days ago: […]

What do you think? Add your comments →