"Fossies" - the Fresh Open Source Software Archive

Member "emacs-26.1/doc/emacs/emacs.texi" (23 Apr 2018, 73734 Bytes) of package /linux/misc/emacs-26.1.tar.xz:


Caution: As a special service "Fossies" has tried to format the requested Texinfo source page into HTML format but that may be not always succeeeded perfectly. Alternatively you can here view or download the uninterpreted Texinfo source code. A member file download can also be achieved by clicking within a package contents listing on the according byte size field. See also the latest Fossies "Diffs" side-by-side code changes report for "emacs.texi": 25.3_vs_26.1.







GNU Emacs Manual





Seventeenth Edition, Updated for Emacs Version 26.1.






Richard Stallman et al.

This is the GNU Emacs Manual, updated for Emacs version 26.1.

Copyright © 1985–1987, 1993–2018 Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being “The GNU Manifesto,” “Distribution” and “GNU GENERAL PUBLIC LICENSE,” with the Front-Cover Texts being “A GNU Manual,” and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled “GNU Free Documentation License.”

(a) The FSF’s Back-Cover Text is: “You have the freedom to copy and modify this GNU manual. Buying copies from the FSF supports it in developing GNU and promoting software freedom.”



Published by the Free Software Foundation
51 Franklin Street, Fifth Floor
Boston, MA 02110-1301 USA
ISBN 978-0-9831592-5-4



Cover art by Etienne Suvasa; cover design by Matt Lee.


[ < ] [ > ]   [Contents] [Index] [ ? ]

The Emacs Editor

Emacs is the extensible, customizable, self-documenting real-time display editor. This manual describes how to edit with Emacs and some of the ways to customize it; it corresponds to GNU Emacs version 26.1.

For information on extending Emacs, see Emacs Lisp in The Emacs Lisp Reference Manual.

This is the GNU Emacs Manual, updated for Emacs version 26.1.

Copyright © 1985–1987, 1993–2018 Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being “The GNU Manifesto,” “Distribution” and “GNU GENERAL PUBLIC LICENSE,” with the Front-Cover Texts being “A GNU Manual,” and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled “GNU Free Documentation License.”

(a) The FSF’s Back-Cover Text is: “You have the freedom to copy and modify this GNU manual. Buying copies from the FSF supports it in developing GNU and promoting software freedom.”


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Distribution

GNU Emacs is free software; this means that everyone is free to use it and free to redistribute it under certain conditions. GNU Emacs is not in the public domain; it is copyrighted and there are restrictions on its distribution, but these restrictions are designed to permit everything that a good cooperating citizen would want to do. What is not allowed is to try to prevent others from further sharing any version of GNU Emacs that they might get from you. The precise conditions are found in the GNU General Public License that comes with Emacs and also appears in this manual(1). See section GNU GENERAL PUBLIC LICENSE.

One way to get a copy of GNU Emacs is from someone else who has it. You need not ask for our permission to do so, or tell anyone else; just copy it. If you have access to the Internet, you can get the latest distribution version of GNU Emacs by anonymous FTP; see https://www.gnu.org/software/emacs on our website for more information.

You may also receive GNU Emacs when you buy a computer. Computer manufacturers are free to distribute copies on the same terms that apply to everyone else. These terms require them to give you the full sources, including whatever changes they may have made, and to permit you to redistribute the GNU Emacs received from them under the usual terms of the General Public License. In other words, the program must be free for you when you get it, not just free for the manufacturer.

If you find GNU Emacs useful, please send a donation to the Free Software Foundation to support our work. Donations to the Free Software Foundation are tax-deductible in the US. If you use GNU Emacs at your workplace, please suggest that the company make a donation. To donate, see https://my.fsf.org/donate/. For other ways in which you can help, see https://www.gnu.org/help/help.html.

We also sell hardcopy versions of this manual and An Introduction to Programming in Emacs Lisp, by Robert J. Chassell. You can visit our online store at https://shop.fsf.org/. The income from sales goes to support the foundation’s purpose: the development of new free software, and improvements to our existing programs including GNU Emacs.

If you need to contact the Free Software Foundation, see https://www.fsf.org/about/contact/, or write to

Free Software Foundation
51 Franklin Street, Fifth Floor
Boston, MA 02110-1301
USA

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section 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 section Manipulating 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 section 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 Preface in An Introduction to Programming in Emacs Lisp, if you want to learn Emacs Lisp programming.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section Frames and Graphical Displays).

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 section Multiple 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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1 Point

The cursor in the selected window shows the location where most editing commands take effect, which is called point(2). Many Emacs commands move point to different places in the buffer; for example, you can place point by clicking mouse button 1 (normally the left button) at the desired location.

By default, the cursor in the selected window is drawn as a solid block and appears to be on a character, but you should think of point as between two characters; it is situated before the character under the cursor. For example, if your text looks like ‘frob’ with the cursor over the ‘b’, then point is between the ‘o’ and the ‘b’. If you insert the character ‘!’ at that position, the result is ‘fro!b’, with point between the ‘!’ and the ‘b’. Thus, the cursor remains over the ‘b’, as before.

If you are editing several files in Emacs, each in its own buffer, each buffer has its own value of point. A buffer that is not currently displayed remembers its value of point if you later display it again. Furthermore, if a buffer is displayed in multiple windows, each of those windows has its own value of point.

See section Displaying the Cursor, for options that control how Emacs displays the cursor.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2 The Echo Area

The line at the very bottom of the frame is the echo area. It is used to display small amounts of text for various purposes.

The echo area is so-named because one of the things it is used for is echoing, which means displaying the characters of a multi-character command as you type. Single-character commands are not echoed. Multi-character commands (see section Keys) are echoed if you pause for more than a second in the middle of a command. Emacs then echoes all the characters of the command so far, to prompt you for the rest. Once echoing has started, the rest of the command echoes immediately as you type it. This behavior is designed to give confident users fast response, while giving hesitant users maximum feedback.

The echo area is also used to display an error message when a command cannot do its job. Error messages may be accompanied by beeping or by flashing the screen.

Some commands display informative messages in the echo area to tell you what the command has done, or to provide you with some specific information. These informative messages, unlike error messages, are not accompanied with a beep or flash. For example, C-x = (hold down <Ctrl> and type x, then let go of <Ctrl> and type =) displays a message describing the character at point, its position in the buffer, and its current column in the window. Commands that take a long time often display messages ending in ‘...’ while they are working (sometimes also indicating how much progress has been made, as a percentage), and add ‘done’ when they are finished.

Informative echo area messages are saved in a special buffer named ‘*Messages*’. (We have not explained buffers yet; see Using Multiple Buffers, for more information about them.) If you miss a message that appeared briefly on the screen, you can switch to the ‘*Messages*’ buffer to see it again. The ‘*Messages*’ buffer is limited to a certain number of lines, specified by the variable message-log-max. (We have not explained variables either; see Variables, for more information about them.) Beyond this limit, one line is deleted from the beginning whenever a new message line is added at the end.

See section Customization of Display, for options that control how Emacs uses the echo area.

The echo area is also used to display the minibuffer, a special window where you can input arguments to commands, such as the name of a file to be edited. When the minibuffer is in use, the text displayed in the echo area begins with a prompt string, and the active cursor appears within the minibuffer, which is temporarily considered the selected window. You can always get out of the minibuffer by typing C-g. See section The Minibuffer.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3 The Mode Line

At the bottom of each window is a mode line, which describes what is going on in the current buffer. When there is only one window, the mode line appears right above the echo area; it is the next-to-last line in the frame. On a graphical display, the mode line is drawn with a 3D box appearance. Emacs also usually draws the mode line of the selected window with a different color than that of unselected windows, in order to make it stand out.

The text displayed in the mode line has the following format:

 cs:ch-fr  buf      pos line   (major minor)

On a text terminal, this text is followed by a series of dashes extending to the right edge of the window. These dashes are omitted on a graphical display.

The cs string and the colon character after it describe the character set and newline convention used for the current buffer. Normally, Emacs automatically handles these settings for you, but it is sometimes useful to have this information.

cs describes the character set of the text in the buffer (see section Coding Systems). If it is a dash (‘-’), that indicates no special character set handling (with the possible exception of end-of-line conventions, described in the next paragraph). ‘=’ means no conversion whatsoever, and is usually used for files containing non-textual data. Other characters represent various coding systems—for example, ‘1’ represents ISO Latin-1.

On a text terminal, cs is preceded by two additional characters that describe the coding systems for keyboard input and terminal output. Furthermore, if you are using an input method, cs is preceded by a string that identifies the input method (see section Input Methods).

The character after cs is usually a colon. If a different string is displayed, that indicates a nontrivial end-of-line convention for encoding a file. Usually, lines of text are separated by newline characters in a file, but two other conventions are sometimes used. The MS-DOS convention uses a carriage return character followed by a linefeed character; when editing such files, the colon changes to either a backslash (‘\’) or ‘(DOS)’, depending on the operating system. Another convention, employed by older Macintosh systems, uses a carriage return character instead of a newline; when editing such files, the colon changes to either a forward slash (‘/’) or ‘(Mac)’. On some systems, Emacs displays ‘(Unix)’ instead of the colon for files that use newline as the line separator.

On frames created for emacsclient (see section Invoking emacsclient), the next character is ‘@’. This indication is typical for frames of an Emacs process running as a daemon (see section Using Emacs as a Server).

The next element on the mode line is the string indicated by ch. This shows two dashes (‘--’) if the buffer displayed in the window has the same contents as the corresponding file on the disk; i.e., if the buffer is unmodified. If the buffer is modified, it shows two stars (‘**’). For a read-only buffer, it shows ‘%*’ if the buffer is modified, and ‘%%’ otherwise.

The character after ch is normally a dash (‘-’). However, if default-directory (see section File Names) for the current buffer is on a remote machine, ‘@’ is displayed instead.

fr gives the selected frame name (see section Frames and Graphical Displays). It appears only on text terminals. The initial frame’s name is ‘F1’.

buf is the name of the buffer displayed in the window. Usually, this is the same as the name of a file you are editing. See section Using Multiple Buffers.

pos tells you whether there is additional text above the top of the window, or below the bottom. If your buffer is small and all of it is visible in the window, pos is ‘All’. Otherwise, it is ‘Top’ if you are looking at the beginning of the buffer, ‘Bot’ if you are looking at the end of the buffer, or ‘nn%’, where nn is the percentage of the buffer above the top of the window. With Size Indication mode, you can display the size of the buffer as well. See section Optional Mode Line Features.

line is the character ‘L’ followed by the line number at point. (You can display the current column number too, by turning on Column Number mode. See section Optional Mode Line Features.)

major is the name of the major mode used in the buffer. A major mode is a principal editing mode for the buffer, such as Text mode, Lisp mode, C mode, and so forth. See section Major Modes. Some major modes display additional information after the major mode name. For example, Compilation buffers and Shell buffers display the status of the subprocess.

minor is a list of some of the enabled minor modes, which are optional editing modes that provide additional features on top of the major mode. See section Minor Modes.

Some features are listed together with the minor modes whenever they are turned on, even though they are not really minor modes. ‘Narrow’ means that the buffer being displayed has editing restricted to only a portion of its text (see section Narrowing). ‘Def’ means that a keyboard macro is currently being defined (see section Keyboard Macros).

In addition, if Emacs is inside a recursive editing level, square brackets (‘[…]’) appear around the parentheses that surround the modes. If Emacs is in one recursive editing level within another, double square brackets appear, and so on. Since recursive editing levels affect Emacs globally, such square brackets appear in the mode line of every window. See section Recursive Editing Levels.

You can change the appearance of the mode line as well as the format of its contents. See section Optional Mode Line Features. In addition, the mode line is mouse-sensitive; clicking on different parts of the mode line performs various commands. See section Mode Line Mouse Commands. Also, hovering the mouse pointer above mouse-sensitive portions of the mode line shows tooltips (see section Tooltips) with information about commands you can invoke by clicking on the mode line.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4 The Menu Bar

Each Emacs frame normally has a menu bar at the top which you can use to perform common operations. There’s no need to list them here, as you can more easily see them yourself.

On a display that supports a mouse, you can use the mouse to choose a command from the menu bar. An arrow on the right edge of a menu item means it leads to a subsidiary menu, or submenu. A ‘...’ at the end of a menu item means that the command will prompt you for further input before it actually does anything.

Some of the commands in the menu bar have ordinary key bindings as well; if so, a key binding is shown after the item itself. To view the full command name and documentation for a menu item, type C-h k, and then select the menu bar with the mouse in the usual way (see section Documentation for a Key).

Instead of using the mouse, you can also invoke the first menu bar item by pressing <F10> (to run the command menu-bar-open). You can then navigate the menus with the arrow keys or with C-b, C-f (left/right), C-p, and C-n (up/down). To activate a selected menu item, press <RET>; to cancel menu navigation, press C-g or <ESC> <ESC> <ESC>. (However, note that when Emacs was built with a GUI toolkit, the menus are drawn and controlled by the toolkit, and the key sequences to cancel menu navigation might be different from the above description.)

On a text terminal, you can optionally access the menu-bar menus in the echo area. To this end, customize the variable tty-menu-open-use-tmm to a non-nil value. Then typing <F10> will run the command tmm-menubar instead of dropping down the menu. (You can also type M-`, which always invokes tmm-menubar.) tmm-menubar lets you select a menu item with the keyboard. A provisional choice appears in the echo area. You can use the up and down arrow keys to move through the menu to different items, and then you can type <RET> to select the item. Each menu item is also designated by a letter or digit (usually the initial of some word in the item’s name). This letter or digit is separated from the item name by ‘==>’. You can type the item’s letter or digit to select the item.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 <SPC>), are entered by typing the corresponding key. Control characters, such as <RET>, <TAB>, <DEL>, <ESC>, <F1>, <Home>, and <LEFT>, are also entered this way, as are certain characters found on non-English keyboards (see section International Character Set Support).

Emacs also recognizes control characters that are entered using modifier keys. Two commonly-used modifier keys are <Control> (usually labeled <Ctrl>), and <Meta> (usually labeled <Alt>)(3). For example, Control-a is entered by holding down the <Ctrl> key while pressing a; we will refer to this as C-a for short. Similarly, <Meta>-a, or M-a for short, is entered by holding down the <Alt> key and pressing a. Modifier keys can also be applied to non-alphanumerical characters, e.g., C-<F1> or M-<LEFT>.

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

On graphical displays, the window manager might block some keyboard inputs, including M-<TAB>, M-<SPC>, 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 section 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 in The Emacs Lisp Reference Manual.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section The 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 <RET>, C-x @, C-x a, C-x n, C-x r, C-x v, C-x 4, C-x 5, C-x 6, <ESC>, M-g, and M-o. (<F1> and <F2> 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 section Customizing Key Bindings.

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


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 in The Emacs Lisp Reference Manual.

The bindings between keys and commands are recorded in tables called keymaps. See section 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 section Variables) and the information about specific variables will make sense.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 How to Start Emacs on MS-Windows.)

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 <RET>, 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 section Multiple 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 section File Handling, 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 section Using Emacs as a 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 section Command Line Arguments for 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 section Lisp Interaction Buffers. You can set the variable inhibit-startup-screen using the Customize facility (see section Easy Customization Interface), or by editing your initialization file (see section The Emacs Initialization File).(4)

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section Running Shell Commands from Emacs).

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 section Using Emacs as a 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 section 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 in The GNU Emacs Lisp Reference Manual.

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 section Keymaps).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.1 Inserting Text

You can insert an ordinary graphic character (e.g., ‘a’, ‘B’, ‘3’, and ‘=’) by typing the associated key. This adds the character to the buffer at point. Insertion moves point forward, so that point remains just after the inserted text. See section Point.

To end a line and start a new one, type <RET> (newline). (The <RET> key may be labeled <Return>, or <Enter>, or with a funny-looking left-pointing arrow on your keyboard, but we refer to it as <RET> in this manual.) This command inserts a newline character into the buffer, then indents (see section Indentation) according to the major mode. If point is at the end of the line, the effect is to create a new blank line after it and indent the new line; if point is in the middle of a line, the line is split at that position. To turn off the auto-indentation, you can either disable Electric Indent mode (see section Convenience Features for Indentation) or type C-j, which inserts just a newline, without any auto-indentation.

As we explain later in this manual, you can change the way Emacs handles text insertion by turning on minor modes. For instance, the minor mode called Auto Fill mode splits lines automatically when they get too long (see section Filling Text). The minor mode called Overwrite mode causes inserted characters to replace (overwrite) existing text, instead of shoving it to the right. See section Minor Modes.

Only graphic characters can be inserted by typing the associated key; other keys act as editing commands and do not insert themselves. For instance, <DEL> runs the command delete-backward-char by default (some modes bind it to a different command); it does not insert a literal ‘DEL’ character (ASCII character code 127).

To insert a non-graphic character, or a character that your keyboard does not support, first quote it by typing C-q (quoted-insert). There are two ways to use C-q:

To use decimal or hexadecimal instead of octal, set the variable read-quoted-char-radix to 10 or 16. If the radix is 16, the letters a to f serve as part of a character code, just like digits. Case is ignored.

A few common Unicode characters can be inserted via a command starting with C-x 8. For example, C-x 8 [ inserts which is Unicode code-point U+2018 LEFT SINGLE QUOTATION MARK, sometimes called a left single “curved quote” or “curly quote”. Similarly, C-x 8 ], C-x 8 { and C-x 8 } insert the curved quotes , and , respectively. Also, a working Alt key acts like C-x 8; e.g., A-[ acts like C-x 8 [ and inserts ‘. To see which characters have C-x 8 shorthands, type C-x 8 C-h.

Alternatively, you can use the command C-x 8 <RET> (insert-char). This prompts for the Unicode name or code-point of a character, using the minibuffer. If you enter a name, the command provides completion (see section Completion). If you enter a code-point, it should be as a hexadecimal number (the convention for Unicode), or a number with a specified radix, e.g., #o23072 (octal); See Integer Basics in The Emacs Lisp Reference Manual. The command then inserts the corresponding character into the buffer.

For example, the following all insert the same character:

C-x 8 <RET> left single quotation mark <RET>
C-x 8 <RET> left sin <TAB> <RET>
C-x 8 <RET> 2018 <RET>
C-x 8 [
A-[  (if the Alt key works)
`    (in Electric Quote mode)

A numeric argument to C-q or C-x 8 ... specifies how many copies of the character to insert (see section Numeric Arguments).

In addition, in some contexts, if you type a quotation using grave accent and apostrophe ‘like this’, it is converted to a form ‘like this’ using single quotation marks, even without C-x 8 commands. Similarly, typing a quotation “like this” using double grave accent and apostrophe converts it to a form “like this” using double quotation marks. See section Quotation Marks.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.2 Changing the Location of Point

To do more than insert characters, you have to know how to move point (see section Point). The keyboard commands C-f, C-b, C-n, and C-p move point to the right, left, down, and up, respectively. You can also move point using the arrow keys present on most keyboards: <RIGHT>, <LEFT>, <DOWN>, and <UP>; however, many Emacs users find that it is slower to use the arrow keys than the control keys, because you need to move your hand to the area of the keyboard where those keys are located.

You can also click the left mouse button to move point to the position clicked. Emacs also provides a variety of additional keyboard commands that move point in more sophisticated ways.

C-f

Move forward one character (forward-char).

<RIGHT>

This command (right-char) behaves like C-f, except when point is in a right-to-left paragraph (see section Bidirectional Editing).

C-b

Move backward one character (backward-char).

<LEFT>

This command (left-char) behaves like C-b, except if the current paragraph is right-to-left (see section Bidirectional Editing).

C-n
<DOWN>

Move down one screen line (next-line). This command attempts to keep the horizontal position unchanged, so if you start in the middle of one line, you move to the middle of the next.

C-p
<UP>

Move up one screen line (previous-line). This command preserves position within the line, like C-n.

C-a
<Home>

Move to the beginning of the line (move-beginning-of-line).

C-e
<End>

Move to the end of the line (move-end-of-line).

M-f

Move forward one word (forward-word). See section Words.

C-<RIGHT>
M-<RIGHT>

This command (right-word) behaves like M-f, except it moves backward by one word if the current paragraph is right-to-left. See section Bidirectional Editing.

M-b

Move backward one word (backward-word). See section Words.

C-<LEFT>
M-<LEFT>

This command (left-word) behaves like M-b, except it moves forward by one word if the current paragraph is right-to-left. See section Bidirectional Editing.

M-r

Without moving the text on the screen, reposition point on the left margin of the center-most text line of the window; on subsequent consecutive invocations, move point to the left margin of the top-most line, the bottom-most line, and so forth, in cyclic order (move-to-window-line-top-bottom).

A numeric argument says which screen line to place point on, counting downward from the top of the window (zero means the top line). A negative argument counts lines up from the bottom (-1 means the bottom line). See section Numeric Arguments, for more information on numeric arguments.

M-<

Move to the top of the buffer (beginning-of-buffer). With numeric argument n, move to n/10 of the way from the top. On graphical displays, C-<HOME> does the same.

M->

Move to the end of the buffer (end-of-buffer). On graphical displays, C-<END> does the same.

C-v
<PageDown>
<next>

Scroll the display one screen forward, and move point onscreen if necessary (scroll-up-command). See section Scrolling.

M-v
<PageUp>
<prior>

Scroll one screen backward, and move point onscreen if necessary (scroll-down-command). See section Scrolling.

M-g c

Read a number n and move point to buffer position n. Position 1 is the beginning of the buffer.

M-g M-g
M-g g

Read a number n and move point to the beginning of line number n (goto-line). Line 1 is the beginning of the buffer. If point is on or just after a number in the buffer, that is the default for n. Just type <RET> in the minibuffer to use it. You can also specify n by giving M-g M-g a numeric prefix argument. See section Creating and Selecting Buffers, for the behavior of M-g M-g when you give it a plain prefix argument.

M-g <TAB>

Read a number n and move to column n in the current line. Column 0 is the leftmost column. If called with a prefix argument, move to the column number specified by the argument’s numeric value.

C-x C-n

Use the current column of point as the semipermanent goal column for C-n and C-p (set-goal-column) in the current buffer. When a semipermanent goal column is in effect, those commands always try to move to this column, or as close as possible to it, after moving vertically. The goal column remains in effect until canceled.

C-u C-x C-n

Cancel the goal column. Henceforth, C-n and C-p try to preserve the horizontal position, as usual.

When a line of text in the buffer is longer than the width of the window, Emacs usually displays it on two or more screen lines. For convenience, C-n and C-p move point by screen lines, as do the equivalent keys <down> and <up>. You can force these commands to move according to logical lines (i.e., according to the text lines in the buffer) by setting the variable line-move-visual to nil; if a logical line occupies multiple screen lines, the cursor then skips over the additional screen lines. For details, see Continuation Lines. See section Variables, for how to set variables such as line-move-visual.

Unlike C-n and C-p, most of the Emacs commands that work on lines work on logical lines. For instance, C-a (move-beginning-of-line) and C-e (move-end-of-line) respectively move to the beginning and end of the logical line. Whenever we encounter commands that work on screen lines, such as C-n and C-p, we will point these out.

When line-move-visual is nil, you can also set the variable track-eol to a non-nil value. Then C-n and C-p, when starting at the end of the logical line, move to the end of the next logical line. Normally, track-eol is nil.

C-n normally stops at the end of the buffer when you use it on the last line in the buffer. However, if you set the variable next-line-add-newlines to a non-nil value, C-n on the last line of a buffer creates an additional line at the end and moves down into it.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.3 Erasing Text

<DEL>
<BACKSPACE>

Delete the character before point, or the region if it is active (delete-backward-char).

<Delete>

Delete the character after point, or the region if it is active (delete-forward-char).

C-d

Delete the character after point (delete-char).

C-k

Kill to the end of the line (kill-line).

M-d

Kill forward to the end of the next word (kill-word).

M-<DEL>
M-<BACKSPACE>

Kill back to the beginning of the previous word (backward-kill-word).

The <DEL> (delete-backward-char) command removes the character before point, moving the cursor and the characters after it backwards. If point was at the beginning of a line, this deletes the preceding newline, joining this line to the previous one.

If, however, the region is active, <DEL> instead deletes the text in the region. See section The Mark and the Region, for a description of the region.

On most keyboards, <DEL> is labeled <BACKSPACE>, but we refer to it as <DEL> in this manual. (Do not confuse <DEL> with the <Delete> key; we will discuss <Delete> momentarily.) On some text terminals, Emacs may not recognize the <DEL> key properly. See section If <DEL> Fails to Delete, if you encounter this problem.

The <Delete> (delete-forward-char) command deletes in the opposite direction: it deletes the character after point, i.e., the character under the cursor. If point was at the end of a line, this joins the following line onto this one. Like <DEL>, it deletes the text in the region if the region is active (see section The Mark and the Region).

C-d (delete-char) deletes the character after point, similar to <Delete>, but regardless of whether the region is active.

See section Deletion, for more detailed information about the above deletion commands.

C-k (kill-line) erases (kills) a line at a time. If you type C-k at the beginning or middle of a line, it kills all the text up to the end of the line. If you type C-k at the end of a line, it joins that line with the following line.

See section Killing and Moving Text, for more information about C-k and related commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4 Undoing Changes

C-/
C-x u
C-_

Undo one entry of the undo records—usually, one command worth (undo). (The first key might be unavailable on text-mode displays.)

Emacs records a list of changes made in the buffer text, so you can undo recent changes. This is done using the undo command, which is bound to C-/ (as well as C-x u and C-_). Normally, this command undoes the last change, moving point back to where it was before the change. The undo command applies only to changes in the buffer; you can’t use it to undo cursor motion.

Although each editing command usually makes a separate entry in the undo records, very simple commands may be grouped together. Sometimes, an entry may cover just part of a complex command.

If you repeat C-/ (or its aliases), each repetition undoes another, earlier change, back to the limit of the undo information available. If all recorded changes have already been undone, the undo command displays an error message and does nothing.

To learn more about the undo command, see Undo.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.5 Files

Text that you insert in an Emacs buffer lasts only as long as the Emacs session. To keep any text permanently, you must put it in a file.

Suppose there is a file named ‘test.emacs’ in your home directory. To begin editing this file in Emacs, type

C-x C-f test.emacs <RET>

Here the file name is given as an argument to the command C-x C-f (find-file). That command uses the minibuffer to read the argument, and you type <RET> to terminate the argument (see section The Minibuffer).

Emacs obeys this command by visiting the file: it creates a buffer, copies the contents of the file into the buffer, and then displays the buffer for editing. If you alter the text, you can save the new text in the file by typing C-x C-s (save-buffer). This copies the altered buffer contents back into the file ‘test.emacs’, making them permanent. Until you save, the changed text exists only inside Emacs, and the file ‘test.emacs’ is unaltered.

To create a file, just visit it with C-x C-f as if it already existed. This creates an empty buffer, in which you can insert the text you want to put in the file. Emacs actually creates the file the first time you save this buffer with C-x C-s.

To learn more about using files in Emacs, see File Handling.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.6 Help

If you forget what a key does, you can find out by typing C-h k (describe-key), followed by the key of interest; for example, C-h k C-n tells you what C-n does.

The prefix key C-h stands for “help”. The key <F1> serves as an alias for C-h. Apart from C-h k, there are many other help commands providing different kinds of help.

See section Help, for details.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.7 Blank Lines

Here are special commands and techniques for inserting and deleting blank lines.

C-o

Insert a blank line after the cursor (open-line).

C-x C-o

Delete all but one of many consecutive blank lines (delete-blank-lines).

We have seen how <RET> (newline) starts a new line of text. However, it may be easier to see what you are doing if you first make a blank line and then insert the desired text into it. This is easy to do using the key C-o (open-line), which inserts a newline after point but leaves point in front of the newline. After C-o, type the text for the new line.

You can make several blank lines by typing C-o several times, or by giving it a numeric argument specifying how many blank lines to make. See section Numeric Arguments, for how. If you have a fill prefix, the C-o command inserts the fill prefix on the new line, if typed at the beginning of a line. See section The Fill Prefix.

The easy way to get rid of extra blank lines is with the command C-x C-o (delete-blank-lines). If point lies within a run of several blank lines, C-x C-o deletes all but one of them. If point is on a single blank line, C-x C-o deletes it. If point is on a nonblank line, C-x C-o deletes all following blank lines, if any exists.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.8 Continuation Lines

Sometimes, a line of text in the buffer—a logical line—is too long to fit in the window, and Emacs displays it as two or more screen lines. This is called line wrapping or continuation, and the long logical line is called a continued line. On a graphical display, Emacs indicates line wrapping with small bent arrows in the left and right window fringes. On a text terminal, Emacs indicates line wrapping by displaying a ‘\’ character at the right margin.

Most commands that act on lines act on logical lines, not screen lines. For instance, C-k kills a logical line. As described earlier, C-n (next-line) and C-p (previous-line) are special exceptions: they move point down and up, respectively, by one screen line (see section Changing the Location of Point).

Emacs can optionally truncate long logical lines instead of continuing them. This means that every logical line occupies a single screen line; if it is longer than the width of the window, the rest of the line is not displayed. On a graphical display, a truncated line is indicated by a small straight arrow in the right fringe; on a text terminal, it is indicated by a ‘$’ character in the right margin. See section Line Truncation.

By default, continued lines are wrapped at the right window edge. Since the wrapping may occur in the middle of a word, continued lines can be difficult to read. The usual solution is to break your lines before they get too long, by inserting newlines. If you prefer, you can make Emacs insert a newline automatically when a line gets too long, by using Auto Fill mode. See section Filling Text.

Sometimes, you may need to edit files containing many long logical lines, and it may not be practical to break them all up by adding newlines. In that case, you can use Visual Line mode, which enables word wrapping: instead of wrapping long lines exactly at the right window edge, Emacs wraps them at the word boundaries (i.e., space or tab characters) nearest to the right window edge. Visual Line mode also redefines editing commands such as C-a, C-n, and C-k to operate on screen lines rather than logical lines. See section Visual Line Mode.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.9 Cursor Position Information

Here are commands to get information about the size and position of parts of the buffer, and to count words and lines.

M-x what-line

Display the line number of point.

M-x line-number-mode
M-x column-number-mode

Toggle automatic display of the current line number or column number. See section Optional Mode Line Features. If you want to have a line number displayed before each line, see Customization of Display.

M-=

Display the number of lines, words, and characters that are present in the region (count-words-region). See section The Mark and the Region, for information about the region.

M-x count-words

Display the number of lines, words, and characters that are present in the buffer. If the region is active (see section The Mark and the Region), display the numbers for the region instead.

C-x =

Display the character code of character after point, character position of point, and column of point (what-cursor-position).

M-x hl-line-mode

Enable or disable highlighting of the current line. See section Displaying the Cursor.

M-x size-indication-mode

Toggle automatic display of the size of the buffer. See section Optional Mode Line Features.

M-x what-line displays the current line number in the echo area. This command is usually redundant because the current line number is shown in the mode line (see section The Mode Line). However, if you narrow the buffer, the mode line shows the line number relative to the accessible portion (see section Narrowing). By contrast, what-line displays both the line number relative to the narrowed region and the line number relative to the whole buffer.

M-= (count-words-region) displays a message reporting the number of lines, words, and characters in the region (see section The Mark and the Region, for an explanation of the region). With a prefix argument, C-u M-=, the command displays a count for the entire buffer.

The command M-x count-words does the same job, but with a different calling convention. It displays a count for the region if the region is active, and for the buffer otherwise.

The command C-x = (what-cursor-position) shows information about the current cursor position and the buffer contents at that position. It displays a line in the echo area that looks like this:

Char: c (99, #o143, #x63) point=28062 of 36168 (78%) column=53

After ‘Char:’, this shows the character in the buffer at point. The text inside the parenthesis shows the corresponding decimal, octal and hex character codes; for more information about how C-x = displays character information, see Introduction to International Character Sets. After ‘point=’ is the position of point as a character count (the first character in the buffer is position 1, the second character is position 2, and so on). The number after that is the total number of characters in the buffer, and the number in parenthesis expresses the position as a percentage of the total. After ‘column=’ is the horizontal position of point, in columns counting from the left edge of the window.

If the buffer has been narrowed, making some of the text at the beginning and the end temporarily inaccessible, C-x = displays additional text describing the currently accessible range. For example, it might display this:

Char: C (67, #o103, #x43) point=252 of 889 (28%) <231-599> column=0

where the two extra numbers give the smallest and largest character position that point is allowed to assume. The characters between those two positions are the accessible ones. See section Narrowing.

Related, but different feature is display-line-numbers-mode (see section Customization of Display).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.10 Numeric Arguments

In the terminology of mathematics and computing, argument means “data provided to a function or operation”. You can give any Emacs command a numeric argument (also called a prefix argument). Some commands interpret the argument as a repetition count. For example, giving C-f an argument of ten causes it to move point forward by ten characters instead of one. With these commands, no argument is equivalent to an argument of one, and negative arguments cause them to move or act in the opposite direction.

The easiest way to specify a numeric argument is to type a digit and/or a minus sign while holding down the <Meta> key. For example,

M-5 C-n

moves down five lines. The keys M-1, M-2, and so on, as well as M--, are bound to commands (digit-argument and negative-argument) that set up an argument for the next command. M-- without digits normally means -1.

If you enter more than one digit, you need not hold down the <Meta> key for the second and subsequent digits. Thus, to move down fifty lines, type

M-5 0 C-n

Note that this does not insert five copies of ‘0’ and move down one line, as you might expect—the ‘0’ is treated as part of the prefix argument.

(What if you do want to insert five copies of ‘0’? Type M-5 C-u 0. Here, C-u terminates the prefix argument, so that the next keystroke begins the command that you want to execute. Note that this meaning of C-u applies only to this case. For the usual role of C-u, see below.)

Instead of typing M-1, M-2, and so on, another way to specify a numeric argument is to type C-u (universal-argument) followed by some digits, or (for a negative argument) a minus sign followed by digits. A minus sign without digits normally means -1.

C-u alone has the special meaning of “four times”: it multiplies the argument for the next command by four. C-u C-u multiplies it by sixteen. Thus, C-u C-u C-f moves forward sixteen characters. Other useful combinations are C-u C-n, C-u C-u C-n (move down a good fraction of a screen), C-u C-u C-o (make sixteen blank lines), and C-u C-k (kill four lines).

You can use a numeric argument before a self-inserting character to insert multiple copies of it. This is straightforward when the character is not a digit; for example, C-u 6 4 a inserts 64 copies of the character ‘a’. But this does not work for inserting digits; C-u 6 4 1 specifies an argument of 641. You can separate the argument from the digit to insert with another C-u; for example, C-u 6 4 C-u 1 does insert 64 copies of the character ‘1’.

Some commands care whether there is an argument, but ignore its value. For example, the command M-q (fill-paragraph) fills text; with an argument, it justifies the text as well. (See section Filling Text, for more information on M-q.) For these commands, it is enough to specify the argument with a single C-u.

Some commands use the value of the argument as a repeat count but do something special when there is no argument. For example, the command C-k (kill-line) with argument n kills n lines, including their terminating newlines. But C-k with no argument is special: it kills the text up to the next newline, or, if point is right at the end of the line, it kills the newline itself. Thus, two C-k commands with no arguments can kill a nonblank line, just like C-k with an argument of one. (See section Killing and Moving Text, for more information on C-k.)

A few commands treat a plain C-u differently from an ordinary argument. A few others may treat an argument of just a minus sign differently from an argument of -1. These unusual cases are described when they come up; they exist to make an individual command more convenient, and they are documented in that command’s documentation string.

We use the term prefix argument to emphasize that you type such arguments before the command, and to distinguish them from minibuffer arguments (see section The Minibuffer), which are entered after invoking the command.

On graphical displays, C-0, C-1, etc. act the same as M-0, M-1, etc.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11 Repeating a Command

Many simple commands, such as those invoked with a single key or with M-x command-name <RET>, can be repeated by invoking them with a numeric argument that serves as a repeat count (see section Numeric Arguments). However, if the command you want to repeat prompts for input, or uses a numeric argument in another way, that method won’t work.

The command C-x z (repeat) provides another way to repeat an Emacs command many times. This command repeats the previous Emacs command, whatever that was. Repeating a command uses the same arguments that were used before; it does not read new arguments each time.

To repeat the command more than once, type additional z’s: each z repeats the command one more time. Repetition ends when you type a character other than z or press a mouse button.

For example, suppose you type C-u 2 0 C-d to delete 20 characters. You can repeat that command (including its argument) three additional times, to delete a total of 80 characters, by typing C-x z z z. The first C-x z repeats the command once, and each subsequent z repeats it once again.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.1 Using the Minibuffer

When the minibuffer is in use, it appears in the echo area, with a cursor. The minibuffer starts with a prompt, usually ending with a colon. The prompt states what kind of input is expected, and how it will be used. The prompt is highlighted using the minibuffer-prompt face (see section Text Faces).

The simplest way to enter a minibuffer argument is to type the text, then <RET> to submit the argument and exit the minibuffer. Alternatively, you can type C-g to exit the minibuffer by canceling the command asking for the argument (see section Quitting and Aborting).

Sometimes, the prompt shows a default argument, inside parentheses before the colon. This default will be used as the argument if you just type <RET>. For example, commands that read buffer names usually show a buffer name as the default; you can type <RET> to operate on that default buffer.

If you enable Minibuffer Electric Default mode, a global minor mode, Emacs hides the default argument as soon as you modify the contents of the minibuffer (since typing <RET> would no longer submit that default). If you ever bring back the original minibuffer text, the prompt again shows the default. Furthermore, if you change the variable minibuffer-eldef-shorten-default to a non-nil value, the default argument is displayed as ‘[default-arg]’ instead of ‘(default default-arg)’, saving some screen space. To enable this minor mode, type M-x minibuffer-electric-default-mode.

Since the minibuffer appears in the echo area, it can conflict with other uses of the echo area. If an error message or an informative message is emitted while the minibuffer is active, the message hides the minibuffer for a few seconds, or until you type something; then the minibuffer comes back. While the minibuffer is in use, Emacs does not echo keystrokes.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.2 Minibuffers for File Names

Commands such as C-x C-f (find-file) use the minibuffer to read a file name argument (see section Files). When the minibuffer is used to read a file name, it typically starts out with some initial text ending in a slash. This is the default directory. For example, it may start out like this:

Find file: /u2/emacs/src/

Here, ‘Find file: ’ is the prompt and ‘/u2/emacs/src/’ is the default directory. If you now type buffer.c as input, that specifies the file ‘/u2/emacs/src/buffer.c’. See section File Names, for information about the default directory.

Alternative defaults for the file name you may want are available by typing M-n, see Minibuffer History.

You can specify a file in the parent directory with ‘..’: ‘/a/b/../foo.el’ is equivalent to ‘/a/foo.el’. Alternatively, you can use M-<DEL> to kill directory names backwards (see section Words).

To specify a file in a completely different directory, you can kill the entire default with C-a C-k (see section Editing in the Minibuffer). Alternatively, you can ignore the default, and enter an absolute file name starting with a slash or a tilde after the default directory. For example, you can specify ‘/etc/termcap’ as follows:

Find file: /u2/emacs/src//etc/termcap

A double slash causes Emacs to ignore everything before the second slash in the pair. In the example above, ‘/u2/emacs/src/’ is ignored, so the argument you supplied is ‘/etc/termcap’. The ignored part of the file name is dimmed if the terminal allows it. (To disable this dimming, turn off File Name Shadow mode with the command M-x file-name-shadow-mode.)

When completing remote file names (see section Remote Files), a double slash behaves slightly differently: it causes Emacs to ignore only the file-name part, leaving the rest (method, host and username, etc.) intact. Typing three slashes in a row ignores everything in remote file names. See File name completion in The Tramp Manual.

Emacs interprets ‘~/’ as your home directory. Thus, ‘~/foo/bar.txt’ specifies a file named ‘bar.txt’, inside a directory named ‘foo’, which is in turn located in your home directory. In addition, ‘~user-id/’ means the home directory of a user whose login name is user-id. Any leading directory name in front of the ‘~’ is ignored: thus, ‘/u2/emacs/~/foo/bar.txt’ is equivalent to ‘~/foo/bar.txt’.

On MS-Windows and MS-DOS systems, where a user doesn’t always have a home directory, Emacs uses several alternatives. For MS-Windows, see HOME and Startup Directories on MS-Windows; for MS-DOS, see File Names on MS-DOS. On these systems, the ‘~user-id/’ construct is supported only for the current user, i.e., only if user-id is the current user’s login name.

To prevent Emacs from inserting the default directory when reading file names, change the variable insert-default-directory to nil. In that case, the minibuffer starts out empty. Nonetheless, relative file name arguments are still interpreted based on the same default directory.

You can also enter remote file names in the minibuffer. See section Remote Files.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.3 Editing in the Minibuffer

The minibuffer is an Emacs buffer, albeit a peculiar one, and the usual Emacs commands are available for editing the argument text. (The prompt, however, is read-only, and cannot be changed.)

Since <RET> in the minibuffer submits the argument, you can’t use it to insert a newline. You can do that with C-q C-j, which inserts a C-j control character, which is formally equivalent to a newline character (see section Inserting Text). Alternatively, you can use the C-o (open-line) command (see section Blank Lines).

Inside a minibuffer, the keys <TAB>, <SPC>, and ? are often bound to completion commands, which allow you to easily fill in the desired text without typing all of it. See section Completion. As with <RET>, you can use C-q to insert a <TAB>, <SPC>, or ‘?’ character.

For convenience, C-a (move-beginning-of-line) in a minibuffer moves point to the beginning of the argument text, not the beginning of the prompt. For example, this allows you to erase the entire argument with C-a C-k.

When the minibuffer is active, the echo area is treated much like an ordinary Emacs window. For instance, you can switch to another window (with C-x o), edit text there, then return to the minibuffer window to finish the argument. You can even kill text in another window, return to the minibuffer window, and yank the text into the argument. There are some restrictions on the minibuffer window, however: for instance, you cannot split it. See section Multiple Windows.

Normally, the minibuffer window occupies a single screen line. However, if you add two or more lines’ worth of text into the minibuffer, it expands automatically to accommodate the text. The variable resize-mini-windows controls the resizing of the minibuffer. The default value is grow-only, which means the behavior we have just described. If the value is t, the minibuffer window will also shrink automatically if you remove some lines of text from the minibuffer, down to a minimum of one screen line. If the value is nil, the minibuffer window never changes size automatically, but you can use the usual window-resizing commands on it (see section Multiple Windows).

The variable max-mini-window-height controls the maximum height for resizing the minibuffer window. A floating-point number specifies a fraction of the frame’s height; an integer specifies the maximum number of lines; nil means do not resize the minibuffer window automatically. The default value is 0.25.

The C-M-v command in the minibuffer scrolls the help text from commands that display help text of any sort in another window. You can also scroll the help text with M-<PageUp> and M-<PageDown> (or, equivalently, M-<prior> and M-<next>). This is especially useful with long lists of possible completions. See section Using Other Windows.

Emacs normally disallows most commands that use the minibuffer while the minibuffer is active. To allow such commands in the minibuffer, set the variable enable-recursive-minibuffers to t.

When not active, the minibuffer is in minibuffer-inactive-mode, and clicking mouse-1 there shows the ‘*Messages*’ buffer. If you use a dedicated frame for minibuffers, Emacs also recognizes certain keys there, for example, n to make a new frame.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.4 Completion

You can often use a feature called completion to help enter arguments. This means that after you type part of the argument, Emacs can fill in the rest, or some of it, based on what was typed so far.

When completion is available, certain keys (usually <TAB>, <RET>, and <SPC>) are rebound in the minibuffer to special completion commands (see section Completion Commands). These commands attempt to complete the text in the minibuffer, based on a set of completion alternatives provided by the command that requested the argument. You can usually type ? to see a list of completion alternatives.

Although completion is usually done in the minibuffer, the feature is sometimes available in ordinary buffers too. See section Completion for Symbol Names.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.4.1 Completion Example

A simple example may help here. M-x uses the minibuffer to read the name of a command, so completion works by matching the minibuffer text against the names of existing Emacs commands. Suppose you wish to run the command auto-fill-mode. You can do that by typing M-x auto-fill-mode <RET>, but it is easier to use completion.

If you type M-x a u <TAB>, the <TAB> looks for completion alternatives (in this case, command names) that start with ‘au’. There are several, including auto-fill-mode and autoconf-mode, but they all begin with auto, so the ‘au’ in the minibuffer completes to ‘auto’. (More commands may be defined in your Emacs session. For example, if a command called authorize-me was defined, Emacs could only complete as far as ‘aut’.)

If you type <TAB> again immediately, it cannot determine the next character; it could be ‘-’, ‘a’, or ‘c’. So it does not add any characters; instead, <TAB> displays a list of all possible completions in another window.

Next, type -f. The minibuffer now contains ‘auto-f’, and the only command name that starts with this is auto-fill-mode. If you now type <TAB>, completion fills in the rest of the argument ‘auto-fill-mode’ into the minibuffer.

Hence, typing just a u <TAB> - f <TAB> allows you to enter ‘auto-fill-mode’.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.4.2 Completion Commands

Here is a list of the completion commands defined in the minibuffer when completion is allowed.

<TAB>

Complete the text in the minibuffer as much as possible; if unable to complete, display a list of possible completions (minibuffer-complete).

<SPC>

Complete up to one word from the minibuffer text before point (minibuffer-complete-word). This command is not available for arguments that often include spaces, such as file names.

<RET>

Submit the text in the minibuffer as the argument, possibly completing first (minibuffer-complete-and-exit). See section Completion Exit.

?

Display a list of completions (minibuffer-completion-help).

<TAB> (minibuffer-complete) is the most fundamental completion command. It searches for all possible completions that match the existing minibuffer text, and attempts to complete as much as it can. See section How Completion Alternatives Are Chosen, for how completion alternatives are chosen.

<SPC> (minibuffer-complete-word) completes like <TAB>, but only up to the next hyphen or space. If you have ‘auto-f’ in the minibuffer and type <SPC>, it finds that the completion is ‘auto-fill-mode’, but it only inserts ‘ill-’, giving ‘auto-fill-’. Another <SPC> at this point completes all the way to ‘auto-fill-mode’.

If <TAB> or <SPC> is unable to complete, it displays a list of matching completion alternatives (if there are any) in another window. You can display the same list with ? (minibuffer-completion-help). The following commands can be used with the completion list:

M-v
<PageUp>
<prior>

Typing M-v, while in the minibuffer, selects the window showing the completion list (switch-to-completions). This paves the way for using the commands below. <PageUp> or <prior> does the same. You can also select the window in other ways (see section Multiple Windows).

<RET>
mouse-1
mouse-2

While in the completion list buffer, this chooses the completion at point (choose-completion).

<RIGHT>

While in the completion list buffer, this moves point to the following completion alternative (next-completion).

<LEFT>

While in the completion list buffer, this moves point to the previous completion alternative (previous-completion).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.4.3 Completion Exit

When a command reads an argument using the minibuffer with completion, it also controls what happens when you type <RET> (minibuffer-complete-and-exit) to submit the argument. There are four types of behavior:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.4.4 How Completion Alternatives Are Chosen

Completion commands work by narrowing a large list of possible completion alternatives to a smaller subset that matches what you have typed in the minibuffer. In Completion Example, we gave a simple example of such matching. The procedure of determining what constitutes a match is quite intricate. Emacs attempts to offer plausible completions under most circumstances.

Emacs performs completion using one or more completion styles—sets of criteria for matching minibuffer text to completion alternatives. During completion, Emacs tries each completion style in turn. If a style yields one or more matches, that is used as the list of completion alternatives. If a style produces no matches, Emacs falls back on the next style.

The list variable completion-styles specifies the completion styles to use. Each list element is the name of a completion style (a Lisp symbol). The default completion styles are (in order):

basic

A matching completion alternative must have the same beginning as the text in the minibuffer before point. Furthermore, if there is any text in the minibuffer after point, the rest of the completion alternative must contain that text as a substring.

partial-completion

This aggressive completion style divides the minibuffer text into words separated by hyphens or spaces, and completes each word separately. (For example, when completing command names, ‘em-l-m’ completes to ‘emacs-lisp-mode’.)

Furthermore, a ‘*’ in the minibuffer text is treated as a wildcard—it matches any string of characters at the corresponding position in the completion alternative.

emacs22

This completion style is similar to basic, except that it ignores the text in the minibuffer after point. It is so-named because it corresponds to the completion behavior in Emacs 22.

The following additional completion styles are also defined, and you can add them to completion-styles if you wish (see section Customization):

substring

A matching completion alternative must contain the text in the minibuffer before point, and the text in the minibuffer after point, as substrings (in that same order).

Thus, if the text in the minibuffer is ‘foobar’, with point between ‘foo’ and ‘bar’, that matches ‘afoobbarc’, where a, b, and c can be any string including the empty string.

initials

This very aggressive completion style attempts to complete acronyms and initialisms. For example, when completing command names, it matches ‘lch’ to ‘list-command-history’.

There is also a very simple completion style called emacs21. In this style, if the text in the minibuffer is ‘foobar’, only matches starting with ‘foobar’ are considered.

You can use different completion styles in different situations, by setting the variable completion-category-overrides. For example, the default setting says to use only basic and substring completion for buffer names.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.4.5 Completion Options

Case is significant when completing case-sensitive arguments, such as command names. For example, when completing command names, ‘AU’ does not complete to ‘auto-fill-mode’. Case differences are ignored when completing arguments in which case does not matter.

When completing file names, case differences are ignored if the variable read-file-name-completion-ignore-case is non-nil. The default value is nil on systems that have case-sensitive file-names, such as GNU/Linux; it is non-nil on systems that have case-insensitive file-names, such as Microsoft Windows. When completing buffer names, case differences are ignored if the variable read-buffer-completion-ignore-case is non-nil; the default is nil.

When completing file names, Emacs usually omits certain alternatives that are considered unlikely to be chosen, as determined by the list variable completion-ignored-extensions. Each element in the list should be a string; any file name ending in such a string is ignored as a completion alternative. Any element ending in a slash (‘/’) represents a subdirectory name. The standard value of completion-ignored-extensions has several elements including ".o", ".elc", and "~". For example, if a directory contains ‘foo.c’ and ‘foo.elc’, ‘foo’ completes to ‘foo.c’. However, if all possible completions end in otherwise-ignored strings, they are not ignored: in the previous example, ‘foo.e’ completes to ‘foo.elc’. Emacs disregards completion-ignored-extensions when showing completion alternatives in the completion list.

Shell completion is an extended version of filename completion, see section Shell Mode Options.

If completion-auto-help is set to nil, the completion commands never display the completion list buffer; you must type ? to display the list. If the value is lazy, Emacs only shows the completion list buffer on the second attempt to complete. In other words, if there is nothing to complete, the first <TAB> echoes ‘Next char not unique’; the second <TAB> shows the completion list buffer.

If completion-cycle-threshold is non-nil, completion commands can cycle through completion alternatives. Normally, if there is more than one completion alternative for the text in the minibuffer, a completion command completes up to the longest common substring. If you change completion-cycle-threshold to t, the completion command instead completes to the first of those completion alternatives; each subsequent invocation of the completion command replaces that with the next completion alternative, in a cyclic manner. If you give completion-cycle-threshold a numeric value n, completion commands switch to this cycling behavior only when there are n or fewer alternatives.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.5 Minibuffer History

Every argument that you enter with the minibuffer is saved in a minibuffer history list so you can easily use it again later. You can use the following arguments to quickly fetch an earlier argument into the minibuffer:

M-p

Move to the previous item in the minibuffer history, an earlier argument (previous-history-element).

M-n

Move to the next item in the minibuffer history (next-history-element).

<UP>
<DOWN>

Like M-p and M-n, but move to the previous or next line of a multi-line item before going to the previous history item (previous-line-or-history-element and next-line-or-history-element) .

M-r regexp <RET>

Move to an earlier item in the minibuffer history that matches regexp (previous-matching-history-element).

M-s regexp <RET>

Move to a later item in the minibuffer history that matches regexp (next-matching-history-element).

While in the minibuffer, M-p (previous-history-element) moves through the minibuffer history list, one item at a time. Each M-p fetches an earlier item from the history list into the minibuffer, replacing its existing contents. Typing M-n (next-history-element) moves through the minibuffer history list in the opposite direction, fetching later entries into the minibuffer.

If you type M-n in the minibuffer when there are no later entries in the minibuffer history (e.g., if you haven’t previously typed M-p), Emacs tries fetching from a list of default arguments: values that you are likely to enter. You can think of this as moving through the “future history”.

The “future history” for file names includes several possible alternatives you may find useful, such as the file name or the URL at point in the current buffer. The defaults put into the “future history” in this case are controlled by the functions mentioned in the value of the option file-name-at-point-functions. By default, its value invokes the ffap package (see section Finding Files and URLs at Point), which tries to guess the default file or URL from the text around point. To disable this guessing, customize the option to a nil value, then the “future history” of file names will include only the file, if any, visited by the current buffer, and the default directory.

The arrow keys <UP> and <DOWN> work like M-p and M-n, but if the current history item is longer than a single line, they allow you to move to the previous or next line of the current history item before going to the previous or next history item.

If you edit the text inserted by the M-p or M-n minibuffer history commands, this does not change its entry in the history list. However, the edited argument does go at the end of the history list when you submit it.

You can use M-r (previous-matching-history-element) to search through older elements in the history list, and M-s (next-matching-history-element) to search through newer entries. Each of these commands asks for a regular expression as an argument, and fetches the first matching entry into the minibuffer. See section Syntax of Regular Expressions, for an explanation of regular expressions. A numeric prefix argument n means to fetch the nth matching entry. These commands are unusual, in that they use the minibuffer to read the regular expression argument, even though they are invoked from the minibuffer. An upper-case letter in the regular expression makes the search case-sensitive (see section Lax Matching During Searching).

You can also search through the history using an incremental search. See section Searching the Minibuffer.

Emacs keeps separate history lists for several different kinds of arguments. For example, there is a list for file names, used by all the commands that read file names. Other history lists include buffer names, command names (used by M-x), and command arguments (used by commands like query-replace).

The variable history-length specifies the maximum length of a minibuffer history list; adding a new element deletes the oldest element if the list gets too long. If the value is t, there is no maximum length.

The variable history-delete-duplicates specifies whether to delete duplicates in history. If it is non-nil, adding a new element deletes from the list all other elements that are equal to it. The default is nil.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.6 Repeating Minibuffer Commands

Every command that uses the minibuffer once is recorded on a special history list, the command history, together with the values of its arguments, so that you can repeat the entire command. In particular, every use of M-x is recorded there, since M-x uses the minibuffer to read the command name.

C-x <ESC> <ESC>

Re-execute a recent minibuffer command from the command history (repeat-complex-command).

M-x list-command-history

Display the entire command history, showing all the commands C-x <ESC> <ESC> can repeat, most recent first.

C-x <ESC> <ESC> re-executes a recent command that used the minibuffer. With no argument, it repeats the last such command. A numeric argument specifies which command to repeat; 1 means the last one, 2 the previous, and so on.

C-x <ESC> <ESC> works by turning the previous command into a Lisp expression and then entering a minibuffer initialized with the text for that expression. Even if you don’t know Lisp, it will probably be obvious which command is displayed for repetition. If you type just <RET>, that repeats the command unchanged. You can also change the command by editing the Lisp expression before you execute it. The executed command is added to the front of the command history unless it is identical to the most recent item.

Once inside the minibuffer for C-x <ESC> <ESC>, you can use the usual minibuffer history commands (see section Minibuffer History) to move through the history list. After finding the desired previous command, you can edit its expression as usual and then execute it by typing <RET>.

Incremental search does not, strictly speaking, use the minibuffer. Therefore, although it behaves like a complex command, it normally does not appear in the history list for C-x <ESC> <ESC>. You can make incremental search commands appear in the history by setting isearch-resume-in-command-history to a non-nil value. See section Incremental Search.

The list of previous minibuffer-using commands is stored as a Lisp list in the variable command-history. Each element is a Lisp expression that describes one command and its arguments. Lisp programs can re-execute a command by calling eval with the command-history element.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.7 Entering passwords

Sometimes, you may need to enter a password into Emacs. For instance, when you tell Emacs to visit a file on another machine via a network protocol such as FTP, you often need to supply a password to gain access to the machine (see section Remote Files).

Entering a password is similar to using a minibuffer. Emacs displays a prompt in the echo area (such as ‘Password: ’); after you type the required password, press <RET> to submit it. To prevent others from seeing your password, every character you type is displayed as a dot (‘.’) instead of its usual form.

Most of the features and commands associated with the minibuffer cannot be used when entering a password. There is no history or completion, and you cannot change windows or perform any other action with Emacs until you have submitted the password.

While you are typing the password, you may press <DEL> to delete backwards, removing the last character entered. C-u deletes everything you have typed so far. C-g quits the password prompt (see section Quitting and Aborting). C-y inserts the current kill into the password (see section Killing and Moving Text). You may type either <RET> or <ESC> to submit the password. Any other self-inserting character key inserts the associated character into the password, and all other input is ignored.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.8 Yes or No Prompts

An Emacs command may require you to answer a yes-or-no question during the course of its execution. Such queries come in two main varieties.

For the first type of yes-or-no query, the prompt ends with ‘(y or n)’. Such a query does not actually use the minibuffer; the prompt appears in the echo area, and you answer by typing either ‘y’ or ‘n’, which immediately delivers the response. For example, if you type C-x C-w (write-file) to save a buffer, and enter the name of an existing file, Emacs issues a prompt like this:

File ‘foo.el’ exists; overwrite? (y or n)

Because this query does not actually use the minibuffer, the usual minibuffer editing commands cannot be used. However, you can perform some window scrolling operations while the query is active: C-l recenters the selected window; C-v (or <PageDown>, or <next>) scrolls forward; M-v (or <PageUp>, or <prior>) scrolls backward; C-M-v scrolls forward in the next window; and C-M-S-v scrolls backward in the next window. Typing C-g dismisses the query, and quits the command that issued it (see section Quitting and Aborting).

The second type of yes-or-no query is typically employed if giving the wrong answer would have serious consequences; it uses the minibuffer, and features a prompt ending with ‘(yes or no)’. For example, if you invoke C-x k (kill-buffer) on a file-visiting buffer with unsaved changes, Emacs activates the minibuffer with a prompt like this:

Buffer foo.el modified; kill anyway? (yes or no)

To answer, you must type ‘yes’ or ‘no’ into the minibuffer, followed by <RET>. The minibuffer behaves as described in the previous sections; you can switch to another window with C-x o, use the history commands M-p and M-n, etc. Type C-g to quit the minibuffer and the querying command.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section Customizing 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 <RET>. 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. <RET> exits the minibuffer and runs the command. See section The 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

M-x forward-char <RET>

or

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 <RET>.

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-bindings can 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 <RET> that terminates the name. Thus we might say M-x auto-fill-mode rather than M-x auto-fill-mode <RET>. We mention the <RET> 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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10 Help

Emacs provides a wide variety of help commands, all accessible through the prefix key C-h (or, equivalently, the function key <F1>). 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 <SPC> and <DEL>, 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 <SPC> and <DEL> to scroll and type <RET> to follow hyperlinks. See section Help Mode Commands.

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 <RET>

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 section Syntax of Regular Expressions). See section Apropos.

C-h i d m emacs <RET> i topic <RET>

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 <RET> s topic <RET>

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 section Keyword Search for Packages.

C-h or <F1> 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 <F1>.)


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.1 Help Summary

Here is a summary of help commands for accessing the built-in documentation. Most of these are described in more detail in the following sections.

C-h a topics <RET>

Display a list of commands whose names match topics (apropos-command).

C-h b

Display all active key bindings; minor mode bindings first, then those of the major mode, then global bindings (describe-bindings).

C-h c key

Show the name of the command that the key sequence key is bound to (describe-key-briefly). Here c stands for “character”. For more extensive information on key, use C-h k.

C-h d topics <RET>

Display the commands and variables whose documentation matches topics (apropos-documentation).

C-h e

Display the ‘*Messages*’ buffer (view-echo-area-messages).

C-h f function <RET>

Display documentation on the Lisp function named function (describe-function). Since commands are Lisp functions, this works for commands too.

C-h h

Display the ‘HELLO’ file, which shows examples of various character sets.

C-h i

Run Info, the GNU documentation browser (info). The Emacs manual is available in Info.

C-h k key

Display the name and documentation of the command that key runs (describe-key).

C-h l

Display a description of your last 300 keystrokes (view-lossage).

C-h m

Display documentation of the current major mode and minor modes (describe-mode).

C-h n

Display news of recent Emacs changes (view-emacs-news).

C-h o symbol

Display documentation of the Lisp symbol named symbol (describe-symbol). This will show the documentation of all kinds of symbols: functions, variables, and faces.

C-h p

Find packages by topic keyword (finder-by-keyword). This lists packages using a package menu buffer. See section Emacs Lisp Packages.

C-h P package <RET>

Display documentation about the specified package (describe-package).

C-h r

Display the Emacs manual in Info (info-emacs-manual).

C-h s

Display the contents of the current syntax table (describe-syntax). The syntax table says which characters are opening delimiters, which are parts of words, and so on. See Syntax Tables in The Emacs Lisp Reference Manual, for details.

C-h t

Enter the Emacs interactive tutorial (help-with-tutorial).

C-h v var <RET>

Display the documentation of the Lisp variable var (describe-variable).

C-h w command <RET>

Show which keys run the command named command (where-is).

C-h C coding <RET>

Describe the coding system coding (describe-coding-system).

C-h C <RET>

Describe the coding systems currently in use.

C-h F command <RET>

Enter Info and go to the node that documents the Emacs command command (Info-goto-emacs-command-node).

C-h I method <RET>

Describe the input method method (describe-input-method).

C-h K key

Enter Info and go to the node that documents the key sequence key (Info-goto-emacs-key-command-node).

C-h L language-env <RET>

Display information on the character sets, coding systems, and input methods used in language environment language-env (describe-language-environment).

C-h S symbol <RET>

Display the Info documentation on symbol symbol according to the programming language you are editing (info-lookup-symbol).

C-h .

Display the help message for a special text area, if point is in one (display-local-help). (These include, for example, links in ‘*Help*’ buffers.)


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.2 Documentation for a Key

The help commands to get information about a key sequence are C-h c (describe-key-briefly) and C-h k (describe-key).

C-h c key displays in the echo area the name of the command that key is bound to. For example, C-h c C-f displays ‘forward-char’.

C-h k key is similar but gives more information: it displays a help buffer containing the command’s documentation string, which describes exactly what the command does.

C-h K key displays the section of the Emacs manual that describes the command corresponding to key.

C-h c, C-h k and C-h K work for any sort of key sequences, including function keys, menus, and mouse events (except that C-h c ignores mouse movement events). For instance, after C-h k you can select a menu item from the menu bar, to view the documentation string of the command it runs.

C-h w command <RET> lists the keys that are bound to command. It displays the list in the echo area. If it says the command is not on any key, that means you must use M-x to run it. C-h w runs the command where-is.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.3 Help by Command or Variable Name

C-h f function <RET> (describe-function) displays the documentation of Lisp function function, in a window. Since commands are Lisp functions, you can use this method to view the documentation of any command whose name you know. For example,

C-h f auto-fill-mode <RET>

displays the documentation of auto-fill-mode. This is the only way to get the documentation of a command that is not bound to any key (one which you would normally run using M-x).

C-h f is also useful for Lisp functions that you use in a Lisp program. For example, if you have just written the expression (make-vector len) and want to check that you are using make-vector properly, type C-h f make-vector <RET>. Because C-h f allows all function names, not just command names, you may find that some of your favorite completion abbreviations that work in M-x don’t work in C-h f. An abbreviation that is unique among command names may not be unique among all function names.

If you type C-h f <RET>, it describes the function called by the innermost Lisp expression in the buffer around point, provided that function name is a valid, defined Lisp function. (That name appears as the default while you enter the argument.) For example, if point is located following the text ‘(make-vector (car x)’, the innermost list containing point is the one that starts with ‘(make-vector’, so C-h f <RET> describes the function make-vector.

C-h f is also useful just to verify that you spelled a function name correctly. If the minibuffer prompt for C-h f shows the function name from the buffer as the default, it means that name is defined as a Lisp function. Type C-g to cancel the C-h f command if you don’t really want to view the documentation.

C-h v (describe-variable) is like C-h f but describes Lisp variables instead of Lisp functions. Its default is the Lisp symbol around or before point, if that is the name of a defined Lisp variable. See section Variables.

Help buffers that describe Emacs variables and functions normally have hyperlinks to the corresponding source code, if you have the source files installed (see section Hyperlinking and Web Navigation Features).

To find a command’s documentation in a manual, use C-h F (Info-goto-emacs-command-node). This knows about various manuals, not just the Emacs manual, and finds the right one.

C-h o (describe-symbol) is like C-h f and C-h v, but it describes any symbol, be it a function, a variable, or a face. If the symbol has more than one definition, like it has both definition as a function and as a variable, this command will show the documentation of all of them, one after the other.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.4 Apropos

The apropos commands answer questions like, “What are the commands for working with files?” More precisely, you specify an apropos pattern, which means either a word, a list of words, or a regular expression.

Each of the following apropos commands reads an apropos pattern in the minibuffer, searches for items that match the pattern, and displays the results in a different window.

C-h a

Search for commands (apropos-command). With a prefix argument, search for noninteractive functions too.

M-x apropos

Search for functions and variables. Both interactive functions (commands) and noninteractive functions can be found by this.

M-x apropos-user-option

Search for user-customizable variables. With a prefix argument, search for non-customizable variables too.

M-x apropos-variable

Search for variables. With a prefix argument, search for customizable variables only.

M-x apropos-local-variable

Search for buffer-local variables.

M-x apropos-value

Search for variables whose values match the specified pattern. With a prefix argument, search also for functions with definitions matching the pattern, and Lisp symbols with properties matching the pattern.

M-x apropos-local-value

Search for buffer-local variables whose values match the specified pattern.

C-h d

Search for functions and variables whose documentation strings match the specified pattern (apropos-documentation).

The simplest kind of apropos pattern is one word. Anything containing that word matches the pattern. Thus, to find commands that work on files, type C-h a file <RET>. This displays a list of all command names that contain ‘file’, including copy-file, find-file, and so on. Each command name comes with a brief description and a list of keys you can currently invoke it with. In our example, it would say that you can invoke find-file by typing C-x C-f.

For more information about a function definition, variable or symbol property listed in an apropos buffer, you can click on it with mouse-1 or mouse-2, or move there and type <RET>.

When you specify more than one word in the apropos pattern, a name must contain at least two of the words in order to match. Thus, if you are looking for commands to kill a chunk of text before point, you could try C-h a kill back backward behind before <RET>. The real command name kill-backward will match that; if there were a command kill-text-before, it would also match, since it contains two of the specified words.

For even greater flexibility, you can specify a regular expression (see section Syntax of Regular Expressions). An apropos pattern is interpreted as a regular expression if it contains any of the regular expression special characters, ‘^$*+?.\[’.

Following the conventions for naming Emacs commands, here are some words that you’ll find useful in apropos patterns. By using them in C-h a, you will also get a feel for the naming conventions.

char, line, word, sentence, paragraph, region, page, sexp, list, defun, rect, buffer, frame, window, face, file, dir, register, mode, beginning, end, forward, backward, next, previous, up, down, search, goto, kill, delete, mark, insert, yank, fill, indent, case, change, set, what, list, find, view, describe, default.

If the variable apropos-do-all is non-nil, most apropos commands behave as if they had been given a prefix argument. There is one exception: apropos-variable without a prefix argument will always search for all variables, no matter what the value of apropos-do-all is.

By default, all apropos commands except apropos-documentation list their results in alphabetical order. If the variable apropos-sort-by-scores is non-nil, these commands instead try to guess the relevance of each result, and display the most relevant ones first. The apropos-documentation command lists its results in order of relevance by default; to list them in alphabetical order, change the variable apropos-documentation-sort-by-scores to nil.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.5 Help Mode Commands

Help buffers provide the same commands as View mode (see section View Mode); for instance, <SPC> scrolls forward, and <DEL> or S-<SPC> scrolls backward. A few special commands are also provided:

<RET>

Follow a cross reference at point (help-follow).

<TAB>

Move point forward to the next hyperlink (forward-button).

S-<TAB>

Move point back to the previous hyperlink (backward-button).

mouse-1
mouse-2

Follow a hyperlink that you click on.

C-c C-c

Show all documentation about the symbol at point (help-follow-symbol).

C-c C-f
r

Go forward to the next help topic (help-go-forward).

C-c C-b
l

Go back to the previous help topic (help-go-back).

When a function name, variable name, or face name (see section Text Faces) appears in the documentation in the help buffer, it is normally an underlined hyperlink. To view the associated documentation, move point there and type <RET> (help-follow), or click on the hyperlink with mouse-1 or mouse-2. Doing so replaces the contents of the help buffer; to retrace your steps, type C-c C-b or l (help-go-back). While retracing your steps, you can go forward by using C-c C-f or r (help-go-forward).

A help buffer can also contain hyperlinks to Info manuals, source code definitions, and URLs (web pages). The first two are opened in Emacs, and the third using a web browser via the browse-url command (see section Following URLs).

In a help buffer, <TAB> (forward-button) moves point forward to the next hyperlink, while S-<TAB> (backward-button) moves point back to the previous hyperlink. These commands act cyclically; for instance, typing <TAB> at the last hyperlink moves back to the first hyperlink.

To view all documentation about any symbol in the text, move point to the symbol and type C-c C-c (help-follow-symbol). This shows the documentation for all the meanings of the symbol—as a variable, as a function, and/or as a face.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.6 Keyword Search for Packages

Most optional features in Emacs are grouped into packages. Emacs contains several hundred built-in packages, and more can be installed over the network (see section Emacs Lisp Packages).

To make it easier to find packages related to a topic, most packages are associated with one or more keywords based on what they do. Type C-h p (finder-by-keyword) to bring up a list of package keywords, together with a description of what the keywords mean. To view a list of packages for a given keyword, type <RET> on that line; this displays the list of packages in a Package Menu buffer (see section The Package Menu Buffer).

C-h P (describe-package) prompts for the name of a package (see section Emacs Lisp Packages), and displays a help buffer describing the attributes of the package and the features that it implements. The buffer lists the keywords that relate to the package in the form of buttons. Click on a button with mouse-1 or mouse-2 to see the list of other packages related to that keyword.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.7 Help for International Language Support

For information on a specific language environment (see section Language Environments), type C-h L (describe-language-environment). This displays a help buffer describing the languages supported by the language environment, and listing the associated character sets, coding systems, and input methods, as well as some sample text for that language environment.

The command C-h h (view-hello-file) displays the file ‘etc/HELLO’, which demonstrates various character sets by showing how to say “hello” in many languages.

The command C-h I (describe-input-method) describes an input method—either a specified input method, or by default the input method currently in use. See section Input Methods.

The command C-h C (describe-coding-system) describes coding systems—either a specified coding system, or the ones currently in use. See section Coding Systems.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.8 Other Help Commands

C-h i (info) runs the Info program, which browses structured documentation files. The entire Emacs manual is available within Info, along with many other manuals for the GNU system. Type h after entering Info to run a tutorial on using Info.

With a numeric argument n, C-h i selects the Info buffer ‘*info*<n>’. This is useful if you want to browse multiple Info manuals simultaneously. If you specify just C-u as the prefix argument, C-h i prompts for the name of a documentation file, so you can browse a file which doesn’t have an entry in the top-level Info menu.

The help commands C-h F function <RET> and C-h K key, described above, enter Info and go straight to the documentation of function or key.

When editing a program, if you have an Info version of the manual for the programming language, you can use C-h S (info-lookup-symbol) to find an entry for a symbol (keyword, function or variable) in the proper manual. The details of how this command works depend on the major mode.

If something surprising happens, and you are not sure what you typed, use C-h l (view-lossage). C-h l displays your last 300 input keystrokes and the commands they invoked. If you see commands that you are not familiar with, you can use C-h k or C-h f to find out what they do.

To review recent echo area messages, use C-h e (view-echo-area-messages). This displays the buffer ‘*Messages*’, where those messages are kept.

Each Emacs major mode typically redefines a few keys and makes other changes in how editing works. C-h m (describe-mode) displays documentation on the current major mode, which normally describes the commands and features that are changed in this mode, and also its key bindings.

C-h b (describe-bindings) and C-h s (describe-syntax) show other information about the current environment within Emacs. C-h b displays a list of all the key bindings now in effect: first the local bindings of the current minor modes, then the local bindings defined by the current major mode, and finally the global bindings (see section Customizing Key Bindings). C-h s displays the contents of the syntax table, with explanations of each character’s syntax (see Syntax Tables in The Emacs Lisp Reference Manual).

You can get a list of subcommands for a particular prefix key by typing C-h, ?, or <F1> (describe-prefix-bindings) after the prefix key. (There are a few prefix keys for which not all of these keys work—those that provide their own bindings for that key. One of these prefix keys is <ESC>, because <ESC> C-h is actually C-M-h, which marks a defun. However, <ESC> <F1> and <ESC> ? work fine.)


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.9 Help Files

Apart from the built-in documentation and manuals, Emacs contains several other files describing topics like copying conditions, release notes, instructions for debugging and reporting bugs, and so forth. You can use the following commands to view these files. Apart from C-h g, they all have the form C-h C-char.

C-h C-c

Display the rules under which you can copy and redistribute Emacs (describe-copying).

C-h C-d

Display help for debugging Emacs (view-emacs-debugging).

C-h C-e

Display information about where to get external packages (view-external-packages).

C-h C-f

Display the Emacs frequently-answered-questions list (view-emacs-FAQ).

C-h g

Visit the page with information about the GNU Project (describe-gnu-project).

C-h C-m

Display information about ordering printed copies of Emacs manuals (view-order-manuals).

C-h C-n

Display the news, which lists the new features in this version of Emacs (view-emacs-news).

C-h C-o

Display how to order or download the latest version of Emacs and other GNU software (describe-distribution).

C-h C-p

Display the list of known Emacs problems, sometimes with suggested workarounds (view-emacs-problems).

C-h C-t

Display the Emacs to-do list (view-emacs-todo).

C-h C-w

Display the full details on the complete absence of warranty for GNU Emacs (describe-no-warranty).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.10 Help on Active Text and Tooltips

In Emacs, stretches of active text (text that does something special in response to mouse clicks or <RET>) often have associated help text. This includes hyperlinks in Emacs buffers, as well as parts of the mode line. On graphical displays, as well as some text terminals which support mouse tracking, moving the mouse over the active text displays the help text as a tooltip. See section Tooltips.

On terminals that don’t support mouse-tracking, you can display the help text for active buffer text at point by typing C-h . (display-local-help). This shows the help text in the echo area. To display help text automatically whenever it is available at point, set the variable help-at-pt-display-when-idle to t.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section Customizing Faces).

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 section Quitting and Aborting).

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 section Disabling Transient Mark Mode.

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 section Multiple 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 section Rectangles.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.1 Setting the Mark

Here are some commands for setting the mark:

C-<SPC>

Set the mark at point, and activate it (set-mark-command).

C-@

The same.

C-x C-x

Set the mark at point, and activate it; then move point where the mark used to be (exchange-point-and-mark).

Drag-mouse-1

Set point and the mark around the text you drag across.

mouse-3

Set the mark at point, then move point to where you click (mouse-save-then-kill).

Shifted cursor motion keys

Set the mark at point if the mark is inactive, then move point. See section Shift Selection.

The most common way to set the mark is with C-<SPC> (set-mark-command)(5). This sets the mark where point is, and activates it. You can then move point away, leaving the mark behind.

For example, suppose you wish to convert part of the buffer to upper case. To accomplish this, go to one end of the desired text, type C-<SPC>, and move point until the desired portion of text is highlighted. Now type C-x C-u (upcase-region). This converts the text in the region to upper case, and then deactivates the mark.

Whenever the mark is active, you can deactivate it by typing C-g (see section Quitting and Aborting). Most commands that operate on the region also automatically deactivate the mark, like C-x C-u in the above example.

Instead of setting the mark in order to operate on a region, you can also use it to remember a position in the buffer (by typing C-<SPC> C-<SPC>), and later jump back there (by typing C-u C-<SPC>). See section The Mark Ring, for details.

The command C-x C-x (exchange-point-and-mark) exchanges the positions of point and the mark. C-x C-x is useful when you are satisfied with the position of point but want to move the other end of the region (where the mark is). Using C-x C-x a second time, if necessary, puts the mark at the new position with point back at its original position. Normally, if the mark is inactive, this command first reactivates the mark wherever it was last set, to ensure that the region is left highlighted. However, if you call it with a prefix argument, it leaves the mark inactive and the region unhighlighted; you can use this to jump to the mark in a manner similar to C-u C-<SPC>.

You can also set the mark with the mouse. If you press the left mouse button (down-mouse-1) and drag the mouse across a range of text, this sets the mark where you first pressed the mouse button and puts point where you release it. Alternatively, clicking the right mouse button (mouse-3) sets the mark at point and then moves point to where you clicked. See section Mouse Commands for Editing, for a more detailed description of these mouse commands.

Finally, you can set the mark by holding down the shift key while typing certain cursor motion commands (such as S-<RIGHT>, S-C-f, S-C-n, etc.). This is called shift-selection. It sets the mark at point before moving point, but only if there is no active mark set via a previous shift-selection or mouse commands. The mark set by mouse commands and by shift-selection behaves slightly differently from the usual mark: any subsequent unshifted cursor motion command deactivates it automatically. For details, see Shift Selection.

Many commands that insert text, such as C-y (yank), set the mark at the other end of the inserted text, without activating it. This lets you easily return to that position (see section The Mark Ring). You can tell that a command does this when it shows ‘Mark set’ in the echo area.

Under X, every time the active region changes, Emacs saves the text in the region to the primary selection. This lets you insert that text into other X applications with mouse-2 clicks. See section Cut and Paste with Other Window Applications.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.2 Commands to Mark Textual Objects

Here are commands for placing point and the mark around a textual object such as a word, list, paragraph or page:

M-@

Set mark at the end of the next word (mark-word). This does not move point.

C-M-@

Set mark after end of following balanced expression (mark-sexp). This does not move point.

M-h

Move point to the beginning of the current paragraph, and set mark at the end (mark-paragraph).

C-M-h

Move point to the beginning of the current defun, and set mark at the end (mark-defun).

C-x C-p

Move point to the beginning of the current page, and set mark at the end (mark-page).

C-x h

Move point to the beginning of the buffer, and set mark at the end (mark-whole-buffer).

M-@ (mark-word) sets the mark at the end of the next word (see section Words, for information about words). Repeated invocations of this command extend the region by advancing the mark one word at a time. As an exception, if the mark is active and located before point, M-@ moves the mark backwards from its current position one word at a time.

This command also accepts a numeric argument n, which tells it to advance the mark by n words. A negative argument moves the mark back by n words.

Similarly, C-M-@ (mark-sexp) puts the mark at the end of the next balanced expression (see section Expressions with Balanced Parentheses). Repeated invocations extend the region to subsequent expressions, while positive or negative numeric arguments move the mark forward or backward by the specified number of expressions.

The other commands in the above list set both point and mark, so as to delimit an object in the buffer. M-h (mark-paragraph) marks paragraphs (see section Paragraphs), C-M-h (mark-defun) marks top-level definitions (see section Moving by Defuns), and C-x C-p (mark-page) marks pages (see section Pages). Repeated invocations again play the same role, extending the region to consecutive objects; similarly, numeric arguments specify how many objects to move the mark by.

C-x h (mark-whole-buffer) sets up the entire buffer as the region, by putting point at the beginning and the mark at the end.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.3 Operating on the Region

Once you have a region, here are some of the ways you can operate on it:

Some commands have a default behavior when the mark is inactive, but operate on the region if the mark is active. For example, M-$ (ispell-word) normally checks the spelling of the word at point, but it checks the text in the region if the mark is active (see section Checking and Correcting Spelling). Normally, such commands use their default behavior if the region is empty (i.e., if mark and point are at the same position). If you want them to operate on the empty region, change the variable use-empty-active-region to t.

As described in Erasing Text, the <DEL> (backward-delete-char) and <Delete> (delete-forward-char) commands also act this way. If the mark is active, they delete the text in the region. (As an exception, if you supply a numeric argument n, where n is not one, these commands delete n characters regardless of whether the mark is active). If you change the variable delete-active-region to nil, then these commands don’t act differently when the mark is active. If you change the value to kill, these commands kill the region instead of deleting it (see section Killing and Moving Text).

Other commands always operate on the region, and have no default behavior. Such commands usually have the word region in their names, like C-w (kill-region) and C-x C-u (upcase-region). If the mark is inactive, they operate on the inactive region—that is, on the text between point and the position at which the mark was last set (see section The Mark Ring). To disable this behavior, change the variable mark-even-if-inactive to nil. Then these commands will instead signal an error if the mark is inactive.

By default, text insertion occurs normally even if the mark is active—for example, typing a inserts the character ‘a’, then deactivates the mark. Delete Selection mode, a minor mode, modifies this behavior: if you enable that mode, then inserting text while the mark is active causes the text in the region to be deleted first. To toggle Delete Selection mode on or off, type M-x delete-selection-mode.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.4 The Mark Ring

Each buffer remembers previous locations of the mark, in the mark ring. Commands that set the mark also push the old mark onto this ring. One of the uses of the mark ring is to remember spots that you may want to go back to.

C-<SPC> C-<SPC>

Set the mark, pushing it onto the mark ring, without activating it.

C-u C-<SPC>

Move point to where the mark was, and restore the mark from the ring of former marks.

The command C-<SPC> C-<SPC> is handy when you want to use the mark to remember a position to which you may wish to return. It pushes the current point onto the mark ring, without activating the mark (which would cause Emacs to highlight the region). This is actually two consecutive invocations of C-<SPC> (set-mark-command); the first C-<SPC> sets the mark, and the second C-<SPC> deactivates it. (When Transient Mark mode is off, C-<SPC> C-<SPC> instead activates Transient Mark mode temporarily; see section Disabling Transient Mark Mode.)

To return to a marked position, use set-mark-command with a prefix argument: C-u C-<SPC>. This moves point to where the mark was, and deactivates the mark if it was active. Each subsequent C-u C-<SPC> jumps to a prior position stored in the mark ring. The positions you move through in this way are not lost; they go to the end of the ring.

If you set set-mark-command-repeat-pop to non-nil, then immediately after you type C-u C-<SPC>, you can type C-<SPC> instead of C-u C-<SPC> to cycle through the mark ring. By default, set-mark-command-repeat-pop is nil.

Each buffer has its own mark ring. All editing commands use the current buffer’s mark ring. In particular, C-u C-<SPC> always stays in the same buffer.

The variable mark-ring-max specifies the maximum number of entries to keep in the mark ring. This defaults to 16 entries. If that many entries exist and another one is pushed, the earliest one in the list is discarded. Repeating C-u C-<SPC> cycles through the positions currently in the ring.

If you want to move back to the same place over and over, the mark ring may not be convenient enough. If so, you can record the position in a register for later retrieval (see section Saving Positions in Registers).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.5 The Global Mark Ring

In addition to the ordinary mark ring that belongs to each buffer, Emacs has a single global mark ring. Each time you set a mark, this is recorded in the global mark ring in addition to the current buffer’s own mark ring, if you have switched buffers since the previous mark setting. Hence, the global mark ring records a sequence of buffers that you have been in, and, for each buffer, a place where you set the mark. The length of the global mark ring is controlled by global-mark-ring-max, and is 16 by default.

The command C-x C-<SPC> (pop-global-mark) jumps to the buffer and position of the latest entry in the global ring. It also rotates the ring, so that successive uses of C-x C-<SPC> take you to earlier buffers and mark positions.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.6 Shift Selection

If you hold down the shift key while typing a cursor motion command, this sets the mark before moving point, so that the region extends from the original position of point to its new position. This feature is referred to as shift-selection. It is similar to the way text is selected in other editors.

The mark set via shift-selection behaves a little differently from what we have described above. Firstly, in addition to the usual ways of deactivating the mark (such as changing the buffer text or typing C-g), the mark is deactivated by any unshifted cursor motion command. Secondly, any subsequent shifted cursor motion command avoids setting the mark anew. Therefore, a series of shifted cursor motion commands will continuously adjust the region.

Shift-selection only works if the shifted cursor motion key is not already bound to a separate command (see section Customization). For example, if you bind S-C-f to another command, typing S-C-f runs that command instead of performing a shift-selected version of C-f (forward-char).

A mark set via mouse commands behaves the same as a mark set via shift-selection (see section Setting the Mark). For example, if you specify a region by dragging the mouse, you can continue to extend the region using shifted cursor motion commands. In either case, any unshifted cursor motion command deactivates the mark.

To turn off shift-selection, set shift-select-mode to nil. Doing so does not disable setting the mark via mouse commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.7 Disabling Transient Mark Mode

The default behavior of the mark and region, in which setting the mark activates it and highlights the region, is called Transient Mark mode. This is a minor mode that is enabled by default. It can be toggled with M-x transient-mark-mode, or with the ‘Active Region Highlighting’ menu item in the ‘Options’ menu. Turning it off switches Emacs to an alternative mode of operation:

While Transient Mark mode is off, you can activate it temporarily using C-<SPC> C-<SPC> or C-u C-x C-x.

C-<SPC> C-<SPC>

Set the mark at point (like plain C-<SPC>) and enable Transient Mark mode just once, until the mark is deactivated. (This is not really a separate command; you are using the C-<SPC> command twice.)

C-u C-x C-x

Exchange point and mark, activate the mark and enable Transient Mark mode temporarily, until the mark is next deactivated. (This is the C-x C-x command, exchange-point-and-mark, with a prefix argument.)

These commands set or activate the mark, and enable Transient Mark mode only until the mark is deactivated. One reason you may want to use them is that some commands operate on the entire buffer instead of the region when Transient Mark mode is off. Enabling Transient Mark mode momentarily gives you a way to use these commands on the region.

When you specify a region with the mouse (see section Setting the Mark), or with shift-selection (see section Shift Selection), this likewise activates Transient Mark mode temporarily and highlights the region.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section The 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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.1 Deletion and Killing

Most commands which erase text from the buffer save it in the kill ring (see section The Kill Ring). These are known as kill commands, and their names normally contain the word ‘kill’ (e.g., kill-line). The kill ring stores several recent kills, not just the last one, so killing is a very safe operation: you don’t have to worry much about losing text that you previously killed. The kill ring is shared by all buffers, so text that is killed in one buffer can be yanked into another buffer.

When you use C-/ (undo) to undo a kill command (see section Undo), that brings the killed text back into the buffer, but does not remove it from the kill ring.

On graphical displays, killing text also copies it to the system clipboard. See section “Cut and Paste” Operations on Graphical Displays.

Commands that erase text but do not save it in the kill ring are known as delete commands; their names usually contain the word ‘delete’. These include C-d (delete-char) and <DEL> (delete-backward-char), which delete only one character at a time, and those commands that delete only spaces or newlines. Commands that can erase significant amounts of nontrivial data generally do a kill operation instead.

You can also use the mouse to kill and yank. See section “Cut and Paste” Operations on Graphical Displays.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.1.1 Deletion

Deletion means erasing text and not saving it in the kill ring. For the most part, the Emacs commands that delete text are those that erase just one character or only whitespace.

<DEL>
<BACKSPACE>

Delete the previous character, or the text in the region if it is active (delete-backward-char).

<Delete>

Delete the next character, or the text in the region if it is active (delete-forward-char).

C-d

Delete the next character (delete-char).

M-\

Delete spaces and tabs around point (delete-horizontal-space).

M-<SPC>

Delete spaces and tabs around point, leaving one space (just-one-space).

C-x C-o

Delete blank lines around the current line (delete-blank-lines).

M-^

Join two lines by deleting the intervening newline, along with any indentation following it (delete-indentation).

We have already described the basic deletion commands <DEL> (delete-backward-char), <delete> (delete-forward-char), and C-d (delete-char). See section Erasing Text. With a numeric argument, they delete the specified number of characters. If the numeric argument is omitted or one, <DEL> and <delete> delete all the text in the region if it is active (see section Operating on the Region).

The other delete commands are those that delete only whitespace characters: spaces, tabs and newlines. M-\ (delete-horizontal-space) deletes all the spaces and tab characters before and after point. With a prefix argument, this only deletes spaces and tab characters before point. M-<SPC> (just-one-space) does likewise but leaves a single space before point, regardless of the number of spaces that existed previously (even if there were none before). With a numeric argument n, it leaves n spaces before point if n is positive; if n is negative, it deletes newlines in addition to spaces and tabs, leaving -n spaces before point. The command cycle-spacing acts like a more flexible version of just-one-space. It does different things if you call it repeatedly in succession. The first call acts like just-one-space, the next removes all whitespace, and a third call restores the original whitespace.

C-x C-o (delete-blank-lines) deletes all blank lines after the current line. If the current line is blank, it deletes all blank lines preceding the current line as well (leaving one blank line, the current line). On a solitary blank line, it deletes that line.

M-^ (delete-indentation) joins the current line and the previous line, by deleting a newline and all surrounding spaces, usually leaving a single space. See section M-^.

The command delete-duplicate-lines searches the region for identical lines, and removes all but one copy of each. Normally it keeps the first instance of each repeated line, but with a C-u prefix argument it keeps the last. With a C-u C-u prefix argument, it only searches for adjacent identical lines. This is a more efficient mode of operation, useful when the lines have already been sorted. With a C-u C-u C-u prefix argument, it retains repeated blank lines.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.1.2 Killing by Lines

C-k

Kill rest of line or one or more lines (kill-line).

C-S-backspace

Kill an entire line at once (kill-whole-line)

The simplest kill command is C-k (kill-line). If used at the end of a line, it kills the line-ending newline character, merging the next line into the current one (thus, a blank line is entirely removed). Otherwise, C-k kills all the text from point up to the end of the line; if point was originally at the beginning of the line, this leaves the line blank.

Spaces and tabs at the end of the line are ignored when deciding which case applies. As long as point is after the last non-whitespace character in the line, you can be sure that C-k will kill the newline. To kill an entire non-blank line, go to the beginning and type C-k twice.

In this context, “line” means a logical text line, not a screen line (see section Continuation Lines).

When C-k is given a positive argument n, it kills n lines and the newlines that follow them (text on the current line before point is not killed). With a negative argument -n, it kills n lines preceding the current line, together with the text on the current line before point. C-k with an argument of zero kills the text before point on the current line.

If the variable kill-whole-line is non-nil, C-k at the very beginning of a line kills the entire line including the following newline. This variable is normally nil.

C-S-backspace (kill-whole-line) kills a whole line including its newline, regardless of the position of point within the line. Note that many text terminals will prevent you from typing the key sequence C-S-backspace.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.1.3 Other Kill Commands

C-w

Kill the region (kill-region).

M-w

Copy the region into the kill ring (kill-ring-save).

M-d

Kill the next word (kill-word). See section Words.

M-<DEL>

Kill one word backwards (backward-kill-word).

C-x <DEL>

Kill back to beginning of sentence (backward-kill-sentence). See section Sentences.

M-k

Kill to the end of the sentence (kill-sentence).

C-M-k

Kill the following balanced expression (kill-sexp). See section Expressions with Balanced Parentheses.

M-z char

Kill through the next occurrence of char (zap-to-char).

One of the commonly-used kill commands is C-w (kill-region), which kills the text in the region (see section The Mark and the Region). Similarly, M-w (kill-ring-save) copies the text in the region into the kill ring without removing it from the buffer. If the mark is inactive when you type C-w or M-w, the command acts on the text between point and where you last set the mark (see section Operating on the Region).

Emacs also provides commands to kill specific syntactic units: words, with M-<DEL> and M-d (see section Words); balanced expressions, with C-M-k (see section Expressions with Balanced Parentheses); and sentences, with C-x <DEL> and M-k (see section Sentences).

The command M-z (zap-to-char) combines killing with searching: it reads a character and kills from point up to (and including) the next occurrence of that character in the buffer. A numeric argument acts as a repeat count; a negative argument means to search backward and kill text before point.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.1.4 Options for Killing

Some specialized buffers contain read-only text, which cannot be modified and therefore cannot be killed. The kill commands work specially in a read-only buffer: they move over text and copy it to the kill ring, without actually deleting it from the buffer. Normally, they also beep and display an error message when this happens. But if you set the variable kill-read-only-ok to a non-nil value, they just print a message in the echo area to explain why the text has not been erased.

If you change the variable kill-do-not-save-duplicates to a non-nil value, identical subsequent kills yield a single kill-ring entry, without duplication.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.2 Yanking

Yanking means reinserting text previously killed. The usual way to move or copy text is to kill it and then yank it elsewhere.

C-y

Yank the last kill into the buffer, at point (yank).

M-y

Replace the text just yanked with an earlier batch of killed text (yank-pop). See section Yanking Earlier Kills.

C-M-w

Cause the following command, if it is a kill command, to append to the previous kill (append-next-kill). See section Appending Kills.

The basic yanking command is C-y (yank). It inserts the most recent kill, leaving the cursor at the end of the inserted text. It also sets the mark at the beginning of the inserted text, without activating the mark; this lets you jump easily to that position, if you wish, with C-u C-<SPC> (see section The Mark Ring).

With a plain prefix argument (C-u C-y), the command instead leaves the cursor in front of the inserted text, and sets the mark at the end. Using any other prefix argument specifies an earlier kill; e.g., C-u 4 C-y reinserts the fourth most recent kill. See section Yanking Earlier Kills.

On graphical displays, C-y first checks if another application has placed any text in the system clipboard more recently than the last Emacs kill. If so, it inserts the clipboard’s text instead. Thus, Emacs effectively treats “cut” or “copy” clipboard operations performed in other applications like Emacs kills, except that they are not recorded in the kill ring. See section “Cut and Paste” Operations on Graphical Displays, for details.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.2.1 The Kill Ring

The kill ring is a list of blocks of text that were previously killed. There is only one kill ring, shared by all buffers, so you can kill text in one buffer and yank it in another buffer. This is the usual way to move text from one buffer to another. (There are several other methods: for instance, you could store the text in a register; see Registers. See section Accumulating Text, for some other ways to move text around.)

The maximum number of entries in the kill ring is controlled by the variable kill-ring-max. The default is 60. If you make a new kill when this limit has been reached, Emacs makes room by deleting the oldest entry in the kill ring.

The actual contents of the kill ring are stored in a variable named kill-ring; you can view the entire contents of the kill ring with C-h v kill-ring.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.2.2 Yanking Earlier Kills

As explained in Yanking, you can use a numeric argument to C-y to yank text that is no longer the most recent kill. This is useful if you remember which kill ring entry you want. If you don’t, you can use the M-y (yank-pop) command to cycle through the possibilities.

If the previous command was a yank command, M-y takes the text that was yanked and replaces it with the text from an earlier kill. So, to recover the text of the next-to-the-last kill, first use C-y to yank the last kill, and then use M-y to replace it with the previous kill. M-y is allowed only after a C-y or another M-y.

You can understand M-y in terms of a last-yank pointer which points at an entry in the kill ring. Each time you kill, the last-yank pointer moves to the newly made entry at the front of the ring. C-y yanks the entry which the last-yank pointer points to. M-y moves the last-yank pointer to a different entry, and the text in the buffer changes to match. Enough M-y commands can move the pointer to any entry in the ring, so you can get any entry into the buffer. Eventually the pointer reaches the end of the ring; the next M-y loops back around to the first entry again.

M-y moves the last-yank pointer around the ring, but it does not change the order of the entries in the ring, which always runs from the most recent kill at the front to the oldest one still remembered.

M-y can take a numeric argument, which tells it how many entries to advance the last-yank pointer by. A negative argument moves the pointer toward the front of the ring; from the front of the ring, it moves around to the last entry and continues forward from there.

Once the text you are looking for is brought into the buffer, you can stop doing M-y commands and it will stay there. It’s just a copy of the kill ring entry, so editing it in the buffer does not change what’s in the ring. As long as no new killing is done, the last-yank pointer remains at the same place in the kill ring, so repeating C-y will yank another copy of the same previous kill.

When you call C-y with a numeric argument, that also sets the last-yank pointer to the entry that it yanks.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.2.3 Appending Kills

Normally, each kill command pushes a new entry onto the kill ring. However, two or more kill commands in a row combine their text into a single entry, so that a single C-y yanks all the text as a unit, just as it was before it was killed.

Thus, if you want to yank text as a unit, you need not kill all of it with one command; you can keep killing line after line, or word after word, until you have killed it all, and you can still get it all back at once.

Commands that kill forward from point add onto the end of the previous killed text. Commands that kill backward from point add text onto the beginning. This way, any sequence of mixed forward and backward kill commands puts all the killed text into one entry without rearrangement. Numeric arguments do not break the sequence of appending kills. For example, suppose the buffer contains this text:

This is a line ∗of sample text.

with point shown by ∗. If you type M-d M-<DEL> M-d M-<DEL>, killing alternately forward and backward, you end up with ‘a line of sample’ as one entry in the kill ring, and ‘This is  text.’ in the buffer. (Note the double space between ‘is’ and ‘text’, which you can clean up with M-<SPC> or M-q.)

Another way to kill the same text is to move back two words with M-b M-b, then kill all four words forward with C-u M-d. This produces exactly the same results in the buffer and in the kill ring. M-f M-f C-u M-<DEL> kills the same text, all going backward; once again, the result is the same. The text in the kill ring entry always has the same order that it had in the buffer before you killed it.

If a kill command is separated from the last kill command by other commands (not just numeric arguments), it starts a new entry on the kill ring. But you can force it to combine with the last killed text, by typing C-M-w (append-next-kill) right beforehand. The C-M-w tells its following command, if it is a kill command, to treat the kill as part of the sequence of previous kills. As usual, the kill is appended to the previous killed text if the command kills forward, and prepended if the command kills backward. In this way, you can kill several separated pieces of text and accumulate them to be yanked back in one place.

A kill command following M-w (kill-ring-save) does not append to the text that M-w copied into the kill ring.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.3 “Cut and Paste” Operations on Graphical Displays

In most graphical desktop environments, you can transfer data (usually text) between different applications using a system facility called the clipboard. On X, two other similar facilities are available: the primary selection and the secondary selection. When Emacs is run on a graphical display, its kill and yank commands integrate with these facilities, so that you can easily transfer text between Emacs and other graphical applications.

By default, Emacs uses UTF-8 as the coding system for inter-program text transfers. If you find that the pasted text is not what you expected, you can specify another coding system by typing C-x <RET> x or C-x <RET> X. You can also request a different data type by customizing x-select-request-type. See section Coding Systems for Interprocess Communication.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.3.1 Using the Clipboard

The clipboard is the facility that most graphical applications use for “cutting and pasting”. When the clipboard exists, the kill and yank commands in Emacs make use of it.

When you kill some text with a command such as C-w (kill-region), or copy it to the kill ring with a command such as M-w (kill-ring-save), that text is also put in the clipboard.

When an Emacs kill command puts text in the clipboard, the existing clipboard contents are normally lost. Optionally, you can change save-interprogram-paste-before-kill to t. Then Emacs will first save the clipboard to its kill ring, preventing you from losing the old clipboard data—at the risk of high memory consumption if that data turns out to be large.

Yank commands, such as C-y (yank), also use the clipboard. If another application “owns” the clipboard—i.e., if you cut or copied text there more recently than your last kill command in Emacs—then Emacs yanks from the clipboard instead of the kill ring.

Normally, rotating the kill ring with M-y (yank-pop) does not alter the clipboard. However, if you change yank-pop-change-selection to t, then M-y saves the new yank to the clipboard.

To prevent kill and yank commands from accessing the clipboard, change the variable select-enable-clipboard to nil.

Many X desktop environments support a feature called the clipboard manager. If you exit Emacs while it is the current “owner” of the clipboard data, and there is a clipboard manager running, Emacs transfers the clipboard data to the clipboard manager so that it is not lost. In some circumstances, this may cause a delay when exiting Emacs; if you wish to prevent Emacs from transferring data to the clipboard manager, change the variable x-select-enable-clipboard-manager to nil.

Since strings containing NUL bytes are usually truncated when passed through the clipboard, Emacs replaces such characters with “\0” before transferring them to the system’s clipboard.

Prior to Emacs 24, the kill and yank commands used the primary selection (see section Cut and Paste with Other Window Applications), not the clipboard. If you prefer this behavior, change select-enable-clipboard to nil, select-enable-primary to t, and mouse-drag-copy-region to t. In this case, you can use the following commands to act explicitly on the clipboard: clipboard-kill-region kills the region and saves it to the clipboard; clipboard-kill-ring-save copies the region to the kill ring and saves it to the clipboard; and clipboard-yank yanks the contents of the clipboard at point.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.3.2 Cut and Paste with Other Window Applications

Under the X Window System, there exists a primary selection containing the last stretch of text selected in an X application (usually by dragging the mouse). Typically, this text can be inserted into other X applications by mouse-2 clicks. The primary selection is separate from the clipboard. Its contents are more fragile; they are overwritten each time you select text with the mouse, whereas the clipboard is only overwritten by explicit cut or copy commands.

Under X, whenever the region is active (see section The Mark and the Region), the text in the region is saved in the primary selection. This applies regardless of whether the region was made by dragging or clicking the mouse (see section Mouse Commands for Editing), or by keyboard commands (e.g., by typing C-<SPC> and moving point; see section Setting the Mark).

If you change the variable select-active-regions to only, Emacs saves only temporarily active regions to the primary selection, i.e., those made with the mouse or with shift selection (see section Shift Selection). If you change select-active-regions to nil, Emacs avoids saving active regions to the primary selection entirely.

To insert the primary selection into an Emacs buffer, click mouse-2 (mouse-yank-primary) where you want to insert it. See section Mouse Commands for Editing.

MS-Windows provides no primary selection, but Emacs emulates it within a single Emacs session by storing the selected text internally. Therefore, all the features and commands related to the primary selection work on Windows as they do on X, for cutting and pasting within the same session, but not across Emacs sessions or with other applications.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.3.3 Secondary Selection

In addition to the primary selection, the X Window System provides a second similar facility known as the secondary selection. Nowadays, few X applications make use of the secondary selection, but you can access it using the following Emacs commands:

M-Drag-mouse-1

Set the secondary selection, with one end at the place where you press down the button, and the other end at the place where you release it (mouse-set-secondary). The selected text is highlighted, using the secondary-selection face, as you drag. The window scrolls automatically if you drag the mouse off the top or bottom of the window, just like mouse-set-region (see section Mouse Commands for Editing).

This command does not alter the kill ring.

M-mouse-1

Set one endpoint for the secondary selection (mouse-start-secondary).

M-mouse-3

Set the secondary selection, with one end at the position clicked and the other at the position specified with M-mouse-1 (mouse-secondary-save-then-kill). This also puts the selected text in the kill ring. A second M-mouse-3 at the same place kills the secondary selection just made.

M-mouse-2

Insert the secondary selection where you click, placing point at the end of the yanked text (mouse-yank-secondary).

Double or triple clicking of M-mouse-1 operates on words and lines, much like mouse-1.

If mouse-yank-at-point is non-nil, M-mouse-2 yanks at point. Then it does not matter precisely where you click, or even which of the frame’s windows you click on. See section Mouse Commands for Editing.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.4 Accumulating Text

Usually we copy or move text by killing it and yanking it, but there are other convenient methods for copying one block of text in many places, or for copying many scattered blocks of text into one place. Here we describe the commands to accumulate scattered pieces of text into a buffer or into a file.

M-x append-to-buffer

Append region to the contents of a specified buffer.

M-x prepend-to-buffer

Prepend region to the contents of a specified buffer.

M-x copy-to-buffer

Copy region into a specified buffer, deleting that buffer’s old contents.

M-x insert-buffer

Insert the contents of a specified buffer into current buffer at point.

M-x append-to-file

Append region to the contents of a specified file, at the end.

To accumulate text into a buffer, use M-x append-to-buffer. This reads a buffer name, then inserts a copy of the region into the buffer specified. If you specify a nonexistent buffer, append-to-buffer creates the buffer. The text is inserted wherever point is in that buffer. If you have been using the buffer for editing, the copied text goes into the middle of the text of the buffer, starting from wherever point happens to be at that moment.

Point in that buffer is left at the end of the copied text, so successive uses of append-to-buffer accumulate the text in the specified buffer in the same order as they were copied. Strictly speaking, append-to-buffer does not always append to the text already in the buffer—it appends only if point in that buffer is at the end. However, if append-to-buffer is the only command you use to alter a buffer, then point is always at the end.

M-x prepend-to-buffer is just like append-to-buffer except that point in the other buffer is left before the copied text, so successive uses of this command add text in reverse order. M-x copy-to-buffer is similar, except that any existing text in the other buffer is deleted, so the buffer is left containing just the text newly copied into it.

The command M-x insert-buffer can be used to retrieve the accumulated text from another buffer. This prompts for the name of a buffer, and inserts a copy of all the text in that buffer into the current buffer at point, leaving point at the beginning of the inserted text. It also adds the position of the end of the inserted text to the mark ring, without activating the mark. See section Using Multiple Buffers, for background information on buffers.

Instead of accumulating text in a buffer, you can append text directly into a file with M-x append-to-file. This prompts for a filename, and adds the text of the region to the end of the specified file. The file is changed immediately on disk.

You should use append-to-file only with files that are not being visited in Emacs. Using it on a file that you are editing in Emacs would change the file behind Emacs’s back, which can lead to losing some of your editing.

Another way to move text around is to store it in a register. See section Registers.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.5 Rectangles

Rectangle commands operate on rectangular areas of the text: all the characters between a certain pair of columns, in a certain range of lines. Emacs has commands to kill rectangles, yank killed rectangles, clear them out, fill them with blanks or text, or delete them. Rectangle commands are useful with text in multicolumn formats, and for changing text into or out of such formats.

To specify a rectangle for a command to work on, set the mark at one corner and point at the opposite corner. The rectangle thus specified is called the region-rectangle. If point and the mark are in the same column, the region-rectangle is empty. If they are in the same line, the region-rectangle is one line high.

The region-rectangle is controlled in much the same way as the region is controlled. But remember that a given combination of point and mark values can be interpreted either as a region or as a rectangle, depending on the command that uses them.

C-x r k

Kill the text of the region-rectangle, saving its contents as the last killed rectangle (kill-rectangle).

C-x r M-w

Save the text of the region-rectangle as the last killed rectangle (copy-rectangle-as-kill).

C-x r d

Delete the text of the region-rectangle (delete-rectangle).

C-x r y

Yank the last killed rectangle with its upper left corner at point (yank-rectangle).

C-x r o

Insert blank space to fill the space of the region-rectangle (open-rectangle). This pushes the previous contents of the region-rectangle to the right.

C-x r N

Insert line numbers along the left edge of the region-rectangle (rectangle-number-lines). This pushes the previous contents of the region-rectangle to the right.

C-x r c

Clear the region-rectangle by replacing all of its contents with spaces (clear-rectangle).

M-x delete-whitespace-rectangle

Delete whitespace in each of the lines on the specified rectangle, starting from the left edge column of the rectangle.

C-x r t string <RET>

Replace rectangle contents with string on each line (string-rectangle).

M-x string-insert-rectangle <RET> string <RET>

Insert string on each line of the rectangle.

C-x <SPC>

Toggle Rectangle Mark mode (rectangle-mark-mode). When this mode is active, the region-rectangle is highlighted and can be shrunk/grown, and the standard kill and yank commands operate on it.

The rectangle operations fall into two classes: commands to erase or insert rectangles, and commands to make blank rectangles.

There are two ways to erase the text in a rectangle: C-x r d (delete-rectangle) to delete the text outright, or C-x r k (kill-rectangle) to remove the text and save it as the last killed rectangle. In both cases, erasing the region-rectangle is like erasing the specified text on each line of the rectangle; if there is any following text on the line, it moves backwards to fill the gap.

Killing a rectangle is not killing in the usual sense; the rectangle is not stored in the kill ring, but in a special place that only records the most recent rectangle killed. This is because yanking a rectangle is so different from yanking linear text that different yank commands have to be used. Yank-popping is not defined for rectangles.

C-x r M-w (copy-rectangle-as-kill) is the equivalent of M-w for rectangles: it records the rectangle as the last killed rectangle, without deleting the text from the buffer.

To yank the last killed rectangle, type C-x r y (yank-rectangle). The rectangle’s first line is inserted at point, the rectangle’s second line is inserted at the same horizontal position one line vertically below, and so on. The number of lines affected is determined by the height of the saved rectangle.

For example, you can convert two single-column lists into a double-column list by killing one of the single-column lists as a rectangle, and then yanking it beside the other list.

You can also copy rectangles into and out of registers with C-x r r r and C-x r i r. See section Saving Rectangles in Registers.

There are two commands you can use for making blank rectangles: C-x r c (clear-rectangle) blanks out existing text in the region-rectangle, and C-x r o (open-rectangle) inserts a blank rectangle.

M-x delete-whitespace-rectangle deletes horizontal whitespace starting from a particular column. This applies to each of the lines in the rectangle, and the column is specified by the left edge of the rectangle. The right edge of the rectangle does not make any difference to this command.

The command C-x r N (rectangle-number-lines) inserts line numbers along the left edge of the region-rectangle. Normally, the numbering begins from 1 (for the first line of the rectangle). With a prefix argument, the command prompts for a number to begin from, and for a format string with which to print the numbers (see Formatting Strings in The Emacs Lisp Reference Manual).

The command C-x r t (string-rectangle) replaces the contents of a region-rectangle with a string on each line. The string’s width need not be the same as the width of the rectangle. If the string’s width is less, the text after the rectangle shifts left; if the string is wider than the rectangle, the text after the rectangle shifts right.

The command M-x string-insert-rectangle is similar to string-rectangle, but inserts the string on each line, shifting the original text to the right.

The command C-x <SPC> (rectangle-mark-mode) toggles whether the region-rectangle or the standard region is highlighted (first activating the region if necessary). When this mode is enabled, commands that resize the region (C-f, C-n etc.) do so in a rectangular fashion, and killing and yanking operate on the rectangle. See section Killing and Moving Text. The mode persists only as long as the region is active.

Unlike the standard region, the region-rectangle can have its corners extended past the end of buffer, or inside stretches of white space that point normally cannot enter, like in the middle of a TAB character.

When the region is in rectangle-mark-mode, C-x C-x runs the command rectangle-exchange-point-and-mark, which cycles between the four corners of the region-rectangle. This comes in handy if you want to modify the dimensions of the region-rectangle before invoking an operation on the marked text.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.6 CUA Bindings

The command M-x cua-mode sets up key bindings that are compatible with the Common User Access (CUA) system used in many other applications.

When CUA mode is enabled, the keys C-x, C-c, C-v, and C-z invoke commands that cut (kill), copy, paste (yank), and undo respectively. The C-x and C-c keys perform cut and copy only if the region is active. Otherwise, they still act as prefix keys, so that standard Emacs commands like C-x C-c still work. Note that this means the variable mark-even-if-inactive has no effect for C-x and C-c (see section Operating on the Region).

To enter an Emacs command like C-x C-f while the mark is active, use one of the following methods: either hold Shift together with the prefix key, e.g., S-C-x C-f, or quickly type the prefix key twice, e.g., C-x C-x C-f.

To disable the overriding of standard Emacs binding by CUA mode, while retaining the other features of CUA mode described below, set the variable cua-enable-cua-keys to nil.

CUA mode by default activates Delete-Selection mode (see section Mouse Commands for Editing) so that typed text replaces the active region. To use CUA without this behavior, set the variable cua-delete-selection to nil.

CUA mode provides enhanced rectangle support with visible rectangle highlighting. Use C-<RET> to start a rectangle, extend it using the movement commands, and cut or copy it using C-x or C-c. <RET> moves the cursor to the next (clockwise) corner of the rectangle, so you can easily expand it in any direction. Normal text you type is inserted to the left or right of each line in the rectangle (on the same side as the cursor).

You can use this rectangle support without activating CUA by calling the cua-rectangle-mark-mode command. There’s also the standard command rectangle-mark-mode, see Rectangles.

With CUA you can easily copy text and rectangles into and out of registers by providing a one-digit numeric prefix to the kill, copy, and yank commands, e.g., C-1 C-c copies the region into register 1, and C-2 C-v yanks the contents of register 2.

CUA mode also has a global mark feature which allows easy moving and copying of text between buffers. Use C-S-<SPC> to toggle the global mark on and off. When the global mark is on, all text that you kill or copy is automatically inserted at the global mark, and text you type is inserted at the global mark rather than at the current position.

For example, to copy words from various buffers into a word list in a given buffer, set the global mark in the target buffer, then navigate to each of the words you want in the list, mark it (e.g., with S-M-f), copy it to the list with C-c or M-w, and insert a newline after the word in the target list by pressing <RET>.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section Quitting and Aborting).

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 <RET> 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 <F1>.

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.1 Saving Positions in Registers

C-x r <SPC> r

Record the position of point and the current buffer in register r (point-to-register).

C-x r j r

Jump to the position and buffer saved in register r (jump-to-register).

Typing C-x r <SPC> (point-to-register), followed by a character r, saves both the position of point and the current buffer in register r. The register retains this information until you store something else in it.

The command C-x r j r switches to the buffer recorded in register r, and moves point to the recorded position. The contents of the register are not changed, so you can jump to the saved position any number of times.

If you use C-x r j to go to a saved position, but the buffer it was saved from has been killed, C-x r j tries to create the buffer again by visiting the same file. Of course, this works only for buffers that were visiting files.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.2 Saving Text in Registers

When you want to insert a copy of the same piece of text several times, it may be inconvenient to yank it from the kill ring, since each subsequent kill moves that entry further down the ring. An alternative is to store the text in a register and later retrieve it.

C-x r s r

Copy region into register r (copy-to-register).

C-x r i r

Insert text from register r (insert-register).

M-x append-to-register <RET> r

Append region to text in register r.

When register r contains text, you can use C-x r + (increment-register) to append to that register. Note that command C-x r + behaves differently if r contains a number. See section Keeping Numbers in Registers.

M-x prepend-to-register <RET> r

Prepend region to text in register r.

C-x r s r stores a copy of the text of the region into the register named r. If the mark is inactive, Emacs first reactivates the mark where it was last set. The mark is deactivated at the end of this command. See section The Mark and the Region. C-u C-x r s r, the same command with a prefix argument, copies the text into register r and deletes the text from the buffer as well; you can think of this as moving the region text into the register.

M-x append-to-register <RET> r appends the copy of the text in the region to the text already stored in the register named r. If invoked with a prefix argument, it deletes the region after appending it to the register. The command prepend-to-register is similar, except that it prepends the region text to the text in the register instead of appending it.

When you are collecting text using append-to-register and prepend-to-register, you may want to separate individual collected pieces using a separator. In that case, configure a register-separator and store the separator text in to that register. For example, to get double newlines as text separator during the collection process, you can use the following setting.

(setq register-separator ?+)
(set-register register-separator "\n\n")

C-x r i r inserts in the buffer the text from register r. Normally it leaves point after the text and sets the mark before, without activating it. With a numeric argument, it instead puts point before the text and the mark after.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.3 Saving Rectangles in Registers

A register can contain a rectangle instead of linear text. See section Rectangles, for basic information on how to specify a rectangle in the buffer.

C-x r r r

Copy the region-rectangle into register r (copy-rectangle-to-register). With numeric argument, delete it as well.

C-x r i r

Insert the rectangle stored in register r (if it contains a rectangle) (insert-register).

The C-x r i r (insert-register) command, previously documented in Saving Text in Registers, inserts a rectangle rather than a text string, if the register contains a rectangle.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.4 Saving Window Configurations in Registers

You can save the window configuration of the selected frame in a register, or even the configuration of all windows in all frames, and restore the configuration later. See section Multiple Windows, for information about window configurations.

C-x r w r

Save the state of the selected frame’s windows in register r (window-configuration-to-register).

C-x r f r

Save the state of all frames, including all their windows, in register r (frameset-to-register).

Use C-x r j r to restore a window or frame configuration. This is the same command used to restore a cursor position. When you restore a frame configuration, any existing frames not included in the configuration become invisible. If you wish to delete these frames instead, use C-u C-x r j r.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.5 Keeping Numbers in Registers

There are commands to store a number in a register, to insert the number in the buffer in decimal, and to increment it. These commands can be useful in keyboard macros (see section Keyboard Macros).

C-u number C-x r n r

Store number into register r (number-to-register).

C-u number C-x r + r

If r contains a number, increment the number in that register by number. Note that command C-x r + (increment-register) behaves differently if r contains text. See section Saving Text in Registers.

C-x r i r

Insert the number from register r into the buffer.

C-x r i is the same command used to insert any other sort of register contents into the buffer. C-x r + with no numeric argument increments the register value by 1; C-x r n with no numeric argument stores zero in the register.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.6 Keeping File Names in Registers

If you visit certain file names frequently, you can visit them more conveniently if you put their names in registers. Here’s the Lisp code used to put a file name into register r:

(set-register r '(file . name))

For example,

(set-register ?z '(file . "/gd/gnu/emacs/19.0/src/ChangeLog"))

puts the file name shown in register ‘z’.

To visit the file whose name is in register r, type C-x r j r. (This is the same command used to jump to a position or restore a frame configuration.)


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.7 Keyboard Macro Registers

If you need to execute a keyboard macro (see section Keyboard Macros) frequently, it is more convenient to put it in a register or save it (see section Naming and Saving Keyboard Macros). C-x C-k x r (kmacro-to-register) stores the last keyboard macro in register r.

To execute the keyboard macro in register r, type C-x r j r. (This is the same command used to jump to a position or restore a frameset.)


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.8 Bookmarks

Bookmarks are somewhat like registers in that they record positions you can jump to. Unlike registers, they have long names, and they persist automatically from one Emacs session to the next. The prototypical use of bookmarks is to record where you were reading in various files.

C-x r m <RET>

Set the bookmark for the visited file, at point.

C-x r m bookmark <RET>

Set the bookmark named bookmark at point (bookmark-set).

C-x r M bookmark <RET>

Like C-x r m, but don’t overwrite an existing bookmark.

C-x r b bookmark <RET>

Jump to the bookmark named bookmark (bookmark-jump).

C-x r l

List all bookmarks (list-bookmarks).

M-x bookmark-save

Save all the current bookmark values in the default bookmark file.

To record the current position in the visited file, use the command C-x r m, which sets a bookmark using the visited file name as the default for the bookmark name. If you name each bookmark after the file it points to, then you can conveniently revisit any of those files with C-x r b, and move to the position of the bookmark at the same time.

The command C-x r M (bookmark-set-no-overwrite) works like C-x r m, but it signals an error if the specified bookmark already exists, instead of overwriting it.

To display a list of all your bookmarks in a separate buffer, type C-x r l (list-bookmarks). If you switch to that buffer, you can use it to edit your bookmark definitions or annotate the bookmarks. Type C-h m in the bookmark buffer for more information about its special editing commands.

When you kill Emacs, Emacs saves your bookmarks, if you have changed any bookmark values. You can also save the bookmarks at any time with the M-x bookmark-save command. Bookmarks are saved to the file ‘~/.emacs.d/bookmarks’ (for compatibility with older versions of Emacs, if you have a file named ‘~/.emacs.bmk’, that is used instead). The bookmark commands load your default bookmark file automatically. This saving and loading is how bookmarks persist from one Emacs session to the next.

If you set the variable bookmark-save-flag to 1, each command that sets a bookmark will also save your bookmarks; this way, you don’t lose any bookmark values even if Emacs crashes. The value, if a number, says how many bookmark modifications should go by between saving. If you set this variable to nil, Emacs only saves bookmarks if you explicitly use M-x bookmark-save.

The variable bookmark-default-file specifies the file in which to save bookmarks by default.

Bookmark position values are saved with surrounding context, so that bookmark-jump can find the proper position even if the file is modified slightly. The variable bookmark-search-size says how many characters of context to record on each side of the bookmark’s position.

Here are some additional commands for working with bookmarks:

M-x bookmark-load <RET> filename <RET>

Load a file named filename that contains a list of bookmark values. You can use this command, as well as bookmark-write, to work with other files of bookmark values in addition to your default bookmark file.

M-x bookmark-write <RET> filename <RET>

Save all the current bookmark values in the file filename.

M-x bookmark-delete <RET> bookmark <RET>

Delete the bookmark named bookmark.

M-x bookmark-insert-location <RET> bookmark <RET>

Insert in the buffer the name of the file that bookmark bookmark points to.

M-x bookmark-insert <RET> bookmark <RET>

Insert in the buffer the contents of the file that bookmark bookmark points to.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.1 Scrolling

If a window is too small to display all the text in its buffer, it displays only a portion of it. Scrolling commands change which portion of the buffer is displayed.

Scrolling forward or up advances the portion of the buffer displayed in the window; equivalently, it moves the buffer text upwards relative to the window. Scrolling backward or down displays an earlier portion of the buffer, and moves the text downwards relative to the window.

In Emacs, scrolling up or down refers to the direction that the text moves in the window, not the direction that the window moves relative to the text. This terminology was adopted by Emacs before the modern meaning of “scrolling up” and “scrolling down” became widespread. Hence, the strange result that <PageDown> scrolls up in the Emacs sense.

The portion of a buffer displayed in a window always contains point. If you move point past the bottom or top of the window, scrolling occurs automatically to bring it back onscreen (see section Automatic Scrolling). You can also scroll explicitly with these commands:

C-v
<PageDown>
<next>

Scroll forward by nearly a full window (scroll-up-command).

M-v
<PageUp>
<prior>

Scroll backward (scroll-down-command).

C-v (scroll-up-command) scrolls forward by nearly the whole window height. The effect is to take the two lines at the bottom of the window and put them at the top, followed by lines that were not previously visible. If point was in the text that scrolled off the top, it ends up on the window’s new topmost line. The <PageDown> (or <next>) key is equivalent to C-v.

M-v (scroll-down-command) scrolls backward in a similar way. The <PageUp> (or <prior>) key is equivalent to M-v.

The number of lines of overlap left by these scroll commands is controlled by the variable next-screen-context-lines, whose default value is 2. You can supply the commands with a numeric prefix argument, n, to scroll by n lines; Emacs attempts to leave point unchanged, so that the text and point move up or down together. C-v with a negative argument is like M-v and vice versa.

By default, these commands signal an error (by beeping or flashing the screen) if no more scrolling is possible, because the window has reached the beginning or end of the buffer. If you change the variable scroll-error-top-bottom to t, these commands move point to the farthest possible position. If point is already there, the commands signal an error.

Some users like scroll commands to keep point at the same screen position, so that scrolling back to the same screen conveniently returns point to its original position. You can enable this behavior via the variable scroll-preserve-screen-position. If the value is t, Emacs adjusts point to keep the cursor at the same screen position whenever a scroll command moves it off-window, rather than moving it to the topmost or bottommost line. With any other non-nil value, Emacs adjusts point this way even if the scroll command leaves point in the window. This variable affects all the scroll commands documented in this section, as well as scrolling with the mouse wheel (see section Mouse Commands for Editing); in general, it affects any command that has a non-nil scroll-command property. See Property Lists in The Emacs Lisp Reference Manual.

Sometimes, particularly when you hold down keys such as C-v and M-v, activating keyboard auto-repeat, Emacs fails to keep up with the rapid rate of scrolling requested; the display doesn’t update and Emacs can become unresponsive to input for quite a long time. You can counter this sluggishness by setting the variable fast-but-imprecise-scrolling to a non-nil value. This instructs the scrolling commands not to fontify (see section Font Lock mode) any unfontified text they scroll over, instead to assume it has the default face. This can cause Emacs to scroll to somewhat wrong buffer positions when the faces in use are not all the same size, even with single (i.e., without auto-repeat) scrolling operations.

The commands M-x scroll-up and M-x scroll-down behave similarly to scroll-up-command and scroll-down-command, except they do not obey scroll-error-top-bottom. Prior to Emacs 24, these were the default commands for scrolling up and down. The commands M-x scroll-up-line and M-x scroll-down-line scroll the current window by one line at a time. If you intend to use any of these commands, you might want to give them key bindings (see section Rebinding Keys in Your Init File).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.2 Recentering

C-l

Scroll the selected window so the current line is the center-most text line; on subsequent consecutive invocations, make the current line the top line, the bottom line, and so on in cyclic order. Possibly redisplay the screen too (recenter-top-bottom).

M-x recenter

Scroll the selected window so the current line is the center-most text line. Possibly redisplay the screen too.

C-M-l

Scroll heuristically to bring useful information onto the screen (reposition-window).

The C-l (recenter-top-bottom) command recenters the selected window, scrolling it so that the current screen line is exactly in the center of the window, or as close to the center as possible.

Typing C-l twice in a row (C-l C-l) scrolls the window so that point is on the topmost screen line. Typing a third C-l scrolls the window so that point is on the bottom-most screen line. Each successive C-l cycles through these three positions.

You can change the cycling order by customizing the list variable recenter-positions. Each list element should be the symbol top, middle, or bottom, or a number; an integer means to move the line to the specified screen line, while a floating-point number between 0.0 and 1.0 specifies a percentage of the screen space from the top of the window. The default, (middle top bottom), is the cycling order described above. Furthermore, if you change the variable scroll-margin to a non-zero value n, C-l always leaves at least n screen lines between point and the top or bottom of the window (see section Automatic Scrolling).

You can also give C-l a prefix argument. A plain prefix argument, C-u C-l, simply recenters point. A positive argument n puts point n lines down from the top of the window. An argument of zero puts point on the topmost line. A negative argument -n puts point n lines from the bottom of the window. When given an argument, C-l does not clear the screen or cycle through different screen positions.

If the variable recenter-redisplay has a non-nil value, each invocation of C-l also clears and redisplays the screen; the special value tty (the default) says to do this on text-terminal frames only. Redisplaying is useful in case the screen becomes garbled for any reason (see section Garbage on the Screen).

The more primitive command M-x recenter behaves like recenter-top-bottom, but does not cycle among screen positions.

C-M-l (reposition-window) scrolls the current window heuristically in a way designed to get useful information onto the screen. For example, in a Lisp file, this command tries to get the entire current defun onto the screen if possible.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.3 Automatic Scrolling

Emacs performs automatic scrolling when point moves out of the visible portion of the text. Normally, automatic scrolling centers point vertically in the window, but there are several ways to alter this behavior.

If you set scroll-conservatively to a small number n, then moving point just a little off the screen (no more than n lines) causes Emacs to scroll just enough to bring point back on screen; if doing so fails to make point visible, Emacs scrolls just far enough to center point in the window. If you set scroll-conservatively to a large number (larger than 100), automatic scrolling never centers point, no matter how far point moves; Emacs always scrolls text just enough to bring point into view, either at the top or bottom of the window depending on the scroll direction. By default, scroll-conservatively is 0, which means to always center point in the window.

Another way to control automatic scrolling is to customize the variable scroll-step. Its value determines the number of lines by which to automatically scroll, when point moves off the screen. If scrolling by that number of lines fails to bring point back into view, point is centered instead. The default value is zero, which (by default) causes point to always be centered after scrolling.

A third way to control automatic scrolling is to customize the variables scroll-up-aggressively and scroll-down-aggressively, which directly specify the vertical position of point after scrolling. The value of scroll-up-aggressively should be either nil (the default), or a floating point number f between 0 and 1. The latter means that when point goes below the bottom window edge (i.e., scrolling forward), Emacs scrolls the window so that point is f parts of the window height from the bottom window edge. Thus, larger f means more aggressive scrolling: more new text is brought into view. The default value, nil, is equivalent to 0.5.

Likewise, scroll-down-aggressively is used when point goes above the top window edge (i.e., scrolling backward). The value specifies how far point should be from the top margin of the window after scrolling. Thus, as with scroll-up-aggressively, a larger value is more aggressive.

Note that the variables scroll-conservatively, scroll-step, and scroll-up-aggressively / scroll-down-aggressively control automatic scrolling in contradictory ways. Therefore, you should pick no more than one of these methods to customize automatic scrolling. In case you customize multiple variables, the order of priority is: scroll-conservatively, then scroll-step, and finally scroll-up-aggressively / scroll-down-aggressively.

The variable scroll-margin restricts how close point can come to the top or bottom of a window (even if aggressive scrolling specifies a fraction f that is larger than the window portion between the top and the bottom margins). Its value is a number of screen lines; if point comes within that many lines of the top or bottom of the window, Emacs performs automatic scrolling. By default, scroll-margin is 0. The effective margin size is limited to a quarter of the window height by default, but this limit can be increased up to half (or decreased down to zero) by customizing maximum-scroll-margin.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.4 Horizontal Scrolling

Horizontal scrolling means shifting all the lines sideways within a window, so that some of the text near the left margin is not displayed. When the text in a window is scrolled horizontally, text lines are truncated rather than continued (see section Line Truncation). If a window shows truncated lines, Emacs performs automatic horizontal scrolling whenever point moves off the left or right edge of the screen. By default, all the lines in the window are scrolled horizontally together, but if you set the variable auto-hscroll-mode to the special value of current-line, only the line showing the cursor will be scrolled. To disable automatic horizontal scrolling entirely, set the variable auto-hscroll-mode to nil. Note that when the automatic horizontal scrolling is turned off, if point moves off the edge of the screen, the cursor disappears to indicate that. (On text terminals, the cursor is left at the edge instead.)

The variable hscroll-margin controls how close point can get to the window’s left and right edges before automatic scrolling occurs. It is measured in columns. For example, if the value is 5, then moving point within 5 columns of an edge causes horizontal scrolling away from that edge.

The variable hscroll-step determines how many columns to scroll the window when point gets too close to the edge. Zero, the default value, means to center point horizontally within the window. A positive integer value specifies the number of columns to scroll by. A floating-point number (whose value should be between 0 and 1) specifies the fraction of the window’s width to scroll by.

You can also perform explicit horizontal scrolling with the following commands:

C-x <

Scroll text in current window to the left (scroll-left).

C-x >

Scroll to the right (scroll-right).

C-x < (scroll-left) scrolls text in the selected window to the left by the full width of the window, less two columns. (In other words, the text in the window moves left relative to the window.) With a numeric argument n, it scrolls by n columns.

If the text is scrolled to the left, and point moves off the left edge of the window, the cursor will freeze at the left edge of the window, until point moves back to the displayed portion of the text. This is independent of the current setting of auto-hscroll-mode, which, for text scrolled to the left, only affects the behavior at the right edge of the window.

C-x > (scroll-right) scrolls similarly to the right. The window cannot be scrolled any farther to the right once it is displayed normally, with each line starting at the window’s left margin; attempting to do so has no effect. This means that you don’t have to calculate the argument precisely for C-x >; any sufficiently large argument will restore the normal display.

If you use those commands to scroll a window horizontally, that sets a lower bound for automatic horizontal scrolling. Automatic scrolling will continue to scroll the window, but never farther to the right than the amount you previously set by scroll-left. When auto-hscroll-mode is set to current-line, all the lines other than the one showing the cursor will be scrolled by that minimal amount.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.5 Narrowing

Narrowing means focusing in on some portion of the buffer, making the rest temporarily inaccessible. The portion which you can still get to is called the accessible portion. Canceling the narrowing, which makes the entire buffer once again accessible, is called widening. The bounds of narrowing in effect in a buffer are called the buffer’s restriction.

Narrowing can make it easier to concentrate on a single subroutine or paragraph by eliminating clutter. It can also be used to limit the range of operation of a replace command or repeating keyboard macro.

C-x n n

Narrow down to between point and mark (narrow-to-region).

C-x n w

Widen to make the entire buffer accessible again (widen).

C-x n p

Narrow down to the current page (narrow-to-page).

C-x n d

Narrow down to the current defun (narrow-to-defun).

When you have narrowed down to a part of the buffer, that part appears to be all there is. You can’t see the rest, you can’t move into it (motion commands won’t go outside the accessible part), you can’t change it in any way. However, it is not gone, and if you save the file all the inaccessible text will be saved. The word ‘Narrow’ appears in the mode line whenever narrowing is in effect.

The primary narrowing command is C-x n n (narrow-to-region). It sets the current buffer’s restrictions so that the text in the current region remains accessible, but all text before the region or after the region is inaccessible. Point and mark do not change.

Alternatively, use C-x n p (narrow-to-page) to narrow down to the current page. See section Pages, for the definition of a page. C-x n d (narrow-to-defun) narrows down to the defun containing point (see section Top-Level Definitions, or Defuns).

The way to cancel narrowing is to widen with C-x n w (widen). This makes all text in the buffer accessible again.

You can get information on what part of the buffer you are narrowed down to using the C-x = command. See section Cursor Position Information.

Because narrowing can easily confuse users who do not understand it, narrow-to-region is normally a disabled command. Attempting to use this command asks for confirmation and gives you the option of enabling it; if you enable the command, confirmation will no longer be required for it. See section Disabling Commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.6 View Mode

View mode is a minor mode that lets you scan a buffer by sequential screenfuls. It provides commands for scrolling through the buffer conveniently but not for changing it. Apart from the usual Emacs cursor motion commands, you can type <SPC> to scroll forward one windowful, S-<SPC> or <DEL> to scroll backward, and s to start an incremental search.

Typing q (View-quit) disables View mode, and switches back to the buffer and position before View mode was enabled. Typing e (View-exit) disables View mode, keeping the current buffer and position.

M-x view-buffer prompts for an existing Emacs buffer, switches to it, and enables View mode. M-x view-file prompts for a file and visits it with View mode enabled.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.7 Follow Mode

Follow mode is a minor mode that makes two windows, both showing the same buffer, scroll as a single tall virtual window. To use Follow mode, go to a frame with just one window, split it into two side-by-side windows using C-x 3, and then type M-x follow-mode. From then on, you can edit the buffer in either of the two windows, or scroll either one; the other window follows it.

In Follow mode, if you move point outside the portion visible in one window and into the portion visible in the other window, that selects the other window—again, treating the two as if they were parts of one large window.

To turn off Follow mode, type M-x follow-mode a second time.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.8 Text Faces

Emacs can display text in several different styles, called faces. Each face can specify various face attributes, such as the font, height, weight, slant, foreground and background color, and underlining or overlining. Most major modes assign faces to the text automatically, via Font Lock mode. See section Font Lock mode, for more information about how these faces are assigned.

To see what faces are currently defined, and what they look like, type M-x list-faces-display. With a prefix argument, this prompts for a regular expression, and displays only faces with names matching that regular expression (see section Syntax of Regular Expressions).

It’s possible for a given face to look different in different frames. For instance, some text terminals do not support all face attributes, particularly font, height, and width, and some support a limited range of colors. In addition, most Emacs faces are defined so that their attributes are different on light and dark frame backgrounds, for reasons of legibility. By default, Emacs automatically chooses which set of face attributes to display on each frame, based on the frame’s current background color. However, you can override this by giving the variable frame-background-mode a non-nil value. A value of dark makes Emacs treat all frames as if they have a dark background, whereas a value of light makes it treat all frames as if they have a light background.

You can customize a face to alter its attributes, and save those customizations for future Emacs sessions. See section Customizing Faces, for details.

The default face is the default for displaying text, and all of its attributes are specified. Its background color is also used as the frame’s background color. See section Colors for Faces.

Another special face is the cursor face. On graphical displays, the background color of this face is used to draw the text cursor. None of the other attributes of this face have any effect; the foreground color for text under the cursor is taken from the background color of the underlying text. On text terminals, the appearance of the text cursor is determined by the terminal, not by the cursor face.

You can also use X resources to specify attributes of any particular face. See section X Resources.

Emacs can display variable-width fonts, but some Emacs commands, particularly indentation commands, do not account for variable character display widths. Therefore, we recommend not using variable-width fonts for most faces, particularly those assigned by Font Lock mode.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.9 Colors for Faces

Faces can have various foreground and background colors. When you specify a color for a face—for instance, when customizing the face (see section Customizing Faces)—you can use either a color name or an RGB triplet.

A color name is a pre-defined name, such as ‘dark orange’ or ‘medium sea green’. To view a list of color names, type M-x list-colors-display. To control the order in which colors are shown, customize list-colors-sort. If you run this command on a graphical display, it shows the full range of color names known to Emacs (these are the standard X11 color names, defined in X’s ‘rgb.txt’ file). If you run the command on a text terminal, it shows only a small subset of colors that can be safely displayed on such terminals. However, Emacs understands X11 color names even on text terminals; if a face is given a color specified by an X11 color name, it is displayed using the closest-matching terminal color.

An RGB triplet is a string of the form ‘#RRGGBB’. Each of the R, G, and B components is a hexadecimal number specifying the component’s relative intensity, one to four digits long (usually two digits are used). The components must have the same number of digits. For hexadecimal values A to F, either upper or lower case are acceptable.

The M-x list-colors-display command also shows the equivalent RGB triplet for each named color. For instance, ‘medium sea green’ is equivalent to ‘#3CB371’.

You can change the foreground and background colors of a face with M-x set-face-foreground and M-x set-face-background. These commands prompt in the minibuffer for a face name and a color, with completion, and then set that face to use the specified color. They affect the face colors on all frames, but their effects do not persist for future Emacs sessions, unlike using the customization buffer or X resources. You can also use frame parameters to set foreground and background colors for a specific frame; See section Frame Parameters.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.10 Standard Faces

Here are the standard faces for specifying text appearance. You can apply them to specific text when you want the effects they produce.

default

This face is used for ordinary text that doesn’t specify any face. Its background color is used as the frame’s background color.

bold

This face uses a bold variant of the default font.

italic

This face uses an italic variant of the default font.

bold-italic

This face uses a bold italic variant of the default font.

underline

This face underlines text.

fixed-pitch

This face forces use of a fixed-width font. It’s reasonable to customize this face to use a different fixed-width font, if you like, but you should not make it a variable-width font.

fixed-pitch-serif

This face is like fixed-pitch, except the font has serifs and looks more like traditional typewriting.

variable-pitch

This face forces use of a variable-width font.

shadow

This face is used for making the text less noticeable than the surrounding ordinary text. Usually this can be achieved by using shades of gray in contrast with either black or white default foreground color.

Here’s an incomplete list of faces used to highlight parts of the text temporarily for specific purposes. (Many other modes define their own faces for this purpose.)

highlight

This face is used for text highlighting in various contexts, such as when the mouse cursor is moved over a hyperlink.

isearch

This face is used to highlight the current Isearch match (see section Incremental Search).

query-replace

This face is used to highlight the current Query Replace match (see section Replacement Commands).

lazy-highlight

This face is used to highlight lazy matches for Isearch and Query Replace (matches other than the current one).

region

This face is used for displaying an active region (see section The Mark and the Region). When Emacs is built with GTK+ support, its colors are taken from the current GTK+ theme.

secondary-selection

This face is used for displaying a secondary X selection (see section Secondary Selection).

trailing-whitespace

The face for highlighting excess spaces and tabs at the end of a line when show-trailing-whitespace is non-nil (see section Useless Whitespace).

escape-glyph

The face for displaying control characters and escape sequences (see section How Text Is Displayed).

homoglyph

The face for displaying lookalike characters, i.e., characters that look like but are not the characters being represented (see section How Text Is Displayed).

nobreak-space

The face for displaying no-break space characters (see section How Text Is Displayed).

nobreak-hyphen

The face for displaying no-break hyphen characters (see section How Text Is Displayed).

The following faces control the appearance of parts of the Emacs frame:

mode-line

This face is used for the mode line of the currently selected window, and for menu bars when toolkit menus are not used. By default, it’s drawn with shadows for a raised effect on graphical displays, and drawn as the inverse of the default face on non-windowed terminals.

mode-line-inactive

Like mode-line, but used for mode lines of the windows other than the selected one (if mode-line-in-non-selected-windows is non-nil). This face inherits from mode-line, so changes in that face affect mode lines in all windows.

mode-line-highlight

Like highlight, but used for mouse-sensitive portions of text on mode lines. Such portions of text typically pop up tooltips (see section Tooltips) when the mouse pointer hovers above them.

mode-line-buffer-id

This face is used for buffer identification parts in the mode line.

header-line

Similar to mode-line for a window’s header line, which appears at the top of a window just as the mode line appears at the bottom. Most windows do not have a header line—only some special modes, such Info mode, create one.

header-line-highlight

Similar to highlight and mode-line-highlight, but used for mouse-sensitive portions of text on header lines. This is a separate face because the header-line face might be customized in a way that does not interact well with highlight.

vertical-border

This face is used for the vertical divider between windows on text terminals.

minibuffer-prompt

This face is used for the prompt strings displayed in the minibuffer. By default, Emacs automatically adds this face to the value of minibuffer-prompt-properties, which is a list of text properties (see Text Properties in the Emacs Lisp Reference Manual) used to display the prompt text. (This variable takes effect when you enter the minibuffer.)

fringe

The face for the fringes to the left and right of windows on graphic displays. (The fringes are the narrow portions of the Emacs frame between the text area and the window’s right and left borders.) See section Window Fringes.

cursor

The :background attribute of this face specifies the color of the text cursor. See section Displaying the Cursor.

tooltip

This face is used for tooltip text. By default, if Emacs is built with GTK+ support, tooltips are drawn via GTK+ and this face has no effect. See section Tooltips.

mouse

This face determines the color of the mouse pointer.

The following faces likewise control the appearance of parts of the Emacs frame, but only on text terminals, or when Emacs is built on X with no toolkit support. (For all other cases, the appearance of the respective frame elements is determined by system-wide settings.)

scroll-bar

This face determines the visual appearance of the scroll bar. See section Scroll Bars.

tool-bar

This face determines the color of tool bar icons. See section Tool Bars.

menu

This face determines the colors and font of Emacs’s menus. See section Menu Bars.

tty-menu-enabled-face

This face is used to display enabled menu items on text-mode terminals.

tty-menu-disabled-face

This face is used to display disabled menu items on text-mode terminals.

tty-menu-selected-face

This face is used to display on text-mode terminals the menu item that would be selected if you click a mouse or press <RET>.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.11 Text Scale

To increase the height of the default face in the current buffer, type C-x C-+ or C-x C-=. To decrease it, type C-x C--. To restore the default (global) face height, type C-x C-0. These keys are all bound to the same command, text-scale-adjust, which looks at the last key typed to determine which action to take.

The final key of these commands may be repeated without the leading C-x. For instance, C-x C-= C-= C-= increases the face height by three steps. Each step scales the text height by a factor of 1.2; to change this factor, customize the variable text-scale-mode-step. A numeric argument of 0 to the text-scale-adjust command restores the default height, the same as typing C-x C-0.

The commands text-scale-increase and text-scale-decrease increase or decrease the height of the default face, just like C-x C-+ and C-x C-- respectively. You may find it convenient to bind to these commands, rather than text-scale-adjust.

The command text-scale-set scales the height of the default face in the current buffer to an absolute level specified by its prefix argument.

The above commands automatically enable the minor mode text-scale-mode if the current font scaling is other than 1, and disable it otherwise.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.12 Font Lock mode

Font Lock mode is a minor mode, always local to a particular buffer, which assigns faces to (or fontifies) the text in the buffer. Each buffer’s major mode tells Font Lock mode which text to fontify; for instance, programming language modes fontify syntactically relevant constructs like comments, strings, and function names.

Font Lock mode is enabled by default. To toggle it in the current buffer, type M-x font-lock-mode. A positive numeric argument unconditionally enables Font Lock mode, and a negative or zero argument disables it.

Type M-x global-font-lock-mode to toggle Font Lock mode in all buffers. To impose this setting for future Emacs sessions, customize the variable global-font-lock-mode (see section Easy Customization Interface), or add the following line to your init file:

(global-font-lock-mode 0)

If you have disabled Global Font Lock mode, you can still enable Font Lock for specific major modes by adding the function font-lock-mode to the mode hooks (see section Hooks). For example, to enable Font Lock mode for editing C files, you can do this:

(add-hook 'c-mode-hook 'font-lock-mode)

Font Lock mode uses several specifically named faces to do its job, including font-lock-string-face, font-lock-comment-face, and others. The easiest way to find them all is to use M-x customize-group <RET> font-lock-faces <RET>. You can then use that customization buffer to customize the appearance of these faces. See section Customizing Faces.

You can customize the variable font-lock-maximum-decoration to alter the amount of fontification applied by Font Lock mode, for major modes that support this feature. The value should be a number (with 1 representing a minimal amount of fontification; some modes support levels as high as 3); or t, meaning “as high as possible” (the default). To be effective for a given file buffer, the customization of font-lock-maximum-decoration should be done before the file is visited; if you already have the file visited in a buffer when you customize this variable, kill the buffer and visit the file again after the customization.

You can also specify different numbers for particular major modes; for example, to use level 1 for C/C++ modes, and the default level otherwise, use the value

'((c-mode . 1) (c++-mode . 1)))

Comment and string fontification (or “syntactic” fontification) relies on analysis of the syntactic structure of the buffer text. For the sake of speed, some modes, including Lisp mode, rely on a special convention: an open-parenthesis or open-brace in the leftmost column always defines the beginning of a defun, and is thus always outside any string or comment. Therefore, you should avoid placing an open-parenthesis or open-brace in the leftmost column, if it is inside a string or comment. See section Left Margin Convention, for details.

Font Lock highlighting patterns already exist for most modes, but you may want to fontify additional patterns. You can use the function font-lock-add-keywords, to add your own highlighting patterns for a particular mode. For example, to highlight ‘FIXME:’ words in C comments, use this:

(add-hook 'c-mode-hook
          (lambda ()
           (font-lock-add-keywords nil
            '(("\\<\\(FIXME\\):" 1
               font-lock-warning-face t)))))

To remove keywords from the font-lock highlighting patterns, use the function font-lock-remove-keywords. See Search-based Fontification in The Emacs Lisp Reference Manual.

Fontifying large buffers can take a long time. To avoid large delays when a file is visited, Emacs initially fontifies only the visible portion of a buffer. As you scroll through the buffer, each portion that becomes visible is fontified as soon as it is displayed; this type of Font Lock is called Just-In-Time (or JIT) Lock. You can control how JIT Lock behaves, including telling it to perform fontification while idle, by customizing variables in the customization group ‘jit-lock’. See section Customizing Specific Items.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.13 Interactive Highlighting

Highlight Changes mode is a minor mode that highlights the parts of the buffer that were changed most recently, by giving that text a different face. To enable or disable Highlight Changes mode, use M-x highlight-changes-mode.

Hi Lock mode is a minor mode that highlights text that matches regular expressions you specify. For example, you can use it to highlight all the references to a certain variable in a program source file, highlight certain parts in a voluminous output of some program, or highlight certain names in an article. To enable or disable Hi Lock mode, use the command M-x hi-lock-mode. To enable Hi Lock mode for all buffers, use M-x global-hi-lock-mode or place (global-hi-lock-mode 1) in your ‘.emacs’ file.

Hi Lock mode works like Font Lock mode (see section Font Lock mode), except that you specify explicitly the regular expressions to highlight. You can control them with the following commands. (The key bindings below that begin with C-x w are deprecated in favor of the global M-s h bindings, and will be removed in some future Emacs version.)

M-s h r regexp <RET> face <RET>
C-x w h regexp <RET> face <RET>

Highlight text that matches regexp using face face (highlight-regexp). The highlighting will remain as long as the buffer is loaded. For example, to highlight all occurrences of the word “whim” using the default face (a yellow background), type M-s h r whim <RET> <RET>. Any face can be used for highlighting, Hi Lock provides several of its own and these are pre-loaded into a list of default values. While being prompted for a face use M-n and M-p to cycle through them.

Setting the option hi-lock-auto-select-face to a non-nil value causes this command (and other Hi Lock commands that read faces) to automatically choose the next face from the default list without prompting.

You can use this command multiple times, specifying various regular expressions to highlight in different ways.

M-s h u regexp <RET>
C-x w r regexp <RET>

Unhighlight regexp (unhighlight-regexp). If you invoke this from the menu, you select the expression to unhighlight from a list. If you invoke this from the keyboard, you use the minibuffer. It will show the most recently added regular expression; use M-n to show the next older expression and M-p to select the next newer expression. (You can also type the expression by hand, with completion.) When the expression you want to unhighlight appears in the minibuffer, press <RET> to exit the minibuffer and unhighlight it.

M-s h l regexp <RET> face <RET>
C-x w l regexp <RET> face <RET>

Highlight entire lines containing a match for regexp, using face face (highlight-lines-matching-regexp).

M-s h p phrase <RET> face <RET>
C-x w p phrase <RET> face <RET>

Highlight matches of phrase, using face face (highlight-phrase). phrase can be any regexp, but spaces will be replaced by matches to whitespace and initial lower-case letters will become case insensitive.

M-s h .
C-x w .

Highlight the symbol found near point, using the next available face (highlight-symbol-at-point).

M-s h w
C-x w b

Insert all the current highlighting regexp/face pairs into the buffer at point, with comment delimiters to prevent them from changing your program. (This key binding runs the hi-lock-write-interactive-patterns command.)

These patterns are extracted from the comments, if appropriate, if you invoke M-x hi-lock-find-patterns, or if you visit the file while Hi Lock mode is enabled (since that runs hi-lock-find-patterns).

M-s h f
C-x w i

Extract regexp/face pairs from comments in the current buffer (hi-lock-find-patterns). Thus, you can enter patterns interactively with highlight-regexp, store them into the file with hi-lock-write-interactive-patterns, edit them (perhaps including different faces for different parenthesized parts of the match), and finally use this command (hi-lock-find-patterns) to have Hi Lock highlight the edited patterns.

The variable hi-lock-file-patterns-policy controls whether Hi Lock mode should automatically extract and highlight patterns found in a file when it is visited. Its value can be nil (never highlight), ask (query the user), or a function. If it is a function, hi-lock-find-patterns calls it with the patterns as argument; if the function returns non-nil, the patterns are used. The default is ask. Note that patterns are always highlighted if you call hi-lock-find-patterns directly, regardless of the value of this variable.

Also, hi-lock-find-patterns does nothing if the current major mode’s symbol is a member of the list hi-lock-exclude-modes.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.14 Window Fringes

On graphical displays, each Emacs window normally has narrow fringes on the left and right edges. The fringes are used to display symbols that provide information about the text in the window. You can type M-x fringe-mode to toggle display of the fringes or to modify their width. This command affects fringes in all frames; to modify fringes on the selected frame only, use M-x set-fringe-style. You can make your changes to the fringes permanent by customizing the variable fringe-mode.

The most common use of the fringes is to indicate a continuation line (see section Continuation Lines). When one line of text is split into multiple screen lines, the left fringe shows a curving arrow for each screen line except the first, indicating that this is not the real beginning. The right fringe shows a curving arrow for each screen line except the last, indicating that this is not the real end. If the line’s direction is right-to-left (see section Bidirectional Editing), the meanings of the curving arrows in the fringes are swapped.

The fringes indicate line truncation (see section Line Truncation) with short horizontal arrows meaning there’s more text on this line which is scrolled horizontally out of view. Clicking the mouse on one of the arrows scrolls the display horizontally in the direction of the arrow.

The fringes can also indicate other things, such as buffer boundaries (see section Displaying Boundaries), and where a program you are debugging is executing (see section Running Debuggers Under Emacs).

The fringe is also used for drawing the cursor, if the current line is exactly as wide as the window and point is at the end of the line. To disable this, change the variable overflow-newline-into-fringe to nil; this causes Emacs to continue or truncate lines that are exactly as wide as the window.

If you customize fringe-mode to remove the fringes on one or both sides of the window display, the features that display on the fringe are not available. Indicators of line continuation and truncation are an exception: when fringes are not available, Emacs uses the leftmost and rightmost character cells to indicate continuation and truncation with special ASCII characters, see Continuation Lines, and Line Truncation. This reduces the width available for displaying text on each line, because the character cells used for truncation and continuation indicators are reserved for that purpose. Since buffer text can include bidirectional text, and thus both left-to-right and right-to-left paragraphs (see section Bidirectional Editing), removing only one of the fringes still reserves two character cells, one on each side of the window, for truncation and continuation indicators, because these indicators are displayed on opposite sides of the window in right-to-left paragraphs.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.15 Displaying Boundaries

On graphical displays, Emacs can indicate the buffer boundaries in the fringes. If you enable this feature, the first line and the last line are marked with angle images in the fringes. This can be combined with up and down arrow images which say whether it is possible to scroll the window.

The buffer-local variable indicate-buffer-boundaries controls how the buffer boundaries and window scrolling is indicated in the fringes. If the value is left or right, both angle and arrow bitmaps are displayed in the left or right fringe, respectively.

If value is an alist (see Association Lists in the Emacs Lisp Reference Manual), each element (indicator . position) specifies the position of one of the indicators. The indicator must be one of top, bottom, up, down, or t which specifies the default position for the indicators not present in the alist. The position is one of left, right, or nil which specifies not to show this indicator.

For example, ((top . left) (t . right)) places the top angle bitmap in left fringe, the bottom angle bitmap in right fringe, and both arrow bitmaps in right fringe. To show just the angle bitmaps in the left fringe, but no arrow bitmaps, use ((top . left) (bottom . left)).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.16 Useless Whitespace

It is easy to leave unnecessary spaces at the end of a line, or empty lines at the end of a buffer, without realizing it. In most cases, this trailing whitespace has no effect, but sometimes it can be a nuisance.

You can make trailing whitespace at the end of a line visible by setting the buffer-local variable show-trailing-whitespace to t. Then Emacs displays trailing whitespace, using the face trailing-whitespace.

This feature does not apply when point is at the end of the line containing the whitespace. Strictly speaking, that is trailing whitespace nonetheless, but displaying it specially in that case looks ugly while you are typing in new text. In this special case, the location of point is enough to show you that the spaces are present.

Type M-x delete-trailing-whitespace to delete all trailing whitespace. This command deletes all extra spaces at the end of each line in the buffer, and all empty lines at the end of the buffer; to ignore the latter, change the variable delete-trailing-lines to nil. If the region is active, the command instead deletes extra spaces at the end of each line in the region.

On graphical displays, Emacs can indicate unused lines at the end of the window with a small image in the left fringe (see section Window Fringes). The image appears for screen lines that do not correspond to any buffer text, so blank lines at the end of the buffer stand out because they lack this image. To enable this feature, set the buffer-local variable indicate-empty-lines to a non-nil value. You can enable or disable this feature for all new buffers by setting the default value of this variable, e.g., (setq-default indicate-empty-lines t).

Whitespace mode is a buffer-local minor mode that lets you visualize many kinds of whitespace in the buffer, by either drawing the whitespace characters with a special face or displaying them as special glyphs. To toggle this mode, type M-x whitespace-mode. The kinds of whitespace visualized are determined by the list variable whitespace-style. Individual elements in that list can be toggled on or off in the current buffer by typing M-x whitespace-toggle-options. Here is a partial list of possible elements (see the variable’s documentation for the full list):

face

Enable all visualizations which use special faces. This element has a special meaning: if it is absent from the list, none of the other visualizations take effect except space-mark, tab-mark, and newline-mark.

trailing

Highlight trailing whitespace.

tabs

Highlight tab characters.

spaces

Highlight space and non-breaking space characters.

lines

Highlight lines longer than 80 columns. To change the column limit, customize the variable whitespace-line-column.

newline

Highlight newlines.

empty

Highlight empty lines.

big-indent

Highlight too-deep indentation. By default any sequence of at least 4 consecutive tab characters or 32 consecutive space characters is highlighted. To change that, customize the regular expression whitespace-big-indent-regexp.

space-mark

Draw space and non-breaking characters with a special glyph.

tab-mark

Draw tab characters with a special glyph.

newline-mark

Draw newline characters with a special glyph.

Global Whitespace mode is a global minor mode that lets you visualize whitespace in all buffers. To toggle individual features, use M-x global-whitespace-toggle-options.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.17 Selective Display

Emacs has the ability to hide lines indented more than a given number of columns. You can use this to get an overview of a part of a program.

To hide lines in the current buffer, type C-x $ (set-selective-display) with a numeric argument n. Then lines with at least n columns of indentation disappear from the screen. The only indication of their presence is that three dots (‘’) appear at the end of each visible line that is followed by one or more hidden ones.

The commands C-n and C-p move across the hidden lines as if they were not there.

The hidden lines are still present in the buffer, and most editing commands see them as usual, so you may find point in the middle of the hidden text. When this happens, the cursor appears at the end of the previous line, after the three dots. If point is at the end of the visible line, before the newline that ends it, the cursor appears before the three dots.

To make all lines visible again, type C-x $ with no argument.

If you set the variable selective-display-ellipses to nil, the three dots do not appear at the end of a line that precedes hidden lines. Then there is no visible indication of the hidden lines. This variable becomes local automatically when set.

See also Outline Mode for another way to hide part of the text in a buffer.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.18 Optional Mode Line Features

The buffer percentage pos indicates the percentage of the buffer above the top of the window. You can additionally display the size of the buffer by typing M-x size-indication-mode to turn on Size Indication mode. The size will be displayed immediately following the buffer percentage like this:

pos of size

Here size is the human readable representation of the number of characters in the buffer, which means that ‘k’ for 10^3, ‘M’ for 10^6, ‘G’ for 10^9, etc., are used to abbreviate.

The current line number of point appears in the mode line when Line Number mode is enabled. Use the command M-x line-number-mode to turn this mode on and off; normally it is on. The line number appears after the buffer percentage pos, with the letter ‘L’ to indicate what it is.

Similarly, you can display the current column number by turning on Column Number mode with M-x column-number-mode. The column number is indicated by the letter ‘C’. However, when both of these modes are enabled, the line and column numbers are displayed in parentheses, the line number first, rather than with ‘L’ and ‘C’. For example: ‘(561,2)’. See section Minor Modes, for more information about minor modes and about how to use these commands.

In Column Number mode, the displayed column number counts from zero starting at the left margin of the window. If you would prefer for the displayed column number to count from one, you may set column-number-indicator-zero-based to nil.

If you have narrowed the buffer (see section Narrowing), the displayed line number is relative to the accessible portion of the buffer. Thus, it isn’t suitable as an argument to goto-line. (Use what-line command to see the line number relative to the whole file.)

If the buffer is very large (larger than the value of line-number-display-limit), Emacs won’t compute the line number, because that would be too slow; therefore, the line number won’t appear on the mode-line. To remove this limit, set line-number-display-limit to nil.

Line-number computation can also be slow if the lines in the buffer are too long. For this reason, Emacs doesn’t display line numbers if the average width, in characters, of lines near point is larger than the value of line-number-display-limit-width. The default value is 200 characters.

Emacs can optionally display the time and system load in all mode lines. To enable this feature, type M-x display-time or customize the option display-time-mode. The information added to the mode line looks like this:

hh:mmPM l.ll

Here hh and mm are the hour and minute, followed always by ‘AM’ or ‘PM’. l.ll is the average number, collected for the last few minutes, of processes in the whole system that were either running or ready to run (i.e., were waiting for an available processor). (Some fields may be missing if your operating system cannot support them.) If you prefer time display in 24-hour format, set the variable display-time-24hr-format to t.

The word ‘Mail’ appears after the load level if there is mail for you that you have not read yet. On graphical displays, you can use an icon instead of ‘Mail’ by customizing display-time-use-mail-icon; this may save some space on the mode line. You can customize display-time-mail-face to make the mail indicator prominent. Use display-time-mail-file to specify the mail file to check, or set display-time-mail-directory to specify the directory to check for incoming mail (any nonempty regular file in the directory is considered to be newly arrived mail).

When running Emacs on a laptop computer, you can display the battery charge on the mode-line, by using the command display-battery-mode or customizing the variable display-battery-mode. The variable battery-mode-line-format determines the way the battery charge is displayed; the exact mode-line message depends on the operating system, and it usually shows the current battery charge as a percentage of the total charge.

On graphical displays, the mode line is drawn as a 3D box. If you don’t like this effect, you can disable it by customizing the mode-line face and setting its box attribute to nil. See section Customizing Faces.

By default, the mode line of nonselected windows is displayed in a different face, called mode-line-inactive. Only the selected window is displayed in the mode-line face. This helps show which window is selected. When the minibuffer is selected, since it has no mode line, the window from which you activated the minibuffer has its mode line displayed using mode-line; as a result, ordinary entry to the minibuffer does not change any mode lines.

You can disable use of mode-line-inactive by setting variable mode-line-in-non-selected-windows to nil; then all mode lines are displayed in the mode-line face.

You can customize the mode line display for each of the end-of-line formats by setting each of the variables eol-mnemonic-unix, eol-mnemonic-dos, eol-mnemonic-mac, and eol-mnemonic-undecided to the strings you prefer.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.19 How Text Is Displayed

Most characters are printing characters: when they appear in a buffer, they are displayed literally on the screen. Printing characters include ASCII numbers, letters, and punctuation characters, as well as many non-ASCII characters.

The ASCII character set contains non-printing control characters. Two of these are displayed specially: the newline character (Unicode code point U+000A) is displayed by starting a new line, while the tab character (U+0009) is displayed as a space that extends to the next tab stop column (normally every 8 columns). The number of spaces per tab is controlled by the buffer-local variable tab-width, which must have an integer value between 1 and 1000, inclusive. Note that how the tab character in the buffer is displayed has nothing to do with the definition of <TAB> as a command.

Other ASCII control characters, whose codes are below U+0020 (octal 40, decimal 32), are displayed as a caret (‘^’) followed by the non-control version of the character, with the escape-glyph face. For instance, the ‘control-A’ character, U+0001, is displayed as ‘^A’.

The raw bytes with codes U+0080 (octal 200) through U+009F (octal 237) are displayed as octal escape sequences, with the escape-glyph face. For instance, character code U+0098 (octal 230) is displayed as ‘\230’. If you change the buffer-local variable ctl-arrow to nil, the ASCII control characters are also displayed as octal escape sequences instead of caret escape sequences.

Some non-ASCII characters have the same appearance as an ASCII space or hyphen (minus) character. Such characters can cause problems if they are entered into a buffer without your realization, e.g., by yanking; for instance, source code compilers typically do not treat non-ASCII spaces as whitespace characters. To deal with this problem, Emacs displays such characters specially: it displays U+00A0 (no-break space) with the nobreak-space face, and it displays U+00AD (soft hyphen), U+2010 (hyphen), and U+2011 (non-breaking hyphen) with the nobreak-hyphen face. To disable this, change the variable nobreak-char-display to nil. If you give this variable a non-nil and non-t value, Emacs instead displays such characters as a highlighted backslash followed by a space or hyphen.

You can customize the way any particular character code is displayed by means of a display table. See Display Tables in The Emacs Lisp Reference Manual.

On graphical displays, some characters may have no glyphs in any of the fonts available to Emacs. These glyphless characters are normally displayed as boxes containing the hexadecimal character code. Similarly, on text terminals, characters that cannot be displayed using the terminal encoding (see section Coding Systems for Terminal I/O) are normally displayed as question signs. You can control the display method by customizing the variable glyphless-char-display-control. You can also customize the glyphless-char face to make these characters more prominent on display. See Glyphless Character Display in The Emacs Lisp Reference Manual, for details.

Emacs tries to determine if the curved quotes ‘’ and ‘’ can be displayed on the current display. By default, if this seems to be so, then Emacs will translate the ASCII quotes (‘`’ and ‘'’), when they appear in messages and help texts, to these curved quotes. You can influence or inhibit this translation by customizing the user option text-quoting-style (see Keys in Documentation in The Emacs Lisp Reference Manual).

If the curved quotes ‘’, ‘’, ‘’, and ‘’ are known to look just like ASCII characters, they are shown with the homoglyph face. Curved quotes that are known not to be displayable are shown as their ASCII approximations ‘`’, ‘'’, and ‘"’ with the homoglyph face.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.20 Displaying the Cursor

On a text terminal, the cursor’s appearance is controlled by the terminal, largely out of the control of Emacs. Some terminals offer two different cursors: a visible static cursor, and a very visible blinking cursor. By default, Emacs uses the very visible cursor, and switches to it when you start or resume Emacs. If the variable visible-cursor is nil when Emacs starts or resumes, it uses the normal cursor.

On a graphical display, many more properties of the text cursor can be altered. To customize its color, change the :background attribute of the face named cursor (see section Customizing Faces). (The other attributes of this face have no effect; the text shown under the cursor is drawn using the frame’s background color.) To change its shape, customize the buffer-local variable cursor-type; possible values are box (the default), hollow (a hollow box), bar (a vertical bar), (bar . n) (a vertical bar n pixels wide), hbar (a horizontal bar), (hbar . n) (a horizontal bar n pixels tall), or nil (no cursor at all).

By default, the cursor stops blinking after 10 blinks, if Emacs does not get any input during that time; any input event restarts the count. You can customize the variable blink-cursor-blinks to control that: its value says how many times to blink without input before stopping. Setting that variable to a zero or negative value will make the cursor blink forever. To disable cursor blinking altogether, change the variable blink-cursor-mode to nil (see section Easy Customization Interface), or add the line

  (blink-cursor-mode 0)

to your init file. Alternatively, you can change how the cursor looks when it blinks off by customizing the list variable blink-cursor-alist. Each element in the list should have the form (on-type . off-type); this means that if the cursor is displayed as on-type when it blinks on (where on-type is one of the cursor types described above), then it is displayed as off-type when it blinks off.

Some characters, such as tab characters, are extra wide. When the cursor is positioned over such a character, it is normally drawn with the default character width. You can make the cursor stretch to cover wide characters, by changing the variable x-stretch-cursor to a non-nil value.

The cursor normally appears in non-selected windows as a non-blinking hollow box. (For a bar cursor, it instead appears as a thinner bar.) To turn off cursors in non-selected windows, change the variable cursor-in-non-selected-windows to nil.

To make the cursor even more visible, you can use HL Line mode, a minor mode that highlights the line containing point. Use M-x hl-line-mode to enable or disable it in the current buffer. M-x global-hl-line-mode enables or disables the same mode globally.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.21 Line Truncation

As an alternative to continuation (see section Continuation Lines), Emacs can display long lines by truncation. This means that all the characters that do not fit in the width of the screen or window do not appear at all. On graphical displays, a small straight arrow in the fringe indicates truncation at either end of the line. On text terminals, this is indicated with ‘$’ signs in the rightmost and/or leftmost columns.

Horizontal scrolling automatically causes line truncation (see section Horizontal Scrolling). You can explicitly enable line truncation for a particular buffer with the command M-x toggle-truncate-lines. This works by locally changing the variable truncate-lines. If that variable is non-nil, long lines are truncated; if it is nil, they are continued onto multiple screen lines. Setting the variable truncate-lines in any way makes it local to the current buffer; until that time, the default value, which is normally nil, is in effect.

If a split window becomes too narrow, Emacs may automatically enable line truncation. See section Splitting Windows, for the variable truncate-partial-width-windows which controls this.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.22 Visual Line Mode

Another alternative to ordinary line continuation is to use word wrap. Here, each long logical line is divided into two or more screen lines, like in ordinary line continuation. However, Emacs attempts to wrap the line at word boundaries near the right window edge. (If the line’s direction is right-to-left, it is wrapped at the left window edge instead.) This makes the text easier to read, as wrapping does not occur in the middle of words.

Word wrap is enabled by Visual Line mode, an optional minor mode. To turn on Visual Line mode in the current buffer, type M-x visual-line-mode; repeating this command turns it off. You can also turn on Visual Line mode using the menu bar: in the Options menu, select the ‘Line Wrapping in this Buffer’ submenu, followed by the ‘Word Wrap (Visual Line mode)’ menu item. While Visual Line mode is enabled, the mode line shows the string ‘wrap’ in the mode display. The command M-x global-visual-line-mode toggles Visual Line mode in all buffers.

In Visual Line mode, some editing commands work on screen lines instead of logical lines: C-a (beginning-of-visual-line) moves to the beginning of the screen line, C-e (end-of-visual-line) moves to the end of the screen line, and C-k (kill-visual-line) kills text to the end of the screen line.

To move by logical lines, use the commands M-x next-logical-line and M-x previous-logical-line. These move point to the next logical line and the previous logical line respectively, regardless of whether Visual Line mode is enabled. If you use these commands frequently, it may be convenient to assign key bindings to them. See section Rebinding Keys in Your Init File.

By default, word-wrapped lines do not display fringe indicators. Visual Line mode is often used to edit files that contain many long logical lines, so having a fringe indicator for each wrapped line would be visually distracting. You can change this by customizing the variable visual-line-fringe-indicators.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

14.23 Customization of Display

This section describes variables that control miscellaneous aspects of the appearance of the Emacs screen. Beginning users can skip it.

If you want to have Emacs display line numbers for every line in the buffer, customize the buffer-local variable display-line-numbers; it is nil by default. This variable can have several different values to support various modes of line-number display:

t

Display (an absolute) line number before each non-continuation screen line that displays buffer text. If the line is a continuation line, or if the entire screen line displays a display or an overlay string, that line will not be numbered.

relative

Display relative line numbers before non-continuation lines which show buffer text. The line numbers are relative to the line showing point, so the numbers grow both up and down as lines become farther from the current line.

visual

This value causes Emacs to count lines visually: only lines actually shown on the display will be counted (disregarding any lines in invisible parts of text), and lines which wrap to consume more than one screen line will be numbered that many times. The displayed numbers are relative, as with relative value above. This is handy in modes that fold text, such as Outline mode (see section Outline Mode), and when you need to move by exact number of screen lines.

anything else

Any other non-nil value is treated as t.

The command M-x display-line-numbers-mode provides a convenient way to turn on display of line numbers. This mode has a globalized variant, global-display-line-numbers-mode. The user option display-line-numbers-type controls which sub-mode of line-number display, described above, will these modes activate.

Note that line numbers are not displayed in the minibuffer and in the tooltips, even if you turn on display-line-numbers-mode globally.

When Emacs displays relative line numbers, you can control the number displayed before the current line, the line showing point. By default, Emacs displays the absolute number of the current line there, even though all the other line numbers are relative. If you customize the variable display-line-numbers-current-absolute to a nil value, the number displayed for the current line will be zero. This is handy if you don’t care about the number of the current line, and want to leave more horizontal space for text in large buffers.

In a narrowed buffer (see section Narrowing) lines are normally numbered starting at the beginning of the narrowing. However, if you customize the variable display-line-numbers-widen to a non-nil value, line numbers will disregard any narrowing and will start at the first character of the buffer.

In selective display mode (see section Selective Display), and other modes that hide many lines from display (such as Outline and Org modes), you may wish to customize the variables display-line-numbers-width-start and display-line-numbers-grow-only, or set display-line-numbers-width to a large enough value, to avoid occasional miscalculations of space reserved for the line numbers.

The line numbers are displayed in a special face line-number. The current line number is displayed in a different face, line-number-current-line, so you can make the current line’s number have a distinct appearance, which will help locating the line showing point.

If the variable visible-bell is non-nil, Emacs attempts to make the whole screen blink when it would normally make an audible bell sound. This variable has no effect if your terminal does not have a way to make the screen blink.

The variable echo-keystrokes controls the echoing of multi-character keys; its value is the number of seconds of pause required to cause echoing to start, or zero, meaning don’t echo at all. The value takes effect when there is something to echo. See section The Echo Area.

On graphical displays, Emacs displays the mouse pointer as an hourglass if Emacs is busy. To disable this feature, set the variable display-hourglass to nil. The variable hourglass-delay determines the number of seconds of busy time before the hourglass is shown; the default is 1.

If the mouse pointer lies inside an Emacs frame, Emacs makes it invisible each time you type a character to insert text, to prevent it from obscuring the text. (To be precise, the hiding occurs when you type a self-inserting character. See section Inserting Text.) Moving the mouse pointer makes it visible again. To disable this feature, set the variable make-pointer-invisible to nil.

On graphical displays, the variable underline-minimum-offset determines the minimum distance between the baseline and underline, in pixels, for underlined text. By default, the value is 1; increasing it may improve the legibility of underlined text for certain fonts. (However, Emacs will never draw the underline below the current line area.) The variable x-underline-at-descent-line determines how to draw underlined text. The default is nil, which means to draw it at the baseline level of the font; if you change it to t, Emacs draws the underline at the same height as the font’s descent line. (If non-default line spacing was specified for the underlined text, see Line Height in The Emacs Lisp Reference Manual, Emacs draws the underline below the additional spacing.)

The variable overline-margin specifies the vertical position of an overline above the text, including the height of the overline itself, in pixels; the default is 2.

On some text terminals, bold face and inverse video together result in text that is hard to read. Call the function tty-suppress-bold-inverse-default-colors with a non-nil argument to suppress the effect of bold-face in this case.

Raw bytes are displayed in octal format by default, for example a byte with a decimal value of 128 is displayed as \200. To change display to the hexadecimal format of \x80, set the variable display-raw-bytes-as-hex to t.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section Searching and Replacing with Identifiers) or through the Dired A command (see section Operating on Files), or ask the grep program to do it (see section Searching with Grep under Emacs).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1 Incremental Search

The principal search command in Emacs is incremental: it begins searching as soon as you type the first character of the search string. As you type in the search string, Emacs shows you where the string (as you have typed it so far) would be found. When you have typed enough characters to identify the place you want, you can stop. Depending on what you plan to do next, you may or may not need to terminate the search explicitly with <RET>.

C-s

Incremental search forward (isearch-forward).

C-r

Incremental search backward (isearch-backward).

You can also invoke incremental search from the menu bar’s ‘Edit->Search’ menu.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1.1 Basics of Incremental Search

C-s

Begin incremental search (isearch-forward).

C-r

Begin reverse incremental search (isearch-backward).

C-s (isearch-forward) starts a forward incremental search. It reads characters from the keyboard, and moves point just past the end of the next occurrence of those characters in the buffer.

For instance, if you type C-s and then F, that puts the cursor after the first ‘F’ that occurs in the buffer after the starting point. If you then type O, the cursor moves to just after the first ‘FO’; the ‘F’ in that ‘FO’ might not be the first ‘F’ previously found. After another O, the cursor moves to just after the first ‘FOO’.

At each step, Emacs highlights the current match—the buffer text that matches the search string—using the isearch face (see section Text Faces). See section Tailoring Search to Your Needs, for various options that customize this highlighting. The current search string is also displayed in the echo area.

If you make a mistake typing the search string, type <DEL>. Each <DEL> cancels the last character of the search string. See section Errors in Incremental Search, for more about dealing with unsuccessful search.

When you are satisfied with the place you have reached, type <RET>. This stops searching, leaving the cursor where the search brought it. Also, any command not specially meaningful in searches stops the searching and is then executed. Thus, typing C-a exits the search and then moves to the beginning of the line; typing one of the arrow keys exits the search and performs the respective movement command; etc. <RET> is necessary only if the next command you want to type is a printing character, <DEL>, <RET>, or another character that is special within searches (C-q, C-w, C-r, C-s, C-y, M-y, M-r, M-c, M-e, and some others described below). You can fine-tune the commands that exit the search; see Not Exiting Incremental Search.

As a special exception, entering <RET> when the search string is empty launches nonincremental search (see section Nonincremental Search). (This can be customized; see Tailoring Search to Your Needs.)

To abandon the search and return to the place where you started, type <ESC> <ESC> <ESC> (isearch-cancel) or C-g C-g (isearch-abort).

When you exit the incremental search, it adds the original value of point to the mark ring, without activating the mark; you can thus use C-u C-<SPC> or C-x C-x to return to where you were before beginning the search. See section The Mark Ring. (Emacs only does this if the mark was not already active; if the mark was active when you started the search, both C-u C-<SPC> and C-x C-x will go to the mark.)

To search backwards, use C-r (isearch-backward) instead of C-s to start the search. A backward search finds matches that end before the starting point, just as a forward search finds matches that begin after it.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1.2 Repeating Incremental Search

Suppose you search forward for ‘FOO’ and find a match, but not the one you expected to find: the ‘FOO’ you were aiming for occurs later in the buffer. In this event, type another C-s to move to the next occurrence of the search string. You can repeat this any number of times. If you overshoot, you can cancel some C-s characters with <DEL>. Similarly, each C-r in a backward incremental search repeats the backward search.

If you pause for a little while during incremental search, Emacs highlights all the other possible matches for the search string that are present on the screen. This helps you anticipate where you can get to by typing C-s or C-r to repeat the search. The other matches are highlighted differently from the current match, using the customizable face lazy-highlight (see section Text Faces). If you don’t like this feature, you can disable it by setting isearch-lazy-highlight to nil. For other customizations related to highlighting matches, see Tailoring Search to Your Needs.

After exiting a search, you can search for the same string again by typing just C-s C-s. The first C-s is the key that invokes incremental search, and the second C-s means to search again for the last search string. Similarly, C-r C-r searches backward for the last search string. In determining the last search string, it doesn’t matter whether that string was searched for with C-s or C-r.

If you are searching forward but you realize you were looking for something before the starting point, type C-r to switch to a backward search, leaving the search string unchanged. Similarly, C-s in a backward search switches to a forward search.

If a search is failing and you ask to repeat it by typing another C-s, it starts again from the beginning of the buffer. Repeating a failing reverse search with C-r starts again from the end. This is called wrapping around, and ‘Wrapped’ appears in the search prompt once this has happened. If you keep on going past the original starting point of the search, it changes to ‘Overwrapped’, which means that you are revisiting matches that you have already seen.

To reuse earlier search strings, use the search ring. The commands M-p and M-n move through the ring to pick a search string to reuse. These commands leave the selected search ring element in the minibuffer, where you can edit it. Type C-s/C-r or <RET> to accept the string and start searching for it. The number of most recently used search strings saved in the search ring is specified by the variable search-ring-max, 16 by default.

To edit the current search string in the minibuffer without replacing it with items from the search ring, type M-e or click mouse-1 in the minibuffer. Type <RET>, C-s or C-r to finish editing the string and search for it. Type C-f or <RIGHT> to add to the search string characters following point from the buffer from which you started the search.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1.3 Isearch Yanking

In many cases, you will want to use text at or near point as your search string. The commands described in this subsection let you do that conveniently.

C-w (isearch-yank-word-or-char) appends the next character or word at point to the search string. This is an easy way to search for another occurrence of the text at point. (The decision of whether to copy a character or a word is heuristic.)

Similarly, M-s C-e (isearch-yank-line) appends the rest of the current line to the search string. If point is already at the end of a line, it appends the next line. With a prefix argument n, it appends the next n lines.

Within incremental search, C-y (isearch-yank-kill) appends the current kill to the search string. M-y (isearch-yank-pop), if called after C-y, replaces that appended text with an earlier kill, similar to the usual M-y (yank-pop) command (see section Yanking). Clicking mouse-2 in the echo area appends the current X selection (see section Cut and Paste with Other Window Applications) to the search string (isearch-yank-x-selection).

C-M-w (isearch-del-char) deletes the last character from the search string, and C-M-y (isearch-yank-char) appends the character after point to the search string. An alternative method to add the character after point is to enter the minibuffer with M-e (see section Repeating Incremental Search) and type C-f or <RIGHT> at the end of the search string in the minibuffer. Each C-f or <RIGHT> you type adds another character following point to the search string.

Normally, when the search is case-insensitive, text yanked into the search string is converted to lower case, so that the search remains case-insensitive (see section case folding). However, if the value of the variable search-upper-case (see section search-upper-case) is other than not-yanks, that disables this down-casing.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1.4 Errors in Incremental Search

If your string is not found at all, the echo area says ‘Failing I-Search’, and the cursor moves past the place where Emacs found as much of your string as it could. Thus, if you search for ‘FOOT’, and there is no ‘FOOT’, you might see the cursor after the ‘FOO’ in ‘FOOL’. In the echo area, the part of the search string that failed to match is highlighted using the face isearch-fail.

At this point, there are several things you can do. If your string was mistyped, you can use <DEL> to erase some of it and correct it, or you can type M-e and edit it. If you like the place you have found, you can type <RET> to remain there. Or you can type C-g, which removes from the search string the characters that could not be found (the ‘T’ in ‘FOOT’), leaving those that were found (the ‘FOO’ in ‘FOOT’). A second C-g at that point cancels the search entirely, returning point to where it was when the search started.

The quit command, C-g, does special things during searches; just what it does depends on the status of the search. If the search has found what you specified and is waiting for input, C-g cancels the entire search, moving the cursor back to where you started the search. If C-g is typed when there are characters in the search string that have not been found—because Emacs is still searching for them, or because it has failed to find them—then the search string characters which have not been found are discarded from the search string. With them gone, the search is now successful and waiting for more input, so a second C-g will cancel the entire search.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1.5 Special Input for Incremental Search

In addition to characters described in the previous subsections, some of the other characters you type during incremental search have special effects. They are described here.

To toggle lax space matching (see section lax space matching), type M-s <SPC>.

To toggle case sensitivity of the search, type M-c or M-s c. See section case folding. If the search string includes upper-case letters, the search is case-sensitive by default.

To toggle whether or not the search will consider similar and equivalent characters as a match, type M-s '. See section character folding. If the search string includes accented characters, that disables character folding during that search.

To toggle whether or not invisible text is searched, type M-s i (isearch-toggle-invisible). See Outline Search.

To toggle between non-regexp and regexp incremental search, type M-r or M-s r (isearch-toggle-regexp). See section Regular Expression Search.

To toggle symbol mode, type M-s _. See section Symbol Search.

To search for a newline character, type C-j as part of the search string.

To search for non-ASCII characters, use one of the following methods:

Typing M-s o in incremental search invokes isearch-occur, which runs occur with the current search string. See section occur.

Typing M-% in incremental search invokes query-replace or query-replace-regexp (depending on search mode) with the current search string used as the string to replace. A negative prefix argument means to replace backward. See section Query Replace.

Typing M-<TAB> in incremental search invokes isearch-complete, which attempts to complete the search string using the search ring (the previous search strings you used) as a list of completion alternatives. See section Completion. In many operating systems, the M-<TAB> key sequence is captured by the window manager; you then need to rebind isearch-complete to another key sequence if you want to use it (see section Changing Key Bindings Interactively).

You can exit the search while leaving the matches for the last search string highlighted on display. To this end, type M-s h r (isearch-highlight-regexp), which will run highlight-regexp (see section Interactive Highlighting) passing it the regexp derived from the last search string and prompting you for the face to use for highlighting. To remove the highlighting, type M-s h u (unhighlight-regexp).

When incremental search is active, you can type C-h C-h (isearch-help-map) to access interactive help options, including a list of special key bindings. These key bindings are part of the keymap isearch-mode-map (see section Keymaps).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1.6 Not Exiting Incremental Search

This subsection describes how to control whether typing a command not specifically meaningful in searches exits the search before executing the command. It also describes two categories of commands which you can type without exiting the current incremental search, even though they are not themselves part of incremental search.

Normally, typing a command that is not bound by the incremental search exits the search before executing the command. Thus, the command operates on the buffer from which you invoked the search. However, if you customize the variable search-exit-option to nil, the characters which you type that are not interpreted by the incremental search are simply appended to the search string. This is so you could include in the search string control characters, such as C-a, that would normally exit the search and invoke the command bound to them on the buffer.

Prefix Arguments

In incremental search, when you type a command that specifies a prefix argument (see section Numeric Arguments), by default it will apply either to the next action in the search or to the command that exits the search. In other words, entering a prefix argument will not by itself terminate the search.

In previous versions of Emacs, entering a prefix argument always terminated the search. You can revert to this behavior by setting the variable isearch-allow-prefix to nil.

When isearch-allow-scroll is non-nil (see below), prefix arguments always have the default behavior described above, i.e., they don’t terminate the search, even if isearch-allow-prefix is nil.

Scrolling Commands

Normally, scrolling commands exit incremental search. If you change the variable isearch-allow-scroll to a non-nil value, that enables the use of the scroll-bar, as well as keyboard scrolling commands like C-v, M-v, and C-l (see section Scrolling). This applies only to calling these commands via their bound key sequences—typing M-x will still exit the search. You can give prefix arguments to these commands in the usual way. This feature won’t let you scroll the current match out of visibility, however.

The isearch-allow-scroll feature also affects some other commands, such as C-x 2 (split-window-below) and C-x ^ (enlarge-window), which don’t exactly scroll but do affect where the text appears on the screen. It applies to any command whose name has a non-nil isearch-scroll property. So you can control which commands are affected by changing these properties.

For example, to make C-h l usable within an incremental search in all future Emacs sessions, use C-h c to find what command it runs (see section Documentation for a Key), which is view-lossage. Then you can put the following line in your init file (see section The Emacs Initialization File):

(put 'view-lossage 'isearch-scroll t)

This feature can be applied to any command that doesn’t permanently change point, the buffer contents, the match data, the current buffer, or the selected window and frame. The command must not itself attempt an incremental search. This feature is disabled if isearch-allow-scroll is nil (which it is by default).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.1.7 Searching the Minibuffer

If you start an incremental search while the minibuffer is active, Emacs searches the contents of the minibuffer. Unlike searching an ordinary buffer, the search string is not shown in the echo area, because that is used to display the minibuffer.

If an incremental search fails in the minibuffer, it tries searching the minibuffer history. See section Minibuffer History. You can visualize the minibuffer and its history as a series of pages, with the earliest history element on the first page and the current minibuffer on the last page. A forward search, C-s, searches forward to later pages; a reverse search, C-r, searches backwards to earlier pages. Like in ordinary buffer search, a failing search can wrap around, going from the last page to the first page or vice versa.

When the current match is on a history element, that history element is pulled into the minibuffer. If you exit the incremental search normally (e.g., by typing <RET>), it remains in the minibuffer afterwards. Canceling the search, with C-g, restores the contents of the minibuffer when you began the search.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.2 Nonincremental Search

Emacs also has conventional nonincremental search commands, which require you to type the entire search string before searching begins.

C-s <RET> string <RET>

Search for string.

C-r <RET> string <RET>

Search backward for string.

To start a nonincremental search, first type C-s <RET>. This enters the minibuffer to read the search string; terminate the string with <RET>, and then the search takes place. If the string is not found, the search command signals an error.

When you type C-s <RET>, the C-s invokes incremental search as usual. That command is specially programmed to invoke the command for nonincremental search, if the string you specify is empty. (Such an empty argument would otherwise be useless.) C-r <RET> does likewise, invoking the nonincremental backward-searching command.

Nonincremental search can also be invoked from the menu bar’s ‘Edit->Search’ menu.

You can also use two simpler commands, M-x search-forward and M-x search-backward. These commands look for the literal strings you specify, and don’t support any of the lax-search features (see section Lax Matching During Searching) except case folding.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.3 Word Search

A word search finds a sequence of words without regard to the type of punctuation between them. For instance, if you enter a search string that consists of two words separated by a single space, the search matches any sequence of those two words separated by one or more spaces, newlines, or other punctuation characters. This is particularly useful for searching text documents, because you don’t have to worry whether the words you are looking for are separated by newlines or spaces. Note that major modes for programming languages or other specialized modes can modify the definition of a word to suit their syntactic needs.

M-s w

If incremental search is active, toggle word search mode (isearch-toggle-word); otherwise, begin an incremental forward word search (isearch-forward-word).

M-s w <RET> words <RET>

Search for words, using a forward nonincremental word search.

M-s w C-r <RET> words <RET>

Search backward for words, using a nonincremental word search.

M-s M-w

Search the Web for the text in region.

To begin a forward incremental word search, type M-s w. If incremental search is not already active, this runs the command isearch-forward-word. If incremental search is already active (whether a forward or backward search), M-s w switches to a word search while keeping the direction of the search and the current search string unchanged. You can toggle word search back off by typing M-s w again.

To begin a nonincremental word search, type M-s w <RET> for a forward search, or M-s w C-r <RET> for a backward search. These run the commands word-search-forward and word-search-backward respectively.

Incremental and nonincremental word searches differ slightly in the way they find a match. In a nonincremental word search, each word in the search string must exactly match a whole word. In an incremental word search, the matching is more lax: while you are typing the search string, its first and last words need not match whole words. This is so that the matching can proceed incrementally as you type. This additional laxity does not apply to the lazy highlight (see section Incremental Search), which always matches whole words. While you are typing the search string, ‘Pending’ appears in the search prompt until you use a search repeating key like C-s.

The word search commands don’t perform character folding, and toggling lax whitespace matching (see section lax space matching) has no effect on them.

To search the Web for the text in region, type M-s M-w. This command performs an Internet search for the words in region using the search engine whose URL is specified by the variable eww-search-prefix (see EWW in The Emacs Web Wowser Manual). If the region is not active, or doesn’t contain any words, this command prompts the user for a URL or keywords to search.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.4 Symbol Search

A symbol search is much like an ordinary search, except that the boundaries of the search must match the boundaries of a symbol. The meaning of symbol in this context depends on the major mode, and usually refers to a source code token, such as a Lisp symbol in Emacs Lisp mode. For instance, if you perform an incremental symbol search for the Lisp symbol forward-word, it would not match isearch-forward-word. This feature is thus mainly useful for searching source code.

M-s _

If incremental search is active, toggle symbol search mode (isearch-toggle-symbol); otherwise, begin an incremental forward symbol search (isearch-forward-symbol).

M-s .

Start a symbol incremental search forward with the symbol found near point added to the search string initially.

M-s _ <RET> symbol <RET>

Search forward for symbol, nonincrementally.

M-s _ C-r <RET> symbol <RET>

Search backward for symbol, nonincrementally.

To begin a forward incremental symbol search, type M-s _ (or M-s . if the symbol to search is near point). If incremental search is not already active, this runs the command isearch-forward-symbol. If incremental search is already active, M-s _ switches to a symbol search, preserving the direction of the search and the current search string; you can disable symbol search by typing M-s _ again. In incremental symbol search, while you are typing the search string, only the beginning of the search string is required to match the beginning of a symbol, and ‘Pending’ appears in the search prompt until you use a search repeating key like C-s.

To begin a nonincremental symbol search, type M-s _ <RET> for a forward search, or M-s _ C-r <RET> or a backward search. In nonincremental symbol searches, the beginning and end of the search string are required to match the beginning and end of a symbol, respectively.

The symbol search commands don’t perform character folding, and toggling lax whitespace matching (see section lax space matching) has no effect on them.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.5 Regular Expression Search

A regular expression (or regexp for short) is a pattern that denotes a class of alternative strings to match. Emacs provides both incremental and nonincremental ways to search for a match for a regexp. The syntax of regular expressions is explained in the next section.

C-M-s

Begin incremental regexp search (isearch-forward-regexp).

C-M-r

Begin reverse incremental regexp search (isearch-backward-regexp).

Incremental search for a regexp is done by typing C-M-s (isearch-forward-regexp), by invoking C-s with a prefix argument (whose value does not matter), or by typing M-r within a forward incremental search. This command reads a search string incrementally just like C-s, but it treats the search string as a regexp rather than looking for an exact match against the text in the buffer. Each time you add text to the search string, you make the regexp longer, and the new regexp is searched for. To search backward for a regexp, use C-M-r (isearch-backward-regexp), C-r with a prefix argument, or M-r within a backward incremental search.

All of the special key sequences in an ordinary incremental search (see section Special Input for Incremental Search) do similar things in an incremental regexp search. For instance, typing C-s immediately after starting the search retrieves the last incremental search regexp used and searches forward for it. Incremental regexp and non-regexp searches have independent defaults. They also have separate search rings, which you can access with M-p and M-n. The maximum number of search regexps saved in the search ring is determined by the value of regexp-search-ring-max, 16 by default.

Unlike ordinary incremental search, incremental regexp search does not use lax space matching by default. To toggle this feature use M-s <SPC> (isearch-toggle-lax-whitespace). Then any <SPC> typed in incremental regexp search will match any sequence of one or more whitespace characters. The variable search-whitespace-regexp specifies the regexp for the lax space matching. See section Special Input for Incremental Search.

Also unlike ordinary incremental search, incremental regexp search cannot use character folding (see section Lax Matching During Searching). (If you toggle character folding during incremental regexp search with M-s ', the search becomes a non-regexp search and the search pattern you typed is interpreted as a literal string.)

In some cases, adding characters to the regexp in an incremental regexp search can make the cursor move back and start again. For example, if you have searched for ‘foo’ and you add ‘\|bar’, the cursor backs up in case the first ‘bar’ precedes the first ‘foo’. See section Syntax of Regular Expressions.

Forward and backward regexp search are not symmetrical, because regexp matching in Emacs always operates forward, starting with the beginning of the regexp. Thus, forward regexp search scans forward, trying a forward match at each possible starting position. Backward regexp search scans backward, trying a forward match at each possible starting position. These search methods are not mirror images.

Nonincremental search for a regexp is done with the commands re-search-forward and re-search-backward. You can invoke these with M-x, or by way of incremental regexp search with C-M-s <RET> and C-M-r <RET>. When you invoke these commands with M-x, they search for the exact regexp you specify, and thus don’t support any lax-search features (see section Lax Matching During Searching) except case folding.

If you use the incremental regexp search commands with a prefix argument, they perform ordinary string search, like isearch-forward and isearch-backward. See section Incremental Search.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.6 Syntax of Regular Expressions

This section (and this manual in general) describes regular expression features that users typically use. See Regular Expressions in The Emacs Lisp Reference Manual, for additional features used mainly in Lisp programs.

Regular expressions have a syntax in which a few characters are special constructs and the rest are ordinary. An ordinary character matches that same character and nothing else. The special characters are ‘$^.*+?[\’. The character ‘]’ is special if it ends a character alternative (see below). The character ‘-’ is special inside a character alternative. Any other character appearing in a regular expression is ordinary, unless a ‘\’ precedes it. (When you use regular expressions in a Lisp program, each ‘\’ must be doubled, see the example near the end of this section.)

For example, ‘f’ is not a special character, so it is ordinary, and therefore ‘f’ is a regular expression that matches the string ‘f’ and no other string. (It does not match the string ‘ff’.) Likewise, ‘o’ is a regular expression that matches only ‘o’. (When case distinctions are being ignored, these regexps also match ‘F’ and ‘O’, but we consider this a generalization of “the same string”, rather than an exception.)

Any two regular expressions a and b can be concatenated. The result is a regular expression which matches a string if a matches some amount of the beginning of that string and b matches the rest of the string. As a trivial example, concatenating the regular expressions ‘f’ and ‘o’ gives the regular expression ‘fo’, which matches only the string ‘fo’. To do something less trivial, you need to use one of the special characters. Here is a list of them.

. (Period)

is a special character that matches any single character except a newline. For example, the regular expressions ‘a.b’ matches any three-character string that begins with ‘a’ and ends with ‘b’.

*

is not a construct by itself; it is a postfix operator that means to match the preceding regular expression repetitively any number of times, as many times as possible. Thus, ‘o*’ matches any number of ‘o’s, including no ‘o’s.

*’ always applies to the smallest possible preceding expression. Thus, ‘fo*’ has a repeating ‘o’, not a repeating ‘fo’. It matches ‘f’, ‘fo’, ‘foo’, and so on.

The matcher processes a ‘*’ construct by matching, immediately, as many repetitions as can be found. Then it continues with the rest of the pattern. If that fails, backtracking occurs, discarding some of the matches of the ‘*’-modified construct in case that makes it possible to match the rest of the pattern. For example, in matching ‘ca*ar’ against the string ‘caaar’, the ‘a*’ first tries to match all three ‘a’s; but the rest of the pattern is ‘ar’ and there is only ‘r’ left to match, so this try fails. The next alternative is for ‘a*’ to match only two ‘a’s. With this choice, the rest of the regexp matches successfully.

+

is a postfix operator, similar to ‘*’ except that it must match the preceding expression at least once. Thus, ‘ca+r’ matches the strings ‘car’ and ‘caaaar’ but not the string ‘cr’, whereas ‘ca*r’ matches all three strings.

?

is a postfix operator, similar to ‘*’ except that it can match the preceding expression either once or not at all. Thus, ‘ca?r’ matches ‘car’ or ‘cr’, and nothing else.

*?, +?, ??

are non-greedy variants of the operators above. The normal operators ‘*’, ‘+’, ‘?’ match as much as they can, as long as the overall regexp can still match. With a following ‘?’, they will match as little as possible.

Thus, both ‘ab*’ and ‘ab*?’ can match the string ‘a’ and the string ‘abbbb’; but if you try to match them both against the text ‘abbb’, ‘ab*’ will match it all (the longest valid match), while ‘ab*?’ will match just ‘a’ (the shortest valid match).

Non-greedy operators match the shortest possible string starting at a given starting point; in a forward search, though, the earliest possible starting point for match is always the one chosen. Thus, if you search for ‘a.*?$’ against the text ‘abbab’ followed by a newline, it matches the whole string. Since it can match starting at the first ‘a’, it does.

\{n\}

is a postfix operator specifying n repetitions—that is, the preceding regular expression must match exactly n times in a row. For example, ‘x\{4\}’ matches the string ‘xxxx’ and nothing else.

\{n,m\}

is a postfix operator specifying between n and m repetitions—that is, the preceding regular expression must match at least n times, but no more than m times. If m is omitted, then there is no upper limit, but the preceding regular expression must match at least n times.
\{0,1\}’ is equivalent to ‘?’.
\{0,\}’ is equivalent to ‘*’.
\{1,\}’ is equivalent to ‘+’.

[ … ]

is a character set, beginning with ‘[’ and terminated by ‘]’.

In the simplest case, the characters between the two brackets are what this set can match. Thus, ‘[ad]’ matches either one ‘a’ or one ‘d’, and ‘[ad]*’ matches any string composed of just ‘a’s and ‘d’s (including the empty string). It follows that ‘c[ad]*r’ matches ‘cr’, ‘car’, ‘cdr’, ‘caddaar’, etc.

You can also include character ranges in a character set, by writing the starting and ending characters with a ‘-’ between them. Thus, ‘[a-z]’ matches any lower-case ASCII letter. Ranges may be intermixed freely with individual characters, as in ‘[a-z$%.]’, which matches any lower-case ASCII letter or ‘$’, ‘%’ or period. As another example, ‘[α-ωί]’ matches all lower-case Greek letters.

You can also include certain special character classes in a character set. A ‘[:’ and balancing ‘:]’ enclose a character class inside a character alternative. For instance, ‘[[:alnum:]]’ matches any letter or digit. See Char Classes in The Emacs Lisp Reference Manual, for a list of character classes.

To include a ‘]’ in a character set, you must make it the first character. For example, ‘[]a]’ matches ‘]’ or ‘a’. To include a ‘-’, write ‘-’ as the first or last character of the set, or put it after a range. Thus, ‘[]-]’ matches both ‘]’ and ‘-’.

To include ‘^’ in a set, put it anywhere but at the beginning of the set. (At the beginning, it complements the set—see below.)

When you use a range in case-insensitive search, you should write both ends of the range in upper case, or both in lower case, or both should be non-letters. The behavior of a mixed-case range such as ‘A-z’ is somewhat ill-defined, and it may change in future Emacs versions.

[^ … ]

[^’ begins a complemented character set, which matches any character except the ones specified. Thus, ‘[^a-z0-9A-Z]’ matches all characters except ASCII letters and digits.

^’ is not special in a character set unless it is the first character. The character following the ‘^’ is treated as if it were first (in other words, ‘-’ and ‘]’ are not special there).

A complemented character set can match a newline, unless newline is mentioned as one of the characters not to match. This is in contrast to the handling of regexps in programs such as grep.

^

is a special character that matches the empty string, but only at the beginning of a line in the text being matched. Otherwise it fails to match anything. Thus, ‘^foo’ matches a ‘foo’ that occurs at the beginning of a line.

For historical compatibility reasons, ‘^’ can be used with this meaning only at the beginning of the regular expression, or after ‘\(’ or ‘\|’.

$

is similar to ‘^’ but matches only at the end of a line. Thus, ‘x+$’ matches a string of one ‘x’ or more at the end of a line.

For historical compatibility reasons, ‘$’ can be used with this meaning only at the end of the regular expression, or before ‘\)’ or ‘\|’.

\

has two functions: it quotes the special characters (including ‘\’), and it introduces additional special constructs.

Because ‘\’ quotes special characters, ‘\$’ is a regular expression that matches only ‘$’, and ‘\[’ is a regular expression that matches only ‘[’, and so on.

See the following section for the special constructs that begin with ‘\’.

Note: for historical compatibility, special characters are treated as ordinary ones if they are in contexts where their special meanings make no sense. For example, ‘*foo’ treats ‘*’ as ordinary since there is no preceding expression on which the ‘*’ can act. It is poor practice to depend on this behavior; it is better to quote the special character anyway, regardless of where it appears.

As a ‘\’ is not special inside a character alternative, it can never remove the special meaning of ‘-’ or ‘]’. So you should not quote these characters when they have no special meaning either. This would not clarify anything, since backslashes can legitimately precede these characters where they have special meaning, as in ‘[^\]’ ("[^\\]" for Lisp string syntax), which matches any single character except a backslash.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.7 Backslash in Regular Expressions

For the most part, ‘\’ followed by any character matches only that character. However, there are several exceptions: two-character sequences starting with ‘\’ that have special meanings. The second character in the sequence is always an ordinary character when used on its own. Here is a table of ‘\’ constructs.

\|

specifies an alternative. Two regular expressions a and b with ‘\|’ in between form an expression that matches some text if either a matches it or b matches it. It works by trying to match a, and if that fails, by trying to match b.

Thus, ‘foo\|bar’ matches either ‘foo’ or ‘bar’ but no other string.

\|’ applies to the largest possible surrounding expressions. Only a surrounding ‘\( … \)’ grouping can limit the grouping power of ‘\|’.

Full backtracking capability exists to handle multiple uses of ‘\|’.

\( … \)

is a grouping construct that serves three purposes:

  1. To enclose a set of ‘\|’ alternatives for other operations. Thus, ‘\(foo\|bar\)x’ matches either ‘foox’ or ‘barx’.
  2. To enclose a complicated expression for the postfix operators ‘*’, ‘+’ and ‘?’ to operate on. Thus, ‘ba\(na\)*’ matches ‘bananana’, etc., with any (zero or more) number of ‘na’ strings.
  3. To record a matched substring for future reference.

This last application is not a consequence of the idea of a parenthetical grouping; it is a separate feature that is assigned as a second meaning to the same ‘\( … \)’ construct. In practice there is usually no conflict between the two meanings; when there is a conflict, you can use a shy group, described below.

\(?: … \)

specifies a shy group that does not record the matched substring; you can’t refer back to it with ‘\d’ (see below). This is useful in mechanically combining regular expressions, so that you can add groups for syntactic purposes without interfering with the numbering of the groups that are meant to be referred to.

\d

matches the same text that matched the dth occurrence of a ‘\( … \)’ construct. This is called a back reference.

After the end of a ‘\( … \)’ construct, the matcher remembers the beginning and end of the text matched by that construct. Then, later on in the regular expression, you can use ‘\’ followed by the digit d to mean “match the same text matched the dth time by the ‘\( … \)’ construct”.

The strings matching the first nine ‘\( … \)’ constructs appearing in a regular expression are assigned numbers 1 through 9 in the order that the open-parentheses appear in the regular expression. So you can use ‘\1’ through ‘\9’ to refer to the text matched by the corresponding ‘\( … \)’ constructs.

For example, ‘\(.*\)\1’ matches any newline-free string that is composed of two identical halves. The ‘\(.*\)’ matches the first half, which may be anything, but the ‘\1’ that follows must match the same exact text.

If a particular ‘\( … \)’ construct matches more than once (which can easily happen if it is followed by ‘*’), only the last match is recorded.

\`

matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against.

\'

matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.

\=

matches the empty string, but only at point.

\b

matches the empty string, but only at the beginning or end of a word. Thus, ‘\bfoo\b’ matches any occurrence of ‘foo’ as a separate word. ‘\bballs?\b’ matches ‘ball’ or ‘balls’ as a separate word.

\b’ matches at the beginning or end of the buffer regardless of what text appears next to it.

\B

matches the empty string, but not at the beginning or end of a word.

\<

matches the empty string, but only at the beginning of a word. ‘\<’ matches at the beginning of the buffer only if a word-constituent character follows.

\>

matches the empty string, but only at the end of a word. ‘\>’ matches at the end of the buffer only if the contents end with a word-constituent character.

\w

matches any word-constituent character. The syntax table determines which characters these are. See Syntax Tables in The Emacs Lisp Reference Manual.

\W

matches any character that is not a word-constituent.

\_<

matches the empty string, but only at the beginning of a symbol. A symbol is a sequence of one or more symbol-constituent characters. A symbol-constituent character is a character whose syntax is either ‘w’ or ‘_’. ‘\_<’ matches at the beginning of the buffer only if a symbol-constituent character follows. As with words, the syntax table determines which characters are symbol-constituent.

\_>

matches the empty string, but only at the end of a symbol. ‘\_>’ matches at the end of the buffer only if the contents end with a symbol-constituent character.

\sc

matches any character whose syntax is c. Here c is a character that designates a particular syntax class: thus, ‘w’ for word constituent, ‘-’ or ‘ ’ for whitespace, ‘.’ for ordinary punctuation, etc. See Syntax Tables in The Emacs Lisp Reference Manual.

\Sc

matches any character whose syntax is not c.

\cc

matches any character that belongs to the category c. For example, ‘\cc’ matches Chinese characters, ‘\cg’ matches Greek characters, etc. For the description of the known categories, type M-x describe-categories <RET>.

\Cc

matches any character that does not belong to category c.

The constructs that pertain to words and syntax are controlled by the setting of the syntax table. See Syntax Tables in The Emacs Lisp Reference Manual.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.8 Regular Expression Example

Here is an example of a regexp—similar to the regexp that Emacs uses, by default, to recognize the end of a sentence, not including the following space (i.e., the variable sentence-end-base):

[.?!][]\"')}]*

This contains two parts in succession: a character set matching period, ‘?’, or ‘!’, and a character set matching close-brackets, quotes, or parentheses, repeated zero or more times.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.9 Lax Matching During Searching

Normally, you’d want search commands to disregard certain minor differences between the search string you type and the text being searched. For example, sequences of whitespace characters of different length are usually perceived as equivalent; letter-case differences usually don’t matter; etc. This is known as character equivalence.

This section describes the Emacs lax search features, and how to tailor them to your needs.

By default, search commands perform lax space matching: each space, or sequence of spaces, matches any sequence of one or more whitespace characters in the text. (Incremental regexp search has a separate default; see Regular Expression Search.) Hence, ‘foo bar’ matches ‘foo bar’, ‘foo  bar’, ‘foo   bar’, and so on (but not ‘foobar’). More precisely, Emacs matches each sequence of space characters in the search string to a regular expression specified by the variable search-whitespace-regexp. For example, to make spaces match sequences of newlines as well as spaces, set it to ‘"[[:space:]\n]+"’. The default value of this variable depends on the buffer’s major mode; most major modes classify spaces, tabs, and formfeed characters as whitespace.

If you want whitespace characters to match exactly, you can turn lax space matching off by typing M-s <SPC> (isearch-toggle-lax-whitespace) within an incremental search. Another M-s <SPC> turns lax space matching back on. To disable lax whitespace matching for all searches, change search-whitespace-regexp to nil; then each space in the search string matches exactly one space.

Searches in Emacs by default ignore the case of the text they are searching through, if you specify the search string in lower case. Thus, if you specify searching for ‘foo’, then ‘Foo’ and ‘fOO’ also match. Regexps, and in particular character sets, behave likewise: ‘[ab]’ matches ‘a’ or ‘A’ or ‘b’ or ‘B’. This feature is known as case folding, and it is supported in both incremental and non-incremental search modes.

An upper-case letter anywhere in the search string makes the search case-sensitive. Thus, searching for ‘Foo’ does not find ‘foo’ or ‘FOO’. This applies to regular expression search as well as to literal string search. The effect ceases if you delete the upper-case letter from the search string. The variable search-upper-case controls this: if it is non-nil (the default), an upper-case character in the search string makes the search case-sensitive; setting it to nil disables this effect of upper-case characters.

If you set the variable case-fold-search to nil, then all letters must match exactly, including case. This is a per-buffer variable; altering the variable normally affects only the current buffer, unless you change its default value. See section Local Variables. This variable applies to nonincremental searches also, including those performed by the replace commands (see section Replacement Commands) and the minibuffer history matching commands (see section Minibuffer History).

Typing M-c or M-s c (isearch-toggle-case-fold) within an incremental search toggles the case sensitivity of that search. The effect does not extend beyond the current incremental search, but it does override the effect of adding or removing an upper-case letter in the current search.

Several related variables control case-sensitivity of searching and matching for specific commands or activities. For instance, tags-case-fold-search controls case sensitivity for find-tag. To find these variables, do M-x apropos-variable <RET> case-fold-search <RET>.

Case folding disregards case distinctions among characters, making upper-case characters match lower-case variants, and vice versa. A generalization of case folding is character folding, which disregards wider classes of distinctions among similar characters. For instance, under character folding the letter a matches all of its accented cousins like ä and á, i.e., the match disregards the diacritics that distinguish these variants. In addition, a matches other characters that resemble it, or have it as part of their graphical representation, such as U+249C PARENTHESIZED LATIN SMALL LETTER A and U+2100 ACCOUNT OF (which looks like a small a over c). Similarly, the ASCII double-quote character " matches all the other variants of double quotes defined by the Unicode standard. Finally, character folding can make a sequence of one or more characters match another sequence of a different length: for example, the sequence of two characters ff matches U+FB00 LATIN SMALL LIGATURE FF. Character sequences that are not identical, but match under character folding are known as equivalent character sequences.

Generally, search commands in Emacs do not by default perform character folding in order to match equivalent character sequences. You can enable this behavior by customizing the variable search-default-mode to char-fold-to-regexp. See section Tailoring Search to Your Needs. Within an incremental search, typing M-s ' (isearch-toggle-char-fold) toggles character folding, but only for that search. (Replace commands have a different default, controlled by a separate option; see Replace Commands and Lax Matches.)

Like with case folding, typing an explicit variant of a character, such as ä, as part of the search string disables character folding for that search. If you delete such a character from the search string, this effect ceases.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.10 Replacement Commands

Emacs provides several commands for performing search-and-replace operations. In addition to the simple M-x replace-string command, there is M-% (query-replace), which presents each occurrence of the search pattern and asks you whether to replace it.

The replace commands normally operate on the text from point to the end of the buffer. When the region is active, they operate on it instead (see section The Mark and the Region). The basic replace commands replace one search string (or regexp) with one replacement string. It is possible to perform several replacements in parallel, using the command expand-region-abbrevs (see section Controlling Abbrev Expansion).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.10.1 Unconditional Replacement

M-x replace-string <RET> string <RET> newstring <RET>

Replace every occurrence of string with newstring.

To replace every instance of ‘foo’ after point with ‘bar’, use the command M-x replace-string with the two arguments ‘foo’ and ‘bar’. Replacement happens only in the text after point, so if you want to cover the whole buffer you must go to the beginning first. All occurrences up to the end of the buffer are replaced; to limit replacement to part of the buffer, activate the region around that part. When the region is active, replacement is limited to the region (see section The Mark and the Region).

When replace-string exits, it leaves point at the last occurrence replaced. It adds the prior position of point (where the replace-string command was issued) to the mark ring, without activating the mark; use C-u C-<SPC> to move back there. See section The Mark Ring.

A prefix argument restricts replacement to matches that are surrounded by word boundaries.

See section Replace Commands and Lax Matches, for details about case-sensitivity and character folding in replace commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.10.2 Regexp Replacement

The M-x replace-string command replaces exact matches for a single string. The similar command M-x replace-regexp replaces any match for a specified regular expression pattern (see section Syntax of Regular Expressions).

M-x replace-regexp <RET> regexp <RET> newstring <RET>

Replace every match for regexp with newstring.

In replace-regexp, the newstring need not be constant: it can refer to all or part of what is matched by the regexp. ‘\&’ in newstring stands for the entire match being replaced. ‘\d’ in newstring, where d is a digit starting from 1, stands for whatever matched the dth parenthesized grouping in regexp. (This is called a “back reference”.) ‘\#’ refers to the count of replacements already made in this command, as a decimal number. In the first replacement, ‘\#’ stands for ‘0’; in the second, for ‘1’; and so on. For example,

M-x replace-regexp <RET> c[ad]+r <RET> \&-safe <RET>

replaces (for example) ‘cadr’ with ‘cadr-safe’ and ‘cddr’ with ‘cddr-safe’.

M-x replace-regexp <RET> \(c[ad]+r\)-safe <RET> \1 <RET>

performs the inverse transformation. To include a ‘\’ in the text to replace with, you must enter ‘\\’.

If you want to enter part of the replacement string by hand each time, use ‘\?’ in the replacement string. Each replacement will ask you to edit the replacement string in the minibuffer, putting point where the ‘\?’ was.

The remainder of this subsection is intended for specialized tasks and requires knowledge of Lisp. Most readers can skip it.

You can use Lisp expressions to calculate parts of the replacement string. To do this, write ‘\,’ followed by the expression in the replacement string. Each replacement calculates the value of the expression and converts it to text without quoting (if it’s a string, this means using the string’s contents), and uses it in the replacement string in place of the expression itself. If the expression is a symbol, one space in the replacement string after the symbol name goes with the symbol name, so the value replaces them both.

Inside such an expression, you can use some special sequences. ‘\&’ and ‘\d’ refer here, as usual, to the entire match as a string, and to a submatch as a string. d may be multiple digits, and the value of ‘\d’ is nil if the d’th parenthesized grouping did not match. You can also use ‘\#&’ and ‘\#d’ to refer to those matches as numbers (this is valid when the match or submatch has the form of a numeral). ‘\#’ here too stands for the number of already-completed replacements.

Repeating our example to exchange ‘x’ and ‘y’, we can thus do it also this way:

M-x replace-regexp <RET> \(x\)\|y <RET>
\,(if \1 "y" "x") <RET>

For computing replacement strings for ‘\,’, the format function is often useful (see Formatting Strings in The Emacs Lisp Reference Manual). For example, to add consecutively numbered strings like ‘ABC00042’ to columns 73 to 80 (unless they are already occupied), you can use

M-x replace-regexp <RET> ^.\{0,72\}$ <RET>
\,(format "%-72sABC%05d" \& \#) <RET>

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.10.3 Replace Commands and Lax Matches

This subsection describes the behavior of replace commands with respect to lax matches (see section Lax Matching During Searching) and how to customize it. In general, replace commands mostly default to stricter matching than their search counterparts.

Unlike incremental search, the replacement commands do not use lax space matching (see section lax space matching) by default. To enable lax space matching for replacement, change the variable replace-lax-whitespace to non-nil. (This only affects how Emacs finds the text to replace, not the replacement text.)

A companion variable replace-regexp-lax-whitespace controls whether query-replace-regexp uses lax whitespace matching when searching for patterns.

If the first argument of a replace command is all lower case, the command ignores case while searching for occurrences to replace—provided case-fold-search is non-nil. If case-fold-search is set to nil, case is always significant in all searches.

In addition, when the newstring argument is all or partly lower case, replacement commands try to preserve the case pattern of each occurrence. Thus, the command

M-x replace-string <RET> foo <RET> bar <RET>

replaces a lower case ‘foo’ with a lower case ‘bar’, an all-caps ‘FOO’ with ‘BAR’, and a capitalized ‘Foo’ with ‘Bar’. (These three alternatives—lower case, all caps, and capitalized, are the only ones that replace-string can distinguish.)

If upper-case letters are used in the replacement string, they remain upper case every time that text is inserted. If upper-case letters are used in the first argument, the second argument is always substituted exactly as given, with no case conversion. Likewise, if either case-replace or case-fold-search is set to nil, replacement is done without case conversion.

The replacement commands by default do not use character folding (see section character folding) when looking for the text to replace. To enable character folding for matching in query-replace and replace-string, set the variable replace-char-fold to a non-nil value. (This setting does not affect the replacement text, only how Emacs finds the text to replace. It also doesn’t affect replace-regexp.)


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.10.4 Query Replace

M-% string <RET> newstring <RET>

Replace some occurrences of string with newstring.

C-M-% regexp <RET> newstring <RET>

Replace some matches for regexp with newstring.

If you want to change only some of the occurrences of ‘foo’ to ‘bar’, not all of them, use M-% (query-replace). This command finds occurrences of ‘foo’ one by one, displays each occurrence and asks you whether to replace it. Aside from querying, query-replace works just like replace-string (see section Unconditional Replacement). In particular, it preserves case provided case-replace is non-nil, as it normally is (see section Replace Commands and Lax Matches). A numeric argument means to consider only occurrences that are bounded by word-delimiter characters. A negative prefix argument replaces backward.

C-M-% performs regexp search and replace (query-replace-regexp). It works like replace-regexp except that it queries like query-replace.

You can reuse earlier replacements with these commands. When query-replace or query-replace-regexp prompts for the search string, use M-p and M-n to show previous replacements in the form ‘from -> to’, where from is the search pattern, to is its replacement, and the separator between them is determined by the value of the variable query-replace-from-to-separator. Type <RET> to select the desired replacement. If the value of this variable is nil, replacements are not added to the command history, and cannot be reused.

These commands highlight the current match using the face query-replace. You can disable this highlight by setting the variable query-replace-highlight to nil. They highlight other matches using lazy-highlight just like incremental search (see section Incremental Search); this can be disabled by setting query-replace-lazy-highlight to nil. By default, query-replace-regexp will show the substituted replacement string for the current match in the minibuffer. If you want to keep special sequences ‘\&’ and ‘\n’ unexpanded, customize query-replace-show-replacement variable.

The variable query-replace-skip-read-only, if set non-nil, will cause replacement commands to ignore matches in read-only text. The default is not to ignore them.

The characters you can type when you are shown a match for the string or regexp are:

<SPC>
y

to replace the occurrence with newstring.

<DEL>
<Delete>
<BACKSPACE>
n

to skip to the next occurrence without replacing this one.

, (Comma)

to replace this occurrence and display the result. You are then asked for another input character to say what to do next. Since the replacement has already been made, <DEL> and <SPC> are equivalent in this situation; both move to the next occurrence.

You can type C-r at this point (see below) to alter the replaced text. You can also type C-x u to undo the replacement; this exits the query-replace, so if you want to do further replacement you must use C-x <ESC> <ESC> <RET> to restart (see section Repeating Minibuffer Commands).

<RET>
q

to exit without doing any more replacements.

. (Period)

to replace this occurrence and then exit without searching for more occurrences.

!

to replace all remaining occurrences without asking again.

^

to go back to the position of the previous occurrence (or what used to be an occurrence), in case you changed it by mistake or want to reexamine it.

u

to undo the last replacement and go back to where that replacement was made.

U

to undo all the replacements and go back to where the first replacement was made.

C-r

to enter a recursive editing level, in case the occurrence needs to be edited rather than just replaced with newstring. When you are done, exit the recursive editing level with C-M-c to proceed to the next occurrence. See section Recursive Editing Levels.

C-w

to delete the occurrence, and then enter a recursive editing level as in C-r. Use the recursive edit to insert text to replace the deleted occurrence of string. When done, exit the recursive editing level with C-M-c to proceed to the next occurrence.

e

to edit the replacement string in the minibuffer. When you exit the minibuffer by typing <RET>, the minibuffer contents replace the current occurrence of the pattern. They also become the new replacement string for any further occurrences.

C-l

to redisplay the screen. Then you must type another character to specify what to do with this occurrence.

Y (Upper-case)

to replace all remaining occurrences in all remaining buffers in multi-buffer replacements (like the Dired Q command that performs query replace on selected files). It answers this question and all subsequent questions in the series with “yes”, without further user interaction.

N (Upper-case)

to skip to the next buffer in multi-buffer replacements without replacing remaining occurrences in the current buffer. It answers this question “no”, gives up on the questions for the current buffer, and continues to the next buffer in the sequence.

C-h
?
<F1>

to display a message summarizing these options. Then you must type another character to specify what to do with this occurrence.

Aside from this, any other character exits the query-replace, and is then reread as part of a key sequence. Thus, if you type C-k, it exits the query-replace and then kills to end of line. In particular, C-g simply exits the query-replace.

To restart a query-replace once it is exited, use C-x <ESC> <ESC>, which repeats the query-replace because it used the minibuffer to read its arguments. See section C-x <ESC> <ESC>.

The option search-invisible determines how query-replace treats invisible text. See Outline Search.

See section Operating on Files, for the Dired Q command which performs query replace on selected files. See also Transforming File Names in Dired, for Dired commands to rename, copy, or link files by replacing regexp matches in file names.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.11 Other Search-and-Loop Commands

Here are some other commands that find matches for a regular expression. They all ignore case in matching, if the pattern contains no upper-case letters and case-fold-search is non-nil. Aside from multi-occur and multi-occur-in-matching-buffers, which always search the whole buffer, all operate on the text from point to the end of the buffer, or on the region if it is active.

M-x multi-isearch-buffers

Prompt for one or more buffer names, ending with <RET>; then, begin a multi-buffer incremental search in those buffers. (If the search fails in one buffer, the next C-s tries searching the next specified buffer, and so forth.) With a prefix argument, prompt for a regexp and begin a multi-buffer incremental search in buffers matching that regexp.

M-x multi-isearch-buffers-regexp

This command is just like multi-isearch-buffers, except it performs an incremental regexp search.

M-x multi-isearch-files

Prompt for one or more file names, ending with <RET>; then, begin a multi-file incremental search in those files. (If the search fails in one file, the next C-s tries searching the next specified file, and so forth.) With a prefix argument, prompt for a regexp and begin a multi-file incremental search in files matching that regexp.

M-x multi-isearch-files-regexp

This command is just like multi-isearch-files, except it performs an incremental regexp search.

In some modes that set the buffer-local variable multi-isearch-next-buffer-function (e.g., in Change Log mode) a multi-file incremental search is activated automatically.

M-x occur
M-s o

Prompt for a regexp, and display a list showing each line in the buffer that contains a match for it. If you type M-n at the prompt, you can reuse search strings from previous incremental searches. The text that matched is highlighted using the match face. A numeric argument n specifies that n lines of context are to be displayed before and after each matching line.

The default number of context lines is specified by the variable list-matching-lines-default-context-lines. When list-matching-lines-jump-to-current-line is non-nil the current line is shown highlighted with face list-matching-lines-current-line-face and the point is set at the first match after such line.

You can also run M-s o when an incremental search is active; this uses the current search string.

Note that matches for the regexp you type are extended to include complete lines, and a match that starts before the previous match ends is not considered a match.

In the ‘*Occur*’ buffer, you can click on each entry, or move point there and type <RET>, to visit the corresponding position in the buffer that was searched. o and C-o display the match in another window; C-o does not select it. Alternatively, you can use the C-x ` (next-error) command to visit the occurrences one by one (see section Compilation Mode).

Typing e in the ‘*Occur*’ buffer switches to Occur Edit mode, in which edits made to the entries are also applied to the text in the originating buffer. Type C-c C-c to return to Occur mode.

The command M-x list-matching-lines is a synonym for M-x occur.

M-x multi-occur

This command is just like occur, except it is able to search through multiple buffers. It asks you to specify the buffer names one by one.

M-x multi-occur-in-matching-buffers

This command is similar to multi-occur, except the buffers to search are specified by a regular expression that matches visited file names. With a prefix argument, it uses the regular expression to match buffer names instead.

M-x how-many

Prompt for a regexp, and print the number of matches for it in the buffer after point. If the region is active, this operates on the region instead.

M-x flush-lines

Prompt for a regexp, and delete each line that contains a match for it, operating on the text after point. This command deletes the current line if it contains a match starting after point. If the region is active, it operates on the region instead; if a line partially contained in the region contains a match entirely contained in the region, it is deleted.

If a match is split across lines, flush-lines deletes all those lines. It deletes the lines before starting to look for the next match; hence, it ignores a match starting on the same line at which another match ended.

M-x keep-lines

Prompt for a regexp, and delete each line that does not contain a match for it, operating on the text after point. If point is not at the beginning of a line, this command always keeps the current line. If the region is active, the command operates on the region instead; it never deletes lines that are only partially contained in the region (a newline that ends a line counts as part of that line).

If a match is split across lines, this command keeps all those lines.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15.12 Tailoring Search to Your Needs

This section describes miscellaneous search-related customizations not described elsewhere.

The default search mode for the incremental search is specified by the variable search-default-mode. It can be nil, t, or a function. If it is nil, the default mode is to do literal searches without character folding, but with case folding and lax-whitespace matches as determined by case-fold-search and search-whitespace-regexp, respectively (see section Lax Matching During Searching). If the value is t, incremental search defaults to regexp searches. The default value specifies a function that only performs case folding and lax-whitespace matching.

The current match of an on-going incremental search is highlighted using the isearch face. This highlighting can be disabled by setting the variable search-highlight to nil.

The other matches for the search string that are visible on display are highlighted using the lazy-highlight face. Setting the variable isearch-lazy-highlight to nil disables this highlighting. Here are some other variables that customize the lazy highlighting:

lazy-highlight-initial-delay

Time in seconds to wait before highlighting visible matches.

lazy-highlight-interval

Time in seconds between highlighting successive matches.

lazy-highlight-max-at-a-time

The maximum number of matches to highlight before checking for input. A large number can take some time to highlight, so if you want to continue searching and type C-s or C-r during that time, Emacs will not respond until it finishes highlighting all those matches. Thus, smaller values make Emacs more responsive.

Normally, entering <RET> within incremental search when the search string is empty launches a nonincremental search. (Actually, it lets you edit the search string, and the next <RET> does the search.) However, if you customize the variable search-nonincremental-instead to nil, typing <RET> will always exit the incremental search, even if the search string is empty.

By default, incremental search and query-replace commands match invisible text, but hide any such matches as soon as the current match moves off the invisible text. If you customize the variable isearch-hide-immediately to nil, any invisible text where matches were found stays on display until the search or the replace command exits.

Searching incrementally on slow terminals, such as displays connected to remote machines over slow connection, could be annoying due to the need to redraw large portions of the display as the search proceeds. Emacs provides a special display mode for slow terminals, whereby search pops up a separate small window and displays the text surrounding the match in that window. Small windows display faster, so the annoying effect of slow speed is alleviated. The variable search-slow-speed determines the baud rate threshold below which Emacs will use this display mode. The variable search-slow-window-lines controls the number of lines in the window Emacs pops up for displaying the search results; the default is 1 line. Normally, this window will pop up at the bottom of the window that displays the buffer where you start searching, but if the value of search-slow-window-lines is negative, that means to put the window at the top and give it the number of lines that is the absolute value of search-slow-window-lines.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 <DEL> (delete-backward-char). These were described earlier in this manual. See section Erasing Text.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.1 Undo

The undo command reverses recent changes in the buffer’s text. Each buffer records changes individually, and the undo command always applies to the current buffer. You can undo all the changes in a buffer for as far back as the buffer’s records go. Usually, each editing command makes a separate entry in the undo records, but some commands such as query-replace divide their changes into multiple entries for flexibility in undoing. Consecutive character insertion commands are usually grouped together into a single undo record, to make undoing less tedious.

C-/
C-x u
C-_

Undo one entry in the current buffer’s undo records (undo).

To begin to undo, type C-/ (or its aliases, C-_ or C-x u)(6). This undoes the most recent change in the buffer, and moves point back to where it was before that change. Consecutive repetitions of C-/ (or its aliases) undo earlier and earlier changes in the current buffer. If all the recorded changes have already been undone, the undo command signals an error.

Any command other than an undo command breaks the sequence of undo commands. Starting from that moment, the entire sequence of undo commands that you have just performed are themselves placed into the undo record. Therefore, to re-apply changes you have undone, type C-f or any other command that harmlessly breaks the sequence of undoing; then type C-/ one or more times to undo some of the undo commands.

Alternatively, if you want to resume undoing, without redoing previous undo commands, use M-x undo-only. This is like undo, but will not redo changes you have just undone.

If you notice that a buffer has been modified accidentally, the easiest way to recover is to type C-/ repeatedly until the stars disappear from the front of the mode line (see section The Mode Line). Whenever an undo command makes the stars disappear from the mode line, it means that the buffer contents are the same as they were when the file was last read in or saved. If you do not remember whether you changed the buffer deliberately, type C-/ once. When you see the last change you made undone, you will see whether it was an intentional change. If it was an accident, leave it undone. If it was deliberate, redo the change as described above.

Alternatively, you can discard all the changes since the buffer was last visited or saved with M-x revert-buffer (see section Reverting a Buffer).

When there is an active region, any use of undo performs selective undo: it undoes the most recent change within the region, instead of the entire buffer. However, when Transient Mark mode is off (see section Disabling Transient Mark Mode), C-/ always operates on the entire buffer, ignoring the region. In this case, you can perform selective undo by supplying a prefix argument to the undo command: C-u C-/. To undo further changes in the same region, repeat the undo command (no prefix argument is needed).

Some specialized buffers do not make undo records. Buffers whose names start with spaces never do; these buffers are used internally by Emacs to hold text that users don’t normally look at or edit.

When the undo information for a buffer becomes too large, Emacs discards the oldest records from time to time (during garbage collection). You can specify how much undo information to keep by setting the variables undo-limit, undo-strong-limit, and undo-outer-limit. Their values are expressed in bytes.

The variable undo-limit sets a soft limit: Emacs keeps undo data for enough commands to reach this size, and perhaps exceed it, but does not keep data for any earlier commands beyond that. Its default value is 80000. The variable undo-strong-limit sets a stricter limit: any previous command (though not the most recent one) that pushes the size past this amount is forgotten. The default value of undo-strong-limit is 120000.

Regardless of the values of those variables, the most recent change is never discarded unless it gets bigger than undo-outer-limit (normally 12,000,000). At that point, Emacs discards the undo data and warns you about it. This is the only situation in which you cannot undo the last command. If this happens, you can increase the value of undo-outer-limit to make it even less likely to happen in the future. But if you didn’t expect the command to create such large undo data, then it is probably a bug and you should report it. See section Reporting Bugs.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.2 Transposing Text

C-t

Transpose two characters (transpose-chars).

M-t

Transpose two words (transpose-words).

C-M-t

Transpose two balanced expressions (transpose-sexps).

C-x C-t

Transpose two lines (transpose-lines).

The common error of transposing two characters can be fixed, when they are adjacent, with the C-t command (transpose-chars). Normally, C-t transposes the two characters on either side of point. When given at the end of a line, rather than transposing the last character of the line with the newline, which would be useless, C-t transposes the last two characters on the line. So, if you catch your transposition error right away, you can fix it with just a C-t. If you don’t catch it so fast, you must move the cursor back between the two transposed characters before you type C-t. If you transposed a space with the last character of the word before it, the word motion commands (M-f, M-b, etc.) are a good way of getting there. Otherwise, a reverse search (C-r) is often the best way. See section Searching and Replacement.

M-t transposes the word before point with the word after point (transpose-words). It moves point forward over a word, dragging the word preceding or containing point forward as well. The punctuation characters between the words do not move. For example, ‘FOO, BAR’ transposes into ‘BAR, FOO’ rather than ‘BAR FOO,’. When point is at the end of the line, it will transpose the word before point with the first word on the next line.

C-M-t (transpose-sexps) is a similar command for transposing two expressions (see section Expressions with Balanced Parentheses), and C-x C-t (transpose-lines) exchanges lines. They work like M-t except as regards the units of text they transpose.

A numeric argument to a transpose command serves as a repeat count: it tells the transpose command to move the character (or word or expression or line) before or containing point across several other characters (or words or expressions or lines). For example, C-u 3 C-t moves the character before point forward across three other characters. It would change ‘f∗oobar’ into ‘oobf∗ar’. This is equivalent to repeating C-t three times. C-u - 4 M-t moves the word before point backward across four words. C-u - C-M-t would cancel the effect of plain C-M-t.

A numeric argument of zero is assigned a special meaning (because otherwise a command with a repeat count of zero would do nothing): to transpose the character (or word or expression or line) ending after point with the one ending after the mark.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3 Case Conversion

M-- M-l

Convert last word to lower case. Note Meta-- is Meta-minus.

M-- M-u

Convert last word to all upper case.

M-- M-c

Convert last word to lower case with capital initial.

A very common error is to type words in the wrong case. Because of this, the word case-conversion commands M-l, M-u, and M-c have a special feature when used with a negative argument: they do not move the cursor. As soon as you see you have mistyped the last word, you can simply case-convert it and go on typing. See section Case Conversion Commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.4 Checking and Correcting Spelling

This section describes the commands to check the spelling of a single word or of a portion of a buffer. These commands only work if a spelling checker program, one of Hunspell, Aspell, Ispell or Enchant, is installed. These programs are not part of Emacs, but one of them is usually installed on GNU/Linux and other free operating systems. See Aspell in The Aspell Manual.

M-$

Check and correct spelling of the word at point (ispell-word). If the region is active, do it for all words in the region instead.

M-x ispell

Check and correct spelling of all words in the buffer. If the region is active, do it for all words in the region instead.

M-x ispell-buffer

Check and correct spelling in the buffer.

M-x ispell-region

Check and correct spelling in the region.

M-x ispell-message

Check and correct spelling in a draft mail message, excluding cited material.

M-x ispell-change-dictionary <RET> dict <RET>

Restart the spell-checker process, using dict as the dictionary.

M-x ispell-kill-ispell

Kill the spell-checker subprocess.

M-<TAB>
<ESC> <TAB>
C-M-i

Complete the word before point based on the spelling dictionary (ispell-complete-word).

M-x flyspell-mode

Enable Flyspell mode, which highlights all misspelled words.

M-x flyspell-prog-mode

Enable Flyspell mode for comments and strings only.

To check the spelling of the word around or before point, and optionally correct it as well, type M-$ (ispell-word). If a region is active, M-$ checks the spelling of all words within the region. See section The Mark and the Region. (When Transient Mark mode is off, M-$ always acts on the word around or before point, ignoring the region; see section Disabling Transient Mark Mode.)

Similarly, the command M-x ispell performs spell-checking in the region if one is active, or in the entire buffer otherwise. The commands M-x ispell-buffer and M-x ispell-region explicitly perform spell-checking on the entire buffer or the region respectively. To check spelling in an email message you are writing, use M-x ispell-message; that command checks the whole buffer, except for material that is indented or appears to be cited from other messages. See section Sending Mail.

When one of these commands encounters what appears to be an incorrect word, it asks you what to do. It usually displays a list of numbered near-misses—words that are close to the incorrect word. Then you must type a single-character response. Here are the valid responses:

digit

Replace the word, just this time, with one of the displayed near-misses. Each near-miss is listed with a digit; type that digit to select it.

<SPC>

Skip this word—continue to consider it incorrect, but don’t change it here.

r new <RET>

Replace the word, just this time, with new. (The replacement string will be rescanned for more spelling errors.)

R new <RET>

Replace the word with new, and do a query-replace so you can replace it elsewhere in the buffer if you wish. (The replacements will be rescanned for more spelling errors.)

a

Accept the incorrect word—treat it as correct, but only in this editing session.

A

Accept the incorrect word—treat it as correct, but only in this editing session and for this buffer.

i

Insert this word in your private dictionary file so that it will be considered correct from now on, even in future sessions.

m

Like i, but you can also specify dictionary completion information.

u

Insert the lower-case version of this word in your private dictionary file.

l word <RET>

Look in the dictionary for words that match word. These words become the new list of near-misses; you can select one of them as the replacement by typing a digit. You can use ‘*’ in word as a wildcard.

C-g
X

Quit interactive spell-checking, leaving point at the word that was being checked. You can restart checking again afterward with C-u M-$.

x

Quit interactive spell-checking and move point back to where it was when you started spell-checking.

q

Quit interactive spell-checking and kill the spell-checker subprocess.

?

Show the list of options.

In Text mode and related modes, M-<TAB> (ispell-complete-word) performs in-buffer completion based on spelling correction. Insert the beginning of a word, and then type M-<TAB>; this shows a list of completions. (If your window manager intercepts M-<TAB>, type <ESC> <TAB> or C-M-i.) Each completion is listed with a digit or character; type that digit or character to choose it.

Once started, the spell-checker subprocess continues to run, waiting for something to do, so that subsequent spell-checking commands complete more quickly. If you want to get rid of the process, use M-x ispell-kill-ispell. This is not usually necessary, since the process uses no processor time except when you do spelling correction.

Spell-checkers look up spelling in two dictionaries: the standard dictionary and your personal dictionary. The standard dictionary is specified by the variable ispell-local-dictionary or, if that is nil, by the variable ispell-dictionary. If both are nil, the spelling program’s default dictionary is used. The command M-x ispell-change-dictionary sets the standard dictionary for the buffer and then restarts the subprocess, so that it will use a different standard dictionary. Your personal dictionary is specified by the variable ispell-personal-dictionary. If that is nil, the spelling program looks for a personal dictionary in a default location, which is specific to each spell-checker.

A separate dictionary is used for word completion. The variable ispell-complete-word-dict specifies the file name of this dictionary. The completion dictionary must be different because it cannot use the information about roots and affixes of the words, which spell-checking uses to detect variations of words. For some languages, there is a spell-checking dictionary but no word completion dictionary.

Flyspell mode is a minor mode that performs automatic spell-checking as you type. When it finds a word that it does not recognize, it highlights that word. Type M-x flyspell-mode to toggle Flyspell mode in the current buffer. To enable Flyspell mode in all text mode buffers, add flyspell-mode to text-mode-hook. See section Hooks.

When Flyspell mode highlights a word as misspelled, you can click on it with mouse-2 (flyspell-correct-word) to display a menu of possible corrections and actions. In addition, C-. or <ESC>-<TAB> (flyspell-auto-correct-word) will propose various successive corrections for the word at point, and C-c $ (flyspell-correct-word-before-point) will pop up a menu of possible corrections. Of course, you can always correct the misspelled word by editing it manually in any way you like.

Flyspell Prog mode works just like ordinary Flyspell mode, except that it only checks words in comments and string constants. This feature is useful for editing programs. Type M-x flyspell-prog-mode to enable or disable this mode in the current buffer. To enable this mode in all programming mode buffers, add flyspell-prog-mode to prog-mode-hook (see section Hooks).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17 Keyboard Macros

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.1 Basic Use

<F3>

Start defining a keyboard macro (kmacro-start-macro-or-insert-counter).

<F4>

If a keyboard macro is being defined, end the definition; otherwise, execute the most recent keyboard macro (kmacro-end-or-call-macro).

C-u <F3>

Re-execute last keyboard macro, then append keys to its definition.

C-u C-u <F3>

Append keys to the last keyboard macro without re-executing it.

C-x C-k r

Run the last keyboard macro on each line that begins in the region (apply-macro-to-region-lines).

To start defining a keyboard macro, type <F3>. From then on, your keys continue to be executed, but also become part of the definition of the macro. ‘Def’ appears in the mode line to remind you of what is going on. When you are finished, type <F4> (kmacro-end-or-call-macro) to terminate the definition. For example,

<F3> M-f foo <F4>

defines a macro to move forward a word and then insert ‘foo’. Note that <F3> and <F4> do not become part of the macro.

After defining the macro, you can call it with <F4>. For the above example, this has the same effect as typing M-f foo again. (Note the two roles of the <F4> command: it ends the macro if you are in the process of defining one, or calls the last macro otherwise.) You can also supply <F4> with a numeric prefix argument ‘n’, which means to invoke the macro ‘n’ times. An argument of zero repeats the macro indefinitely, until it gets an error or you type C-g (or, on MS-DOS, C-<BREAK>).

The above example demonstrates a handy trick that you can employ with keyboard macros: if you wish to repeat an operation at regularly spaced places in the text, include a motion command as part of the macro. In this case, repeating the macro inserts the string ‘foo’ after each successive word.

After terminating the definition of a keyboard macro, you can append more keystrokes to its definition by typing C-u <F3>. This is equivalent to plain <F3> followed by retyping the whole definition so far. As a consequence, it re-executes the macro as previously defined. If you change the variable kmacro-execute-before-append to nil, the existing macro will not be re-executed before appending to it (the default is t). You can also add to the end of the definition of the last keyboard macro without re-executing it by typing C-u C-u <F3>.

When a command reads an argument with the minibuffer, your minibuffer input becomes part of the macro along with the command. So when you replay the macro, the command gets the same argument as when you entered the macro. For example,

<F3> C-a C-k C-x b foo <RET> C-y C-x b <RET> <F4>

defines a macro that kills the current line, yanks it into the buffer ‘foo’, then returns to the original buffer.

Most keyboard commands work as usual in a keyboard macro definition, with some exceptions. Typing C-g (keyboard-quit) quits the keyboard macro definition. Typing C-M-c (exit-recursive-edit) can be unreliable: it works as you’d expect if exiting a recursive edit that started within the macro, but if it exits a recursive edit that started before you invoked the keyboard macro, it also necessarily exits the keyboard macro too. Mouse events are also unreliable, even though you can use them in a keyboard macro: when the macro replays the mouse event, it uses the original mouse position of that event, the position that the mouse had while you were defining the macro. The effect of this may be hard to predict.

The command C-x C-k r (apply-macro-to-region-lines) repeats the last defined keyboard macro on each line that begins in the region. It does this line by line, by moving point to the beginning of the line and then executing the macro.

In addition to the <F3> and <F4> commands described above, Emacs also supports an older set of key bindings for defining and executing keyboard macros. To begin a macro definition, type C-x ( (kmacro-start-macro); as with <F3>, a prefix argument appends this definition to the last keyboard macro. To end a macro definition, type C-x ) (kmacro-end-macro). To execute the most recent macro, type C-x e (kmacro-end-and-call-macro). If you enter C-x e while defining a macro, the macro is terminated and executed immediately. Immediately after typing C-x e, you can type e repeatedly to immediately repeat the macro one or more times. You can also give C-x e a repeat argument, just like <F4> (when it is used to execute a macro).

C-x ) can be given a repeat count as an argument. This means to repeat the macro right after defining it. The macro definition itself counts as the first repetition, since it is executed as you define it, so C-u 4 C-x ) executes the macro immediately 3 additional times.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.2 The Keyboard Macro Ring

All defined keyboard macros are recorded in the keyboard macro ring. There is only one keyboard macro ring, shared by all buffers.

C-x C-k C-k

Execute the keyboard macro at the head of the ring (kmacro-end-or-call-macro-repeat).

C-x C-k C-n

Rotate the keyboard macro ring to the next macro (defined earlier) (kmacro-cycle-ring-next).

C-x C-k C-p

Rotate the keyboard macro ring to the previous macro (defined later) (kmacro-cycle-ring-previous).

All commands which operate on the keyboard macro ring use the same C-x C-k prefix. Most of these commands can be executed and repeated immediately after each other without repeating the C-x C-k prefix. For example,

C-x C-k C-p C-p C-k C-k C-k C-n C-n C-k C-p C-k C-d

will rotate the keyboard macro ring to the second-previous macro, execute the resulting head macro three times, rotate back to the original head macro, execute that once, rotate to the previous macro, execute that, and finally delete it from the macro ring.

The command C-x C-k C-k (kmacro-end-or-call-macro-repeat) executes the keyboard macro at the head of the macro ring. You can repeat the macro immediately by typing another C-k, or you can rotate the macro ring immediately by typing C-n or C-p.

When a keyboard macro is being defined, C-x C-k C-k behaves like <F4> except that, immediately afterward, you can use most key bindings of this section without the C-x C-k prefix. For instance, another C-k will re-execute the macro.

The commands C-x C-k C-n (kmacro-cycle-ring-next) and C-x C-k C-p (kmacro-cycle-ring-previous) rotate the macro ring, bringing the next or previous keyboard macro to the head of the macro ring. The definition of the new head macro is displayed in the echo area. You can continue to rotate the macro ring immediately by repeating just C-n and C-p until the desired macro is at the head of the ring. To execute the new macro ring head immediately, just type C-k.

Note that Emacs treats the head of the macro ring as the last defined keyboard macro. For instance, <F4> will execute that macro, and C-x C-k n will give it a name.

The maximum number of macros stored in the keyboard macro ring is determined by the customizable variable kmacro-ring-max.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.3 The Keyboard Macro Counter

Each keyboard macro has an associated counter, which is initialized to 0 when you start defining the macro. This counter allows you to insert a number into the buffer that depends on the number of times the macro has been called. The counter is incremented each time its value is inserted into the buffer.

<F3>

In a keyboard macro definition, insert the keyboard macro counter value in the buffer (kmacro-start-macro-or-insert-counter).

C-x C-k C-i

Insert the keyboard macro counter value in the buffer (kmacro-insert-counter).

C-x C-k C-c

Set the keyboard macro counter (kmacro-set-counter).

C-x C-k C-a

Add the prefix arg to the keyboard macro counter (kmacro-add-counter).

C-x C-k C-f

Specify the format for inserting the keyboard macro counter (kmacro-set-format).

When you are defining a keyboard macro, the command <F3> (kmacro-start-macro-or-insert-counter) inserts the current value of the keyboard macro’s counter into the buffer, and increments the counter by 1. (If you are not defining a macro, <F3> begins a macro definition instead. See section Basic Use.) You can use a numeric prefix argument to specify a different increment. If you just specify a C-u prefix, that is the same as an increment of zero: it inserts the current counter value without changing it.

As an example, let us show how the keyboard macro counter can be used to build a numbered list. Consider the following key sequence:

<F3> C-a <F3> . <SPC> <F4>

As part of this keyboard macro definition, the string ‘0. ’ was inserted into the beginning of the current line. If you now move somewhere else in the buffer and type <F4> to invoke the macro, the string ‘1. ’ is inserted at the beginning of that line. Subsequent invocations insert ‘2. ’, ‘3. ’, and so forth.

The command C-x C-k C-i (kmacro-insert-counter) does the same thing as <F3>, but it can be used outside a keyboard macro definition. When no keyboard macro is being defined or executed, it inserts and increments the counter of the macro at the head of the keyboard macro ring.

The command C-x C-k C-c (kmacro-set-counter) sets the current macro counter to the value of the numeric argument. If you use it inside the macro, it operates on each repetition of the macro. If you specify just C-u as the prefix, while executing the macro, that resets the counter to the value it had at the beginning of the current repetition of the macro (undoing any increments so far in this repetition).

The command C-x C-k C-a (kmacro-add-counter) adds the prefix argument to the current macro counter. With just C-u as argument, it resets the counter to the last value inserted by any keyboard macro. (Normally, when you use this, the last insertion will be in the same macro and it will be the same counter.)

The command C-x C-k C-f (kmacro-set-format) prompts for the format to use when inserting the macro counter. The default format is ‘%d’, which means to insert the number in decimal without any padding. You can exit with empty minibuffer to reset the format to this default. You can specify any format string that the format function accepts and that makes sense with a single integer extra argument (see Formatting Strings in The Emacs Lisp Reference Manual). Do not put the format string inside double quotes when you insert it in the minibuffer.

If you use this command while no keyboard macro is being defined or executed, the new format affects all subsequent macro definitions. Existing macros continue to use the format in effect when they were defined. If you set the format while defining a keyboard macro, this affects the macro being defined from that point on, but it does not affect subsequent macros. Execution of the macro will, at each step, use the format in effect at that step during its definition. Changes to the macro format during execution of a macro, like the corresponding changes during its definition, have no effect on subsequent macros.

The format set by C-x C-k C-f does not affect insertion of numbers stored in registers.

If you use a register as a counter, incrementing it on each repetition of the macro, that accomplishes the same thing as a keyboard macro counter. See section Keeping Numbers in Registers. For most purposes, it is simpler to use a keyboard macro counter.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.4 Executing Macros with Variations

In a keyboard macro, you can create an effect similar to that of query-replace, in that the macro asks you each time around whether to make a change.

C-x q

When this point is reached during macro execution, ask for confirmation (kbd-macro-query).

While defining the macro, type C-x q at the point where you want the query to occur. During macro definition, the C-x q does nothing, but when you run the macro later, C-x q asks you interactively whether to continue.

The valid responses when C-x q asks are:

<SPC> (or y)

Continue executing the keyboard macro.

<DEL> (or n)

Skip the remainder of this repetition of the macro, and start right away with the next repetition.

<RET> (or q)

Skip the remainder of this repetition and cancel further repetitions.

C-r

Enter a recursive editing level, in which you can perform editing which is not part of the macro. When you exit the recursive edit using C-M-c, you are asked again how to continue with the keyboard macro. If you type a <SPC> at this time, the rest of the macro definition is executed. It is up to you to leave point and the text in a state such that the rest of the macro will do what you want.

C-u C-x q, which is C-x q with a numeric argument, performs a completely different function. It enters a recursive edit reading input from the keyboard, both when you type it during the definition of the macro, and when it is executed from the macro. During definition, the editing you do inside the recursive edit does not become part of the macro. During macro execution, the recursive edit gives you a chance to do some particularized editing on each repetition. See section Recursive Editing Levels.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.5 Naming and Saving Keyboard Macros

C-x C-k n

Give a command name (for the duration of the Emacs session) to the most recently defined keyboard macro (kmacro-name-last-macro).

C-x C-k b

Bind the most recently defined keyboard macro to a key sequence (for the duration of the session) (kmacro-bind-to-key).

M-x insert-kbd-macro

Insert in the buffer a keyboard macro’s definition, as Lisp code.

If you wish to save a keyboard macro for later use, you can give it a name using C-x C-k n (kmacro-name-last-macro). This reads a name as an argument using the minibuffer and defines that name to execute the last keyboard macro, in its current form. (If you later add to the definition of this macro, that does not alter the name’s definition as a macro.) The macro name is a Lisp symbol, and defining it in this way makes it a valid command name for calling with M-x or for binding a key to with global-set-key (see section Keymaps). If you specify a name that has a prior definition other than a keyboard macro, an error message is shown and nothing is changed.

You can also bind the last keyboard macro (in its current form) to a key, using C-x C-k b (kmacro-bind-to-key) followed by the key sequence you want to bind. You can bind to any key sequence in the global keymap, but since most key sequences already have other bindings, you should select the key sequence carefully. If you try to bind to a key sequence with an existing binding (in any keymap), this command asks you for confirmation before replacing the existing binding.

To avoid problems caused by overriding existing bindings, the key sequences C-x C-k 0 through C-x C-k 9 and C-x C-k A through C-x C-k Z are reserved for your own keyboard macro bindings. In fact, to bind to one of these key sequences, you only need to type the digit or letter rather than the whole key sequences. For example,

C-x C-k b 4

will bind the last keyboard macro to the key sequence C-x C-k 4.

Once a macro has a command name, you can save its definition in a file. Then it can be used in another editing session. First, visit the file you want to save the definition in. Then use this command:

M-x insert-kbd-macro <RET> macroname <RET>

This inserts some Lisp code that, when executed later, will define the same macro with the same definition it has now. (You don’t need to understand Lisp code to do this, because insert-kbd-macro writes the Lisp code for you.) Then save the file. You can load the file later with load-file (see section Libraries of Lisp Code for Emacs). If the file you save in is your init file ‘~/.emacs’ (see section The Emacs Initialization File) then the macro will be defined each time you run Emacs.

If you give insert-kbd-macro a numeric argument, it makes additional Lisp code to record the keys (if any) that you have bound to macroname, so that the macro will be reassigned the same keys when you load the file.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.6 Editing a Keyboard Macro

C-x C-k C-e

Edit the last defined keyboard macro (kmacro-edit-macro).

C-x C-k e name <RET>

Edit a previously defined keyboard macro name (edit-kbd-macro).

C-x C-k l

Edit the last 300 keystrokes as a keyboard macro (kmacro-edit-lossage).

You can edit the last keyboard macro by typing C-x C-k C-e or C-x C-k <RET> (kmacro-edit-macro). This formats the macro definition in a buffer and enters a specialized major mode for editing it. Type C-h m once in that buffer to display details of how to edit the macro. When you are finished editing, type C-c C-c.

You can edit a named keyboard macro or a macro bound to a key by typing C-x C-k e (edit-kbd-macro). Follow that with the keyboard input that you would use to invoke the macro—C-x e or M-x name or some other key sequence.

You can edit the last 300 keystrokes as a macro by typing C-x C-k l (kmacro-edit-lossage).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.7 Stepwise Editing a Keyboard Macro

You can interactively replay and edit the last keyboard macro, one command at a time, by typing C-x C-k <SPC> (kmacro-step-edit-macro). Unless you quit the macro using q or C-g, the edited macro replaces the last macro on the macro ring.

This macro editing feature shows the last macro in the minibuffer together with the first (or next) command to be executed, and prompts you for an action. You can enter ? to get a summary of your options. These actions are available:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.1 File Names

Many Emacs commands that operate on a file require you to specify the file name, using the minibuffer (see section Minibuffers for File Names).

While in the minibuffer, you can use the usual completion and history commands (see section The Minibuffer). Note that file name completion ignores file names whose extensions appear in the variable completion-ignored-extensions (see section Completion Options). Note also that most commands use permissive completion with confirmation for reading file names: you are allowed to submit a nonexistent file name, but if you type <RET> immediately after completing up to a nonexistent file name, Emacs prints ‘[Confirm]’ and you must type a second <RET> to confirm. See section Completion Exit, for details.

Minibuffer history commands offer some special features for reading file names, see Minibuffer History.

Each buffer has a default directory, stored in the buffer-local variable default-directory. Whenever Emacs reads a file name using the minibuffer, it usually inserts the default directory into the minibuffer as the initial contents. You can inhibit this insertion by changing the variable insert-default-directory to nil (see section Minibuffers for File Names). Regardless, Emacs always assumes that any relative file name is relative to the default directory, e.g., entering a file name without a directory specifies a file in the default directory.

When you visit a file, Emacs sets default-directory in the visiting buffer to the directory of its file. When you create a new buffer that is not visiting a file, via a command like C-x b, its default directory is usually copied from the buffer that was current at the time (see section Creating and Selecting Buffers). You can use the command M-x pwd to see the value of default-directory in the current buffer. The command M-x cd prompts for a directory’s name, and sets the buffer’s default-directory to that directory (doing this does not change the buffer’s file name, if any).

As an example, when you visit the file ‘/u/rms/gnu/gnu.tasks’, the default directory is set to ‘/u/rms/gnu/’. If you invoke a command that reads a file name, entering just ‘foo’ in the minibuffer, with a directory omitted, specifies the file ‘/u/rms/gnu/foo’; entering ‘../.login’ specifies ‘/u/rms/.login’; and entering ‘new/foo’ specifies ‘/u/rms/gnu/new/foo’.

When typing a file name into the minibuffer, you can make use of a couple of shortcuts: a double slash ignores everything before the second slash in the pair, and ‘~/’ is your home directory. See section Minibuffers for File Names.

The character ‘$’ is used to substitute an environment variable into a file name. The name of the environment variable consists of all the alphanumeric characters after the ‘$’; alternatively, it can be enclosed in braces after the ‘$’. For example, if you have used the shell command export FOO=rms/hacks to set up an environment variable named FOO, then both ‘/u/$FOO/test.c’ and ‘/u/${FOO}/test.c’ are abbreviations for ‘/u/rms/hacks/test.c’. If the environment variable is not defined, no substitution occurs, so that the character ‘$’ stands for itself. Note that environment variables set outside Emacs affect Emacs only if they are applied before Emacs is started.

To access a file with ‘$’ in its name, if the ‘$’ causes expansion, type ‘$$’. This pair is converted to a single ‘$’ at the same time that variable substitution is performed for a single ‘$’. Alternatively, quote the whole file name with ‘/:’ (see section Quoted File Names). File names which begin with a literal ‘~’ should also be quoted with ‘/:’.

You can include non-ASCII characters in file names. See section Coding Systems for File Names.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.2 Visiting Files

C-x C-f

Visit a file (find-file).

C-x C-r

Visit a file for viewing, without allowing changes to it (find-file-read-only).

C-x C-v

Visit a different file instead of the one visited last (find-alternate-file).

C-x 4 f

Visit a file, in another window (find-file-other-window). Don’t alter what is displayed in the selected window.

C-x 5 f

Visit a file, in a new frame (find-file-other-frame). Don’t alter what is displayed in the selected frame.

M-x find-file-literally

Visit a file with no conversion of the contents.

Visiting a file means reading its contents into an Emacs buffer so you can edit them. Emacs makes a new buffer for each file that you visit.

To visit a file, type C-x C-f (find-file) and use the minibuffer to enter the name of the desired file. While in the minibuffer, you can abort the command by typing C-g. See section File Names, for details about entering file names into minibuffers.

If the specified file exists but the system does not allow you to read it, an error message is displayed in the echo area (on GNU and Unix systems you might be able to visit such a file using the ‘su’ or ‘sudo’ methods; see section Remote Files). Otherwise, you can tell that C-x C-f has completed successfully by the appearance of new text on the screen, and by the buffer name shown in the mode line (see section The Mode Line). Emacs normally constructs the buffer name from the file name, omitting the directory name. For example, a file named ‘/usr/rms/emacs.tex’ is visited in a buffer named ‘emacs.tex’. If there is already a buffer with that name, Emacs constructs a unique name; the normal method is to add a suffix based on the directory name (e.g., ‘<rms>’, ‘<tmp>’, and so on), but you can select other methods. See section Making Buffer Names Unique.

To create a new file, just visit it using the same command, C-x C-f. Emacs displays ‘(New file)’ in the echo area, but in other respects behaves as if you had visited an existing empty file.

After visiting a file, the changes you make with editing commands are made in the Emacs buffer. They do not take effect in the visited file, until you save the buffer (see section Saving Files). If a buffer contains changes that have not been saved, we say the buffer is modified. This implies that some changes will be lost if the buffer is not saved. The mode line displays two stars near the left margin to indicate that the buffer is modified.

If you visit a file that is already in Emacs, C-x C-f switches to the existing buffer instead of making another copy. Before doing so, it checks whether the file has changed since you last visited or saved it. If the file has changed, Emacs offers to reread it.

If you try to visit a file larger than large-file-warning-threshold (the default is 10000000, which is about 10 megabytes), Emacs asks you for confirmation first. You can answer y to proceed with visiting the file. Note, however, that Emacs cannot visit files that are larger than the maximum Emacs buffer size, which is limited by the amount of memory Emacs can allocate and by the integers that Emacs can represent (see section Using Multiple Buffers). If you try, Emacs displays an error message saying that the maximum buffer size has been exceeded.

If the file name you specify contains shell-style wildcard characters, Emacs visits all the files that match it. (On case-insensitive filesystems, Emacs matches the wildcards disregarding the letter case.) Wildcards include ‘?’, ‘*’, and ‘[…]’ sequences. To enter the wild card ‘?’ in a file name in the minibuffer, you need to type C-q ?. See section Quoted File Names, for information on how to visit a file whose name actually contains wildcard characters. You can disable the wildcard feature by customizing find-file-wildcards.

If you visit the wrong file unintentionally by typing its name incorrectly, type C-x C-v (find-alternate-file) to visit the file you really wanted. C-x C-v is similar to C-x C-f, but it kills the current buffer (after first offering to save it if it is modified). When C-x C-v reads the file name to visit, it inserts the entire default file name in the buffer, with point just after the directory part; this is convenient if you made a slight error in typing the name.

If you visit a file that is actually a directory, Emacs invokes Dired, the Emacs directory browser. See section Dired, the Directory Editor. You can disable this behavior by setting the variable find-file-run-dired to nil; in that case, it is an error to try to visit a directory.

Files which are actually collections of other files, or file archives, are visited in special modes which invoke a Dired-like environment to allow operations on archive members. See section File Archives, for more about these features.

If you visit a file that the operating system won’t let you modify, or that is marked read-only, Emacs makes the buffer read-only too, so that you won’t go ahead and make changes that you’ll have trouble saving afterward. You can make the buffer writable with C-x C-q (read-only-mode). See section Miscellaneous Buffer Operations.

If you want to visit a file as read-only in order to protect yourself from entering changes accidentally, visit it with the command C-x C-r (find-file-read-only) instead of C-x C-f.

C-x 4 f (find-file-other-window) is like C-x C-f except that the buffer containing the specified file is selected in another window. The window that was selected before C-x 4 f continues to show the same buffer it was already showing. If this command is used when only one window is being displayed, that window is split in two, with one window showing the same buffer as before, and the other one showing the newly requested file. See section Multiple Windows.

C-x 5 f (find-file-other-frame) is similar, but opens a new frame, or selects any existing frame showing the specified file. See section Frames and Graphical Displays.

On graphical displays, there are two additional methods for visiting files. Firstly, when Emacs is built with a suitable GUI toolkit, commands invoked with the mouse (by clicking on the menu bar or tool bar) use the toolkit’s standard file selection dialog instead of prompting for the file name in the minibuffer. On GNU/Linux and Unix platforms, Emacs does this when built with GTK+, LessTif, and Motif toolkits; on MS-Windows and Mac, the GUI version does that by default. For information on how to customize this, see Using Dialog Boxes.

Secondly, Emacs supports drag and drop: dropping a file into an ordinary Emacs window visits the file using that window. As an exception, dropping a file into a window displaying a Dired buffer moves or copies the file into the displayed directory. For details, see Drag and Drop, and Other Dired Features.

On text-mode terminals and on graphical displays when Emacs was built without a GUI toolkit, you can visit files via the menu-bar ‘File’ menu, which has the ‘Visit New File’ and the ‘Open File’ items.

Each time you visit a file, Emacs automatically scans its contents to detect what character encoding and end-of-line convention it uses, and converts these to Emacs’s internal encoding and end-of-line convention within the buffer. When you save the buffer, Emacs performs the inverse conversion, writing the file to disk with its original encoding and end-of-line convention. See section Coding Systems.

If you wish to edit a file as a sequence of ASCII characters with no special encoding or conversion, use the M-x find-file-literally command. This visits a file, like C-x C-f, but does not do format conversion (see Format Conversion in the Emacs Lisp Reference Manual), character code conversion (see section Coding Systems), or automatic uncompression (see section Accessing Compressed Files), and does not add a final newline because of require-final-newline (see section Customizing Saving of Files). If you have already visited the same file in the usual (non-literal) manner, this command asks you whether to visit it literally instead.

Two special hook variables allow extensions to modify the operation of visiting files. Visiting a file that does not exist runs the functions in find-file-not-found-functions; this variable holds a list of functions, which are called one by one (with no arguments) until one of them returns non-nil. This is not a normal hook, and the name ends in ‘-functions’ rather than ‘-hook’ to indicate that fact.

Successful visiting of any file, whether existing or not, calls the functions in find-file-hook, with no arguments. This variable is a normal hook. In the case of a nonexistent file, the find-file-not-found-functions are run first. See section Hooks.

There are several ways to specify automatically the major mode for editing the file (see section Choosing File Modes), and to specify local variables defined for that file (see section Local Variables in Files).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3 Saving Files

Saving a buffer in Emacs means writing its contents back into the file that was visited in the buffer.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.1 Commands for Saving Files

These are the commands that relate to saving and writing files.

C-x C-s

Save the current buffer to its file (save-buffer).

C-x s

Save any or all buffers to their files (save-some-buffers).

M-~

Forget that the current buffer has been changed (not-modified). With prefix argument (C-u), mark the current buffer as changed.

C-x C-w

Save the current buffer with a specified file name (write-file).

M-x set-visited-file-name

Change the file name under which the current buffer will be saved.

When you wish to save the file and make your changes permanent, type C-x C-s (save-buffer). After saving is finished, C-x C-s displays a message like this:

Wrote /u/rms/gnu/gnu.tasks

If the current buffer is not modified (no changes have been made in it since the buffer was created or last saved), saving is not really done, because it would have no effect. Instead, C-x C-s displays a message like this in the echo area:

(No changes need to be saved)

With a prefix argument, C-u C-x C-s, Emacs also marks the buffer to be backed up when the next save is done. See section Backup Files.

The command C-x s (save-some-buffers) offers to save any or all modified buffers. It asks you what to do with each buffer. The possible responses are analogous to those of query-replace:

y

Save this buffer and ask about the rest of the buffers.

n

Don’t save this buffer, but ask about the rest of the buffers.

!

Save this buffer and all the rest with no more questions.

<RET>

Terminate save-some-buffers without any more saving.

.

Save this buffer, then exit save-some-buffers without even asking about other buffers.

C-r

View the buffer that you are currently being asked about. When you exit View mode, you get back to save-some-buffers, which asks the question again.

d

Diff the buffer against its corresponding file, so you can see what changes you would be saving. This calls the command diff-buffer-with-file (see section Comparing Files).

C-h

Display a help message about these options.

You can customize the value of save-some-buffers-default-predicate to control which buffers Emacs will ask about.

C-x C-c, the key sequence to exit Emacs, invokes save-some-buffers and therefore asks the same questions.

If you have changed a buffer but do not wish to save the changes, you should take some action to prevent it. Otherwise, each time you use C-x s or C-x C-c, you are liable to save this buffer by mistake. One thing you can do is type M-~ (not-modified), which clears out the indication that the buffer is modified. If you do this, none of the save commands will believe that the buffer needs to be saved. (‘~’ is often used as a mathematical symbol for “not”; thus M-~ is “not”, metafied.) Alternatively, you can cancel all the changes made since the file was visited or saved, by reading the text from the file again. This is called reverting. See section Reverting a Buffer. (You could also undo all the changes by repeating the undo command C-x u until you have undone all the changes; but reverting is easier.)

M-x set-visited-file-name alters the name of the file that the current buffer is visiting. It reads the new file name using the minibuffer. Then it marks the buffer as visiting that file name, and changes the buffer name correspondingly. set-visited-file-name does not save the buffer in the newly visited file; it just alters the records inside Emacs in case you do save later. It also marks the buffer as modified so that C-x C-s in that buffer will save.

If you wish to mark the buffer as visiting a different file and save it right away, use C-x C-w (write-file). This is equivalent to set-visited-file-name followed by C-x C-s, except that C-x C-w asks for confirmation if the file exists. C-x C-s used on a buffer that is not visiting a file has the same effect as C-x C-w; that is, it reads a file name, marks the buffer as visiting that file, and saves it there. The default file name in a buffer that is not visiting a file is made by combining the buffer name with the buffer’s default directory (see section File Names).

If the new file name implies a major mode, then C-x C-w switches to that major mode, in most cases. The command set-visited-file-name also does this. See section Choosing File Modes.

If Emacs is about to save a file and sees that the date of the latest version on disk does not match what Emacs last read or wrote, Emacs notifies you of this fact, because it probably indicates a problem caused by simultaneous editing and requires your immediate attention. See section Simultaneous Editing.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.2 Backup Files

On most operating systems, rewriting a file automatically destroys all record of what the file used to contain. Thus, saving a file from Emacs throws away the old contents of the file—or it would, except that Emacs carefully copies the old contents to another file, called the backup file, before actually saving.

Emacs makes a backup for a file only the first time the file is saved from a buffer. No matter how many times you subsequently save the file, its backup remains unchanged. However, if you kill the buffer and then visit the file again, a new backup file will be made.

For most files, the variable make-backup-files determines whether to make backup files. On most operating systems, its default value is t, so that Emacs does write backup files.

For files managed by a version control system (see section Version Control), the variable vc-make-backup-files determines whether to make backup files. By default it is nil, since backup files are redundant when you store all the previous versions in a version control system. See section General Options.

At your option, Emacs can keep either a single backup for each file, or make a series of numbered backup files for each file that you edit. See section Single or Numbered Backups.

The default value of the backup-enable-predicate variable prevents backup files being written for files in the directories used for temporary files, specified by temporary-file-directory or small-temporary-file-directory.

You can explicitly tell Emacs to make another backup file from a buffer, even though that buffer has been saved before. If you save the buffer with C-u C-x C-s, the version thus saved will be made into a backup file if you save the buffer again. C-u C-u C-x C-s saves the buffer, but first makes the previous file contents into a new backup file. C-u C-u C-u C-x C-s does both things: it makes a backup from the previous contents, and arranges to make another from the newly saved contents if you save again.

You can customize the variable backup-directory-alist to specify that files matching certain patterns should be backed up in specific directories. A typical use is to add an element ("." . dir) to make all backups in the directory with absolute name dir. Emacs modifies the backup file names to avoid clashes between files with the same names originating in different directories. Alternatively, adding, ("." . ".~") would make backups in the invisible subdirectory ‘.~’ of the original file’s directory. Emacs creates the directory, if necessary, to make the backup.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.2.1 Single or Numbered Backups

When Emacs makes a backup file, its name is normally constructed by appending ‘~’ to the file name being edited; thus, the backup file for ‘eval.c’ would be ‘eval.c~’.

If access control stops Emacs from writing backup files under the usual names, it writes the backup file as ‘~/.emacs.d/%backup%~’. Only one such file can exist, so only the most recently made such backup is available.

Emacs can also make numbered backup files. Numbered backup file names contain ‘.~’, the number, and another ‘~’ after the original file name. Thus, the backup files of ‘eval.c’ would be called ‘eval.c.~1~’, ‘eval.c.~2~’, and so on, all the way through names like ‘eval.c.~259~’ and beyond.

The variable version-control determines whether to make single backup files or multiple numbered backup files. Its possible values are:

nil

Make numbered backups for files that have numbered backups already. Otherwise, make single backups. This is the default.

t

Make numbered backups.

never

Never make numbered backups; always make single backups.

The usual way to set this variable is globally, through your init file or the customization buffer. However, you can set version-control locally in an individual buffer to control the making of backups for that buffer’s file (see section Local Variables). You can have Emacs set version-control locally whenever you visit a given file (see section Local Variables in Files). Some modes, such as Rmail mode, set this variable.

If you set the environment variable VERSION_CONTROL, to tell various GNU utilities what to do with backup files, Emacs also obeys the environment variable by setting the Lisp variable version-control accordingly at startup. If the environment variable’s value is ‘t’ or ‘numbered’, then version-control becomes t; if the value is ‘nil’ or ‘existing’, then version-control becomes nil; if it is ‘never’ or ‘simple’, then version-control becomes never.

If you set the variable make-backup-file-name-function to a suitable Lisp function, you can override the usual way Emacs constructs backup file names.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.2.2 Automatic Deletion of Backups

To prevent excessive consumption of disk space, Emacs can delete numbered backup versions automatically. Generally Emacs keeps the first few backups and the latest few backups, deleting any in between. This happens every time a new backup is made.

The two variables kept-old-versions and kept-new-versions control this deletion. Their values are, respectively, the number of oldest (lowest-numbered) backups to keep and the number of newest (highest-numbered) ones to keep, each time a new backup is made. The backups in the middle (excluding those oldest and newest) are the excess middle versions—those backups are deleted. These variables’ values are used when it is time to delete excess versions, just after a new backup version is made; the newly made backup is included in the count in kept-new-versions. By default, both variables are 2.

If delete-old-versions is t, Emacs deletes the excess backup files silently. If it is nil, the default, Emacs asks you whether it should delete the excess backup versions. If it has any other value, then Emacs never automatically deletes backups.

Dired’s . (Period) command can also be used to delete old versions. See section Flagging Many Files at Once.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.2.3 Copying vs. Renaming

Backup files can be made by copying the old file or by renaming it. This makes a difference when the old file has multiple names (hard links). If the old file is renamed into the backup file, then the alternate names become names for the backup file. If the old file is copied instead, then the alternate names remain names for the file that you are editing, and the contents accessed by those names will be the new contents.

The method of making a backup file may also affect the file’s owner and group. If copying is used, these do not change. If renaming is used, you become the file’s owner, and the file’s group becomes the default (different operating systems have different defaults for the group).

The choice of renaming or copying is made as follows:

When a file is managed with a version control system (see section Version Control), Emacs does not normally make backups in the usual way for that file. But committing (a.k.a. checking in, see section Concepts of Version Control) new versions of files is similar in some ways to making backups. One unfortunate similarity is that these operations typically break hard links, disconnecting the file name you visited from any alternate names for the same file. This has nothing to do with Emacs—the version control system does it.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.3 Customizing Saving of Files

If the value of the variable require-final-newline is t, saving or writing a file silently puts a newline at the end if there isn’t already one there. If the value is visit, Emacs adds a newline at the end of any file that doesn’t have one, just after it visits the file. (This marks the buffer as modified, and you can undo it.) If the value is visit-save, Emacs adds such newlines both on visiting and on saving. If the value is nil, Emacs leaves the end of the file unchanged; any other non-nil value means Emacs asks you whether to add a newline. The default is nil.

Some major modes are designed for specific kinds of files that are always supposed to end in newlines. Such major modes set the variable require-final-newline to the value of mode-require-final-newline, which defaults to t. By setting the latter variable, you can control how these modes handle final newlines.

Normally, when a program writes a file, the operating system briefly caches the file’s data in main memory before committing the data to disk. This can greatly improve performance; for example, when running on laptops, it can avoid a disk spin-up each time a file is written. However, it risks data loss if the operating system crashes before committing the cache to disk.

To lessen this risk, Emacs can invoke the fsync system call after saving a file. Using fsync does not eliminate the risk of data loss, partly because many systems do not implement fsync properly, and partly because Emacs’s file-saving procedure typically relies also on directory updates that might not survive a crash even if fsync works properly.

The write-region-inhibit-fsync variable controls whether Emacs invokes fsync after saving a file. The variable’s default value is nil when Emacs is interactive, and t when Emacs runs in batch mode (see section Batch Mode).

Emacs never uses fsync when writing auto-save files, as these files might lose data anyway.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.4 Protection against Simultaneous Editing

Simultaneous editing occurs when two users visit the same file, both make changes, and then both save them. If nobody is informed that this is happening, whichever user saves first would later find that their changes were lost.

On some systems, Emacs notices immediately when the second user starts to change the file, and issues an immediate warning. On all systems, Emacs checks when you save the file, and warns if you are about to overwrite another user’s changes. You can prevent loss of the other user’s work by taking the proper corrective action instead of saving the file.

When you make the first modification in an Emacs buffer that is visiting a file, Emacs records that the file is locked by you. (It does this by creating a specially-named symbolic link(7) with special contents in the same directory.) Emacs removes the lock when you save the changes. The idea is that the file is locked whenever an Emacs buffer visiting it has unsaved changes.

You can prevent the creation of lock files by setting the variable create-lockfiles to nil. Caution: by doing so you will lose the benefits that this feature provides.

If you begin to modify the buffer while the visited file is locked by someone else, this constitutes a collision. When Emacs detects a collision, it asks you what to do, by calling the Lisp function ask-user-about-lock. You can redefine this function for the sake of customization. The standard definition of this function asks you a question and accepts three possible answers:

s

Steal the lock. Whoever was already changing the file loses the lock, and you gain the lock.

p

Proceed. Go ahead and edit the file despite its being locked by someone else.

q

Quit. This causes an error (file-locked), and the buffer contents remain unchanged—the modification you were trying to make does not actually take place.

If Emacs or the operating system crashes, this may leave behind lock files which are stale, so you may occasionally get warnings about spurious collisions. When you determine that the collision is spurious, just use p to tell Emacs to go ahead anyway.

Note that locking works on the basis of a file name; if a file has multiple names, Emacs does not prevent two users from editing it simultaneously under different names.

A lock file cannot be written in some circumstances, e.g., if Emacs lacks the system permissions or cannot create lock files for some other reason. In these cases, Emacs can still detect the collision when you try to save a file, by checking the file’s last-modification date. If the file has changed since the last time Emacs visited or saved it, that implies that changes have been made in some other way, and will be lost if Emacs proceeds with saving. Emacs then displays a warning message and asks for confirmation before saving; answer yes to save, and no or C-g cancel the save.

If you are notified that simultaneous editing has already taken place, one way to compare the buffer to its file is the M-x diff-buffer-with-file command. See section Comparing Files.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.5 Shadowing Files

You can arrange to keep identical shadow copies of certain files in more than one place—possibly on different machines. To do this, first you must set up a shadow file group, which is a set of identically-named files shared between a list of sites. The file group is permanent and applies to further Emacs sessions as well as the current one. Once the group is set up, every time you exit Emacs, it will copy the file you edited to the other files in its group. You can also do the copying without exiting Emacs, by typing M-x shadow-copy-files.

A shadow cluster is a group of hosts that share directories, so that copying to or from one of them is sufficient to update the file on all of them. Each shadow cluster has a name, and specifies the network address of a primary host (the one we copy files to), and a regular expression that matches the host names of all the other hosts in the cluster. You can define a shadow cluster with M-x shadow-define-cluster.

M-x shadow-initialize

Set up file shadowing.

M-x shadow-define-literal-group

Declare a single file to be shared between sites.

M-x shadow-define-regexp-group

Make all files that match each of a group of files be shared between hosts.

M-x shadow-define-cluster <RET> name <RET>

Define a shadow file cluster name.

M-x shadow-copy-files

Copy all pending shadow files.

M-x shadow-cancel

Cancel the instruction to shadow some files.

To set up a shadow file group, use M-x shadow-define-literal-group or M-x shadow-define-regexp-group. See their documentation strings for further information.

Before copying a file to its shadows, Emacs asks for confirmation. You can answer “no” to bypass copying of this file, this time. If you want to cancel the shadowing permanently for a certain file, use M-x shadow-cancel to eliminate or change the shadow file group.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3.6 Updating Time Stamps Automatically

You can arrange to put a time stamp in a file, so that it is updated automatically each time you edit and save the file. The time stamp must be in the first eight lines of the file, and you should insert it like this:

Time-stamp: <>

or like this:

Time-stamp: " "

Then add the function time-stamp to the hook before-save-hook (see section Hooks). When you save the file, this function then automatically updates the time stamp with the current date and time. You can also use the command M-x time-stamp to update the time stamp manually. By default the time stamp is formatted according to your locale setting (see section Environment Variables) and time zone (see Time of Day in The Emacs Lisp Reference Manual). For customizations, see the Custom group time-stamp.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.4 Reverting a Buffer

If you have made extensive changes to a file-visiting buffer and then change your mind, you can revert the changes and go back to the saved version of the file. To do this, type M-x revert-buffer. Since reverting unintentionally could lose a lot of work, Emacs asks for confirmation first.

The revert-buffer command tries to position point in such a way that, if the file was edited only slightly, you will be at approximately the same part of the text as before. But if you have made major changes, point may end up in a totally different location.

Reverting marks the buffer as not modified. It also clears the buffer’s undo history (see section Undo). Thus, the reversion cannot be undone—if you change your mind yet again, you can’t use the undo commands to bring the reverted changes back.

Some kinds of buffers that are not associated with files, such as Dired buffers, can also be reverted. For them, reverting means recalculating their contents. Buffers created explicitly with C-x b cannot be reverted; revert-buffer reports an error if you try.

When you edit a file that changes automatically and frequently—for example, a log of output from a process that continues to run—it may be useful for Emacs to revert the file without querying you. To request this behavior, set the variable revert-without-query to a list of regular expressions. When a file name matches one of these regular expressions, find-file and revert-buffer will revert it automatically if it has changed—provided the buffer itself is not modified. (If you have edited the text, it would be wrong to discard your changes.)

You can also tell Emacs to revert buffers periodically. To do this for a specific buffer, enable the minor mode Auto-Revert mode by typing M-x auto-revert-mode. This automatically reverts the current buffer when its visited file changes on disk. To do the same for all file buffers, type M-x global-auto-revert-mode to enable Global Auto-Revert mode. These minor modes do not check or revert remote files, because that is usually too slow. This behavior can be changed by setting the variable auto-revert-remote-files to non-nil.

By default, Auto-Revert mode works using file notifications, whereby changes in the filesystem are reported to Emacs by the OS. You can disable use of file notifications by customizing the variable auto-revert-use-notify to a nil value, then Emacs will check for file changes by polling every five seconds. You can change the polling interval through the variable auto-revert-interval.

Not all systems support file notifications; where they are not supported, auto-revert-use-notify will be nil by default.

One use of Auto-Revert mode is to “tail” a file such as a system log, so that changes made to that file by other programs are continuously displayed. To do this, just move the point to the end of the buffer, and it will stay there as the file contents change. However, if you are sure that the file will only change by growing at the end, use Auto-Revert Tail mode instead (auto-revert-tail-mode). It is more efficient for this. Auto-Revert Tail mode works also for remote files.

When a buffer is auto-reverted, a message is generated. This can be suppressed by setting auto-revert-verbose to nil.

In Dired buffers (see section Dired, the Directory Editor), Auto-Revert mode refreshes the buffer when a file is created or deleted in the buffer’s directory.

See section Undoing Version Control Actions, for commands to revert to earlier versions of files under version control. See section Version Control and the Mode Line, for Auto Revert peculiarities when visiting files under version control.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.5 Auto Reverting Non-File Buffers

Global Auto Revert Mode normally only reverts file buffers. There are two ways to auto-revert certain non-file buffers: by enabling Auto Revert Mode in those buffers (using M-x auto-revert-mode); and by setting global-auto-revert-non-file-buffers to a non-nil value. The latter enables Auto Reverting for all types of buffers for which it is implemented (listed in the menu below).

Like file buffers, non-file buffers should normally not revert while you are working on them, or while they contain information that might get lost after reverting. Therefore, they do not revert if they are modified. This can get tricky, because deciding when a non-file buffer should be marked modified is usually more difficult than for file buffers.

Another tricky detail is that, for efficiency reasons, Auto Revert often does not try to detect all possible changes in the buffer, only changes that are major or easy to detect. Hence, enabling auto-reverting for a non-file buffer does not always guarantee that all information in the buffer is up-to-date, and does not necessarily make manual reverts useless.

At the other extreme, certain buffers automatically revert every auto-revert-interval seconds. (This currently only applies to the Buffer Menu.) In this case, Auto Revert does not print any messages while reverting, even when auto-revert-verbose is non-nil.

The details depend on the particular types of buffers and are explained in the corresponding sections.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.5.1 Auto Reverting the Buffer Menu

If auto-reverting of non-file buffers is enabled, the Buffer Menu (see section Operating on Several Buffers) automatically reverts every auto-revert-interval seconds, whether there is a need for it or not. (It would probably take longer to check whether there is a need than to actually revert.)

If the Buffer Menu inappropriately gets marked modified, just revert it manually using g and auto-reverting will resume. However, if you marked certain buffers to get deleted or to be displayed, you have to be careful, because reverting erases all marks. The fact that adding marks sets the buffer’s modified flag prevents Auto Revert from automatically erasing the marks.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.5.2 Auto Reverting Dired buffers

Dired buffers only auto-revert when the file list of the buffer’s main directory changes (e.g., when a new file is added or deleted). They do not auto-revert when information about a particular file changes (e.g., when the size changes) or when inserted subdirectories change. To be sure that all listed information is up to date, you have to manually revert using g, even if auto-reverting is enabled in the Dired buffer. Sometimes, you might get the impression that modifying or saving files listed in the main directory actually does cause auto-reverting. This is because making changes to a file, or saving it, very often causes changes in the directory itself; for instance, through backup files or auto-save files. However, this is not guaranteed.

If the Dired buffer is marked modified and there are no changes you want to protect, then most of the time you can make auto-reverting resume by manually reverting the buffer using g. There is one exception. If you flag or mark files, you can safely revert the buffer. This will not erase the flags or marks (unless the marked file has been deleted, of course). However, the buffer will stay modified, even after reverting, and auto-reverting will not resume. This is because, if you flag or mark files, you may be working on the buffer and you might not want the buffer to change without warning. If you want auto-reverting to resume in the presence of marks and flags, mark the buffer non-modified using M-~. However, adding, deleting or changing marks or flags will mark it modified again.

Remote Dired buffers are currently not auto-reverted. Neither are Dired buffers for which you used shell wildcards or file arguments to list only some of the files. ‘*Find*’ and ‘*Locate*’ buffers do not auto-revert either.

Note that auto-reverting Dired buffers may not work satisfactorily on some systems.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6 Auto-Saving: Protection Against Disasters

From time to time, Emacs automatically saves each visited file in a separate file, without altering the file you actually use. This is called auto-saving. It prevents you from losing more than a limited amount of work if the system crashes.

When Emacs determines that it is time for auto-saving, it considers each buffer, and each is auto-saved if auto-saving is enabled for it and it has been changed since the last time it was auto-saved. The message ‘Auto-saving...’ is displayed in the echo area during auto-saving, if any files are actually auto-saved. Errors occurring during auto-saving are caught so that they do not interfere with the execution of commands you have been typing.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6.1 Auto-Save Files

Auto-saving does not normally save in the files that you visited, because it can be very undesirable to save a change that you did not want to make permanent. Instead, auto-saving is done in a different file called the auto-save file, and the visited file is changed only when you request saving explicitly (such as with C-x C-s).

Normally, the auto-save file name is made by appending ‘#’ to the front and rear of the visited file name. Thus, a buffer visiting file ‘foo.c’ is auto-saved in a file ‘#foo.c#’. Most buffers that are not visiting files are auto-saved only if you request it explicitly; when they are auto-saved, the auto-save file name is made by appending ‘#’ to the front and rear of buffer name, then adding digits and letters at the end for uniqueness. For example, the ‘*mail*’ buffer in which you compose messages to be sent might be auto-saved in a file named ‘#*mail*#704juu’. Auto-save file names are made this way unless you reprogram parts of Emacs to do something different (the functions make-auto-save-file-name and auto-save-file-name-p). The file name to be used for auto-saving in a buffer is calculated when auto-saving is turned on in that buffer.

The variable auto-save-file-name-transforms allows a degree of control over the auto-save file name. It lets you specify a series of regular expressions and replacements to transform the auto save file name. The default value puts the auto-save files for remote files (see section Remote Files) into the temporary file directory on the local machine.

When you delete a substantial part of the text in a large buffer, auto save turns off temporarily in that buffer. This is because if you deleted the text unintentionally, you might find the auto-save file more useful if it contains the deleted text. To reenable auto-saving after this happens, save the buffer with C-x C-s, or use C-u 1 M-x auto-save-mode.

If you want auto-saving to be done in the visited file rather than in a separate auto-save file, enable the global minor mode auto-save-visited-mode. In this mode, auto-saving is identical to explicit saving. Note that this mode is orthogonal to the auto-save mode described above; you can enable both at the same time. However, if auto-save mode is active in some buffer and the obsolete auto-save-visited-file-name variable is set to a non-nil value, that buffer won’t be affected by auto-save-visited-mode.

You can use the variable auto-save-visited-interval to customize the interval between auto-save operations in auto-save-visited-mode; by default it’s five seconds. auto-save-interval and auto-save-timeout have no effect on auto-save-visited-mode. See section Controlling Auto-Saving, for details on these variables.

A buffer’s auto-save file is deleted when you save the buffer in its visited file. (You can inhibit this by setting the variable delete-auto-save-files to nil.) Changing the visited file name with C-x C-w or set-visited-file-name renames any auto-save file to go with the new visited name.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6.2 Controlling Auto-Saving

Each time you visit a file, auto-saving is turned on for that file’s buffer if the variable auto-save-default is non-nil (but not in batch mode; see section Initial Options). The default for this variable is t, so auto-saving is the usual practice for file-visiting buffers. To toggle auto-saving in the current buffer, type M-x auto-save-mode. Auto Save mode acts as a buffer-local minor mode (see section Minor Modes).

Emacs auto-saves periodically based on how many characters you have typed since the last auto-save. The variable auto-save-interval specifies how many characters there are between auto-saves. By default, it is 300. Emacs doesn’t accept values that are too small: if you customize auto-save-interval to a value less than 20, Emacs will behave as if the value is 20.

Auto-saving also takes place when you stop typing for a while. By default, it does this after 30 seconds of idleness (at this time, Emacs may also perform garbage collection; see Garbage Collection in The Emacs Lisp Reference Manual). To change this interval, customize the variable auto-save-timeout. The actual time period is longer if the current buffer is long; this is a heuristic which aims to keep out of your way when you are editing long buffers, in which auto-save takes an appreciable amount of time. Auto-saving during idle periods accomplishes two things: first, it makes sure all your work is saved if you go away from the terminal for a while; second, it may avoid some auto-saving while you are actually typing.

When auto-save-visited-mode is enabled, Emacs will auto-save file-visiting buffers after five seconds of idle time. You can customize the variable auto-save-visited-interval to change the idle time interval.

Emacs also does auto-saving whenever it gets a fatal error. This includes killing the Emacs job with a shell command such as ‘kill %emacs’, or disconnecting a phone line or network connection.

You can perform an auto-save explicitly with the command M-x do-auto-save.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6.3 Recovering Data from Auto-Saves

You can use the contents of an auto-save file to recover from a loss of data with the command M-x recover-file <RET> file <RET>. This visits file and then (after your confirmation) restores the contents from its auto-save file ‘#file#’. You can then save with C-x C-s to put the recovered text into file itself. For example, to recover file ‘foo.c’ from its auto-save file ‘#foo.c#’, do:

M-x recover-file <RET> foo.c <RET>
yes <RET>
C-x C-s

Before asking for confirmation, M-x recover-file displays a directory listing describing the specified file and the auto-save file, so you can compare their sizes and dates. If the auto-save file is older, M-x recover-file does not offer to read it.

If Emacs or the computer crashes, you can recover all the files you were editing from their auto save files with the command M-x recover-session. This first shows you a list of recorded interrupted sessions. Move point to the one you choose, and type C-c C-c.

Then recover-session asks about each of the files that were being edited during that session, asking whether to recover that file. If you answer y, it calls recover-file, which works in its normal fashion. It shows the dates of the original file and its auto-save file, and asks once again whether to recover that file.

When recover-session is done, the files you’ve chosen to recover are present in Emacs buffers. You should then save them. Only this—saving them—updates the files themselves.

Emacs records information about interrupted sessions in files named ‘.saves-pid-hostname~’ in the directory ‘~/.emacs.d/auto-save-list/’. This directory is determined by the variable auto-save-list-file-prefix. If you set auto-save-list-file-prefix to nil, sessions are not recorded for recovery.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.7 File Name Aliases

Symbolic links and hard links both make it possible for several file names to refer to the same file. Hard links are alternate names that refer directly to the file; all the names are equally valid, and no one of them is preferred. By contrast, a symbolic link is a kind of defined alias: when ‘foo’ is a symbolic link to ‘bar’, you can use either name to refer to the file, but ‘bar’ is the real name, while ‘foo’ is just an alias. More complex cases occur when symbolic links point to directories.

Normally, if you visit a file which Emacs is already visiting under a different name, Emacs displays a message in the echo area and uses the existing buffer visiting that file. This can happen on systems that support hard or symbolic links, or if you use a long file name on a system that truncates long file names, or on a case-insensitive file system. You can suppress the message by setting the variable find-file-suppress-same-file-warnings to a non-nil value. You can disable this feature entirely by setting the variable find-file-existing-other-name to nil: then if you visit the same file under two different names, you get a separate buffer for each file name.

If the variable find-file-visit-truename is non-nil, then the file name recorded for a buffer is the file’s truename (made by replacing all symbolic links with their target names), rather than the name you specify. Setting find-file-visit-truename also implies the effect of find-file-existing-other-name.

Sometimes, a directory is ordinarily accessed through a symbolic link, and you may want Emacs to preferentially show its linked name. To do this, customize directory-abbrev-alist. Each element in this list should have the form (from . to), which means to replace from with to whenever from appears in a directory name. The from string is a regular expression (see section Syntax of Regular Expressions). It is matched against directory names anchored at the first character, and should start with ‘\`’ (to support directory names with embedded newlines, which would defeat ‘^’). The to string should be an ordinary absolute directory name pointing to the same directory. Do not use ‘~’ to stand for a home directory in the to string; Emacs performs these substitutions separately. Here’s an example, from a system on which ‘/home/fsf’ is normally accessed through a symbolic link named ‘/fsf’:

(("\\`/home/fsf" . "/fsf"))

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.8 File Directories

The file system groups files into directories. A directory listing is a list of all the files in a directory. Emacs provides commands to create and delete directories, and to make directory listings in brief format (file names only) and verbose format (sizes, dates, and other attributes included). Emacs also includes a directory browser feature called Dired, which you can invoke with C-x d; see Dired, the Directory Editor.

C-x C-d dir-or-pattern <RET>

Display a brief directory listing (list-directory).

C-u C-x C-d dir-or-pattern <RET>

Display a verbose directory listing.

M-x make-directory <RET> dirname <RET>

Create a new directory named dirname.

M-x delete-directory <RET> dirname <RET>

Delete the directory named dirname. If it isn’t empty, you will be asked whether you want to delete it recursively.

The command to display a directory listing is C-x C-d (list-directory). It reads using the minibuffer a file name which is either a directory to be listed or a wildcard-containing pattern for the files to be listed. For example,

C-x C-d /u2/emacs/etc <RET>

lists all the files in directory ‘/u2/emacs/etc’. Here is an example of specifying a file name pattern:

C-x C-d /u2/emacs/src/*.c <RET>

Normally, C-x C-d displays a brief directory listing containing just file names. A numeric argument (regardless of value) tells it to make a verbose listing including sizes, dates, and owners (like ‘ls -l’).

The text of a directory listing is mostly obtained by running ls in an inferior process. Two Emacs variables control the switches passed to ls: list-directory-brief-switches is a string giving the switches to use in brief listings ("-CF" by default), and list-directory-verbose-switches is a string giving the switches to use in a verbose listing ("-l" by default).

In verbose directory listings, Emacs adds information about the amount of free space on the disk that contains the directory. You can customize how this is done for local filesystems via the variables directory-free-space-program and directory-free-space-args: the former specifies what program to run (default: df), the latter which arguments to pass to that program (default is system-dependent). (On MS-Windows and MS-DOS, these two variables are ignored, and an internal Emacs implementation of the same functionality is used instead.)

The command M-x delete-directory prompts for a directory’s name using the minibuffer, and deletes the directory if it is empty. If the directory is not empty, you will be asked whether you want to delete it recursively. On systems that have a “Trash” (or “Recycle Bin”) feature, you can make this command move the specified directory to the Trash instead of deleting it outright, by changing the variable delete-by-moving-to-trash to t. See section Miscellaneous File Operations, for more information about using the Trash.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.9 Comparing Files

The command M-x diff prompts for two file names, using the minibuffer, and displays the differences between the two files in a buffer named ‘*diff*’. This works by running the diff program, using options taken from the variable diff-switches. The value of diff-switches should be a string; the default is "-u" to specify a unified context diff. See Diff in Comparing and Merging Files, for more information about the diff program.

The output of the diff command is shown using a major mode called Diff mode. See section Diff Mode.

A (much more sophisticated) alternative is M-x ediff (see Ediff in The Ediff Manual).

The command M-x diff-backup compares a specified file with its most recent backup. If you specify the name of a backup file, diff-backup compares it with the source file that it is a backup of. In all other respects, this behaves like M-x diff.

The command M-x diff-buffer-with-file compares a specified buffer with its corresponding file. This shows you what changes you would make to the file if you save the buffer.

The command M-x compare-windows compares the text in the current window with that in the window that was the selected window before you selected the current one. (For more information about windows in Emacs, Multiple Windows.) Comparison starts at point in each window, after pushing each initial point value on the mark ring (see section The Mark Ring) in its respective buffer. Then it moves point forward in each window, one character at a time, until it reaches characters that don’t match. Then the command exits.

If point in the two windows is followed by non-matching text when the command starts, M-x compare-windows tries heuristically to advance up to matching text in the two windows, and then exits. So if you use M-x compare-windows repeatedly, each time it either skips one matching range or finds the start of another.

With a numeric argument, compare-windows ignores changes in whitespace. If the variable compare-ignore-case is non-nil, the comparison ignores differences in case as well. If the variable compare-ignore-whitespace is non-nil, compare-windows by default ignores changes in whitespace, but a prefix argument turns that off for that single invocation of the command.

You can use M-x smerge-mode to turn on Smerge mode, a minor mode for editing output from the diff3 program. This is typically the result of a failed merge from a version control system update outside VC, due to conflicting changes to a file. Smerge mode provides commands to resolve conflicts by selecting specific changes.

See section Merging Files with Emerge, for the Emerge facility, which provides a powerful interface for merging files.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.10 Diff Mode

Diff mode is a major mode used for the output of M-x diff and other similar commands. This kind of output is called a patch, because it can be passed to the patch command to automatically apply the specified changes. To select Diff mode manually, type M-x diff-mode.

The changes specified in a patch are grouped into hunks, which are contiguous chunks of text that contain one or more changed lines. Hunks can also include unchanged lines to provide context for the changes. Each hunk is preceded by a hunk header, which specifies the old and new line numbers at which the hunk occurs. Diff mode highlights each hunk header, to distinguish it from the actual contents of the hunk.

You can edit a Diff mode buffer like any other buffer. (If it is read-only, you need to make it writable first. See section Miscellaneous Buffer Operations.) Whenever you change a hunk, Diff mode attempts to automatically correct the line numbers in the hunk headers, to ensure that the patch remains correct. To disable automatic line number correction, change the variable diff-update-on-the-fly to nil.

Diff mode treats each hunk as an error message, similar to Compilation mode. Thus, you can use commands such as C-x ` to visit the corresponding source locations. See section Compilation Mode.

In addition, Diff mode provides the following commands to navigate, manipulate and apply parts of patches:

M-n

Move to the next hunk-start (diff-hunk-next).

This command has a side effect: it refines the hunk you move to, highlighting its changes with better granularity. To disable this feature, type M-x diff-auto-refine-mode to toggle off the minor mode Diff Auto-Refine mode. To disable Diff Auto-Refine mode by default, add this to your init file (see section Hooks):

(add-hook 'diff-mode-hook
          (lambda () (diff-auto-refine-mode -1)))
M-p

Move to the previous hunk-start (diff-hunk-prev). Like M-n, this has the side-effect of refining the hunk you move to, unless you disable Diff Auto-Refine mode.

M-}

Move to the next file-start, in a multi-file patch (diff-file-next).

M-{

Move to the previous file-start, in a multi-file patch (diff-file-prev).

M-k

Kill the hunk at point (diff-hunk-kill).

M-K

In a multi-file patch, kill the current file part. (diff-file-kill).

C-c C-a

Apply this hunk to its target file (diff-apply-hunk). With a prefix argument of C-u, revert this hunk.

C-c C-b

Highlight the changes of the hunk at point with a finer granularity (diff-refine-hunk). This allows you to see exactly which parts of each changed line were actually changed.

C-c C-c

Go to the source file and line corresponding to this hunk (diff-goto-source).

C-c C-e

Start an Ediff session with the patch (diff-ediff-patch). See Ediff in The Ediff Manual.

C-c C-n

Restrict the view to the current hunk (diff-restrict-view). See section Narrowing. With a prefix argument of C-u, restrict the view to the current file of a multiple-file patch. To widen again, use C-x n w (widen).

C-c C-r

Reverse the direction of comparison for the entire buffer (diff-reverse-direction).

C-c C-s

Split the hunk at point (diff-split-hunk). This is for manually editing patches, and only works with the unified diff format produced by the ‘-u’ or ‘--unified’ options to the diff program. If you need to split a hunk in the context diff format produced by the ‘-c’ or ‘--context’ options to diff, first convert the buffer to the unified diff format with C-c C-u.

C-c C-d

Convert the entire buffer to the context diff format (diff-unified->context). With a prefix argument, convert only the text within the region.

C-c C-u

Convert the entire buffer to unified diff format (diff-context->unified). With a prefix argument, convert unified format to context format. When the mark is active, convert only the text within the region.

C-c C-w

Re-diff the current hunk, disregarding changes in whitespace (diff-ignore-whitespace-hunk).

C-x 4 A

Generate a ChangeLog entry, like C-x 4 a does (see section Change Logs), for each one of the hunks (diff-add-change-log-entries-other-window). This creates a skeleton of the log of changes that you can later fill with the actual descriptions of the changes. C-x 4 a itself in Diff mode operates on behalf of the current hunk’s file, but gets the function name from the patch itself. This is useful for making log entries for functions that are deleted by the patch.

Patches sometimes include trailing whitespace on modified lines, as an unintentional and undesired change. There are two ways to deal with this problem. Firstly, if you enable Whitespace mode in a Diff buffer (see section Useless Whitespace), it automatically highlights trailing whitespace in modified lines. Secondly, you can use the command M-x diff-delete-trailing-whitespace, which searches for trailing whitespace in the lines modified by the patch, and removes that whitespace in both the patch and the patched source file(s). This command does not save the modifications that it makes, so you can decide whether to save the changes (the list of modified files is displayed in the echo area). With a prefix argument, it tries to modify the original source files rather than the patched source files.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.11 Copying, Naming and Renaming Files

Emacs has several commands for copying, naming, and renaming files. All of them read two file names, old (or target) and new, using the minibuffer, and then copy or adjust a file’s name accordingly; they do not accept wildcard file names.

In all these commands, if the argument new is just a directory name (see Directory Names in the Emacs Lisp Reference Manual), the real new name is in that directory, with the same non-directory component as old. For example, the command M-x rename-file <RET> ~/foo <RET> /tmp/ <RET> renames ‘~/foo’ to ‘/tmp/foo’. On GNU and other POSIX-like systems, directory names end in ‘/’.

All these commands ask for confirmation when the new file name already exists.

M-x copy-file copies the contents of the file old to the file new.

M-x copy-directory copies directories, similar to the cp -r shell command. If new is a directory name, it creates a copy of the old directory and puts it in new. Otherwise it copies all the contents of old into a new directory named new.

M-x rename-file renames file old as new. If the file name new already exists, you must confirm with yes or renaming is not done; this is because renaming causes the old meaning of the name new to be lost. If old and new are on different file systems, the file old is copied and deleted.

If a file is under version control (see section Version Control), you should rename it using M-x vc-rename-file instead of M-x rename-file. See section Deleting and Renaming Version-Controlled Files.

M-x add-name-to-file adds an additional name to an existing file without removing the old name. The new name is created as a hard link to the existing file. The new name must belong on the same file system that the file is on. On MS-Windows, this command works only if the file resides in an NTFS file system. On MS-DOS, and some remote system types, it works by copying the file.

M-x make-symbolic-link creates a symbolic link named new, which points at target. The effect is that future attempts to open file new will refer to whatever file is named target at the time the opening is done, or will get an error if the name target is nonexistent at that time. This command does not expand the argument target, so that it allows you to specify a relative name as the target of the link. However, this command does expand leading ‘~’ in target so that you can easily specify home directories, and strips leading ‘/:’ so that you can specify relative names beginning with literal ‘~’ or ‘/:’. See section Quoted File Names. On MS-Windows, this command works only on MS Windows Vista and later. When new is remote, it works depending on the system type.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.12 Miscellaneous File Operations

Emacs has commands for performing many other operations on files. All operate on one file; they do not accept wildcard file names.

M-x delete-file prompts for a file and deletes it. If you are deleting many files in one directory, it may be more convenient to use Dired rather than delete-file. See section Deleting Files with Dired.

M-x move-file-to-trash moves a file into the system Trash (or Recycle Bin). This is a facility available on most operating systems; files that are moved into the Trash can be brought back later if you change your mind.

By default, Emacs deletion commands do not use the Trash. To use the Trash (when it is available) for common deletion commands, change the variable delete-by-moving-to-trash to t. This affects the commands M-x delete-file and M-x delete-directory (see section File Directories), as well as the deletion commands in Dired (see section Deleting Files with Dired). Supplying a prefix argument to M-x delete-file or M-x delete-directory makes them delete outright, instead of using the Trash, regardless of delete-by-moving-to-trash.

If a file is under version control (see section Version Control), you should delete it using M-x vc-delete-file instead of M-x delete-file. See section Deleting and Renaming Version-Controlled Files.

M-x insert-file (also C-x i) inserts a copy of the contents of the specified file into the current buffer at point, leaving point unchanged before the contents. The position after the inserted contents is added to the mark ring, without activating the mark (see section The Mark Ring).

M-x insert-file-literally is like M-x insert-file, except the file is inserted literally: it is treated as a sequence of ASCII characters with no special encoding or conversion, similar to the M-x find-file-literally command (see section Visiting Files).

M-x write-region is the inverse of M-x insert-file; it copies the contents of the region into the specified file. M-x append-to-file adds the text of the region to the end of the specified file. See section Accumulating Text. The variable write-region-inhibit-fsync applies to these commands, as well as saving files; see Customizing Saving of Files.

M-x set-file-modes reads a file name followed by a file mode, and applies that file mode to the specified file. File modes, also called file permissions, determine whether a file can be read, written to, or executed, and by whom. This command reads file modes using the same symbolic or octal format accepted by the chmod command; for instance, ‘u+x’ means to add execution permission for the user who owns the file. It has no effect on operating systems that do not support file modes. chmod is a convenience alias for this function.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.13 Accessing Compressed Files

Emacs automatically uncompresses compressed files when you visit them, and automatically recompresses them if you alter them and save them. Emacs recognizes compressed files by their file names. File names ending in ‘.gz’ indicate a file compressed with gzip. Other endings indicate other compression programs.

Automatic uncompression and compression apply to all the operations in which Emacs uses the contents of a file. This includes visiting it, saving it, inserting its contents into a buffer, loading it, and byte compiling it.

To disable this feature, type the command M-x auto-compression-mode. You can disable it permanently by customizing the variable auto-compression-mode.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.14 File Archives

A file whose name ends in ‘.tar’ is normally an archive made by the tar program. Emacs views these files in a special mode called Tar mode which provides a Dired-like list of the contents (see section Dired, the Directory Editor). You can move around through the list just as you would in Dired, and visit the subfiles contained in the archive. However, not all Dired commands are available in Tar mode.

If Auto Compression mode is enabled (see section Accessing Compressed Files), then Tar mode is used also for compressed archives—files with extensions ‘.tgz’, .tar.Z and .tar.gz.

The keys e, f and <RET> all extract a component file into its own buffer. You can edit it there, and if you save the buffer, the edited version will replace the version in the Tar buffer. Clicking with the mouse on the file name in the Tar buffer does likewise. v extracts a file into a buffer in View mode (see section View Mode). o extracts the file and displays it in another window, so you could edit the file and operate on the archive simultaneously.

The I key adds a new (regular) file to the archive. The file is initially empty, but can readily be edited using the commands above. The command inserts the new file before the current one, so that using it on the topmost line of the Tar buffer makes the new file the first one in the archive, and using it at the end of the buffer makes it the last one.

d marks a file for deletion when you later use x, and u unmarks a file, as in Dired. C copies a file from the archive to disk and R renames a file within the archive. g reverts the buffer from the archive on disk. The keys M, G, and O change the file’s permission bits, group, and owner, respectively.

Saving the Tar buffer writes a new version of the archive to disk with the changes you made to the components.

You don’t need the tar program to use Tar mode—Emacs reads the archives directly. However, accessing compressed archives requires the appropriate uncompression program.

A separate but similar Archive mode is used for arc, jar, lzh, zip, rar, 7z, and zoo archives, as well as exe files that are self-extracting executables.

The key bindings of Archive mode are similar to those in Tar mode, with the addition of the m key which marks a file for subsequent operations, and M-<DEL> which unmarks all the marked files. Also, the a key toggles the display of detailed file information, for those archive types where it won’t fit in a single line. Operations such as renaming a subfile, or changing its mode or owner, are supported only for some of the archive formats.

Unlike Tar mode, Archive mode runs the archiving programs to unpack and repack archives. However, you don’t need these programs to look at the archive table of contents, only to extract or manipulate the subfiles in the archive. Details of the program names and their options can be set in the ‘Archive’ Customize group (see section Customization Groups).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.15 Remote Files

You can refer to files on other machines using a special file name syntax:

/method:host:filename
/method:user@host:filename
/method:user@host#port:filename

To carry out this request, Emacs uses a remote-login program such as ssh. You must always specify in the file name which method to use—for example, ‘/ssh:user@host:filename’ uses ssh. When you specify the pseudo method ‘-’ in the file name, Emacs chooses the method as follows:

  1. If the host name starts with ‘ftp.’ (with dot), Emacs uses FTP.
  2. If the user name is ‘ftp’ or ‘anonymous’, Emacs uses FTP.
  3. If the variable tramp-default-method is set to ‘ftp’, Emacs uses FTP.
  4. If ssh-agent is running, Emacs uses scp.
  5. Otherwise, Emacs uses ssh.

You can entirely turn off the remote file name feature by setting the variable tramp-mode to nil. You can turn off the feature in individual cases by quoting the file name with ‘/:’ (see section Quoted File Names).

Remote file access through FTP is handled by the Ange-FTP package, which is documented in the following. Remote file access through the other methods is handled by the Tramp package, which has its own manual. See The Tramp Manual in The Tramp Manual.

When the Ange-FTP package is used, Emacs logs in through FTP using the name user, if that is specified in the remote file name. If user is unspecified, Emacs logs in using your user name on the local system; but if you set the variable ange-ftp-default-user to a string, that string is used instead. When logging in, Emacs may also ask for a password.

For performance reasons, Emacs does not make backup files for files accessed via FTP by default. To make it do so, change the variable ange-ftp-make-backup-files to a non-nil value.

By default, auto-save files for remote files are made in the temporary file directory on the local machine, as specified by the variable auto-save-file-name-transforms. See section Auto-Save Files.

To visit files accessible by anonymous FTP, you use special user names ‘anonymous’ or ‘ftp’. Passwords for these user names are handled specially. The variable ange-ftp-generate-anonymous-password controls what happens: if the value of this variable is a string, then that string is used as the password; if non-nil (the default), then the value of user-mail-address is used; if nil, then Emacs prompts you for a password as usual (see section Entering passwords).

Sometimes you may be unable to access files on a remote machine because a firewall in between blocks the connection for security reasons. If you can log in on a gateway machine from which the target files are accessible, and whose FTP server supports gatewaying features, you can still use remote file names; all you have to do is specify the name of the gateway machine by setting the variable ange-ftp-gateway-host, and set ange-ftp-smart-gateway to t. Otherwise you may be able to make remote file names work, but the procedure is complex. You can read the instructions by typing M-x finder-commentary <RET> ange-ftp <RET>.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.16 Quoted File Names

You can quote an absolute file name to prevent special characters and syntax in it from having their special effects. The way to do this is to add ‘/:’ at the beginning.

For example, you can quote a local file name which appears remote, to prevent it from being treated as a remote file name. Thus, if you have a directory named ‘/foo:’ and a file named ‘bar’ in it, you can refer to that file in Emacs as ‘/:/foo:/bar’.

If you want to quote only special characters in the local part of a remote file name, you can quote just the local part. ‘/ssh:baz:/:/foo:/bar’ refers to the file ‘bar’ of directory ‘/foo:’ on the host ‘baz’.

/:’ can also prevent ‘~’ from being treated as a special character for a user’s home directory. For example, ‘/:/tmp/~hack’ refers to a file whose name is ‘~hack’ in directory ‘/tmp’.

Quoting with ‘/:’ is also a way to enter in the minibuffer a file name that contains ‘$’. In order for this to work, the ‘/:’ must be at the beginning of the minibuffer contents. (You can also double each ‘$’; see File Names with $.)

You can also quote wildcard characters with ‘/:’, for visiting. For example, ‘/:/tmp/foo*bar’ visits the file ‘/tmp/foo*bar’.

Another method of getting the same result is to enter ‘/tmp/foo[*]bar’, which is a wildcard specification that matches only ‘/tmp/foo*bar’. However, in many cases there is no need to quote the wildcard characters because even unquoted they give the right result. For example, if the only file name in ‘/tmp’ that starts with ‘foo’ and ends with ‘bar’ is ‘foo*bar’, then specifying ‘/tmp/foo*bar’ will visit only ‘/tmp/foo*bar’.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.17 File Name Cache

You can use the file name cache to make it easy to locate a file by name, without having to remember exactly where it is located. When typing a file name in the minibuffer, C-<TAB> (file-cache-minibuffer-complete) completes it using the file name cache. If you repeat C-<TAB>, that cycles through the possible completions of what you had originally typed. (However, note that the C-<TAB> character cannot be typed on most text terminals.)

The file name cache does not fill up automatically. Instead, you load file names into the cache using these commands:

M-x file-cache-add-directory <RET> directory <RET>

Add each file name in directory to the file name cache.

M-x file-cache-add-directory-using-find <RET> directory <RET>

Add each file name in directory and all of its nested subdirectories to the file name cache.

M-x file-cache-add-directory-using-locate <RET> directory <RET>

Add each file name in directory and all of its nested subdirectories to the file name cache, using locate to find them all.

M-x file-cache-add-directory-list <RET> variable <RET>

Add each file name in each directory listed in variable to the file name cache. variable should be a Lisp variable whose value is a list of directories, like load-path.

M-x file-cache-clear-cache <RET>

Clear the cache; that is, remove all file names from it.

The file name cache is not persistent: it is kept and maintained only for the duration of the Emacs session. You can view the contents of the cache with the file-cache-display command.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.18 Convenience Features for Finding Files

In this section, we introduce some convenient facilities for finding recently-opened files, reading file names from a buffer, and viewing image files.

If you enable Recentf mode, with M-x recentf-mode, the ‘File’ menu includes a submenu containing a list of recently opened files. M-x recentf-save-list saves the current recent-file-list to a file, and M-x recentf-edit-list edits it.

The M-x ffap command generalizes find-file with more powerful heuristic defaults (see section Finding Files and URLs at Point), often based on the text at point. Partial Completion mode offers other features extending find-file, which can be used with ffap. See section Completion Options.

Visiting image files automatically selects Image mode. In this major mode, you can type C-c C-c (image-toggle-display) to toggle between displaying the file as an image in the Emacs buffer, and displaying its underlying text (or raw byte) representation. Additionally you can type C-c C-x (image-toggle-hex-display) to toggle between displaying the file as an image in the Emacs buffer, and displaying it in hex representation. Displaying the file as an image works only if Emacs is compiled with support for displaying such images. If the displayed image is wider or taller than the frame, the usual point motion keys (C-f, C-p, and so forth) cause different parts of the image to be displayed. You can press n (image-next-file) and p (image-previous-file) to visit the next image file and the previous image file in the same directory, respectively.

If the image can be animated, the command <RET> (image-toggle-animation) starts or stops the animation. Animation plays once, unless the option image-animate-loop is non-nil. With f (image-next-frame) and b (image-previous-frame) you can step through the individual frames. Both commands accept a numeric prefix to step through several frames at once. You can go to a specific frame with F (image-goto-frame). Frames are indexed from 1. Typing a + (image-increase-speed) increases the speed of the animation, a - (image-decrease-speed) decreases it, and a r (image-reverse-speed) reverses it. The command a 0 (image-reset-speed) resets the speed to the original value.

If Emacs was compiled with support for the ImageMagick library, it can use ImageMagick to render a wide variety of images. The variable imagemagick-enabled-types lists the image types that Emacs may render using ImageMagick; each element in the list should be an internal ImageMagick name for an image type, as a symbol or an equivalent string (e.g., BMP for ‘.bmp’ images). To enable ImageMagick for all possible image types, change imagemagick-enabled-types to t. The variable imagemagick-types-inhibit lists the image types which should never be rendered using ImageMagick, regardless of the value of imagemagick-enabled-types (the default list includes types like C and HTML, which ImageMagick can render as an image but Emacs should not). To disable ImageMagick entirely, change imagemagick-types-inhibit to t.

The Image-Dired package can also be used to view images as thumbnails. See section Viewing Image Thumbnails in Dired.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.19 Filesets

If you regularly edit a certain group of files, you can define them as a fileset. This lets you perform certain operations, such as visiting, query-replace, and shell commands on all the files at once. To make use of filesets, you must first add the expression (filesets-init) to your init file (see section The Emacs Initialization File). This adds a ‘Filesets’ sub-menu to the menu bar’s ‘File’ menu.

The simplest way to define a fileset is by adding files to it one at a time. To add a file to fileset name, visit the file and type M-x filesets-add-buffer <RET> name <RET>. If there is no fileset name, this creates a new one, which initially contains only the current file. The command M-x filesets-remove-buffer removes the current file from a fileset.

You can also edit the list of filesets directly, with M-x filesets-edit (or by choosing ‘Edit Filesets’ from the ‘Filesets’ menu). The editing is performed in a Customize buffer (see section Easy Customization Interface). Normally, a fileset is a simple list of files, but you can also define a fileset as a regular expression matching file names. Some examples of these more complicated filesets are shown in the Customize buffer. Remember to select ‘Save for future sessions’ if you want to use the same filesets in future Emacs sessions.

You can use the command M-x filesets-open to visit all the files in a fileset, and M-x filesets-close to close them. Use M-x filesets-run-cmd to run a shell command on all the files in a fileset. These commands are also available from the ‘Filesets’ menu, where each existing fileset is represented by a submenu.

See section Version Control, for a different concept of filesets: groups of files bundled together for version control operations. Filesets of that type are unnamed, and do not persist across Emacs sessions.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 section The 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 section Lisp Interaction Buffers).

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 section Multiple Windows.

A buffer’s contents consist of a series of characters, each of which optionally carries a set of text properties (see section 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 section Major and Minor Modes). These are stored in buffer-local variables—variables that can have a different value in each buffer. See section Local Variables.

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 Ei