The auto-mode-alist variable is an AssociationList that associates MajorModes with a pattern to match a buffer filename when it is first opened. See SetAutoMode.

Something like this:

   (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))

Where ‘python-mode’ is a function that is either AutoLoaded or already defined.

Note that \' matches the end of a string, whereas $ matches the empty string before a newline. Thus, $ may lead to unexpected behavior when dealing with filenames containing newlines. (Should be pretty rare… ;))

The \. matches ‘.’ (a period); ‘.’ must be escaped by a backslash because the period is a special character in Regular Expressions.

If you write your own major mode that associate with a file extension, here is what you do:

  1. Put some documentation in the commentary section.
  2. As part of the documentation, your users should:
    1. add the file to a directory in their LoadPath
    2. add the following lines to their InitFile:
    (autoload 'foo-mode "foo" "Some documentation." t)
    (add-to-list 'auto-mode-alist '("\\.foo\\'" . foo-mode))

The autoload expression makes sure that the library “foo” is loaded when the function ‘foo-mode’ is called. Use ‘M-x locate-library RET foo RET’ to figure out what file this will be. The last parameter says that foo-mode is interactive. Most major modes are.

The add-to-list expression associates the .foo extension with foo-mode. As mentioned above, the \\' matches the end of the filename; a $ would match newlines within filenames (true, this should be rare… ;)).


When building REGEXPs for auto-mode-alist, keep in mind that the string matched is the full pathname. In the examples below, replace the modes with your preference.

Match the git commit message filename:

    (add-to-list 'auto-mode-alist '(".*_EDITMSG\\'" . log-entry-mode))

Match the CVS commit message filename:

    (add-to-list 'auto-mode-alist
                 (cons (concat temporary-file-directory "cvs[[:alnum:]]*\\'")

CategoryDotEmacs CategoryModes