No more source code indentation arguments


We’ve all been there. Maybe you’ve joined a new team that uses a one space indent which is driving you crazy. Perhaps your team already compromised on a four space indent and a new hot-shot joins your team and tells you that Linus says that if you don’t use an eight space indent nature will screw you2

What is the solution? Simple – add a hook on check-in to your source repository that automatically reindents the code with the team’s standard. Then, anyone who wants to can configure their editor to reformat the code the way they like it when opening a file. When they check the code back in, their screwy indentation is fixed again. That way, everyone can develop using the style they like.3

You’re probably wondering where the emacs is in this post. Well, I don’t know about you, but I haven’t had much luck with getting indent(1) to format C++ in the way that I want. However, emacs knows how to indent my code just fine.

;; ---------------------------------------------------------------------- ;;

(defconst *my-cc-style*
  '((c-basic-offset . 4)
    (c-comment-only-line-offset . 0)
    (c-hanging-braces-alist . ((brace-list-open)
                               (substatement-open after)
                               (block-close . c-snug-do-while)))
    (c-cleanup-list . (brace-else-brace))
    (c-offsets-alist . ((statement-block-intro . +)
                        (knr-argdecl-intro     . 0)
                        (substatement-open     . 0)
                        (substatement-label    . 0)
                        (innamespace           . 0)
                        (case-label            . +)
                        (statement-cont        . +)))))

;; ---------------------------------------------------------------------- ;;

(provide 'cc-style)

;; ---------------------------------------------------------------------- ;;

A simple shell script wrapper will let you call <filename>. Warning: this script has not been tested and may break your code. Use at your own risk.



emacs --batch -eval "
    (load \"$CC_STYLE\")
    (c-add-style \"PERSONAL\" *my-cc-style*)
    (find-file \"$1\")
    (c-set-style \"PERSONAL\")
    (setq tab-width 4)
    ;; (setq make-backup-files nil)
    (ident-region (point-min) (point-max))
    (untabify (point-min) (point-max))

1. (or your money back)

2. Yep, horribly misquoted and probably misattributed – sorry

3. They might not like the output from the diff tool though. Tell them about diff -b


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: