I use a template engine for a lot of files in my project. The specific one is irrelevant -- let's say all my template files end with .template.

Now, I've got many different kinds of templated files, like foo.txt.template, bar.html.template, baz.py.template, and qux.json.template.

By default, Emacs doesn't know about my template engine, so they all open in fundamental-mode. I could manually add each templated filetype to my .emacs file (.txt.template, .html.template, etc), but that's tedious, and I'll have to update it whenever anybody finds a new filetype that's useful to template.

Is there an easy way to tell Emacs' major-mode-selection functionality that .template is special, and that any file that looks like foo.ext.template should be opened as if it were called foo.ext?


2 Answers 2


auto-mode-alist is the variable that determines what major mode a file is opened in. Part of its documentation is:

Alist of filename patterns vs corresponding major mode functions.
Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).


If the element has the form (REGEXP FUNCTION NON-NIL), then after
calling FUNCTION (if it’s not nil), we delete the suffix that matched
REGEXP and search the list again for another match.

So this will make Emacs open, for example, foo.html.template in html-mode:

(push '("\\.template\\'" nil t) auto-mode-alist)
  • this is much more elegant than my solution. I even read that part of the documentation without realizing this is what it could be used for.
    – user2699
    Nov 17, 2015 at 5:33

The normal procedure for specifying file extensions works here,

(add-to-list 'auto-mode-alist '("\\.ext.template" . ext-mode))

Just add a line like this for each mode you're interested in. To speed things up you can use C-h v to find the current value of auto-mode-alist and copy the entries for extensions you want.

  • The point of the question (paragraph 3) is that I don't know a priori what modes I'm interested in.
    – Ken
    Nov 18, 2015 at 1:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.