Friday, 30 November 2007

Emacs and indenting styles

Emacs, as we all know, is quite flexible. One of it's most useful features is that it allows you to define indentation styles in a portable, text format. I think it is useful to set up per-project coding styles, if you work on various teams, or even just to document the style. For example, I have the following in my .emacs file:

(defconst project-c-style
'((c-basic-offset . 4)
(c-comment-only-line-offset . 4) ; this is an odd one!
(c-offsets-alist . ((statement-block-intro . +)
(substatement-open . 0)
(substatement-label . 0)
(label . 0)
(statement-cont . +))))
"Project coding style" )

(c-add-style "project" project-c-style)

(defun project-c-mode-common-hook()
(c-set-style "project")
(setq tab-width 4)
(setq indent-tabs-mode nil)
(c-toggle-auto-newline -1))

(add-hook 'c-mode-common-hook 'project-c-mode-common-hook)

This is pretty much the stroustrup coding style, taken from cc-styles.el except for the comment about the "odd one". Here, I am (for some reason), deciding that I want to indent my comments above the line they reference. So for example, instead of:

// Hello, how are you;

I want:

// Hello, how are you;

If Emacs can support that weird style, it can definitely support your style! Do yourself a favour and document it using Emacs so your code looks as consistent as possible.

No comments: