ARCHIVED: In Emacs, how can I make the program start in a given mode?

This content has been archived, and is no longer maintained by Indiana University. Information here may no longer be accurate, and links may no longer be available or reliable.

Emacs has many different major modes available that help with editing specific types of files (e.g., English text, C programs, TeX manuscripts). There are three primary methods that Emacs uses to determine what mode to use, as described below:

  • The first method uses the file extension. For example, when Emacs is started on a file that ends in .c, c-mode is started. You can extend the list of recognized extensions by adding lines similar to the following to your .emacs file:
      (setq auto-mode-alist
        (cons '("\\.foo$" . text-mode) auto-mode-alist))
    The above example ensures that, when you edit a file that ends in .foo, Emacs will start in text-mode.
  • The second method is a little less convenient and will not work well with all types of files. Anywhere in the first non-blank line of a file, you can place the following:
      -*-Mode-*-
    Replace Mode with the mode of your choice (e.g., C, TeX, Perl), and Emacs will then use that mode for its major mode. Obviously, this method isn't very useful unless you're editing a file format that has a commenting character available. A practical example of this is to place the following in the first line of a Lisp file:
      ;-*-Lisp-*-

    Since the semicolon is a comment character in Lisp programs, only Emacs looks at this line.

  • The third method for mode determination works a little better than the second with situations where the first line is used for something specific (e.g., the "#!/bin/sh" that occurs as the first line of a Bourne shell script wouldn't work properly if you use the second method). Emacs will look for a set of lines anywhere in a file that begins with "Local Variables:" and ends with "End:" and allow you to specify local variables and the mode. A good example is one that works well with Perl scripts. Add the following to the end of a Perl script to force perl-mode:
      # Local Variables:
      # mode: perl
      # End:

    Since the hash mark (#) is Perl's comment character, these lines will be ignored.

At Indiana University, for personal or departmental Linux or Unix systems support, see Get help for Linux or Unix at IU.

This is document acix in the Knowledge Base.
Last modified on 2018-01-18 09:31:56.