Emacs Init: Set Default Major Mode

By Xah Lee. Date: . Last updated: .

Set Default Major Mode for New Empty Buffer

This works for setting default mode for scratch buffer too.

Put this in your Emacs Init File:

;; example of setting a default major mode for new buffer
(setq initial-major-mode 'python-mode)

;; other sample values
;; 'text-mode (for plain text)
;; 'emacs-lisp-mode
;; 'lisp-interaction-mode  (the lisp mode used in scratch buffer)
;; 'python
;; 'js (JavaScript)

Remap a Default Major Mode to Another

major-mode-remap-alist
an Association List for changing a default major mode to another.

In each element, key is the old mode symbol, value is the new symbol.

new in Emacs 29 (Released 2023-07)

(when (>= emacs-major-version 29)
  (push '(css-mode . xah-css-mode) major-mode-remap-alist))

Associate Major Mode by File Name Extension

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

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

;; setup files ending in .html to open in xah-html-mode
(push '("\\.html?\\'" . xah-html-mode) auto-mode-alist)

Remove File Extension Association

;; remove any file name suffix associated with js-mode
(setq auto-mode-alist (rassq-delete-all 'js-mode auto-mode-alist))
;; check if js-mode is in the list
(rassoc 'js-mode auto-mode-alist)

[see Evaluate Emacs Lisp Code]

💡 TIP: you do not need to remove items in auto-mode-alist . Best to simply add to the front using push.

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] Use it like this:

;; example of associate a major mode by first line of file

;; case matters

(push '("<!doctype html>" . xah-html-mode) magic-mode-alist)
(push '("<!DOCTYPE html>" . xah-html-mode) magic-mode-alist)

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. e.g. if first line in the file contains -*- mode: xx-*-, emacs loads xx-mode. (File Variables (Emacs Manual))
  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. Try to match first line text with magic-mode-alist.
  4. Match the file name with auto-mode-alist.

Choosing Modes (Emacs Manual)

Major Mode, Minor Mode, Minibuffer, Hook