Emacs' Official Manual

0.Introduction

You are reading about GNU Emacs, the GNU incarnation of the advanced, self-documenting, customizable, extensible editor Emacs. (The ‘G’ in GNU (GNU’s Not Unix) is not silent.)

We call Emacs advanced because it can do much more than simple insertion and deletion of text. It can control subprocesses, indent programs automatically, show multiple files at once, and more. Emacs editing commands operate in terms of characters, words, lines, sentences, paragraphs, and pages, as well as expressions and comments in various programming languages.

Self-documenting means that at any time you can use special commands, known as help commands, to find out what your options are, or to find out what any command does, or to find all the commands that pertain to a given topic. See Help.

Customizable means that you can easily alter the behavior of Emacs commands in simple ways. For instance, if you use a programming language in which comments start with ‘<’ and end with ‘>’, you can tell the Emacs comment manipulation commands to use those strings (see Comments). To take another example, you can rebind the basic cursor motion commands (up, down, left and right) to any keys on the keyboard that you find comfortable. See Customization.

Extensible means that you can go beyond simple customization and create entirely new commands. New commands are simply programs written in the Lisp language, which are run by Emacs’s own Lisp interpreter. Existing commands can even be redefined in the middle of an editing session, without having to restart Emacs. Most of the editing commands in Emacs are written in Lisp; the few exceptions could have been written in Lisp but use C instead for efficiency. Writing an extension is programming, but non-programmers can use it afterwards. See Emacs Lisp Intro, if you want to learn Emacs Lisp programming.

1 The Organization of the Screen

On a graphical display, such as on GNU/Linux using the X Window System, Emacs occupies a graphical window. On a text terminal, Emacs occupies the entire terminal screen. We will use the term frame to mean a graphical window or terminal screen occupied by Emacs. Emacs behaves very similarly on both kinds of frames. It normally starts out with just one frame, but you can create additional frames if you wish (see Frames).

Each frame consists of several distinct regions. At the top of the frame is a menu bar, which allows you to access commands via a series of menus. On a graphical display, directly below the menu bar is a tool bar, a row of icons that perform editing commands when you click on them. At the very bottom of the frame is an echo area, where informative messages are displayed and where you enter information when Emacs asks for it.

The main area of the frame, below the tool bar (if one exists) and above the echo area, is called the window. Henceforth in this manual, we will use the word “window” in this sense. Graphical display systems commonly use the word “window” with a different meaning; but, as stated above, we refer to those graphical windows as “frames”.

An Emacs window is where the buffer—the text or other graphics you are editing or viewing—is displayed. On a graphical display, the window possesses a scroll bar on one side, which can be used to scroll through the buffer. The last line of the window is a mode line. This displays various information about what is going on in the buffer, such as whether there are unsaved changes, the editing modes that are in use, the current line number, and so forth.

When you start Emacs, there is normally only one window in the frame. However, you can subdivide this window horizontally or vertically to create multiple windows, each of which can independently display a buffer (see Windows).

At any time, one window is the selected window. On a graphical display, the selected window shows a more prominent cursor (usually solid and blinking); other windows show a less prominent cursor (usually a hollow box). On a text terminal, there is only one cursor, which is shown in the selected window. The buffer displayed in the selected window is called the current buffer, and it is where editing happens. Most Emacs commands implicitly apply to the current buffer; the text displayed in unselected windows is mostly visible for reference. If you use multiple frames on a graphical display, selecting a particular frame selects a window in that frame.

  • Point: The place in the text where editing commands operate.
  • Echo Area: Short messages appear at the bottom of the screen.
  • Mode Line: Interpreting the mode line.
  • Menu Bar: How to use the menu bar.

2 Kinds of User Input

GNU Emacs is primarily designed for use with the keyboard. While it is possible to use the mouse to issue editing commands through the menu bar and tool bar, that is not as efficient as using the keyboard. Therefore, this manual mainly documents how to edit with the keyboard.

Keyboard input into Emacs is based on a heavily-extended version of ASCII.

  • Simple characters, like ‘a’, ‘B’, ‘3’, ‘=’, and the space character (denoted as ), are entered by typing the corresponding key.
  • Control characters, such as , , , , , , and , are also entered this way, as are certain characters found on non-English keyboards (see International).
  • Emacs also recognizes control characters that are entered using modifier keys. Two commonly-used modifier keys are (usually labeled ), and (usually labeled )1. For example, Control-a is entered by holding down the key while pressing a; we will refer to this as C-a for short. Similarly, -a, or M-a for short, is entered by holding down the key and pressing a. Modifier keys can also be applied to non-alphanumerical characters, e.g., C- or M-.

分类清晰, User Input, 从这里设置键盘一类别,
1) Simple 2) Control 3) Modifier

You can also type Meta characters using two-character sequences starting with . Thus, you can enter M-a by typing a. You can enter C-M-a (holding down both and , then pressing a) by typing C-a. Unlike , is entered as a separate character. You don’t hold down while typing the next character; instead, press and release it, then enter the next character. This feature is useful on certain text terminals where the key does not function reliably.

On graphical displays, the window manager might block some keyboard inputs, including M-, M-, C-M-d and C-M-l. If you have this problem, you can either customize your window manager to not block those keys, or rebind the affected Emacs commands (see Customization).

Simple characters and control characters, as well as certain non-keyboard inputs such as mouse clicks, are collectively referred to as input events. For details about how Emacs internally handles input events, see Input Events.


3 Keys

Some Emacs commands are invoked by just one input event; for example, C-f moves forward one character in the buffer. Other commands take two or more input events to invoke, such as C-x C-f and C-x 4 C-f.

A key sequence, or key for short, is a sequence of one or more input events that is meaningful as a unit. If a key sequence invokes a command, we call it a complete key; for example,C-f, C-x C-f and C-x 4 C-f are all complete keys. If a key sequence isn’t long enough to invoke a command, we call it a prefix key; from the preceding example, we see that C-x and C-x 4 are prefix keys. Every key sequence is either a complete key or a prefix key.

A prefix key combines with the following input event to make a longer key sequence. For example, C-x is a prefix key, so typing C-x alone does not invoke a command; instead, Emacs waits for further input (if you pause for longer than a second, it echoes the C-x key to prompt for that input; see Echo Area). C-x combines with the next input event to make a two-event key sequence, which could itself be a prefix key (such as C-x 4), or a complete key (such as C-x C-f). There is no limit to the length of key sequences, but in practice they are seldom longer than three or four input events.

You can’t add input events onto a complete key. For example, because C-f is a complete key, the two-event sequence C-f C-k is two key sequences, not one.

By default, the prefix keys in Emacs are C-c, C-h, C-x, C-x , C-x @, C-x a, C-x n, C-x r, C-x v, C-x 4, C-x 5, C-x 6, , M-g, and M-o. ( and are aliases for C-h and C-x 6.) This list is not cast in stone; if you customize Emacs, you can make new prefix keys. You could even eliminate some of the standard ones, though this is not recommended for most users; for example, if you remove the prefix definition of C-x 4, then C-x 4 C-f becomes an invalid key sequence. See Key Bindings.

Typing the help character (C-h or ) after a prefix key displays a list of the commands starting with that prefix. The sole exception to this rule is : C-h is equivalent to C-M-h, which does something else entirely. You can, however, use to display a list of commands starting with .

4 Keys and Commands

This manual is full of passages that tell you what particular keys do. But Emacs does not assign meanings to keys directly. Instead, Emacs assigns meanings to named commands, and then gives keys their meanings by binding them to commands.

Every command has a name chosen by a programmer. The name is usually made of a few English words separated by dashes; for example, next-line or forward-word. Internally, each command is a special type of Lisp function, and the actions associated with the command are performed by running the function. See What Is a Function.

The bindings between keys and commands are recorded in tables called keymaps. See Keymaps.

When we say that “C-n moves down vertically one line” we are glossing over a subtle distinction that is irrelevant in ordinary use, but vital for Emacs customization. The command next-line does a vertical move downward. C-n has this effect because it is bound to next-line. If you rebind C-n to the command forward-word, C-n will move forward one word instead.

In this manual, we will often speak of keys like C-n as commands, even though strictly speaking the key is bound to a command. Usually, we state the name of the command which really does the work in parentheses after mentioning the key that runs it. For example, we will say that “The command C-n (next-line) moves point vertically down”, meaning that the command next-line moves vertically down, and the key C-n is normally bound to it.

Since we are discussing customization, we should tell you about variables. Often the description of a command will say, “To change this, set the variable mumble-foo.” A variable is a name used to store a value. Most of the variables documented in this manual are meant for customization: some command or other part of Emacs examines the variable and behaves differently according to the value that you set. You can ignore the information about variables until you are interested in customizing them. Then read the basic information on variables (see Variables) and the information about specific variables will make sense.

5 Entering Emacs

The usual way to invoke Emacs is with the shell command emacs. From a terminal window running a Unix shell on a GUI terminal, you can run Emacs in the background with emacs &; this way, Emacs won’t tie up the terminal window, so you can use it to run other shell commands. (For comparable methods of starting Emacs on MS-Windows, see Windows Startup.)

When Emacs starts up, the initial frame displays a special buffer named ‘GNU Emacs’. This startup screen contains information about Emacs and links to common tasks that are useful for beginning users. For instance, activating the ‘Emacs Tutorial’ link opens the Emacs tutorial; this does the same thing as the command C-h t (help-with-tutorial). To activate a link, either move point onto it and type , or click on it with mouse-1 (the left mouse button).

Using a command line argument, you can tell Emacs to visit one or more files as soon as it starts up. For example, emacs foo.txt starts Emacs with a buffer displaying the contents of the file ‘foo.txt’. This feature exists mainly for compatibility with other editors, which are designed to be launched from the shell for short editing sessions. If you call Emacs this way, the initial frame is split into two windows—one showing the specified file, and the other showing the startup screen. See Windows.

Generally, it is unnecessary and wasteful to start Emacs afresh each time you want to edit a file. The recommended way to use Emacs is to start it just once, just after you log in, and do all your editing in the same Emacs session. See Files, for information on visiting more than one file. If you use Emacs this way, the Emacs session accumulates valuable context, such as the kill ring, registers, undo history, and mark ring data, which together make editing more convenient. These features are described later in the manual.

To edit a file from another program while Emacs is running, you can use the emacsclient helper program to open a file in the existing Emacs session. See Emacs Server.

Emacs accepts other command line arguments that tell it to load certain Lisp files, where to put the initial frame, and so forth. See Emacs Invocation.

If the variable inhibit-startup-screen is non-nil, Emacs does not display the startup screen. In that case, if one or more files were specified on the command line, Emacs simply displays those files; otherwise, it displays a buffer named scratch, which can be used to evaluate Emacs Lisp expressions interactively. See Lisp Interaction. You can set the variable inhibit-startup-screen using the Customize facility (see Easy Customization), or by editing your initialization file (see Init File).1

You can also force Emacs to display a file or directory at startup by setting the variable initial-buffer-choice to a string naming that file or directory. The value of initial-buffer-choice may also be a function (of no arguments) that should return a buffer which is then displayed. If initial-buffer-choice is non-nil, then if you specify any files on the command line, Emacs still visits them, but does not display them initially.


6 Exiting Emacs

  • C-x C-c

    Kill Emacs (save-buffers-kill-terminal).

  • C-z

    On a text terminal, suspend Emacs; on a graphical display, iconify (or “minimize”) the selected frame (suspend-frame).

Killing Emacs means terminating the Emacs program. To do this, type C-x C-c (save-buffers-kill-terminal). A two-character key sequence is used to make it harder to type by accident. If there are any modified file-visiting buffers when you type C-x C-c, Emacs first offers to save these buffers. If you do not save them all, it asks for confirmation again, since the unsaved changes will be lost. Emacs also asks for confirmation if any subprocesses are still running, since killing Emacs will also kill the subprocesses (see Shell).

C-x C-c behaves specially if you are using Emacs as a server. If you type it from a client frame, it closes the client connection. See Emacs Server.

Emacs can, optionally, record certain session information when you kill it, such as the files you were visiting at the time. This information is then available the next time you start Emacs. See Saving Emacs Sessions.

If the value of the variable confirm-kill-emacs is non-nil, C-x C-c assumes that its value is a predicate function, and calls that function. If the result of the function call is non-nil, the session is killed, otherwise Emacs continues to run. One convenient function to use as the value of confirm-kill-emacs is the function yes-or-no-p. The default value of confirm-kill-emacs is nil.

If the value of the variable confirm-kill-processes is nil, C-x C-c does not ask for confirmation before killing subprocesses started by Emacs. The value is t by default.

To further customize what happens when Emacs is exiting, see Killing Emacs.

To kill Emacs without being prompted about saving, type M-x kill-emacs.

C-z runs the command suspend-frame. On a graphical display, this command minimizes (or iconifies) the selected Emacs frame, hiding it in a way that lets you bring it back later (exactly how this hiding occurs depends on the window system). On a text terminal, the C-z command suspends Emacs, stopping the program temporarily and returning control to the parent process (usually a shell); in most shells, you can resume Emacs after suspending it with the shell command %emacs.

Text terminals usually listen for certain special characters whose meaning is to kill or suspend the program you are running. This terminal feature is turned off while you are in Emacs. The meanings of C-z and C-x C-c as keys in Emacs were inspired by the use of C-z and C-c on several operating systems as the characters for stopping or killing a program, but that is their only relationship with the operating system. You can customize these keys to run any commands of your choice (see Keymaps).

7 Basic Editing Commands

Here we explain the basics of how to enter text, make corrections, and save the text in a file. If this material is new to you, we suggest you first run the Emacs learn-by-doing tutorial, by typing C-h t (help-with-tutorial).

  • Inserting Text: Inserting text by simply typing it.
  • Moving Point: Moving the cursor to the place where you want to change something.
  • Erasing: Deleting and killing text.
  • Basic Undo: Undoing recent changes in the text.
  • Files: Visiting, creating, and saving files.
  • Help: Asking what a character does.
  • Blank Lines: Making and deleting blank lines.
  • Continuation Lines: How Emacs displays lines too wide for the screen.
  • Position Info: What line, row, or column is point on?
  • Arguments: Numeric arguments for repeating a command N times.
  • Repeating: Repeating the previous command quickly.

basic editing, 重要的基本概念.
pointer moving,

8 The Minibuffer

The minibuffer is where Emacs commands read complicated arguments, such as file names, buffer names, Emacs command names, or Lisp expressions. We call it the “minibuffer” because it’s a special-purpose buffer with a small amount of screen space. You can use the usual Emacs editing commands in the minibuffer to edit the argument text.

9 Running Commands by Name

Every Emacs command has a name that you can use to run it. For convenience, many commands also have key bindings. You can run those commands by typing the keys, or run them by name. Most Emacs commands have no key bindings, so the only way to run them is by name. (See Key Bindings, for how to set up key bindings.)

By convention, a command name consists of one or more words, separated by hyphens; for example, auto-fill-mode or manual-entry. Command names mostly use complete English words to make them easier to remember.

To run a command by name, start with M-x, type the command name, then terminate it with . M-x uses the minibuffer to read the command name. The string ‘M-x’ appears at the beginning of the minibuffer as a prompt to remind you to enter a command name to be run. exits the minibuffer and runs the command. See Minibuffer, for more information on the minibuffer.

You can use completion to enter the command name. For example, to invoke the command forward-char, you can type

1
M-x forward-char <RET>

or

1
M-x forw <TAB> c <RET>

Note that forward-char is the same command that you invoke with the key C-f. The existence of a key binding does not stop you from running the command by name.

When M-x completes on commands, it ignores the commands that are declared obsolete; for these, you will have to type their full name. Obsolete commands are those for which newer, better alternatives exist, and which are slated for removal in some future Emacs release.

To cancel the M-x and not run a command, type C-g instead of entering the command name. This takes you back to command level.

To pass a numeric argument to the command you are invoking with M-x, specify the numeric argument before M-x. The argument value appears in the prompt while the command name is being read, and finally M-x passes the argument to that command. For example, to pass the numeric argument of 42 to the command forward-char you can type C-u 42 M-x forward-char .

When the command you run with M-x has a key binding, Emacs mentions this in the echo area after running the command. For example, if you type M-x forward-word, the message says that you can run the same command by typing M-f. You can turn off these messages by setting the variable suggest-key-bindings to nil. The value of suggest-key-bindingscan also be a number, in which case Emacs will show the binding for that many seconds before removing it from display. The default behavior is to display the binding for 2 seconds.

Commands that don’t have key bindings, can still be invoked after typing less than their full name at the ‘M-x’ prompt. Emacs mentions such shorthands in the echo area if they are significantly shorter than the full command name, and extended-command-suggest-shorter is non-nil. The setting of suggest-key-bindings affects these hints as well.

In this manual, when we speak of running a command by name, we often omit the that terminates the name. Thus we might say M-x auto-fill-mode rather than M-x auto-fill-mode . We mention the only for emphasis, such as when the command is followed by arguments.

M-x works by running the command execute-extended-command, which is responsible for reading the name of another command and invoking it.

10 Help

Emacs provides a wide variety of help commands, all accessible through the prefix key C-h (or, equivalently, the function key ). These help commands are described in the following sections. You can also type C-h C-h to view a list of help commands (help-for-help). You can scroll the list with and , then type the help command you want. To cancel, type C-g.

Many help commands display their information in a special help buffer. In this buffer, you can type and to scroll and type to follow hyperlinks. See Help Mode.

If you are looking for a certain feature, but don’t know what it is called or where to look, we recommend three methods. First, try an apropos command, then try searching the manual index, then look in the FAQ and the package keywords.

  • C-h a topics

    This searches for commands whose names match the argument topics. The argument can be a keyword, a list of keywords, or a regular expression (see Regexps). See Apropos.

  • C-h i d m emacs i topic

    This searches for topic in the indices of the Emacs Info manual, displaying the first match found. Press , to see subsequent matches. You can use a regular expression as topic.

  • C-h i d m emacs s topic

    Similar, but searches the text of the manual rather than the indices.

  • C-h C-f

    This displays the Emacs FAQ, using Info.

  • C-h p

    This displays the available Emacs packages based on keywords. See Package Keywords.

C-h or mean “help” in various other contexts as well. For instance, you can type them after a prefix key to view a list of the keys that can follow the prefix key. (You can also use ? in this context. A few prefix keys don’t support C-h or ? in this way, because they define other meanings for those inputs, but they all support .)

  • Help Summary: Brief list of all Help commands.
  • Key Help: Asking what a key does in Emacs.
  • Name Help: Asking about a command, variable or function name.
  • Apropos: Asking what pertains to a given topic.
  • Help Mode: Special features of Help mode and Help buffers.
  • Package Keywords: Finding Lisp libraries by keywords (topics).
  • Language Help: Help relating to international language support.
  • Misc Help: Other help commands.
  • Help Files: Commands to display auxiliary help files.
  • Help Echo: Help on active text and tooltips (balloon help’’).

11 The Mark and the Region

Many Emacs commands operate on an arbitrary contiguous part of the current buffer. To specify the text for such a command to operate on, you set the mark at one end of it, and move point to the other end. The text between point and the mark is called the region. The region always extends between point and the mark, no matter which one comes earlier in the text; each time you move point, the region changes.

Setting the mark at a position in the text also activates it. When the mark is active, we say also that the region is active; Emacs indicates its extent by highlighting the text within it, using the region face (see Face Customization).

After certain non-motion commands, including any command that changes the text in the buffer, Emacs automatically deactivates the mark; this turns off the highlighting. You can also explicitly deactivate the mark at any time, by typing C-g (see Quitting).

The above default behavior is known as Transient Mark mode. Disabling Transient Mark mode switches Emacs to an alternative behavior, in which the region is usually not highlighted. See Disabled Transient Mark.

Setting the mark in one buffer has no effect on the marks in other buffers. When you return to a buffer with an active mark, the mark is at the same place as before. When multiple windows show the same buffer, they can have different values of point, and thus different regions, but they all share one common mark position. See Windows. Ordinarily, only the selected window highlights its region; however, if the variable highlight-nonselected-windows is non-nil, each window highlights its own region.

There is another kind of region: the rectangular region. See Rectangles.

12 Killing and Moving Text

In Emacs, killing means erasing text and copying it into the kill ring. Yanking means bringing text from the kill ring back into the buffer. (Some applications use the terms “cutting” and “pasting” for similar operations.) The kill ring is so-named because it can be visualized as a set of blocks of text arranged in a ring, which you can access in cyclic order. See Kill Ring.

Killing and yanking are the most common way to move or copy text within Emacs. It is very versatile, because there are commands for killing many different types of syntactic units.

13 Registers

Emacs registers are compartments where you can save text, rectangles, positions, and other things for later use. Once you save text or a rectangle in a register, you can copy it into the buffer once or many times; once you save a position in a register, you can jump back to that position once or many times.

Each register has a name that consists of a single character, which we will denote by r; r can be a letter (such as ‘a’) or a number (such as ‘1’); case matters, so register ‘a’ is not the same as register ‘A’. You can also set a register in non-alphanumeric characters, for instance ‘*’ or ‘C-d’. Note, it’s not possible to set a register in ‘C-g’ or ‘ESC’, because these keys are reserved for quitting (see Quitting).

A register can store a position, a piece of text, a rectangle, a number, a window configuration, or a file name, but only one thing at any given time. Whatever you store in a register remains there until you store something else in that register. To see what register r contains, use M-x view-register:

  • M-x view-register r

    Display a description of what register r contains.

All of the commands that prompt for a register will display a preview window that lists the existing registers (if there are any) after a short delay. To change the length of the delay, customize register-preview-delay. To prevent this display, set that option to nil. You can explicitly request a preview window by pressing C-h or .

Bookmarks record files and positions in them, so you can return to those positions when you look at the file again. Bookmarks are similar in spirit to registers, so they are also documented in this chapter.

14 Controlling the Display

Since only part of a large buffer fits in the window, Emacs has to show only a part of it. This chapter describes commands and variables that let you specify which part of the text you want to see, and how the text is displayed.

15 Searching and Replacement

需要关注的部分.

Like other editors, Emacs has commands to search for occurrences of a string. Emacs also has commands to replace occurrences of a string with a different string. There are also commands that do the same thing, but search for patterns instead of fixed strings.

You can also search multiple files under the control of xref (see Identifier Search) or through the Dired A command (see Operating on Files), or ask the grep program to do it (see Grep Searching).

16 Commands for Fixing Typos

In this chapter we describe commands that are useful when you catch a mistake while editing. The most fundamental of these commands is the undo command C-/ (also bound to C-x u and C-_). This undoes a single command, or a part of a command (as in the case of query-replace), or several consecutive character insertions. Consecutive repetitions of C-/ undo earlier and earlier changes, back to the limit of the undo information available.

Aside from the commands described here, you can erase text using deletion commands such as (delete-backward-char). These were described earlier in this manual. See Erasing.

  • Undo: The Undo commands.
  • Transpose: Exchanging two characters, words, lines, lists…
  • Fixing Case: Correcting case of last word entered.
  • Spelling: Apply spelling checker to a word, or a whole file.

17 Keyboard Macros

device的部分.

In this chapter we describe how to record a sequence of editing commands so you can repeat it conveniently later.

A keyboard macro is a command defined by an Emacs user to stand for another sequence of keys. For example, if you discover that you are about to type C-n M-d C-d forty times, you can speed your work by defining a keyboard macro to do C-n M-d C-d, and then executing it 39 more times.

You define a keyboard macro by executing and recording the commands which are its definition. Put differently, as you define a keyboard macro, the definition is being executed for the first time. This way, you can see the effects of your commands, so that you don’t have to figure them out in your head. When you close the definition, the keyboard macro is defined and also has been, in effect, executed once. You can then do the whole thing over again by invoking the macro.

Keyboard macros differ from ordinary Emacs commands in that they are written in the Emacs command language rather than in Lisp. This makes it easier for the novice to write them, and makes them more convenient as temporary hacks. However, the Emacs command language is not powerful enough as a programming language to be useful for writing anything intelligent or general. For such things, Lisp must be used.

18 File Handling

The operating system stores data permanently in named files, so most of the text you edit with Emacs comes from a file and is ultimately stored in a file.

To edit a file, you must tell Emacs to read the file and prepare a buffer containing a copy of the file’s text. This is called visiting the file. Editing commands apply directly to text in the buffer; that is, to the copy inside Emacs. Your changes appear in the file itself only when you save the buffer back into the file.

In addition to visiting and saving files, Emacs can delete, copy, rename, and append to files, keep multiple versions of them, and operate on file directories.

19 Using Multiple Buffers

The text you are editing in Emacs resides in an object called a buffer. Each time you visit a file, a buffer is used to hold the file’s text. Each time you invoke Dired, a buffer is used to hold the directory listing. If you send a message with C-x m, a buffer is used to hold the text of the message. When you ask for a command’s documentation, that appears in a buffer named Help.

Each buffer has a unique name, which can be of any length. When a buffer is displayed in a window, its name is shown in the mode line (see Mode Line). The distinction between upper and lower case matters in buffer names. Most buffers are made by visiting files, and their names are derived from the files’ names; however, you can also create an empty buffer with any name you want. A newly started Emacs has several buffers, including one named scratch, which can be used for evaluating Lisp expressions and is not associated with any file (see Lisp Interaction).

At any time, one and only one buffer is selected; we call it the current buffer. We sometimes say that a command operates on “the buffer”; this really means that it operates on the current buffer. When there is only one Emacs window, the buffer displayed in that window is current. When there are multiple windows, the buffer displayed in the selected window is current. See Windows.

A buffer’s contents consist of a series of characters, each of which optionally carries a set of text properties (see Text properties) that can specify more information about that character.

Aside from its textual contents, each buffer records several pieces of information, such as what file it is visiting (if any), whether it is modified, and what major mode and minor modes are in effect (see Modes). These are stored in buffer-local variables—variables that can have a different value in each buffer. See Locals.

A buffer’s size cannot be larger than some maximum, which is defined by the largest buffer position representable by Emacs integers. This is because Emacs tracks buffer positions using that data type. For typical 64-bit machines, this maximum buffer size is 2^61 - 2 bytes, or about 2 EiB. For typical 32-bit machines, the maximum is usually 2^29 - 2 bytes, or about 512 MiB. Buffer sizes are also limited by the amount of memory in the system.

  • Select Buffer: Creating a new buffer or reselecting an old one.
  • List Buffers: Getting a list of buffers that exist.
  • Misc Buffer: Renaming; changing read-only status; copying text.
  • Kill Buffer: Killing buffers you no longer need.
  • Several Buffers: How to go through the list of all buffers and operate variously on several of them.
  • Indirect Buffers: An indirect buffer shares the text of another buffer.
  • Buffer Convenience: Convenience and customization features for buffer handling.

20 Multiple Windows

Emacs can split a frame into two or many windows. Multiple windows can display parts of different buffers, or different parts of one buffer. Multiple frames always imply multiple windows, because each frame has its own set of windows. Each window belongs to one and only one frame.

21 Frames and Graphical Displays

When Emacs is started on a graphical display, e.g., on the X Window System, it occupies a graphical system-level display region. In this manual, we call this a frame, reserving the word “window” for the part of the frame used for displaying a buffer. A frame initially contains one window, but it can be subdivided into multiple windows (see Windows). A frame normally also contains a menu bar, tool bar, and echo area.

You can also create additional frames (see Creating Frames). All frames created in the same Emacs session have access to the same underlying buffers and other data. For instance, if a buffer is being shown in more than one frame, any changes made to it in one frame show up immediately in the other frames too.

Typing C-x C-c closes all the frames on the current display, and ends the Emacs session if it has no frames open on any other displays (see Exiting). To close just the selected frame, type C-x 5 0 (that is zero, not o).

This chapter describes Emacs features specific to graphical displays (particularly mouse commands), and features for managing multiple frames. On text terminals, many of these features are unavailable. However, it is still possible to create multiple frames on text terminals; such frames are displayed one at a time, filling the entire terminal screen (see Non-Window Terminals). It is also possible to use the mouse on some text terminals (see Text-Only Mouse, for doing so on GNU and Unix systems; and see MS-DOS Mouse, for doing so on MS-DOS). Menus are supported on all text terminals.

23 Major and Minor Modes

Emacs contains many editing modes that alter its basic behavior in useful ways. These are divided into major modes and minor modes.

Major modes provide specialized facilities for working on a particular file type, such as a C source file (see Programs), or a particular type of non-file buffer, such as a shell buffer (see Shell). Major modes are mutually exclusive; each buffer has one and only one major mode at any time.

Minor modes are optional features which you can turn on or off, not necessarily specific to a type of file or buffer. For example, Auto Fill mode is a minor mode in which breaks lines between words as you type (see Auto Fill). Minor modes are independent of one another, and of the selected major mode.

  • Major Modes: Text mode vs. Lisp mode vs. C mode…
  • Minor Modes: Each minor mode is a feature you can turn on independently of any others.
  • Choosing Modes: How modes are chosen when visiting files.

24 Indentation

Indentation refers to inserting or adjusting whitespace characters (space and/or tab characters) at the beginning of a line of text. This chapter documents indentation commands and options which are common to Text mode and related modes, as well as programming language modes. See Program Indent, for additional documentation about indenting in programming modes.

The simplest way to perform indentation is the key. In most major modes, this runs the command indent-for-tab-command. (In C and related modes, runs the command c-indent-line-or-region, which behaves similarly, see C Indent).

  • Insert whitespace, or indent the current line, in a mode-appropriate way (indent-for-tab-command). If the region is active, indent all the lines within it.

The exact behavior of depends on the major mode. In Text mode and related major modes, normally inserts some combination of space and tab characters to advance point to the next tab stop (see Tab Stops). For this purpose, the position of the first non-whitespace character on the preceding line is treated as an additional tab stop, so you can use to align point with the preceding line. If the region is active (see Using Region), acts specially: it indents each line in the region so that its first non-whitespace character is aligned with the preceding line.

In programming modes, indents the current line of code in a way that makes sense given the code in the preceding lines. If the region is active, all the lines in the region are indented this way. If point was initially within the current line’s indentation, it is repositioned to the first non-whitespace character on the line.

If you just want to insert a tab character in the buffer, type C-q (see Inserting Text).

22 International Character Set Support

Emacs supports a wide variety of international character sets, including European and Vietnamese variants of the Latin alphabet, as well as Arabic scripts, Brahmic scripts (for languages such as Bengali, Hindi, and Thai), Cyrillic, Ethiopic, Georgian, Greek, Han (for Chinese and Japanese), Hangul (for Korean), Hebrew and IPA. Emacs also supports various encodings of these characters that are used by other internationalized software, such as word processors and mailers.

Emacs allows editing text with international characters by supporting all the related activities:

  • You can visit files with non-ASCII characters, save non-ASCII text, and pass non-ASCII text between Emacs and programs it invokes (such as compilers, spell-checkers, and mailers). Setting your language environment (see Language Environments) takes care of setting up the coding systems and other options for a specific language or culture. Alternatively, you can specify how Emacs should encode or decode text for each command; see Text Coding.

  • You can display non-ASCII characters encoded by the various scripts. This works by using appropriate fonts on graphics displays (see Defining Fontsets), and by sending special codes to text displays (see Terminal Coding). If some characters are displayed incorrectly, refer to Undisplayable Characters, which describes possible problems and explains how to solve them.

  • Characters from scripts whose natural ordering of text is from right to left are reordered for display (see Bidirectional Editing). These scripts include Arabic, Hebrew, Syriac, Thaana, and a few others.

  • You can insert non-ASCII characters or search for them. To do that, you can specify an input method (see Select Input Method) suitable for your language, or use the default input method set up when you choose your language environment. If your keyboard can produce non-ASCII characters, you can select an appropriate keyboard coding system (see Terminal Coding), and Emacs will accept those characters. Latin-1 characters can also be input by using the C-x 8 prefix, see Unibyte Mode.

    With the X Window System, your locale should be set to an appropriate value to make sure Emacs interprets keyboard input correctly; see locales.

The rest of this chapter describes these issues in detail.

25 Commands for Human Languages

This chapter describes Emacs commands that act on text, by which we mean sequences of characters in a human language (as opposed to, say, a computer programming language). These commands act in ways that take into account the syntactic and stylistic conventions of human languages: conventions involving words, sentences, paragraphs, and capital letters. There are also commands for filling, which means rearranging the lines of a paragraph to be approximately equal in length. These commands, while intended primarily for editing text, are also often useful for editing programs.

Emacs has several major modes for editing human-language text. If the file contains ordinary text, use Text mode, which customizes Emacs in small ways for the syntactic conventions of text. Outline mode provides special commands for operating on text with an outline structure. See Outline Mode.

Org mode extends Outline mode and turns Emacs into a full-fledged organizer: you can manage TODO lists, store notes and publish them in many formats. See the Org Info manual, which is distributed with Emacs.

Emacs has other major modes for text which contains embedded commands, such as TeX and LaTeX (see TeX Mode); HTML and SGML (see HTML Mode); XML (see the nXML mode Info manual, which is distributed with Emacs); and Groff and Nroff (see Nroff Mode).

If you need to edit ASCII art pictures made out of text characters, use Picture mode, a special major mode for editing such pictures. See Picture Mode.

26 Editing Programs

This chapter describes Emacs features for facilitating editing programs. Some of the things these features can do are:

  • Find or move over top-level definitions (see Defuns).
  • Apply the usual indentation conventions of the language (see Program Indent).
  • Balance parentheses (see Parentheses).
  • Insert, kill or align comments (see Comments).
  • Highlight program syntax (see Font Lock).

  • Program Modes: Major modes for editing programs.

  • Defuns: Commands to operate on major top-level parts of a program.
  • Program Indent: Adjusting indentation to show the nesting.
  • Parentheses: Commands that operate on parentheses.
  • Comments: Inserting, killing, and aligning comments.
  • Documentation: Getting documentation of functions you plan to call.
  • Hideshow: Displaying blocks selectively.
  • Symbol Completion: Completion on symbol names of your program or language.
  • MixedCase Words: Dealing with identifiersLikeThis.
  • Semantic: Suite of editing tools based on source code parsing.
  • Misc for Programs: Other Emacs features useful for editing programs.
  • C Modes: Special commands of C, C++, Objective-C, Java, IDL, Pike and AWK modes.
  • Asm Mode: Asm mode and its special features.
  • Fortran: Fortran mode and its special features.

27 Compiling and Testing Programs

The previous chapter discusses the Emacs commands that are useful for making changes in programs. This chapter deals with commands that assist in the process of compiling and testing programs.

  • Compilation: Compiling programs in languages other than Lisp (C, Pascal, etc.).

  • Compilation Mode: The mode for visiting compiler errors.

  • Compilation Shell: Customizing your shell properly for use in the compilation buffer.

  • Grep Searching: Searching with grep.

    功能不错.

  • Flymake: Finding syntax errors on the fly.

  • Debuggers: Running symbolic debuggers for non-Lisp programs.

  • Executing Lisp: Various modes for editing Lisp programs, with different facilities for running the Lisp programs.

  • Libraries: How Lisp programs are loaded into Emacs.

  • Eval: Executing a single Lisp expression in Emacs.

  • Interaction: Executing Lisp in an Emacs buffer.

  • External Lisp: Communicating through Emacs with a separate Lisp.

功能性的部分. Project management,,

28 Maintaining Large Programs

This chapter describes Emacs features for maintaining medium- to large-size programs and packages. These features include:

  • Unified interface to Support for Version Control Systems (VCS) that record the history of changes to source files.
  • A specialized mode for maintaining ChangeLog files that provide a chronological log of program changes.
  • Xref, a set of commands for displaying definitions of symbols (a.k.a. “identifiers”) and their references.
  • EDE, the Emacs’s own IDE.
  • A mode for merging changes to program sources made on separate branches of development.

If you are maintaining a large Lisp program, then in addition to the features described here, you may find the Emacs Lisp Regression Testing (ERT) library useful (see ERT).

  • Version Control: Using version control systems.
  • Change Log: Maintaining a change history for your program.
  • Xref: Find definitions and references of any function, method, struct, macro, … in your program.
  • EDE: An integrated development environment for Emacs.
  • Emerge: A convenient way of merging two versions of a program.

29 Abbrevs

A defined abbrev is a word which expands, if you insert it, into some different text. Abbrevs are defined by the user to expand in specific ways. For example, you might define ‘foo’ as an abbrev expanding to ‘find outer otter’. Then you could insert ‘find outer otter ’ into the buffer by typing f o o .

A second kind of abbreviation facility is called dynamic abbrev expansion. You use dynamic abbrev expansion with an explicit command to expand the letters in the buffer before point by looking for other words in the buffer that start with those letters. See Dynamic Abbrevs.

A third kind, hippie expansion, generalizes abbreviation expansion. See Hippie Expansion.

30 Dired, the Directory Editor

Dired makes an Emacs buffer containing a listing of a directory, and optionally some of its subdirectories as well. You can use the normal Emacs commands to move around in this buffer, and special Dired commands to operate on the listed files. Dired works with both local and remote directories.

The Dired buffer is normally read-only, and inserting text in it is not allowed (however, the Wdired mode allows that, see Wdired). Ordinary printing characters such as d and x are redefined for special Dired commands. Some Dired commands mark or flag the current file (that is, the file on the current line); other commands operate on the marked files or on the flagged files. You first mark certain files in order to operate on all of them with one command.

The Dired-X package provides various extra features for Dired mode. See Dired-X.

You can also view a list of files in a directory with C-x C-d (list-directory). Unlike Dired, this command does not allow you to operate on the listed files. See Directories.

31 The Calendar and the Diary

掌握的部分.

Emacs provides the functions of a desk calendar, with a diary of planned or past events. It also has facilities for managing your appointments, and keeping track of how much time you spend working on certain projects.

To enter the calendar, type M-x calendar. This displays a three-month calendar centered on the current month, with point on the current date. With a numeric argument, as in C-u M-x calendar, it prompts you for the month and year to be the center of the three-month calendar. The calendar uses its own buffer, whose major mode is Calendar mode.

mouse-3 in the calendar brings up a menu of operations on a particular date; mouse-2 brings up a menu of commonly used calendar features that are independent of any particular date. To exit the calendar, type q.

32 Sending Mail

To send an email message from Emacs, type C-x m. This switches to a buffer named unsent mail, where you can edit the text and headers of the message. When done, type C-c C-s or C-c C-c to send it.

  • C-x m

    Begin composing mail (compose-mail).

  • C-x 4 m

    Likewise, in another window (compose-mail-other-window).

  • C-x 5 m

    Likewise, but in a new frame (compose-mail-other-frame).

  • C-c C-s

    In the mail buffer, send the message (message-send).

  • C-c C-c

    In the mail buffer, send the message and bury the buffer (message-send-and-exit).

The mail buffer is an ordinary Emacs buffer, so you can switch to other buffers while composing the mail. If you want to send another mail before finishing the current one, type C-x m again to open a new mail buffer whose name has a different numeric suffix (see Misc Buffer). If you invoke the command with a prefix argument, C-u C-x m, Emacs switches back to the last mail buffer, and asks if you want to erase the message in that buffer; if you answer no, this lets you pick up editing the message where you left off.

The command C-x 4 m (compose-mail-other-window) does the same as C-x m, except it displays the mail buffer in a different window. The command C-x 5 m (compose-mail-other-frame) does it in a new frame.

When you type C-c C-c or C-c C-s to send the mail, Emacs may ask you how it should deliver the mail—either directly via SMTP, or using some other method. See Mail Sending, for details.

  • Format: Format of a mail message.
  • Headers: Details of some standard mail header fields.
  • Aliases: Abbreviating and grouping mail addresses.
  • Commands: Special commands for editing mail being composed.
  • Signature: Adding a signature to every message.
  • Amuse: Distracting the NSA; adding fortune messages.
  • Methods: Using alternative mail-composition methods.

33 Reading Mail with Rmail

Rmail is an Emacs subsystem for reading and disposing of mail that you receive. Rmail stores mail messages in files called Rmail files. Reading the messages in an Rmail file is done in a special major mode, Rmail mode, which redefines most letters to run commands for managing mail.

Emacs also comes with a much more sophisticated and flexible subsystem for reading mail, called Gnus. Gnus is a very large package, and is therefore described in its own manual, see Top.

  • Basic: Basic concepts of Rmail, and simple use.
  • Scroll: Scrolling through a message.
  • Motion: Moving to another message.
  • Deletion: Deleting and expunging messages.
  • Inbox: How mail gets into the Rmail file.
  • Files: Using multiple Rmail files.
  • Output: Copying messages out to files.
  • Labels: Classifying messages by labeling them.
  • Attrs: Certain standard labels, called attributes.
  • Reply: Sending replies to messages you are viewing.
  • Summary: Summaries show brief info on many messages.
  • Sort: Sorting messages in Rmail.
  • Display: How Rmail displays a message; customization.
  • Coding: How Rmail handles decoding character sets.
  • Editing: Editing message text and headers in Rmail.
  • Digest: Extracting the messages from a digest message.
  • Rot13: Reading messages encoded in the rot13 code.
  • Movemail: More details of fetching new mail.
  • Remote Mailboxes: Retrieving mail from remote mailboxes.
  • Other Mailbox Formats: Retrieving mail from local mailboxes in various formats.

34 Email and Usenet News with Gnus

Reading and writing email with emacs - Emacs Stack Exchange

Gnus is an Emacs package primarily designed for reading and posting Usenet news. It can also be used to read and respond to messages from a number of other sources—email, remote directories, digests, and so on. Here we introduce Gnus and describe several basic features. For full details, see Gnus.

35 Host Security

Emacs runs inside an operating system such as GNU/Linux, and relies on the operating system to check security constraints such as accesses to files. The default settings for Emacs are designed for typical use; they may require some tailoring in environments where security is more of a concern, or less of a concern, than usual. For example, file-local variables can be risky, and you can set the variable enable-local-variables to :safe or (even more conservatively) to nil; conversely, if your files can all be trusted and the default checking for these variables is irritating, you can set enable-local-variables to :all. See Safe File Variables.

See Security Considerations, for more information about security considerations when using Emacs as part of a larger application.

36 Network Security

Whenever Emacs establishes any network connection, it passes the established connection to the Network Security Manager (NSM). NSM is responsible for enforcing the network security under your control. Currently, this works by using the Transport Layer Security (TLS) features.

The network-security-level variable determines the security level that NSM enforces. If its value is low, no security checks are performed.

If this variable is medium (which is the default), a number of checks will be performed. If as result NSM determines that the network connection might not be trustworthy, it will make you aware of that, and will ask you what to do about the network connection.

You can decide to register a permanent security exception for an unverified connection, a temporary exception, or refuse the connection entirely.

Below is a list of the checks done on the medium level.

  • unable to verify a TLS certificate

    If the connection is a TLS, SSL or STARTTLS connection, NSM will check whether the certificate used to establish the identity of the server we’re connecting to can be verified.While an invalid certificate is often the cause for concern (there could be a Man-in-the-Middle hijacking your network connection and stealing your password), there may be valid reasons for going ahead with the connection anyway. For instance, the server may be using a self-signed certificate, or the certificate may have expired. It’s up to you to determine whether it’s acceptable to continue with the connection.

  • a self-signed certificate has changed

    If you’ve previously accepted a self-signed certificate, but it has now changed, that could mean that the server has just changed the certificate, but it might also mean that the network connection has been hijacked.

  • previously encrypted connection now unencrypted

    If the connection is unencrypted, but it was encrypted in previous sessions, this might mean that there is a proxy between you and the server that strips away STARTTLSannouncements, leaving the connection unencrypted. This is usually very suspicious.

  • talking to an unencrypted service when sending a password

    When connecting to an IMAP or POP3 server, these should usually be encrypted, because it’s common to send passwords over these connections. Similarly, if you’re sending email via SMTP that requires a password, you usually want that connection to be encrypted. If the connection isn’t encrypted, NSM will warn you.

If network-security-level is high, the following checks will be made, in addition to the above:

  • a validated certificate changes the public key

    Servers change their keys occasionally, and that is normally nothing to be concerned about. However, if you are worried that your network connections are being hijacked by agencies who have access to pliable Certificate Authorities which issue new certificates for third-party services, you may want to keep track of these changes.

  • Diffie-Hellman low prime bits

    When doing the public key exchange, the number of prime bits should be high to ensure that the channel can’t be eavesdropped on by third parties. If this number is too low, you will be warned.

  • RC4 stream cipher

    The RC4 stream cipher is believed to be of low quality and may allow eavesdropping by third parties.

  • SSL1, SSL2 and SSL3

    The protocols older than TLS1.0 are believed to be vulnerable to a variety of attacks, and you may want to avoid using these if what you’re doing requires higher security.

Finally, if network-security-level is paranoid, you will also be notified the first time NSM sees any new certificate. This will allow you to inspect all the certificates from all the connections that Emacs makes.

The following additional variables can be used to control details of NSM operation:

  • nsm-settings-file

    This is the file where NSM stores details about connections. It defaults to ~/.emacs.d/network-security.data.

  • nsm-save-host-names

    By default, host names will not be saved for non-STARTTLS connections. Instead a host/port hash is used to identify connections. This means that one can’t casually read the settings file to see what servers the user has connected to. If this variable is t, NSM will also save host names in the nsm-settings-file.

37 Document Viewing

DocView mode is a major mode for viewing DVI, PostScript (PS), PDF, OpenDocument, and Microsoft Office documents. It provides features such as slicing, zooming, and searching inside documents. It works by converting the document to a set of images using the gs (GhostScript) or mudraw/pdfdraw (MuPDF) commands and other external tools 1, and displaying those images.

When you visit a document file that can be displayed with DocView mode, Emacs automatically uses that mode 2. As an exception, when you visit a PostScript file, Emacs switches to PS mode, a major mode for editing PostScript files as text; however, it also enables DocView minor mode, so you can type C-c C-c to view the document with DocView. In either DocView mode or DocView minor mode, repeating C-c C-c (doc-view-toggle-display) toggles between DocView and the underlying file contents.

When you visit a file which would normally be handled by DocView mode but some requirement is not met (e.g., you operate in a terminal frame or Emacs has no PNG support), you are queried if you want to view the document’s contents as plain text. If you confirm, the buffer is put in text mode and DocView minor mode is activated. Thus, by typing C-c C-cyou switch to the fallback mode. With another C-c C-c you return to DocView mode. The plain text contents can also be displayed from within DocView mode by typing C-c C-t(doc-view-open-text).

You can explicitly enable DocView mode with the command M-x doc-view-mode. You can toggle DocView minor mode with M-x doc-view-minor-mode.

When DocView mode starts, it displays a welcome screen and begins formatting the file, page by page. It displays the first page once that has been formatted.

To kill the DocView buffer, type k (doc-view-kill-proc-and-buffer). To bury it, type q (quit-window).

  • Navigation: Navigating DocView buffers.
  • Searching: Searching inside documents.
  • Slicing: Specifying which part of a page is displayed.
  • Conversion: Influencing and triggering conversion.

38 Running Shell Commands from Emacs

基本的命令能调动,
program invoke editors.

Emacs has commands for passing single command lines to shell subprocesses, and for running a shell interactively with input and output to an Emacs buffer, and for running a shell in a terminal emulator window.

  • M-! cmd

    Run the shell command cmd and display the output (shell-command).

  • M-| cmd

    Run the shell command cmd with region contents as input; optionally replace the region with the output (shell-command-on-region).

  • M-& cmd

    Run the shell command cmd asynchronously, and display the output (async-shell-command).

  • M-x shell

    Run a subshell with input and output through an Emacs buffer. You can then give commands interactively.

  • M-x term

    Run a subshell with input and output through an Emacs buffer. You can then give commands interactively. Full terminal emulation is available.

Whenever you specify a relative file name for an executable program (either in the cmd argument to one of the above commands, or in other contexts), Emacs searches for the program in the directories specified by the variable exec-path. The value of this variable must be a list of directories; the default value is initialized from the environment variable PATH when Emacs is started (see General Variables).

M-x eshell invokes a shell implemented entirely in Emacs. It is documented in its own manual. See Eshell.

39 Using Emacs as a Server

Various programs can invoke your choice of editor to edit a particular piece of text.

这话说得真绕弯儿.
Using Emacs as a Server

For instance, version control programs invoke an editor to enter version control logs (see Version Control), and the Unix mail utility invokes an editor to enter a message to send. By convention, your choice of editor is specified by the environment variable EDITOR. If you setEDITOR to ‘emacs’, Emacs would be invoked, but in an inconvenient way—by starting a new Emacs process. This is inconvenient because the new Emacs process doesn’t share buffers, a command history, or other kinds of information with any existing Emacs process.

You can solve this problem by setting up Emacs as an edit server, so that it “listens” for external edit requests and acts accordingly. There are various ways to start an Emacs server:

  • Run the command server-start in an existing Emacs process: either type M-x server-start, or put the expression (server-start) in your init file (see Init File). The existing Emacs process is the server; when you exit Emacs, the server dies with the Emacs process.

  • Run Emacs as a daemon, using one of the ‘–daemon’ command-line options. See Initial Options. When Emacs is started this way, it calls server-start after initialization and does not open an initial frame. It then waits for edit requests from clients.

  • If your operating system uses systemd to manage startup, you can automatically start Emacs in daemon mode when you login using the supplied systemd unit file. To activate this:

    1
    2
    systemctl --user enable emacs
    # 此方法不可行.

    (If your Emacs was installed into a non-standard location, you may need to copy the emacs.service file to a standard directory such as ~/.config/systemd/user/.)

  • An external process can invoke the Emacs server when a connection event occurs upon a specified socket and pass the socket to the new Emacs server process. An instance of this is the socket functionality of systemd: the systemd service creates a socket and listens for connections on it; when emacsclient connects to it for the first time, systemd can launch the Emacs server and hand over the socket to it for servicing emacsclient connections. A setup to use this functionality could be:

    ~/.config/systemd/user/emacs.socket:

    1
    2
    3
    4
    [Socket]
    ListenStream=/path/to/.emacs.socket
    [Install]
    WantedBy=sockets.target

    (The emacs.service file described above must also be installed.)

    The ListenStream path will be the path that Emacs listens for connections from emacsclient; this is a file of your choice.

Once an Emacs server is started, you can use a shell command called emacsclient to connect to the Emacs process and tell it to visit a file. You can then set the EDITOR environment variable to ‘emacsclient’, so that external programs will use the existing Emacs process for editing.1

You can run multiple Emacs servers on the same machine by giving each one a unique server name, using the variable server-name. For example, M-x set-variable server-name “foo” sets the server name to ‘foo’. The emacsclient program can specify a server by name, using the ‘-s’ or the ‘-f’ option (see emacsclient Options), depending on whether or not the server uses a TCP socket (see TCP Emacs server).

If you want to run multiple Emacs daemons (see Initial Options), you can give each daemon its own server name like this:

1
emacs --daemon=foo

If you have defined a server by a unique server name, it is possible to connect to the server from another Emacs instance and evaluate Lisp expressions on the server, using the server-eval-at function. For instance, (server-eval-at "foo" '(+ 1 2)) evaluates the expression (+ 1 2) on the ‘foo’ server, and returns 3. (If there is no server with that name, an error is signaled.) Currently, this feature is mainly useful for developers.

39.1 TCP Emacs server

An Emacs server usually listens to connections on a local Unix domain socket. Some operating systems, such as MS-Windows, do not support local sockets; in that case, the server uses TCP sockets instead. In some cases it is useful to have the server listen on a TCP socket even if local sockets are supported, e.g., if you need to contact the Emacs server from a remote machine. You can set server-use-tcp to non-nil to have Emacs listen on a TCP socket instead of a local socket. This is the default if your OS does not support local sockets.

If the Emacs server is set to use TCP, it will by default listen on a random port on the localhost interface. This can be changed to another interface and/or a fixed port using the variables server-host and server-port.

A TCP socket is not subject to file system permissions. To retain some control over which users can talk to an Emacs server over TCP sockets, the emacsclient program must send an authorization key to the server. This key is normally randomly generated by the Emacs server. This is the recommended mode of operation.

If needed, you can set the authorization key to a static value by setting the server-auth-key variable. The key must consist of 64 ASCII printable characters except for space (this means characters from ‘!’ to ‘~’, or from decimal code 33 to 126). You can use M-x server-generate-key to get a random key.

When you start a TCP Emacs server, Emacs creates a server file containing the TCP information to be used by emacsclient to connect to the server. The variable server-auth-dirspecifies the default directory containing the server file; by default, this is ~/.emacs.d/server/. In the absence of a local socket with file permissions, the permissions of this directory determine which users can have their emacsclient processes talk to the Emacs server. If server-name is an absolute file name, the server file is created where specified by that file name.

To tell emacsclient to connect to the server over TCP with a specific server file, use the ‘-f’ or ‘–server-file’ option, or set the EMACS_SERVER_FILE environment variable (see emacsclient Options). If server-auth-dir is set to a non-standard value, or if server-name is set to an absolute file name, emacsclient needs an absolute file name to the server file, as the default server-auth-dir is hard-coded in emacsclient to be used as the directory for resolving relative filenames.

39.2 Invoking emacsclient

The simplest way to use the emacsclient program is to run the shell command ‘emacsclient file’, where file is a file name. This connects to an Emacs server, and tells that Emacs process to visit file in one of its existing frames—either a graphical frame, or one in a text terminal (see Frames). You can then select that frame to begin editing.

If there is no Emacs server, the emacsclient program halts with an error message (you can prevent this from happening by using the ‘–alternate-editor=””’ option to emacsclient, see emacsclient Options). If the Emacs process has no existing frame—which can happen if it was started as a daemon (see Emacs Server)—then Emacs opens a frame on the terminal in which you called emacsclient.

You can also force emacsclient to open a new frame on a graphical display using the ‘-c’ option, or on a text terminal using the ‘-t’ option. See emacsclient Options.

If you are running on a single text terminal, you can switch between emacsclient’s shell and the Emacs server using one of two methods: (i) run the Emacs server and emacsclienton different virtual terminals, and switch to the Emacs server’s virtual terminal after calling emacsclient; or (ii) call emacsclient from within the Emacs server itself, using Shell mode (see Interactive Shell) or Term mode (see Term Mode); emacsclient blocks only the subshell under Emacs, and you can still use Emacs to edit the file.

When you finish editing file in the Emacs server, type C-x # (server-edit) in its buffer. This saves the file and sends a message back to the emacsclient program, telling it to exit. Programs that use EDITOR usually wait for the editor—in this case emacsclient—to exit before doing something else.

You can also call emacsclient with multiple file name arguments: ‘emacsclient file1 file2 …’ tells the Emacs server to visit file1, file2, and so forth. Emacs selects the buffer visiting file1, and buries the other buffers at the bottom of the buffer list (see Buffers). The emacsclient program exits once all the specified files are finished (i.e., once you have typed C-x # in each server buffer).

Finishing with a server buffer also kills the buffer, unless it already existed in the Emacs session before the server was asked to create it. However, if you set server-kill-new-buffers to nil, then a different criterion is used: finishing with a server buffer kills it if the file name matches the regular expression server-temp-file-regexp. This is set up to distinguish certain temporary files.

Each C-x # checks for other pending external requests to edit various files, and selects the next such file. You can switch to a server buffer manually if you wish; you don’t have to arrive at it with C-x #. But C-x # is the way to tell emacsclient that you are finished.

If you set the value of the variable server-window to a window or a frame, C-x # always displays the next server buffer in that window or in that frame.

39.3 emacsclient Options

You can pass some optional arguments to the emacsclient program, such as:

1
emacsclient -c +12 file1 +4:3 file2

The ‘+line’ or ‘+line:column’ arguments specify line numbers, or line and column numbers, for the next file argument. These behave like the command line arguments for Emacs itself. See Action Arguments.

The other optional arguments recognized by emacsclient are listed below:

  • ‘-a command’

  • ‘–alternate-editor=command’

    Specify a shell command to run if emacsclient fails to contact Emacs. This is useful when running emacsclient in a script. The command may include arguments, which may be quoted “like this”. Currently, escaping of quotes is not supported.As a special exception, if command is the empty string, then emacsclient starts Emacs in daemon mode (as ‘emacs –daemon’) and then tries connecting again.The environment variable ALTERNATE_EDITOR has the same effect as the ‘-a’ option. If both are present, the latter takes precedence.

  • ‘-c’

  • ‘–create-frame’

    Create a new graphical client frame, instead of using an existing Emacs frame. See below for the special behavior of C-x C-c in a client frame. If Emacs cannot create a new graphical frame (e.g., if it cannot connect to the X server), it tries to create a text terminal client frame, as though you had supplied the ‘-t’ option instead.On MS-Windows, a single Emacs session cannot display frames on both graphical and text terminals, nor on multiple text terminals. Thus, if the Emacs server is running on a text terminal, the ‘-c’ option, like the ‘-t’ option, creates a new frame in the server’s current text terminal. See Windows Startup.If you omit a filename argument while supplying the ‘-c’ option, the new frame displays the scratch buffer by default. You can customize this behavior with the variable initial-buffer-choice (see Entering Emacs).

  • ‘-F alist’

  • ‘–frame-parameters=alist’

    Set the parameters for a newly-created graphical frame (see Frame Parameters).

  • ‘-d display’

  • ‘–display=display’

    Tell Emacs to open the given files on the X display display (assuming there is more than one X display available).

  • ‘-e’

  • ‘–eval’

    Tell Emacs to evaluate some Emacs Lisp code, instead of visiting some files. When this option is given, the arguments to emacsclient are interpreted as a list of expressions to evaluate, not as a list of files to visit.

  • ‘-f server-file’

  • ‘–server-file=server-file’

    Specify a server file (see TCP Emacs server) for connecting to an Emacs server via TCP. Alternatively, you can set the EMACS_SERVER_FILE environment variable to point to the server file. (The command-line option overrides the environment variable.)An Emacs server usually uses a local socket to listen for connections, but also supports connections over TCP. To connect to a TCP Emacs server, emacsclient needs to read a server file containing the connection details of the Emacs server. The name of this file is specified with this option, either as a file name relative to ~/.emacs.d/server or as an absolute file name. See TCP Emacs server.

  • ‘-n’

  • ‘–no-wait’

    Let emacsclient exit immediately, instead of waiting until all server buffers are finished. You can take as long as you like to edit the server buffers within Emacs, and they are not killed when you type C-x # in them.

  • ‘–parent-id id’

    Open an emacsclient frame as a client frame in the parent X window with id id, via the XEmbed protocol. Currently, this option is mainly useful for developers.

  • ‘-q’

  • ‘–quiet’

    Do not let emacsclient display messages about waiting for Emacs or connecting to remote server sockets.

  • ‘-u’

  • ‘–suppress-output’

    Do not let emacsclient display results returned from the server. Mostly useful in combination with ‘-e’ when the evaluation performed is for side-effect rather than result.

  • ‘-s server-name’

  • ‘–socket-name=server-name’

    Connect to the Emacs server named server-name. (This option is not supported on MS-Windows.) The server name is given by the variable server-name on the Emacs server. If this option is omitted, emacsclient connects to the first server it finds. If you set server-name of the Emacs server to an absolute file name, give the same absolute file name as server-name to this option to instruct emacsclient to connect to that server.

  • ‘-t’

  • ‘–tty’

  • ‘-nw’

    Create a new client frame on the current text terminal, instead of using an existing Emacs frame. This behaves just like the ‘-c’ option, described above, except that it creates a text terminal frame (see Non-Window Terminals).On MS-Windows, ‘-t’ behaves just like ‘-c’ if the Emacs server is using the graphical display, but if the Emacs server is running on a text terminal, it creates a new frame in the current text terminal.

  • ‘-T tramp-prefix’

  • ‘–tramp-prefix=tramp-prefix’

    Set the prefix to add to filenames for Emacs to locate files on remote machines (see Remote Files) using TRAMP (see The Tramp Manual). This is mostly useful in combination with using the Emacs server over TCP (see TCP Emacs server). By ssh-forwarding the listening port and making the server-file available on a remote machine, programs on the remote machine can use emacsclient as the value for the EDITOR and similar environment variables, but instead of talking to an Emacs server on the remote machine, the files will be visited in the local Emacs session using TRAMP.Setting the environment variable EMACSCLIENT_TRAMP has the same effect as using the ‘-T’ option. If both are specified, the command-line option takes precedence.For example, assume two hosts, ‘local’ and ‘remote’, and that the local Emacs listens on tcp port 12345. Assume further that /home is on a shared file system, so that the server file ~/.emacs.d/server/server is readable on both hosts.

    1
    2
    3
    4
    5
    local$ ssh -R12345:localhost:12345 remote
    remote$ export EDITOR="emacsclient \
    --server-file=server \
    --tramp=/ssh:remote:"
    remote$ $EDITOR /tmp/foo.txt #Should open in local emacs.

The new graphical or text terminal frames created by the ‘-c’ or ‘-t’ options are considered client frames. Any new frame that you create from a client frame is also considered a client frame. If you type C-x C-c (save-buffers-kill-terminal) in a client frame, that command does not kill the Emacs session as it normally does (see Exiting). Instead, Emacs deletes the client frame; furthermore, if the client frame has an emacsclient waiting to regain control (i.e., if you did not supply the ‘-n’ option), Emacs deletes all other frames of the same client, and marks the client’s server buffers as finished, as though you had typed C-x # in all of them. If it so happens that there are no remaining frames after the client frame(s) are deleted, the Emacs session exits.

As an exception, when Emacs is started as a daemon, all frames are considered client frames, and C-x C-c never kills Emacs. To kill a daemon session, type M-x kill-emacs.

Note that the ‘-t’ and ‘-n’ options are contradictory: ‘-t’ says to take control of the current text terminal to create a new client frame, while ‘-n’ says not to take control of the text terminal. If you supply both options, Emacs visits the specified files(s) in an existing frame rather than a new client frame, negating the effect of ‘-t’.

40 Printing Hard Copies

Device的部分.

Emacs provides commands for printing hardcopies of either an entire buffer or part of one. You can invoke the printing commands directly, as detailed below, or using the ‘File’ menu on the menu bar.

Aside from the commands described in this section, you can also print hardcopies from Dired (see Operating on Files) and the diary (see Displaying the Diary). You can also “print” an Emacs buffer to HTML with the command M-x htmlfontify-buffer, which converts the current buffer to a HTML file, replacing Emacs faces with CSS-based markup. Furthermore, Org mode allows you to print Org files to a variety of formats, such as PDF (see Org Mode).

  • M-x print-buffer

    Print hardcopy of current buffer with page headings containing the file name and page number.

  • M-x lpr-buffer

    Print hardcopy of current buffer without page headings.

  • M-x print-region

    Like print-buffer but print only the current region.

  • M-x lpr-region

    Like lpr-buffer but print only the current region.

On most operating systems, the above hardcopy commands submit files for printing by calling the lpr program. To change the printer program, customize the variable lpr-command. To specify extra switches to give the printer program, customize the list variable lpr-switches. Its value should be a list of option strings, each of which should start with ‘-’ (e.g., the option string "-w80" specifies a line width of 80 columns). The default is the empty list, nil.

To specify the printer to use, set the variable printer-name. The default, nil, specifies the default printer. If you set it to a printer name (a string), that name is passed to lpr with the ‘-P’ switch; if you are not using lpr, you should specify the switch with lpr-printer-switch.

The variable lpr-headers-switches similarly specifies the extra switches to use to make page headers. The variable lpr-add-switches controls whether to supply ‘-T’ and ‘-J’ options (suitable for lpr) to the printer program: nil means don’t add them (this should be the value if your printer program is not compatible with lpr).

41 Sorting Text

Emacs provides several commands for sorting text in the buffer. All operate on the contents of the region. They divide the text of the region into many sort records, identify a sort key for each record, and then reorder the records into the order determined by the sort keys. The records are ordered so that their keys are in alphabetical order, or, for numeric sorting, in numeric order. In alphabetic sorting, all upper-case letters ‘A’ through ‘Z’ come before lower-case ‘a’, in accordance with the ASCII character sequence (but sort-fold-case, described below, can change that).

The various sort commands differ in how they divide the text into sort records and in which part of each record is used as the sort key. Most of the commands make each line a separate sort record, but some commands use paragraphs or pages as sort records. Most of the sort commands use each entire sort record as its own sort key, but some use only a portion of the record as the sort key.

  • M-x sort-lines

    Divide the region into lines, and sort by comparing the entire text of a line. A numeric argument means sort into descending order.

  • M-x sort-paragraphs

    Divide the region into paragraphs, and sort by comparing the entire text of a paragraph (except for leading blank lines). A numeric argument means sort into descending order.

  • M-x sort-pages

    Divide the region into pages, and sort by comparing the entire text of a page (except for leading blank lines). A numeric argument means sort into descending order.

  • M-x sort-fields

    Divide the region into lines, and sort by comparing the contents of one field in each line. Fields are defined as separated by whitespace, so the first run of consecutive non-whitespace characters in a line constitutes field 1, the second such run constitutes field 2, etc.Specify which field to sort by with a numeric argument: 1 to sort by field 1, etc.; the default is 1. A negative argument means count fields from the right instead of from the left; thus, minus 1 means sort by the last field. If several lines have identical contents in the field being sorted, they keep the same relative order that they had in the original buffer.

  • M-x sort-numeric-fields

    Like M-x sort-fields except the specified field is converted to an integer for each line, and the numbers are compared. ‘10’ comes before ‘2’ when considered as text, but after it when considered as a number. By default, numbers are interpreted according to sort-numeric-base, but numbers beginning with ‘0x’ or ‘0’ are interpreted as hexadecimal and octal, respectively.

  • M-x sort-columns

    Like M-x sort-fields except that the text within each line used for comparison comes from a fixed range of columns. With a prefix argument, sort in reverse order. See below for more details on this command.

  • M-x reverse-region

    Reverse the order of the lines in the region. This is useful for sorting into descending order by fields, since those sort commands do not have a feature for doing that.

For example, if the buffer contains this:

1
2
3
4
5
On systems where clash detection (locking of files being edited) is
implemented, Emacs also checks the first time you modify a buffer
whether the file has changed on disk since it was last visited or
saved. If it has, you are asked to confirm that you want to change
the buffer.

applying M-x sort-lines to the entire buffer produces this:

1
2
3
4
5
On systems where clash detection (locking of files being edited) is
implemented, Emacs also checks the first time you modify a buffer
saved. If it has, you are asked to confirm that you want to change
the buffer.
whether the file has changed on disk since it was last visited or

where the upper-case ‘O’ sorts before all lower-case letters. If you use C-u 2 M-x sort-fields instead, you get this:

1
2
3
4
5
implemented, Emacs also checks the first time you modify a buffer
saved. If it has, you are asked to confirm that you want to change
the buffer.
On systems where clash detection (locking of files being edited) is
whether the file has changed on disk since it was last visited or

where the sort keys were ‘Emacs’, ‘If’, ‘buffer’, ‘systems’ and ‘the’.

M-x sort-columns requires more explanation. You specify the columns by putting point at one of the columns and the mark at the other column. Because this means you cannot put point or the mark at the beginning of the first line of the text you want to sort, this command uses an unusual definition of “region”: all of the line point is in is considered part of the region, and so is all of the line the mark is in, as well as all the lines in between.

For example, to sort a table by information found in columns 10 to 15, you could put the mark on column 10 in the first line of the table, and point on column 15 in the last line of the table, and then run sort-columns. Equivalently, you could run it with the mark on column 15 in the first line and point on column 10 in the last line.

This can be thought of as sorting the rectangle specified by point and the mark, except that the text on each line to the left or right of the rectangle moves along with the text inside the rectangle. See Rectangles.

Many of the sort commands ignore case differences when comparing, if sort-fold-case is non-nil.

42 Editing Pictures

To edit a picture made out of text characters (for example, a picture of the division of a register into fields, as a comment in a program), use the command M-x picture-mode to enter Picture mode.

In Picture mode, editing is based on the quarter-plane model of text, according to which the text characters lie studded on an area that stretches infinitely far to the right and downward. The concept of the end of a line does not exist in this model; the most you can say is where the last nonblank character on the line is found.

Of course, Emacs really always considers text as a sequence of characters, and lines really do have ends. But Picture mode replaces the most frequently-used commands with variants that simulate the quarter-plane model of text. They do this by inserting spaces or by converting tabs to spaces.

Most of the basic editing commands of Emacs are redefined by Picture mode to do essentially the same thing but in a quarter-plane way. In addition, Picture mode defines various keys starting with the C-c prefix to run special picture editing commands.

One of these keys, C-c C-c, is particularly important. Often a picture is part of a larger file that is usually edited in some other major mode. Picture mode records the name of the previous major mode so you can use the C-c C-c command (picture-mode-exit) later to go back to that mode. C-c C-c also deletes spaces from the ends of lines, unless given a numeric argument.

The special commands of Picture mode all work in other modes (provided the picture library is loaded), but are not bound to keys except in Picture mode. The descriptions below talk of moving “one column” and so on, but all the picture mode commands handle numeric arguments as their normal equivalents do.

Turning on Picture mode runs the hook picture-mode-hook. Additional extensions to Picture mode can be found in artist.el.

43 Editing Binary Files

There is a special major mode for editing binary files: Hexl mode. To use it, use M-x hexl-find-file instead of C-x C-f to visit the file. This command converts the file’s contents to hexadecimal and lets you edit the translation. When you save the file, it is converted automatically back to binary.

You can also use M-x hexl-mode to translate an existing buffer into hex. This is useful if you visit a file normally and then discover it is a binary file.

Ordinary text characters overwrite in Hexl mode. This is to reduce the risk of accidentally spoiling the alignment of data in the file. There are special commands for insertion. Here is a list of the commands of Hexl mode:

  • C-M-d

    Insert a byte with a code typed in decimal.

  • C-M-o

    Insert a byte with a code typed in octal.

  • C-M-x

    Insert a byte with a code typed in hex.

  • C-x [

    Move to the beginning of a 1k-byte page.

  • C-x ]

    Move to the end of a 1k-byte page.

  • M-g

    Move to an address specified in hex.

  • M-j

    Move to an address specified in decimal.

  • C-c C-c

    Leave Hexl mode, going back to the major mode this buffer had before you invoked hexl-mode.

Other Hexl commands let you insert strings (sequences) of binary bytes, move by shorts or ints, etc.; type C-h a hexl- for details.

44 Saving Emacs Sessions

Use the desktop library to save the state of Emacs from one session to another. Once you save the Emacs desktop—the buffers, their file names, major modes, buffer positions, and so on—then subsequent Emacs sessions reload the saved desktop. By default, the desktop also tries to save the frame and window configuration. To disable this, set desktop-restore-frames to nil. (See that variable’s documentation for some related options that you can customize to fine-tune this behavior.)

Information about buffers visiting remote files is not saved by default. Customize the variable desktop-files-not-to-save to change this.

When the desktop restores the frame and window configuration, it uses the recorded values of frame parameters, disregarding any settings for those parameters you have in your init file (see Init File). This means that frame parameters such as fonts and faces for the restored frames will come from the desktop file, where they were saved when you exited your previous Emacs session; any settings for those parameters in your init file will be ignored. To disable this, customize the value of frameset-filter-alist to filter out the frame parameters you don’t want to be restored.

You can save the desktop manually with the command M-x desktop-save. You can also enable automatic saving of the desktop when you exit Emacs, and automatic restoration of the last saved desktop when Emacs starts: use the Customization buffer (see Easy Customization) to set desktop-save-mode to t for future sessions, or add this line in your init file (see Init File):

1
(desktop-save-mode 1)

If you turn on desktop-save-mode in your init file, then when Emacs starts, it looks for a saved desktop in the current directory. (More precisely, it looks in the directories specified by desktop-path, and uses the first desktop it finds.) Thus, you can have separate saved desktops in different directories, and the starting directory determines which one Emacs reloads. You can save the current desktop and reload one saved in another directory by typing M-x desktop-change-dir. Typing M-x desktop-revert reverts to the desktop previously reloaded.

Specify the option ‘–no-desktop’ on the command line when you don’t want it to reload any saved desktop. This turns off desktop-save-mode for the current session. Starting Emacs with the ‘–no-init-file’ option also disables desktop reloading, since it bypasses the init file, where desktop-save-mode is usually turned on.

By default, all the buffers in the desktop are restored in one go. However, this may be slow if there are a lot of buffers in the desktop. You can specify the maximum number of buffers to restore immediately with the variable desktop-restore-eager; the remaining buffers are restored lazily, when Emacs is idle.

Type M-x desktop-clear to empty the Emacs desktop. This kills all buffers except for internal ones, and clears the global variables listed in desktop-globals-to-clear. If you want this to preserve certain buffers, customize the variable desktop-clear-preserve-buffers-regexp, whose value is a regular expression matching the names of buffers not to kill.

If you want to save minibuffer history from one session to another, use the savehist library.

While Emacs runs with desktop-save-mode turned on, it by default auto-saves the desktop whenever any of it changes. The variable desktop-auto-save-timeout determines how frequently Emacs checks for modifications to your desktop.

The file in which Emacs saves the desktop is locked while the session runs, to avoid inadvertently overwriting it from another Emacs session. That lock is normally removed when Emacs exits, but if Emacs or your system crashes, the lock stays, and when you restart Emacs, it will by default ask you whether to use the locked desktop file. You can avoid the question by customizing the variable desktop-load-locked-desktop to either nil, which means never load the desktop in this case, or t, which means load the desktop without asking.

When Emacs starts in daemon mode, it cannot ask you any questions, so if it finds the desktop file locked, it will not load it, unless desktop-load-locked-desktop is t. Note that restoring the desktop in daemon mode is somewhat problematic for other reasons: e.g., the daemon cannot use GUI features, so parameters such as frame position, size, and decorations cannot be restored. For that reason, you may wish to delay restoring the desktop in daemon mode until the first client connects, by calling desktop-read in a hook function that you add to after-make-frame-functions (see Creating Frames).

45 Recursive Editing Levels

A recursive edit is a situation in which you are using Emacs commands to perform arbitrary editing while in the middle of another Emacs command. For example, when you type C-rinside of a query-replace, you enter a recursive edit in which you can change the current buffer. On exiting from the recursive edit, you go back to the query-replace. See Query Replace.

Exiting the recursive edit means returning to the unfinished command, which continues execution. The command to exit is C-M-c (exit-recursive-edit).

You can also abort the recursive edit. This is like exiting, but also quits the unfinished command immediately. Use the command C-] (abort-recursive-edit) to do this. See Quitting.

The mode line shows you when you are in a recursive edit by displaying square brackets around the parentheses that always surround the major and minor mode names. Every window’s mode line shows this in the same way, since being in a recursive edit is true of Emacs as a whole rather than any particular window or buffer.

It is possible to be in recursive edits within recursive edits. For example, after typing C-r in a query-replace, you may type a command that enters the debugger. This begins a recursive editing level for the debugger, within the recursive editing level for C-r. Mode lines display a pair of square brackets for each recursive editing level currently in progress.

Exiting the inner recursive edit (such as with the debugger c command) resumes the command running in the next level up. When that command finishes, you can then use C-M-c to exit another recursive editing level, and so on. Exiting applies to the innermost level only. Aborting also gets out of only one level of recursive edit; it returns immediately to the command level of the previous recursive edit. If you wish, you can then abort the next recursive editing level.

Alternatively, the command M-x top-level aborts all levels of recursive edits, returning immediately to the top-level command reader. It also exits the minibuffer, if it is active.

The text being edited inside the recursive edit need not be the same text that you were editing at top level. It depends on what the recursive edit is for. If the command that invokes the recursive edit selects a different buffer first, that is the buffer you will edit recursively. In any case, you can switch buffers within the recursive edit in the normal manner (as long as the buffer-switching keys have not been rebound). You could probably do all the rest of your editing inside the recursive edit, visiting files and all. But this could have surprising effects (such as stack overflow) from time to time. So remember to exit or abort the recursive edit when you no longer need it.

In general, we try to minimize the use of recursive editing levels in GNU Emacs. This is because they constrain you to go back in a particular order—from the innermost level toward the top level. When possible, we present different activities in separate buffers so that you can switch between them as you please. Some commands switch to a new major mode which provides a command to switch back. These approaches give you more flexibility to go back to unfinished tasks in the order you choose.

46 Hyperlinking and Web Navigation Features

The following subsections describe convenience features for handling URLs and other types of links occurring in Emacs buffer text.

47 Games and Other Amusements

The animate package makes text dance (e.g., M-x animate-birthday-present).

M-x blackbox, M-x mpuz and M-x 5x5 are puzzles. blackbox challenges you to determine the location of objects inside a box by tomography. mpuz displays a multiplication puzzle with letters standing for digits in a code that you must guess—to guess a value, type a letter and then the digit you think it stands for. The aim of 5x5 is to fill in all the squares.

M-x bubbles is a game in which the object is to remove as many bubbles as you can in the smallest number of moves.

M-x decipher helps you to cryptanalyze a buffer which is encrypted in a simple monoalphabetic substitution cipher.

M-x dissociated-press scrambles the text in the current Emacs buffer, word by word or character by character, writing its output to a buffer named Dissociation. A positive argument tells it to operate character by character, and specifies the number of overlap characters. A negative argument tells it to operate word by word, and specifies the number of overlap words. Dissociated Press produces results fairly like those of a Markov chain, but is however, an independent, ignoriginal invention; it techniquitously copies several consecutive characters from the sample text between random jumps, unlike a Markov chain which would jump randomly after each word or character. Keep dissociwords out of your documentation, if you want it to be well userenced and properbose.

M-x dunnet runs a text-based adventure game.

If you want a little more personal involvement, try M-x gomoku, which plays the game Go Moku with you.

If you are a little bit bored, you can try M-x hanoi. If you are considerably bored, give it a numeric argument. If you are very, very bored, try an argument of 9. Sit back and watch.

M-x life runs Conway’s Game of Life cellular automaton.

M-x morse-region converts the text in the region to Morse code; M-x unmorse-region converts it back. M-x nato-region converts the text in the region to NATO phonetic alphabet; M-x denato-region converts it back.

M-x pong, M-x snake and M-x tetris are implementations of the well-known Pong, Snake and Tetris games.

M-x solitaire plays a game of solitaire in which you jump pegs across other pegs.

The command M-x zone plays games with the display when Emacs is idle.

“Real Programmers” deploy M-x butterfly, which uses butterflies to flip a bit on the drive platter, see https://xkcd.com/378.

Finally, if you find yourself frustrated, try describing your problems to the famous psychotherapist Eliza. Just do M-x doctor. End each input by typing twice.

48 Emacs Lisp Packages

Emacs includes a facility that lets you easily download and install packages that implement additional features. Each package is a separate Emacs Lisp program, sometimes including other components such as an Info manual.

M-x list-packages brings up a buffer named Packages with a list of all packages. You can install or uninstall packages via this buffer. See Package Menu.

The command C-h P (describe-package) prompts for the name of a package, and displays a help buffer describing the attributes of the package and the features that it implements.

By default, Emacs downloads packages from a package archive maintained by the Emacs developers and hosted by the GNU project. Optionally, you can also download packages from archives maintained by third parties. See Package Installation.

For information about turning an Emacs Lisp program into an installable package, See Packaging.

49 Customization

This chapter describes some simple methods to customize the behavior of Emacs.

Apart from the methods described here, see X Resources for information about using X resources to customize Emacs, and see Keyboard Macros for information about recording and replaying keyboard macros. Making more far-reaching and open-ended changes involves writing Emacs Lisp code; see Emacs Lisp.

  • Easy Customization: Convenient way to browse and change settings.
  • Variables: Many Emacs commands examine Emacs variables to decide what to do; by setting variables, you can control their functioning.
  • Key Bindings: The keymaps say what command each key runs. By changing them, you can redefine keys.
  • Init File: How to write common customizations in the initialization file.
  • Authentication: Keeping persistent authentication information.

49.4 The Emacs Initialization File

When Emacs is started, it normally tries to load a Lisp program from an initialization file, or init file for short. This file, if it exists, specifies how to initialize Emacs for you. Emacs looks for your init file using the filenames ~/.emacs, ~/.emacs.el, or ~/.emacs.d/init.el; you can choose to use any one of these three names (see Find Init). Here, ~/ stands for your home directory.

You can use the command line switch ‘-q’ to prevent loading your init file, and ‘-u’ (or ‘–user’) to specify a different user’s init file (see Initial Options).

There can also be a default init file, which is the library named default.el, found via the standard search path for libraries. The Emacs distribution contains no such library; your site may create one for local customizations. If this library exists, it is loaded whenever you start Emacs (except when you specify ‘-q’). But your init file, if any, is loaded first; if it setsinhibit-default-init non-nil, then default is not loaded.

Your site may also have a site startup file; this is named site-start.el, if it exists. Like default.el, Emacs finds this file via the standard search path for Lisp libraries. Emacs loads this library before it loads your init file. To inhibit loading of this library, use the option ‘–no-site-file’. See Initial Options. We recommend against using site-start.elfor changes that some users may not like. It is better to put them in default.el, so that users can more easily override them.

You can place default.el and site-start.el in any of the directories which Emacs searches for Lisp libraries. The variable load-path (see Lisp Libraries) specifies these directories. Many sites put these files in a subdirectory named site-lisp in the Emacs installation directory, such as /usr/local/share/emacs/site-lisp.

Byte-compiling your init file is not recommended (see Byte Compilation). It generally does not speed up startup very much, and often leads to problems when you forget to recompile the file. A better solution is to use the Emacs server to reduce the number of times you have to start Emacs (see Emacs Server). If your init file defines many functions, consider moving them to a separate (byte-compiled) file that you load in your init file.

If you are going to write actual Emacs Lisp programs that go beyond minor customization, you should read the Emacs Lisp Reference Manual. See Emacs Lisp.

50 Quitting and Aborting

  • C-g

  • C- (MS-DOS only)

    Quit: cancel running or partially typed command.

  • C-]

    Abort innermost recursive editing level and cancel the command which invoked it (abort-recursive-edit).

  • Either quit or abort, whichever makes sense (keyboard-escape-quit).

  • M-x top-level

    Abort all recursive editing levels that are currently executing.

  • C-/

  • C-x u

  • C-_

    Cancel a previously made change in the buffer contents (undo).

There are two ways of canceling a command before it has finished: quitting with C-g, and aborting with C-] or M-x top-level. Quitting cancels a partially typed command, or one which is still running. Aborting exits a recursive editing level and cancels the command that invoked the recursive edit (see Recursive Edit).

Quitting with C-g is the way to get rid of a partially typed command, or a numeric argument that you don’t want. Furthermore, if you are in the middle of a command that is running, C-g stops the command in a relatively safe way. For example, if you quit out of a kill command that is taking a long time, either your text will all still be in the buffer, or it will all be in the kill ring, or maybe both. If the region is active, C-g deactivates the mark, unless Transient Mark mode is off (see Disabled Transient Mark). If you are in the middle of an incremental search, C-g behaves specially; it may take two successive C-g characters to get out of a search. See Incremental Search, for details.

On MS-DOS, the character C- serves as a quit character like C-g. The reason is that it is not feasible, on MS-DOS, to recognize C-g while a command is running, between interactions with the user. By contrast, it is feasible to recognize C- at all times. See MS-DOS Keyboard.

C-g works by setting the variable quit-flag to t the instant C-g is typed; Emacs Lisp checks this variable frequently, and quits if it is non-nil. C-g is only actually executed as a command if you type it while Emacs is waiting for input. In that case, the command it runs is keyboard-quit.

On a text terminal, if you quit with C-g a second time before the first C-g is recognized, you activate the emergency-escape feature and return to the shell. See Emergency Escape.

There are some situations where you cannot quit. When Emacs is waiting for the operating system to do something, quitting is impossible unless special pains are taken for the particular system call within Emacs where the waiting occurs. We have done this for the system calls that users are likely to want to quit from, but it’s possible you will encounter a case not handled. In one very common case—waiting for file input or output using NFS—Emacs itself knows how to quit, but many NFS implementations simply do not allow user programs to stop waiting for NFS when the NFS server is hung.

Aborting with C-] (abort-recursive-edit) is used to get out of a recursive editing level and cancel the command which invoked it. Quitting with C-g does not do this, and could not do this, because it is used to cancel a partially typed command within the recursive editing level. Both operations are useful. For example, if you are in a recursive edit and type C-u 8to enter a numeric argument, you can cancel that argument with C-g and remain in the recursive edit.

The sequence (keyboard-escape-quit) can either quit or abort. (We defined it this way because means “get out” in many PC programs.) It can cancel a prefix argument, clear a selected region, or get out of a Query Replace, like C-g. It can get out of the minibuffer or a recursive edit, like C-]. It can also get out of splitting the frame into multiple windows, as with C-x 1. One thing it cannot do, however, is stop a command that is running. That’s because it executes as an ordinary command, and Emacs doesn’t notice it until it is ready for the next command.

The command M-x top-level is equivalent to enough C-] commands to get you out of all the levels of recursive edits that you are in; it also exits the minibuffer if it is active. C-]gets you out one level at a time, but M-x top-level goes out all levels at once. Both C-] and M-x top-level are like all other commands, and unlike C-g, in that they take effect only when Emacs is ready for a command. C-] is an ordinary key and has its meaning only because of its binding in the keymap. See Recursive Edit.

C-/ (undo) is not strictly speaking a way of canceling a command, but you can think of it as canceling a command that already finished executing. See Undo, for more information about the undo facility.