The magic-mode-alist

Most Emacs users know how to associate a file type with a major mode by using the auto-mode-alist variable to associate a file extension with a major mode. I recently learned of another way thanks to Xah Lee who posted a note on associating files with a major mode.

It turns out that you can use the beginning of a file to associate it with a major mode in much the same way that the Unix file command determines the type of file from the first few bytes of the file. To do this you add a cons of a regular expression matching the beginning of the file and the major mode to invoke to the magic-mode-alist variable. Lee gives this example to invoke nxml-mode for html files:

(add-to-list 'magic-mode-alist '("<!DOCTYPE html .+DTD XHTML .+>" . nxml-mode))

Emacs checks the magic-mode-alist variable before checking auto-mode-alist so the beginning of file check takes precedence. You can also specify a function instead of the regex to deal with situations too complex for a regular expression.

Lee's post has a nice summary of all the ways Emacs can associate a major mode with a file so you should give it a look.

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