Thursday, September 4, 2008

Emacs File Mode Tricks

Usually emacs figures out what mode to be in -- such as which programming or script language -- based on the extension of the filename you're editing. It can also figure it out from a "pound-bang" line, like #!/bin/bash. You want the right file mode: it colorizes the text correctly, makes indentation easier, and lets you easily comment regions of text.

But sometimes you have a file with no extension and no pound-bang. You can still make emacs automatically choose the right file mode, by specifying it in a comment on the first line of the file, like:

# -*-tcl-*-

or

##############-*-makefile-*-##############

The -*- markers tell emacs to look for the mode name between them. You can have any other text you need in the line.

Another use for file-mode comments is if your C++ header files have the extension ".h", which emacs decides is a C file. Just make the first line be a comment containing -*-c++-*-.

Sometimes you do have a file extension which is meaningful to you, but emacs just doesn't recognize it. For example, if you're crazy enough to use the Inline Guard Macro idiom, emacs doesn't automatically recognize ".ipp" as a C++ extension.

Rather than put mode comments in every ".ipp" file, put this line in your .emacs file:

(if (null (assoc "\\.ipp\\'" auto-mode-alist))
(setq auto-mode-alist
(cons '("\\.ipp\\'" . c++-mode) auto-mode-alist)))

No comments: