Chuyển đến nội dung

Bài 26 · Packages and Programming Modes

Programming in Emacs: Major Modes, Eglot (LSP) and Tree-sitter

How Emacs chooses a major mode, how to get language-server features with Eglot, what Tree-sitter modes add, and the built-in tools for code navigation.

Emacs supports programming languages through major modes. A major mode gives a buffer language-specific indentation, syntax coloring and commands. Since Emacs 29 the editor also includes two big modern pieces: Eglot, a client for the Language Server Protocol (LSP), and Tree-sitter support, which parses code into a real syntax tree. In this lesson you learn how modes are selected and how to turn Emacs into a full IDE-like environment for a language of your choice.

Commands and Lisp here are real. The runnable blocks are JavaScript stand-ins for the file-matching rules and the LSP message format.

Major and minor modes

Each buffer has exactly one major mode (for example python-mode, c-mode, org-mode) and any number of minor modes (for example flymake-mode, electric-pair-mode). Major modes form families: python-mode derives from prog-mode, so anything you add to prog-mode-hook applies to all of them.

Emacs picks the major mode when you open a file using auto-mode-alist, a list of regexp/mode pairs. The first match wins:

ELISP
(add-to-list 'auto-mode-alist '("\\.tsx\\'" . typescript-ts-mode))
(add-to-list 'auto-mode-alist '("Dockerfile\\'" . dockerfile-mode))

If no pattern matches, Emacs looks at the first line of the file (#!/usr/bin/env python3 selects the Python mode through interpreter-mode-alist) and at special cookies such as -*- mode: org -*-. You can switch by hand with M-x python-mode.

JS Stand-in: auto-mode-alist

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Tree-sitter modes

Traditional modes colorize and indent code with regular expressions. Tree-sitter modes (names ending in -ts-mode, for example python-ts-mode, c-ts-mode, js-ts-mode, go-ts-mode) build a concrete syntax tree, which allows more accurate highlighting, structural navigation and indentation. Requirements: Emacs built with tree-sitter support, and a compiled grammar library for each language.

ELISP
(setq treesit-language-source-alist
      '((python "https://github.com/tree-sitter/tree-sitter-python")
        (go     "https://github.com/tree-sitter/tree-sitter-go")))
;; then: M-x treesit-install-language-grammar RET python RET
(setq major-mode-remap-alist
      '((python-mode . python-ts-mode)
        (c-mode      . c-ts-mode)))
(setq treesit-font-lock-level 4)    ; more detailed highlighting

major-mode-remap-alist (Emacs 29+) makes Emacs use the -ts-mode automatically wherever the classic mode would have been used, as long as the grammar is installed. Check (treesit-available-p) with M-: to see whether your build supports it. Emacs 30 added more -ts-modes and easier grammar handling, so check the manual for your version.

Eglot: language servers

A language server is a separate program that understands a language and speaks LSP: it supplies completion, diagnostics, go-to-definition, rename, hover documentation and formatting. Eglot (built in since Emacs 29) is the client. Install the server for your language (for example pylsp, pyright, gopls, rust-analyzer, clangd, typescript-language-server), open a file and run M-x eglot. For automatic start:

ELISP
(add-hook 'python-ts-mode-hook #'eglot-ensure)
(add-hook 'c-ts-mode-hook      #'eglot-ensure)

Eglot plugs into Emacs's own frameworks instead of inventing new interfaces:

Feature Emacs mechanism Keys
Diagnostics Flymake M-n / M-p next/prev, C-c ! l list
Hover docs ElDoc shown in the echo area, C-h . for more
Completion completion-at-point C-M-i or Corfu/Company popup
Go to definition Xref M-., back with M-,
Find references Xref M-?
Rename Eglot M-x eglot-rename
Code actions Eglot M-x eglot-code-actions
Format Eglot M-x eglot-format

Choose a different server for a mode with eglot-server-programs: (add-to-list 'eglot-server-programs '(python-ts-mode . ("pyright-langserver" "--stdio"))). Run M-x eglot-shutdown to stop a server, and open the buffer *EGLOT ... events* to see the traffic if something misbehaves.

What LSP messages look like

Under the hood, Eglot and the server exchange JSON-RPC messages over standard input and output. Each message has a header giving the body size in bytes, a blank line, then JSON. Seeing one demystifies debugging.

JS Stand-in: building an LSP request

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Built-in code navigation and helpers

Even without LSP, Emacs offers:

  • xref with M-. (find definition), M-, (go back), M-? (references); non-LSP modes use tags or etags.
  • imenu (M-x imenu) to jump to functions and headings; which-function-mode shows the current function in the mode line.
  • electric-pair-mode for closing brackets, show-paren-mode for matching, hs-minor-mode (C-c @ C-c) to fold blocks.
  • M-; (comment-dwim) to comment or uncomment a line or region, and C-M-\ (indent-region) to reindent.
  • compile and project.el (see shells, compilation and search).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How does Emacs choose the major mode for a file named app.py?

    auto-mode-alist maps name patterns to modes; the first matching pattern wins.
  2. 2. What does an Eglot-based setup need besides Emacs 29 or later?

    Eglot is only the client; the language server (pyright, gopls, clangd...) must be installed.
  3. 3. What is major-mode-remap-alist used for?

    It remaps classic modes to Tree-sitter modes automatically.
  4. 4. Which key sequence jumps to a definition and which comes back?

    M-. finds the definition via xref, M-, pops back to where you were.

Summary

  • One major mode per buffer, chosen by auto-mode-alist, then the shebang line.
  • -ts-mode modes use Tree-sitter grammars; remap classic modes with major-mode-remap-alist.
  • Eglot (built in since Emacs 29) connects to a language server and feeds Flymake, ElDoc, Xref and completion.
  • Use eglot-ensure in a mode hook to start it automatically.
  • Built-in helpers (xref, imenu, electric-pair, hs-minor-mode) work without LSP.

Next: Completion, Snippets and Diagnostics

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.