Emacs Knowledge
Kip Landergren
(Updated: )
My Emacs knowledge base that evolves as I learn more.
Contents
Overview
Emacs sets up an environment for interpreting Emacs Lisp, and, along the way, provides tools to interact with, manage, and modify data on your computer. Often this data is in the form of text files.
In particular, Emacs specializes in creating an environment that excels at:
- displaying text
- interacting with, and editing, that text
The union of display and editing is through modes, which themselves are Emacs Lisp functions that configure the environment appropriate to the data being worked with.
Every input you make—mainly through the keyboard—is really an invocation of (or argument to) an Emacs Lisp function.
When you want to type “hello world” and begin by typing the letter:
h
the code bound to it is actually:
(self-insert-command N &optional C)
This environment Emacs configures for you, and you interact with, is live.
You can inspect it. Modify its behavior. Set variables to different values and write custom functions to hook into standard behavior and adjust it to your liking.
The limit to its customization is only your imagination and ability to write the code to do it. Hackers who came before you shared this mindset and ethos and left a lot of the desirable customization knobs within easy reach.
In short, everything is customizable.
Core Idea
Every user interaction—every key press and input event—is executing Emacs Lisp functions that modify the environment you are working in.
Emacs:
- provides an interpreter for Emacs Lisp
- creates a user interface and couples it tightly with the execution of that interpreter
- strives to make the code powering that interface easy to inspect, modify, and augment
Key Concepts
Displaying Text
The Screen
An Emacs frame is the operating system window of the running application. That frame, before any customization, is, from top to bottom, comprised of:
- the menu bar
- the tool bar
- the window, which itself is comprised of:
- the buffer, which displays a view of the text or graphics you are editing
- the mode line, which describes what is going on in the current buffer
- the echo area, which itself is comprised of:
- the minibuffer, a specialized window
The blinking block over an area of a single character’s dimensions is the cursor, and the location of the cursor is called point (note: not “the point”, just “point”). Typed text is inserted to the left of the cursor. Said another way: text is inserted to the left of whatever character the cursor appears to be “over”.
Multiple Windows
Each window belongs to exactly one frame.
One window is considered selected and the buffer it displays is the current buffer.
Side windows are special windows placed on the sides of a frame’s root window.
Multiple windows of the same buffer have:
- different values of point
- the same value of mark
Mark, Point, and Region
The cursor is at point. C-SPC saves the current location and refers to it as mark. The area in between mark and point is called the region. This gives a specific area within which operations like undo, delete, find and replace, and other operations can be performed.
A history of mark locations are maintained in a per-buffer mark ring.
It may be helpful to think of mark as literally the action of taking a neon marker and pushing it to the page at the location of point. C-SPC places the highlighter down and the tip follows wherever point goes.
If point moves and C-SPC is pressed again, a new mark location is pushed onto the mark ring and the behavior continues like normal.
If point does not move and C-SPC is run a second time, the mark is deactivated but still present in the mark ring.
This latter behavior is useful because C-u SPC traverses the mark ring history, allowing you to cycle through mark locations within the buffer. This is intended as a user convenience.
A global mark ring is accessible via C-x C-SPC.
Controlling the Display
A buffer is scrolled automatically when point moves outside of the visible region. Intentional scrolling may be accomplished conventionally using the mouse or Page Up / Page Down presses. Recentering, using C-l, is particularly useful to cycle through specific positions relative to the window.
Narrowing refers to the restriction of a buffer to only a portion of its text.
Faces are the styles for which emacs displays text.
Face attributes are things like:
- font
- height
- weight
- slant
- foreground / background color
- underlying / overlining
- etc
Editing Text
User Input, Keys, and Commands
Input events are what comes from the keyboard or mouse. Emacs is primarily set up for keyboard input.
Keyboard events—key presses—can be simple characters or control characters. Some control characters are considered modifier keys which change the interpretation of subsequently typed characters.
A key sequence, or key, is a series of keyboard events that are meaningful as a unit.
An example key sequence, written in Emacs’ style string form, is:
C-c c
which reads as:
- press and hold ⌃ Control
- press c
- release both
- press c
A complete key is a key sequence that invokes a command.
The above example contains is comprised of the prefix key C-c followed by the simple character c. A prefix key is a key sequence that does not itself invoke a command, but may be added in series to create a complete key.
A list of default prefix keys may be found in the reference.
Keys do not have meaning. Commands have meanings and are implemented as functions. Keys are given meaning by binding them to commands. Keys can be customized and rebound but the underlying functions are unaffected.
Arguments may be supplied to the underlying commands by using special prefix keys called prefix arguments. These are invoked multiple ways:
- by the meta key, pressed and held, followed by a single digit (with subsequent digits input after releasing the meta key)
- by C-u, followed by a number (or, if not followed by a number, means 4 by itself)
Commands may be repeated via C-x z with successive presses to z repeating the command.
Editing Commands
Editing occurs in a buffer. When making changes to a file the buffer is not the file itself but a view of the file. Text is inserted at point and point may be moved. Text may be erased and changes undone. The presentation of the text—like where to wrap lines—is configurable.
The Minibuffer and Running Commands
The minibuffer is a special window within the echo area that takes input for commands. All commands, including those already bound to keys, are able to be run via M-x. This focuses the minibuffer where further input is possible.
Input is aided by completion, which makes suggestions based on what is typed so far. Completion, and the presentation of alternatives, is highly customizable.
A convention for “yes or no” input prompting is based on the impact of the action result:
- normal significance (e.g. changing a setting): (y or n), with immediate exit if y or n is detected
- serious significance (e.g. deleting a file): (yes or no), with required RET if explicit yes or no is detected
Killing, Deleting, and Moving Text
Commands that erase text and save it in the kill ring are known as kill commands.
Commands that erase text but do not save it in the kill ring are known as delete commands.
The kill ring is a list of blocks of text that were previously killed. The kill ring is shared by all buffers.
Bringing text from the kill ring back into the buffer is called yanking. Using undo also brings the killed text back into the buffer and does not remove it from the kill ring. Killed text is also copied to the system clipboard.
M-y has two modes:
- when invoked without a preceding “yank” command it presents selectable options from the kill ring and updates
last-yank
pointer - when invoked—possibly repeatedly—with a preceding “yank” command it replaces the yanked value with previous values in the kill ring
You can think of M-y as moving the last-yank pointer around the ring. It can be invoked with numeric arguments where positive values move the pointer “backward” and negative values move the pointer “forward”. Values within the kill ring are unaffected.
Columnar text can be worked with through rectangles which mimic normal text editing commands but in the y, rather than x, direction.
Registers
Registers are compartments where you can save text, rectangles, positions, and other things for later use.
M-x view-register
Accomplishing Tasks
Getting Help
Help falls into two categories:
- what does this do?
- what went wrong?
C-h h is all you need to bootstrap.
Documented Emacs lisp code gets turned into a form that is displayed in *Help* buffers in response to user commands.
Some helpful commands are:
C-h k | describe-key ; helps with commands bound to keys |
C-h o | describe-symbol ; helps with Emacs lisp functions and variables |
C-h a | apropos-command ; helps with searching for commands that match PATTERN |
Manuals contain more descriptive and illustrative collections of text that explain usage and behavior at a higher level than individual functions. They are displayed through a special Info mode. The Emacs manual is accessed via C-h r.
Commands like M-x man give access to system manual pages.
To figure out what went wrong:
view-lossage
- inspecting the *Messages* buffer
Searching and Replacement
Incremental search is available through isearch-forward
and isearch-backward
. replace-string
and replace-regexp
allow you to perform replacements within a region. Both of these operations are customizable and offer specialized versions.
Spell-check
External programs like ispell and hunspell can be hooked into Emacs.
Keyboard Macros
Keyboard macros are recordings of keys that can be replayed, modified, and saved for future use.
Backups and Auto Revert
Emacs contains provisions for backing up, reverting, and recovering files in the event of a crash or other problem.
Major and Minor Modes
Major modes are mutually exclusive; each buffer has one and only one major mode at a time.
Most major modes fall into three major groups:
- modes for normal text (e.g. Text mode, HTML mode)
- modes for specific programming languages (e.g. Lisp mode, C mode)
- modes not directly associated with files; modes used instead in buffers created for specific purposes (e.g. Dired mode, Shell mode)
Buffer-local variable major-mode
is set automatically and should not be changed yourself.
Every major mode, apart from Fundamental mode, defines a mode hook which is a customizable list of Lisp functions to run each time the mode is enabled in a buffer (e.g. fortran-mode
has a fortran-mode-hook
). All text-based major modes run text-mode-hook
and many programming language modes run prog-mode-hook
prior to running their own mode hooks. These can inspect the value of major-mode
to see which code is being entered (and behave accordingly).
Mode hooks are commonly used to enable minor modes.
Any number of minor modes can be in effect at any time.
Minor modes can be:
- buffer-local (i.e. enabled or disabled on a per-buffer basis)
- global (i.e. affecting everything you do in the Emacs session, in all buffers)
Major mode is chosen automatically, and normally done based on the file name.
File variables can be used to control mode.
A dir-locals.el file present in the containing directory can be used to check and control which mode to use by the file extension (e.g. if an nginx conf file exists in a directory then dir-locals.el can control that an nginx-specific conf mode can be used).
Dired, the Directory Editor
Invoking Dired creates a special buffer containing a directory listing within which Dired mode provides specialized commands for working within a filesystem.
Emacs Lisp Packages
A package is an Emacs Lisp library, sometimes including other components such as an Info manual.
A package archive is a large collection of Emacs Lisp packages from which Emacs has a facility to download, install, and manage.
Emacs ships pointing to a default package archive but 3rd party may also be used.
- M-x list-packages to list the packages available for installation from a package archive
- once installed, the contents of a package are placed in a subdirectory of ~/.emacs/elpa/ (via package-user-dir)
Customization
Most Emacs settings and behaviors are changed through customizable variables. Use M-x customize, and its related commands, to customize things. Settings are organized into customization groups, all the way up to a master group “Emacs”.
Within that customization interface:
- “STANDARD” means you have not changed the variable
- “EDITED” means you have edited it, but it will not yet take effect
- values will be checked for validity—don’t worry about inputting an incorrect value
- “SET” can be used for the remaining session
- “Save...” can be used to persist
- comments can be added from [State] menu
- customizations and comments will be saved to a file (usually your initialization file)
- Faces, which determine how Emacs displays different types of text, can also be customized
- use M-x customize-changed after Emacs version upgrade
On Themes:
- custom themes are collections of settings that can be enabled or disabled as a unit
- use M-x customize-themes to customize
- be aware of variables
custom-theme-directory
anddata-directory
On Variables:
- the symbol
t
stands fortrue
- variables can be made local to a specific buffer (even if it is global)
- major modes always make variables local to the buffer before setting the variables (which explains why changing major modes in one buffer has no effect on other buffers); same for minor modes
- file variables can be specified in the file itself
- use case for file variables: per-file indentation style
- per-directory local variables can also be specified via .dir-locals.el file
- use case for directory variables: per-project indentation style, LSP server configuration, etc
- both file and directory local variables can be added through utilities, rather than by hand
On Hooks:
- a variable holding a list of functions
- called on a well-defined occasion
- recommended: add a function via
add-hook
- recommended: design hook functions so that order of execution does not matter
- major mode hooks also apply to other major modes derived from the original, allowing us e.g. to apply a hook function to
prog-mode-hook
to run in any major mode that derives from it
On Keys:
- key bindings map keys to commands
- keymaps are data structures that record key bindings
- most modes define their own key bindings
- activating a mode may override your custom key bindings
- some keys, like C-c followed by a letter, are reserved for user-defined bindings
- the global keymap is always in effect and defines keys for Fundamental mode
- interesting: g is a self-inserting character because the global keymap binds it to the command
self-insert-command
- interpreting a key sequence of multiple events involves a chain of keymaps: e.g. C-x g first gets a keymap for C-x and then looks up in that for g
- the prefix keys C-c, C-x, C-h and ESC appear in the global map and are always available
- minibuffer has its own keymaps
(global-set-key (kbd "C-z") 'shell)
can be used in your init file to write a key binding- multiple alternatives to using
kbd
if your key sequence has non-ASCII characters or some other requirements - tip: because a mode’s keymaps are not constructed until it has been loaded, you must delay running code which modifies them, e.g., by putting it in a mode hook
- tip: unwanted bindings can be set to nil to remove or via
global-unset-key
- tip: function keys can be specified via Lisp symbols (refer to documentation)
On Commands:
- to disable a command
foo
use(put 'foo 'disabled t)
- alternately M-x disable-command
On the Emacs Initialization File:
- can use
-q
to prevent loading your init file - can add custom code to load specific files (use case: loading a different file per Emacs version)
- byte-compiling your init file is not recommended
- tip: you likely want
setq-default
rather thansetq
because they automatically become buffer-local - specify the coding system if non-ASCII characters are used
- an early init file exists, if you need it
- passwords and other secure information available through the auth-source library