Emacs: Set Default Major Mode

By Xah Lee. Date: . Last updated: .

Set Default Major Mode for New Empty Buffer

Put this in your Emacs Init File:

(setq initial-major-mode 'js-mode)

Associate Major Mode by File Name Extension

Use auto-mode-alist to associate a major mode with file name extension.

;; setup files ending in “.js” to open in xah-js-mode
(add-to-list 'auto-mode-alist '("\\.js\\'" . xah-js-mode))

auto-mode-alist is a built-in variable. Its value is a Association List . Each key is a regex string, and value is mode name symbol. [see Emacs: Show Variable Value, List Variables]

[see Emacs: Regular Expression]

Remove File Extension Association

You can remove file name association with a major mode. Example:

;; remove any file name suffix associated with js-mode
(setq auto-mode-alist (rassq-delete-all 'js-mode auto-mode-alist))

To check if a mode is in the list, eval the following.

;; check if js-mode is in the list
(rassoc 'js-mode auto-mode-alist)

[see Evaluate Emacs Lisp Code]

Normally, you do not need to remove items in auto-mode-alist . Simply add to the front using add-to-list.

Associate Major Mode by First Line in File

The magic-mode-alist is variable with value a Association List, for associating first line of a file with a mode. [see Emacs: Show Variable Value, List Variables] Use it like this:

;; if first line of file matches, activate nxml-mode
(add-to-list 'magic-mode-alist '("<!DOCTYPE html .+DTD XHTML .+>" . nxml-mode) )

How Emacs Determines Which Major Mode to Load

Emacs determines what mode to activate by the following mechanisms, in order. If a match is found, the process stops.

  1. Look for a special emacs-specific syntax in the file. For example: if first line in the file contains -*- mode: xyz-*-, emacs will load “xyz-mode”. This is from a general mechanism for emacs to load elisp variables. (See: (info "(emacs) File Variables").) This has the top priority, but this mechanism is not the usual way for programing language files to associate with a major mode.
  2. Check the first line in the file for unix “shebang” syntax (For example, #!/usr/bin/perl) and match it with interpreter-mode-alist.
  3. Trys to match first line text with magic-mode-alist. (As of emacs 24.1.1, by default this list is empty.)
  4. Match the file name with auto-mode-alist.

(info "(emacs) Choosing Modes")

Note that when you install a new package, some has the file association setting code within the package, while others ask you to put a few lines in your emacs init file instead.

Major Mode and Minor Mode

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Emacs Init

Init Basics



Text Editing



Restore Things





Advanced Init Tips