Code Formatting With Emacs

Code formatters. Many people swear by them and always run their code through a formatter before checking it in. I’ve never seen the need for them. I have strong feelings about code format and I always write my code to that format: no need for a separate formatter. At the same time, I recognize that others have strong feelings about their preferred format so I never want to reformat someone else’s code.

There are, in every organization, control freaks who think it critically important that everyone’s code look the same. I’ve never accepted that premise and have ignored formatting guidelines. Somehow, I’ve always managed to get away with that minor recalcitrance.

Still, some people appear to like code formatters and for those people, Bozhidar Batsov has an interesting post on code formatters and how to use them in Emacs. It turns out that there’s a plethora of formatters with slightly different behavior to choose from

Happily the Lisp languages—which I use almost exclusively these days—don’t really need one since for a Lisp, code formatting is really just a matter of indentation, which Emacs handles on its own. Other languages need more work.

One of the problems with code formatters run from within Emacs is that they can freeze Emacs while they run. This is the case of formatters that run before the file is saved. There are formatters that run after the save by asynchronously reading the saved file, reformatting it, and writing it back to disk. This has the small defect that an unformatted file exists on disk for a short while.

Batsov’s post covers reformatters implementing both methods. Some of them allow extensive configuration of the reformatting rules. Others enforce a fixed format. Take a look at Batsov’s post for a really good rundown of all the possibilities.

This entry was posted in General and tagged . Bookmark the permalink.