Emacs is the extensible, customizable, self-documenting real-time display editor. This Info file describes how to edit with Emacs and some of how to customize it; it corresponds to GNU Emacs version 22.1.
For information on extending Emacs, see Emacs Lisp.
Indexes (each index contains a large menu)
Important General Concepts
Fundamental Editing Commands
Important Text-Changing Commands
Major Structures of Emacs
Advanced Features
Recovery from Problems
--- The Detailed Node Listing --- ---------------------------------
Here are some other nodes which are really inferiors of the ones already listed, mentioned here so you can get to them in one step:
The Organization of the Screen
Basic Editing Commands
The Minibuffer
Completion
Help
The Mark and the Region
Killing and Moving Text
Yanking
Registers
Controlling the Display
Searching and Replacement
Incremental Search
Replacement Commands
Commands for Fixing Typos
Keyboard Macros
File Handling
Saving Files
Backup Files
Auto-Saving: Protection Against Disasters
Version Control
Using Multiple Buffers
Multiple Windows
Frames and Graphical Displays
International Character Set Support
Major Modes
Indentation
Commands for Human Languages
Filling Text
Outline Mode
TeX Mode
Editing Formatted Text
Editing Text-based Tables
Editing Programs
Top-Level Definitions, or Defuns
Indentation for Programs
Commands for Editing with Parentheses
Manipulating Comments
Documentation Lookup
C and Related Modes
Compiling and Testing Programs
Running Debuggers Under Emacs
Maintaining Large Programs
Tags Tables
Abbrevs
Editing Pictures
Sending Mail
Reading Mail with Rmail
Dired, the Directory Editor
The Calendar and the Diary
Movement in the Calendar
Conversion To and From Other Calendars
The Diary
Gnus
Running Shell Commands from Emacs
Using Emacs as a Server
Printing Hard Copies
Hyperlinking and Navigation Features
Customization
Variables
Customizing Key Bindings
The Init File, ~/.emacs
Dealing with Emacs Trouble
Reporting Bugs
Command Line Arguments for Emacs Invocation
Environment Variables
X Options and Resources
Emacs and Mac OS
Emacs and Microsoft Windows/MS-DOS
GNU Emacs is free software; this means that everyone is free to use it and free to redistribute it on 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 manual1. See Copying.
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 any one 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 http://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.
You can also order copies of GNU Emacs from the Free Software Foundation. This is a convenient and reliable way to get a copy; it is also a good way to help fund our work. We also sell hardcopy versions of this manual and An Introduction to Programming in Emacs Lisp, by Robert J. Chassell. You can find an order form on our web site at http://www.gnu.org/order/order.html. For further information, write to
Free Software Foundation
51 Franklin Street, Fifth Floor
Boston, MA 02110-1301
USA
The income from distribution fees goes to support the foundation's purpose: the development of new free software, and improvements to our existing programs including GNU Emacs.
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. If company policy is unsympathetic to the idea of donating to charity, you might instead suggest ordering a CD-ROM from the Foundation occasionally, or subscribing to periodic updates.
You are reading about GNU Emacs, the GNU incarnation of the advanced, self-documenting, customizable, extensible editor Emacs. (The `G' in `GNU' is not silent.)
We call Emacs advanced because it provides much more than simple insertion and deletion. It can control subprocesses, indent programs automatically, show two or more files at once, and edit formatted text. 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 type a special character, Control-h, to find out what your options are. You can also use it to find out what any command does, or to find all the commands that pertain to a topic. See Help.
Customizable means that you can alter Emacs commands' behavior in simple ways. For example, if you use a programming language in which comments start with `<**' and end with `**>', you can tell the Emacs comment manipulation commands to use those strings (see Comments). Another sort of customization is rearrangement of the command set. For example, you can rebind the basic cursor motion commands (up, down, left and right) to any keys on the keyboard that you find comfortable. See Customization.
Extensible means that you can go beyond simple customization and write entirely new commands—programs in the Lisp language to be run by Emacs's own Lisp interpreter. Emacs is an “on-line extensible” system, which means that it is divided into many functions that call each other, any of which can be redefined in the middle of an editing session. Almost any part of Emacs can be replaced without making a separate copy of all of Emacs. Most of the editing commands of Emacs are written in Lisp; the few exceptions could have been written in Lisp but use C instead for efficiency. Writing an extension is programming, but non-programmers can use it afterwards. See Emacs Lisp Intro, if you want to learn Emacs Lisp programming.
When running on a graphical display, Emacs provides its own menus and convenient handling of mouse buttons. In addition, Emacs provides many of the benefits of a graphical display even on a text-only terminal. For instance, it can highlight parts of a file, display and edit several files at once, move text between files, and edit files while running shell commands.
On a text-only terminal, the Emacs display occupies the whole screen. On a graphical display, such as on GNU/Linux using the X Window System, Emacs creates its own windows to use. We use the term frame to mean the entire text-only screen or an entire system-level window used by Emacs. Emacs uses both kinds of frames, in the same way, to display your editing. Emacs normally starts out with just one frame, but you can create additional frames if you wish. See Frames.
When you start Emacs, the main central area of the frame, all except for the top and bottom and sides, displays the text you are editing. This area is called the window. At the top there is normally a menu bar where you can access a series of menus; then there may be a tool bar, a row of icons that perform editing commands if you click on them. Below this, the window begins, often with a scroll bar on one side. Below the window comes the last line of the frame, a special echo area or minibuffer window, where prompts appear and you enter information when Emacs asks for it. See following sections for more information about these special lines.
You can subdivide the window horizontally or vertically to make multiple text windows, each of which can independently display some file or text (see Windows). In this manual, the word “window” refers to the initial large window if not subdivided, or any one of the multiple windows you have subdivided it into.
At any time, one window is the selected window. On graphical displays, the selected window normally shows a more prominent cursor (usually solid and blinking) while other windows show a weaker cursor (such as a hollow box). Text terminals have just one cursor, so it always appears in the selected window.
Most Emacs commands implicitly apply to the text in the selected window; the text in unselected windows is mostly visible for reference. However, mouse commands generally operate on whatever window you click them in, whether selected or not. If you use multiple frames on a graphical display, then giving the input focus to a particular frame selects a window in that frame.
Each window's last line is a mode line, which describes what is going on in that window. It appears in different color and/or a “3D” box if the terminal supports them; its contents normally begin with `--:-- *scratch*' when Emacs starts. The mode line displays status information such as what buffer is being displayed above it in the window, what major and minor modes are in use, and whether the buffer contains unsaved changes.
Within Emacs, the active cursor shows the location at which editing commands will take effect. This location is called point. Many Emacs commands move point through the text, so that you can edit at different places in it. You can also place point by clicking mouse button 1 (normally the left button).
While the cursor appears to be on a character, you should think of point as between two characters; it points before the character that appears 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.
Sometimes people speak of “the cursor” when they mean “point,” or speak of commands that move point as “cursor motion” commands.
If you are editing several files in Emacs, each in its own buffer, each buffer has its own point location. A buffer that is not currently displayed remembers its point location in case you display it again later. When Emacs displays multiple windows, each window has its own point location. If the same buffer appears in more than one window, each window has its own point position in that buffer, and (when possible) its own cursor.
A text-only terminal has just one cursor, in the selected window. The other windows do not show a cursor, even though they do have their own position of point. When Emacs updates the screen on a text-only terminal, it has to put the cursor temporarily at the place the output goes. This doesn't mean point is there, though. Once display updating finishes, Emacs puts the cursor where point is.
On graphical displays, Emacs shows a cursor in each window; the selected window's cursor is solid and blinking, and the other cursors are just hollow. Thus, the most prominent cursor always shows you the selected window, on all kinds of terminals.
See Cursor Display, for customizable variables that control display of the cursor or cursors.
The term “point” comes from the character `.', which was the command in TECO (the language in which the original Emacs was written) for accessing the value now called “point.”
The line at the bottom of the frame (below the mode line) is the echo area. It is used to display small amounts of text for various purposes.
Echoing means displaying the characters that you type. At the command line, the operating system normally echoes all your input. Emacs handles echoing differently.
Single-character commands do not echo in Emacs, and multi-character commands echo only if you pause while typing them. As soon as you pause for more than a second in the middle of a command, Emacs echoes all the characters of the command so far. This is to prompt you for the rest of the command. 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. You can change this behavior by setting a variable (see Display Custom).
If a command cannot do its job, it may display an error message in the echo area. Error messages are accompanied by beeping or by flashing the screen. The error also discards any input you have typed ahead.
Some commands display informative messages in the echo area. These messages look much like error messages, but they are not announced with a beep and do not throw away input. Sometimes the message tells you what the command has done, when this is not obvious from looking at the text being edited. Sometimes the sole purpose of a command is to show you a message giving you specific information—for example, C-x = (hold down <CTRL> and type x, then let go of <CTRL> and type =) displays a message describing the character position of point in the text and its current column in the window. Commands that take a long time often display messages ending in `...' while they are working, and add `done' at the end when they are finished. They may also indicate progress with percentages.
Echo-area informative messages are saved in an editor buffer named `*Messages*'. (We have not explained buffers yet; see Buffers, for more information about them.) If you miss a message that appears briefly on the screen, you can switch to the `*Messages*' buffer to see it again. (Successive progress messages are often collapsed into one in that buffer.)
The size of `*Messages*' is limited to a certain number of
lines. The variable message-log-max specifies how many lines.
Once the buffer has that many lines, adding lines at the end deletes lines
from the beginning, to keep the size constant. See Variables, for
how to set variables such as message-log-max.
The echo area is also used to display the minibuffer, a 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 echo area begins with a prompt string that usually ends with a colon; also, the cursor appears in that line because it is the selected window. You can always get out of the minibuffer by typing C-g. See Minibuffer.
Each text window's last line is a mode line, which describes what is going on in that window. The mode line starts and ends with dashes. When there is only one text window, the mode line appears right above the echo area; it is the next-to-last line in the frame. On a text-only terminal, the mode line is in inverse video if the terminal supports that; on a graphics display, the mode line has a 3D box appearance to help it stand out. The mode line of the selected window is highlighted if possible; see Optional Mode Line, for more information.
Normally, the mode line looks like this:
-cs:ch-fr buf pos line (major minor)------
This gives information about the window and the buffer it displays: the buffer's name, what major and minor modes are in use, whether the buffer's text has been changed, and how far down the buffer you are currently looking.
ch contains two stars `**' if the text in the buffer has been edited (the buffer is “modified”), or `--' if the buffer has not been edited. For a read-only buffer, it is `%*' if the buffer is modified, and `%%' otherwise.
fr gives the selected frame name (see Frames). It appears only on text-only terminals. The initial frame's name is `F1'.
buf is the name of the window's buffer. Usually this is the same as the name of a file you are editing. See Buffers.
The buffer displayed in the selected window (the window with the cursor) is the current buffer, where editing happens. When a command's effect applies to “the buffer,” we mean it does those things to the current buffer.
pos tells you whether there is additional text above the top of the window, or below the bottom. If your buffer is small and it is all 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 Optional Mode Line.
line is `L' followed by the current line number of point. This is present when Line Number mode is enabled (it normally is). You can display the current column number too, by turning on Column Number mode. It is not enabled by default because it is somewhat slower. See Optional Mode Line.
major is the name of the major mode in effect in the buffer. A buffer can only be in one major mode at a time. The major modes available include Fundamental mode (the least specialized), Text mode, Lisp mode, C mode, Texinfo mode, and many others. See Major Modes, for details of how the modes differ and how to select them.
Some major modes display additional information after the major mode name. For example, Rmail buffers display the current message number and the total number of messages. Compilation buffers and Shell buffers display the status of the subprocess.
minor is a list of some of the minor modes that are turned on at the moment in the window's chosen buffer. For example, `Fill' means that Auto Fill mode is on. `Abbrev' means that Word Abbrev mode is on. `Ovwrt' means that Overwrite mode is on. See Minor Modes, for more information.
`Narrow' means that the buffer being displayed has editing restricted to only a portion of its text. (This is not really a minor mode, but is like one.) See Narrowing. `Def' means that a keyboard macro is being defined. See 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, not just one buffer, the square brackets appear in every window's mode line or not in any of them. See Recursive Edit.
cs states the coding system used for the file you are editing. A dash indicates the default state of affairs: no code conversion, except for end-of-line translation if the file contents call for that. `=' means no conversion whatsoever. Nontrivial code conversions are represented by various letters—for example, `1' refers to ISO Latin-1. See Coding Systems, for more information.
On a text-only terminal, cs includes two additional characters which describe the coding system for keyboard input and the coding system for terminal output. They come right before the coding system used for the file you are editing.
If you are using an input method, a string of the form `i>' is added to the beginning of cs; i identifies the input method. (Some input methods show `+' or `@' instead of `>'.) See Input Methods.
When multibyte characters are not enabled, cs does not appear at all. See Enabling Multibyte.
The colon after cs changes to another string in some cases. Emacs uses newline characters to separate lines in the buffer. Some files use different conventions for separating lines: either carriage-return linefeed (the MS-DOS convention) or just carriage-return (the Macintosh convention). If the buffer's file uses carriage-return linefeed, the colon changes to either a backslash (`\') or `(DOS)', depending on the operating system. If the file uses just carriage-return, the colon indicator 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.
See Optional Mode Line, to add other handy information to the mode line, such as the size of the buffer, the current column number of point, and whether new mail for you has arrived.
The mode line is mouse-sensitive; when you move the mouse across various parts of it, Emacs displays help text to say what a click in that place will do. See Mode Line Mouse.
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 graphical display, you can use the mouse to choose a command from the menu bar. A right-arrow at the end of the menu item means it leads to a subsidiary menu; `...' at the end means that the command invoked will read arguments (further input from you) before it actually does anything.
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. You select an item by pressing <RET> and cancel menu
navigation with <ESC>.
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 Key Help).
On text-only terminals with no mouse, you can use the menu bar by
typing M-` or <F10> (these run the command
tmm-menubar). This 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 also has an assigned letter or digit which designates that item; it is 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.
Some of the commands in the menu bar have ordinary key bindings as well; one such binding is shown in parentheses after the item itself.
GNU Emacs is designed for use with keyboard commands because that is the most efficient way to edit. You can do editing with the mouse, as in other editors, and you can give commands with the menu bar and tool bar, and scroll with the scroll bar. But if you keep on editing that way, you won't get the benefits of Emacs. Therefore, this manual documents primarily how to edit with the keyboard. You can force yourself to practice using the keyboard by using the shell command `emacs -nw' to start Emacs, so that the mouse won't work.
Emacs uses an extension of the ASCII character set for keyboard input; it also accepts non-character input events including function keys and mouse button actions.
ASCII consists of 128 character codes. Some of these codes are assigned graphic symbols such as `a' and `='; the rest are control characters, such as Control-a (usually written C-a for short). C-a gets its name from the fact that you type it by holding down the <CTRL> key while pressing a.
Some ASCII control characters have special names, and most terminals have special keys you can type them with: for example, <RET>, <TAB>, <DEL> and <ESC>. The space character is usually known as <SPC>, even though strictly speaking it is a graphic character that is blank.
Emacs extends the ASCII character set with thousands more printing characters (see International), additional control characters, and a few more modifiers that can be combined with any character.
On ASCII terminals, there are only 32 possible control characters. These are the control variants of letters and `@[]\^_'. In addition, the shift key is meaningless with control characters: C-a and C-A are the same character, and Emacs cannot distinguish them.
The Emacs character set has room for control variants of all printing characters, and distinguishes C-A from C-a. Graphical terminals make it possible to enter all these characters. For example, C-- (that's Control-Minus) and C-5 are meaningful Emacs commands on a graphical terminal.
Another Emacs character-set extension is additional modifier bits. Only one modifier bit is commonly used; it is called Meta. Every character has a Meta variant; examples include Meta-a (normally written M-a, for short), M-A (different from M-a, but they are normally equivalent in Emacs), M-<RET>, and M-C-a. That last means a with both the <CTRL> and <META> modifiers. We usually write it as C-M-a rather than M-C-a, for reasons of tradition.
Some terminals have a <META> key, and allow you to type Meta characters by holding this key down. Thus, you can type Meta-a by holding down <META> and pressing a. The <META> key works much like the <SHIFT> key. In fact, this key is more often labeled <ALT> or <EDIT>, instead of <META>; on a Sun keyboard, it may have a diamond on it.
If there is no <META> key, you can still 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 by typing <ESC> C-a. Unlike <META>, which modifies other characters, <ESC> is a separate character. You don't hold down <ESC> while typing the next character; instead, you press it and release it, then you enter the next character. <ESC> is allowed on terminals with <META> keys, too, in case you have formed a habit of using it.
Emacs defines several other modifier keys that can be applied to any input character. These are called <SUPER>, <HYPER> and <ALT>. We write `s-', `H-' and `A-' to say that a character uses these modifiers. Thus, s-H-C-x is short for Super-Hyper-Control-x. Not all graphical terminals actually provide keys for these modifier flags—in fact, many terminals have a key labeled <ALT> which is really a <META> key. The standard key bindings of Emacs do not include any characters with these modifiers. But you can assign them meanings of your own by customizing Emacs.
If your keyboard lacks one of these modifier keys, you can enter it using C-x @: C-x @ h adds the “hyper” flag to the next character, C-x @ s adds the “super” flag, and C-x @ a adds the “alt” flag. For instance, C-x @ h C-a is a way to enter Hyper-Control-a. (Unfortunately there is no way to add two modifiers by using C-x @ twice for the same character, because the first one goes to work on the C-x.)
Keyboard input includes keyboard keys that are not characters at all, such as function keys and arrow keys. Mouse buttons are also not characters. However, you can modify these events with the modifier keys <CTRL>, <META>, <SUPER>, <HYPER> and <ALT>, just like keyboard characters.
Input characters and non-character inputs are collectively called input events. See Input Events, for the full Lisp-level details. If you are not doing Lisp programming, but simply want to redefine the meaning of some characters or non-character events, see Customization.
ASCII terminals cannot really send anything to the computer except ASCII characters. These terminals use a sequence of characters to represent each function key. But that is invisible to the Emacs user, because the keyboard input routines catch these special sequences and convert them to function key events before any other part of Emacs gets to see them.
On graphical displays, the window manager is likely to block the character Meta-<TAB> before Emacs can see it. It may also block Meta-<SPC>, C-M-d and C-M-l. If you have these problems, we recommend that you customize your window manager to turn off those commands, or put them on key combinations that Emacs does not use.
A key sequence (key, for short) is a sequence of input events that is meaningful as a unit—a “single command.” Some Emacs command sequences are invoked by just one character or one event; for example, just C-f moves forward one character in the buffer. But Emacs also has commands that take two or more events to invoke.
If a sequence of events is enough to invoke a command, it is a complete key. Examples of complete keys include C-a, X, <RET>, <NEXT> (a function key), <DOWN> (an arrow key), C-x C-f, and C-x 4 C-f. If it isn't long enough to be complete, we call it a prefix key. The above examples show that C-x and C-x 4 are prefix keys. Every key sequence is either a complete key or a prefix key.
Most single characters constitute complete keys in the standard Emacs command bindings. A few of them are prefix keys. A prefix key combines with the following input event to make a longer key sequence, which may itself be complete or a prefix. For example, C-x is a prefix key, so C-x and the next input event combine to make a two-event key sequence. Most of these key sequences are complete keys, including C-x C-f and C-x b. A few, such as C-x 4 and C-x r, are themselves prefix keys that lead to three-event key sequences. There's no limit to the length of a key sequence, but in practice people rarely use sequences longer than four events.
You can't add input events onto a complete key. For example, the two-event sequence C-f C-k is not a key, because the C-f is a complete key in itself. It's impossible to give C-f C-k an independent meaning as a command. C-f C-k is two key sequences, not one.
All told, 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; it describes the standard key bindings. If you customize Emacs, you can make new prefix keys, or eliminate some of the standard ones (not recommended for most users). See Key Bindings.
If you make or eliminate prefix keys, that changes the set of possible key sequences. For example, if you redefine C-f as a prefix, C-f C-k automatically becomes a key (complete, unless you define that too as a prefix). Conversely, if you remove the prefix definition of C-x 4, then C-x 4 f and C-x 4 anything are no longer keys.
Typing the help character (C-h or <F1>) after a prefix key displays a list of the commands starting with that prefix. There are a few prefix keys after which C-h does not work—for historical reasons, they define other meanings for C-h which are painful to change. <F1> works after all prefix keys.
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. A command also has a
function definition which is a Lisp program; this is how the
command does its work. In Emacs Lisp, a command is a Lisp function with
special options to read arguments and for interactive use. For more
information on commands and functions, see What Is a Function. (The
definition here is simplified slightly.)
The bindings between keys and commands are recorded in tables called keymaps. See Keymaps.
When we say that “C-n moves down vertically one line” we are
glossing over a subtle distinction that is irrelevant in ordinary use,
but vital for Emacs customization. The command next-line does
a vertical move downward. C-n has this effect because it
is bound to next-line. If you rebind C-n to the command
forward-word, C-n will move forward one word instead.
Rebinding keys is an important method of customization.
In the rest of this manual, we usually ignore this distinction to
keep things simple. We will often speak of keys like C-n as
commands, even though strictly speaking the key is bound to a command.
Usually we state the name of the command which really does the work in
parentheses after mentioning the key that runs it. For example, we
will say that “The command C-n (next-line) moves point
vertically down,” meaning that the command next-line moves
vertically down, and the key C-n is normally bound to it.
Since we are discussing customization, we should tell you about
variables. Often the description of a command will say, “To
change this, set the variable mumble-foo.” A variable is a
name used to store a value. Most of the variables documented in this
manual are meant for customization: some command or other part of
Emacs examines the variable and behaves differently according to the
value that you set. You can ignore the information about variables
until you are interested in customizing them. Then read the basic
information on variables (see Variables) and the information about
specific variables will make sense.
Text in Emacs buffers is a sequence of characters. In the simplest case, these are ASCII characters, each stored in one 8-bit byte. Both ASCII control characters (octal codes 000 through 037, and 0177) and ASCII printing characters (codes 040 through 0176) are allowed. The other modifier flags used in keyboard input, such as Meta, are not allowed in buffers.
Non-ASCII printing characters can also appear in buffers, when multibyte characters are enabled. They have character codes starting at 256, octal 0400, and each one is represented as a sequence of two or more bytes. See International. Single-byte characters with codes 128 through 255 can also appear in multibyte buffers. However, non-ASCII control characters cannot appear in a buffer.
Some ASCII control characters serve special purposes in text, and have special names. For example, the newline character (octal code 012) is used in the buffer to end a line, and the tab character (octal code 011) is used for indenting to the next tab stop column (normally every 8 columns). See Text Display.
If you disable multibyte characters, then you can use only one alphabet of non-ASCII characters, which all fit in one byte. They use octal codes 0200 through 0377. See Unibyte Mode.
The usual way to invoke Emacs is with the shell command emacs. Emacs clears the screen, then displays an initial help message and copyright notice. Some operating systems discard your type-ahead when Emacs starts up; they give Emacs no way to prevent this. On those systems, wait for Emacs to clear the screen before you start typing.
From a shell window under the X Window System, run Emacs in the background with emacs&. This way, Emacs won't tie up the shell window, so you can use it to run other shell commands while Emacs is running. You can type Emacs commands as soon as you direct your keyboard input to an Emacs frame.
When Emacs starts up, it creates a buffer named `*scratch*'.
That's the buffer you start out in. The `*scratch*' buffer uses
Lisp Interaction mode; you can use it to type Lisp expressions and
evaluate them. You can also ignore that capability and just write notes
there. You can specify a different major mode for this buffer by
setting the variable initial-major-mode in your init file.
See Init File.
It is possible to specify files to be visited, Lisp files to be loaded, and functions to be called through Emacs command-line arguments. See Emacs Invocation. The feature exists mainly for compatibility with other editors, and for scripts.
Many editors are designed to edit one file. When done with that file, you exit the editor. The next time you want to edit a file, you must start the editor again. Working this way, it is convenient to use a command-line argument to say which file to edit.
However, killing Emacs after editing one each and starting it afresh for the next file is both unnecessary and harmful, since it denies you the full power of Emacs. Emacs can visit more than one file in a single editing session, and that is the right way to use it. Exiting the Emacs session loses valuable accumulated context, such as the kill ring, registers, undo history, and mark ring. These features are useful for operating on multiple files, or even continuing to edit one file. If you kill Emacs after each file, you don't take advantage of them.
The recommended way to use GNU Emacs is to start it only once, just after you log in, and do all your editing in the same Emacs session. Each time you edit a file, you visit it with the existing Emacs, which eventually has many files in it ready for editing. Usually you do not kill Emacs until you are about to log out. See Files, for more information on visiting more than one file.
To edit a file from another program while Emacs is running, you can use the emacsclient helper program to open a file in the already running Emacs. See Emacs Server.
There are two commands for exiting Emacs, and three kinds of exiting: iconifying Emacs, suspending Emacs, and killing Emacs.
Iconifying means replacing the Emacs frame with a small box or “icon” on the screen. This is the usual way to exit Emacs when you're using a graphical display—if you bother to “exit” at all. (Just switching to another application is usually sufficient.)
Suspending means stopping Emacs temporarily and returning control to its parent process (usually a shell), allowing you to resume editing later in the same Emacs job. This is the usual way to exit Emacs when running it on a text terminal.
Killing Emacs means destroying the Emacs job. You can run Emacs again later, but you will get a fresh Emacs; there is no way to resume the same editing session after it has been killed.
suspend-emacs) or iconify a frame
(iconify-or-deiconify-frame).
save-buffers-kill-emacs).
On graphical displays, C-z runs the command
iconify-or-deiconify-frame, which temporarily iconifies (or
“minimizes”) the selected Emacs frame (see Frames). You can
then use the window manager to select some other application. (You
could select another application without iconifying Emacs first, but
getting the Emacs frame out of the way can make it more convenient to
find the other application.)
On a text terminal, C-z runs the command suspend-emacs.
Suspending Emacs takes you back to the shell from which you invoked
Emacs. You can resume Emacs with the shell command %emacs
in most common shells. On systems that don't support suspending
programs, C-z starts an inferior shell that communicates
directly with the terminal, and Emacs waits until you exit the
subshell. (The way to do that is probably with C-d or
exit, but it depends on which shell you use.) On these
systems, you can only get back to the shell from which Emacs was run
(to log out, for example) when you kill Emacs.
Suspending can fail if you run Emacs under a shell that doesn't
support suspendion of its subjobs, even if the system itself does
support it. In such a case, you can set the variable
cannot-suspend to a non-nil value to force C-z to
start an inferior shell.
To exit and kill Emacs, type C-x C-c
(save-buffers-kill-emacs). A two-character key is used to make
it harder to type by accident. This command first offers to save any
modified file-visiting buffers. If you do not save them all, it asks
for confirmation with yes before killing Emacs, since any
changes not saved now will be lost forever. Also, if any subprocesses are
still running, C-x C-c asks for confirmation about them, since
killing Emacs will also kill the subprocesses.
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 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.
You can't resume an Emacs session after killing it. Emacs can, however, record certain session information when you kill it, such as which files you visited, so the next time you start Emacs it will try to visit the same files. See Saving Emacs Sessions.
The operating system usually listens for certain special characters whose meaning is to kill or suspend the program you are running. This operating system feature is turned off while you are in Emacs. The meanings of C-z and C-x C-c as keys in Emacs were inspired by the use of C-z and C-c on several operating systems as the characters for stopping or killing a program, but that is their only relationship with the operating system. You can customize these keys to run any commands of your choice (see Keymaps).
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
Control-h t inside Emacs. (help-with-tutorial).
To clear and redisplay the screen, type C-l (recenter).
Typing printing characters inserts them into the text you are editing. It inserts them into the buffer at the cursor; more precisely, it inserts them at point, but the cursor normally shows where point is. See Point.
Insertion moves the cursor forward, and the following text moves forward with the cursor. If the text in the buffer is `FOOBAR', with the cursor before the `B', and you type XX, you get `FOOXXBAR', with the cursor still before the `B'.
To delete text you have just inserted, use the large key labeled <DEL>, <BACKSPACE> or <DELETE> which is a short distance above the <RET> or <ENTER> key. Regardless of the label on that key, Emacs thinks of it as <DEL>, and that's what we call it in this manual. <DEL> is the key you normally use outside Emacs to erase the last character that you typed.
The <DEL> key deletes the character before the cursor. As a consequence, the cursor and all the characters after it move backwards. If you type a printing character and then type <DEL>, they cancel out.
On most computers, Emacs sets up <DEL> automatically. In some cases, especially with text-only terminals, Emacs may guess wrong. If the key that ought to erase the last character doesn't do it in Emacs, see DEL Does Not Delete.
Most PC keyboards have both a <BACKSPACE> key a little ways above <RET> or <ENTER>, and a <DELETE> key elsewhere. On these keyboards, Emacs tries to set up <BACKSPACE> as <DEL>. The <DELETE> key deletes “forwards” like C-d (see below), which means it deletes the character underneath the cursor (after point).
To end a line and start typing a new one, type <RET>. (This key may be labeled <RETURN> or <ENTER>, but in Emacs we call it <RET>.) This inserts a newline character in the buffer. If point is at the end of the line, this creates a new blank line after it. If point is in the middle of a line, the effect is to split that line. Typing <DEL> when the cursor is at the beginning of a line deletes the preceding newline character, thus joining the line with the one before it.
Emacs can split lines automatically when they become too long, if you turn on a special minor mode called Auto Fill mode. See Filling, for Auto Fill mode and other methods of filling text.
If you prefer printing characters to replace (overwrite) existing text, rather than shove it to the right, you should enable Overwrite mode, a minor mode. See Minor Modes.
Only printing characters and <SPC> insert themselves in Emacs.
Other characters act as editing commands and do not insert themselves.
These include control characters, and characters with codes above 200
octal. If you need to insert one of these characters in the buffer,
you must quote it by typing the character Control-q
(quoted-insert) first. (This character's name is normally
written C-q for short.) There are two ways to use
C-q:
The use of octal sequences is disabled in ordinary non-binary Overwrite mode, to give you a convenient way to insert a digit instead of overwriting with it.
When multibyte characters are enabled, if you specify a code in the range 0200 through 0377 octal, C-q assumes that you intend to use some ISO 8859-n character set, and converts the specified code to the corresponding Emacs character code. See Enabling Multibyte. You select which of the ISO 8859 character sets to use through your choice of language environment (see Language Environments).
To use decimal or hexadecimal instead of octal, set the variable
read-quoted-char-radix to 10 or 16. If the radix is greater than
10, some letters starting with a serve as part of a character
code, just like digits.
A numeric argument tells C-q how many copies of the quoted character to insert (see Arguments).
Customization information: <DEL> in most modes runs the command
delete-backward-char; <RET> runs the command
newline, and self-inserting printing characters run the command
self-insert, which inserts whatever character you typed. Some
major modes rebind <DEL> to other commands.
To do more than insert characters, you have to know how to move point (see Point). The simplest way to do this is with arrow keys, or by clicking the left mouse button where you want to move to.
There are also control and meta characters for cursor motion. Some are equivalent to the arrow keys (it is faster to use these control keys than move your hand over to the arrow keys). Others do more sophisticated things.
move-beginning-of-line).
move-end-of-line).
forward-char). The right-arrow key
does the same thing.
backward-char). The left-arrow
key has the same effect.
forward-word).
backward-word).
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. The
down-arrow key does the same thing.
previous-line). The up-arrow key
has the same effect. This command preserves position within the line,
like C-n.
move-to-window-line). Text does not move on the screen.
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).
beginning-of-buffer). With
numeric argument n, move to n/10 of the way from the top.
See Arguments, for more information on numeric arguments.
end-of-buffer).
scroll-up). This doesn't always move
point, but it is commonly used to do so. If your keyboard has a
<PAGEDOWN> or <PRIOR> key, it does the same thing.
Scrolling commands are described further in Scrolling.
scroll-down). This doesn't always move point, but
it is commonly used to do so. If your keyboard has a <PAGEUP> or
<NEXT> key, it does the same thing.
set-goal-column). 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.
If you set the variable track-eol to a non-nil value,
then C-n and C-p, when starting at the end of the line, move
to the end of another line. Normally, track-eol is nil.
See Variables, for how to set variables such as track-eol.
C-n normally stops at the end of the buffer when you use it on
the last line of 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.
delete-backward-char).
delete-char).
kill-line).
kill-word).
backward-kill-word).
You already know about the <DEL> key which deletes the character before point (that is, before the cursor). Another key, Control-d (C-d for short), deletes the character after point (that is, the character that the cursor is on). This shifts the rest of the text on the line to the left. If you type C-d at the end of a line, it joins that line with the following line.
To erase a larger amount of text, use the C-k key, which 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 Killing, for more flexible ways of killing text.
Emacs records a list of changes made in the buffer text, so you can you can undo recent changes, as far as the records go. Usually each editing command makes a separate entry in the undo records, but sometimes an entry covers just part of a command, and very simple commands may be grouped.
undo).
The command C-x u (or C-_ or C-/) is how you undo. Normally this command undoes the last change, and moves point back to where it was before the change.
If you repeat C-x u (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.
The undo command applies only to changes in the buffer; you can't use it to undo mere cursor motion. However, some cursor motion commands set the mark, so if you use these commands from time to time, you can move back to the neighborhoods you have moved through by popping the mark ring (see Mark Ring).
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. Files are named units of text which are stored by the operating system for you to retrieve later by name. To use the contents of a file in any way, you must specify the file name. That includes editing the file with Emacs.
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 Minibuffer).
Emacs obeys this command by visiting the file: it creates a
buffer, it 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 Files.
If you forget what a key does, you can find out with the Help
character, which is C-h (or <F1>, which is an alias for
C-h). Type C-h k followed by the key of interest; for
example, C-h k C-n tells you what C-n does. C-h is
a prefix key; C-h k is just one of its subcommands (the command
describe-key). The other subcommands of C-h provide
different kinds of help. Type C-h twice to get a description of
all the help facilities. See Help.
Here are special commands and techniques for inserting and deleting blank lines.
open-line).
delete-blank-lines).
To insert a new line of text before an existing line,
type the new line of text, followed by <RET>.
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. C-o F O O has the same effect as
F O O <RET>, except for the final location of point.
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 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 Fill Prefix.
The easy way to get rid of extra blank lines is with the command
C-x C-o (delete-blank-lines). C-x C-o in a run of
several blank lines deletes all but one of them. C-x C-o on a
lone blank line deletes that one. When point is on a nonblank line,
C-x C-o deletes all following blank lines (if any).
When a text line is too long to fit in one screen line, Emacs displays it on two or more screen lines. This is called continuation or line wrapping. On graphical displays, Emacs indicates line wrapping with small bent arrows in the left and right window fringes. On text-only terminals, Emacs displays a `\' character at the right margin of a screen line if it is not the last in its text line. This `\' character says that the following screen line is not really a new text line.
When line wrapping occurs just before a character that is wider than one column, some columns at the end of the previous screen line may be “empty.” In this case, Emacs displays additional `\' characters in the “empty” columns before the `\' character that indicates continuation.
Continued lines can be difficult to read, since lines can break in the middle of a word. If you prefer, you can make Emacs insert a newline automatically when a line gets too long, by using Auto Fill mode. Or enable Long Lines mode, which ensures that wrapping only occurs between words. See Filling.
Emacs can optionally truncate long lines—this means displaying just one screen line worth, and the rest of the long line does not appear at all. `$' in the last column or a small straight arrow in the window's right fringe indicates a truncated line.
See Line Truncation, for more about line truncation, and other variables that control how text is displayed.
Here are commands to get information about the size and position of parts of the buffer, and to count lines.
count-lines-region).
See Mark, for information about the region.
what-cursor-position).
M-x what-line displays the current line number
in the echo area. You can also see the current line number in the
mode line; see Mode Line; but if you narrow the buffer, the
line number in the mode line is relative to the accessible portion
(see Narrowing). By contrast, what-line shows both the
line number relative to the narrowed region and the line number
relative to the whole buffer.
M-x what-page counts pages from the beginning of the file, and counts lines within the page, showing both numbers in the echo area. See Pages.
Use M-= (count-lines-region) to displays the number of
lines in the region (see Mark). See Pages, for the command
C-x l which counts the lines in the current page.
The command C-x = (what-cursor-position) shows what
cursor's column position, and other information about point and the
character after it. It displays a line in the echo area that looks
like this:
Char: c (99, #o143, #x63) point=28062 of 36168 (78%) column=53
The four values after `Char:' describe the character that follows point, first by showing it and then by giving its character code in decimal, octal and hex. For a non-ASCII multibyte character, these are followed by `file' and the character's representation, in hex, in the buffer's coding system, if that coding system encodes the character safely and with a single byte (see Coding Systems). If the character's encoding is longer than one byte, Emacs shows `file ...'.
However, if the character displayed is in the range 0200 through 0377 octal, it may actually stand for an invalid UTF-8 byte read from a file. In Emacs, that byte is represented as a sequence of 8-bit characters, but all of them together display as the original invalid byte, in octal code. In this case, C-x = shows `part of display ...' instead of `file'.
`point=' is followed by the position of point expressed as a character count. The start of the buffer is position 1, one character later is position 2, and so on. The next, larger, number is the total number of characters in the buffer. Afterward in parentheses comes the position expressed as a percentage of the total size.
`column=' is followed by the horizontal position of point, in columns 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 Narrowing.
If point is at the end of the buffer (or the end of the accessible part), the C-x = output does not describe a character after point. The output might look like this:
point=36169 of 36168 (EOB) column=0
C-u C-x = displays the following additional information about a character.
ascii character set.
Here's an example showing the Latin-1 character A with grave accent,
in a buffer whose coding system is iso-latin-1, whose
terminal coding system is iso-latin-1 (so the terminal actually
displays the character as `À'), and which has font-lock-mode
(see Font Lock) enabled:
character: À (2240, #o4300, #x8c0, U+00C0)
charset: latin-iso8859-1
(Right-Hand Part of Latin Alphabet 1...
code point: #x40
syntax: w which means: word
category: l:Latin
to input: type "`A" with latin-1-prefix
buffer code: #x81 #xC0
file code: #xC0 (encoded by coding system iso-latin-1)
display: terminal code #xC0
There are text properties here:
fontified t
In mathematics and computer usage, 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, C-f with an argument of ten moves forward ten characters instead of one. With these commands, no argument is equivalent to an argument of one. Negative arguments tell most such commands to move or act in the opposite direction.
If your terminal keyboard has a <META> key (labeled <ALT> on PC keyboards), the easiest way to specify a numeric argument is to type digits and/or a minus sign while holding down the <META> key. For example,
M-5 C-n
moves down five lines. The characters Meta-1, Meta-2,
and so on, as well as Meta--, do this because they are keys bound
to commands (digit-argument and negative-argument) that
are defined to set up an argument for the next command.
Meta-- without digits normally means −1. Digits and
- modified with Control, or Control and Meta, also specify numeric
arguments.
You can also specify a numeric argument by typing C-u
(universal-argument) followed by the digits. The advantage of
C-u is that you can type the digits without modifier keys; thus,
C-u works on all terminals. For a negative argument, type a
minus sign after C-u. 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. This is a good way to move forward “fast,” since it moves about 1/5 of a line in the usual size screen. 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 “a lot” of blank lines), and C-u C-k (kill four lines).
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 Filling, for more information on M-q.) Plain C-u
is a handy way of providing an argument for such commands.
Some commands use the value of the argument as a repeat count, but do
something peculiar 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 Killing, 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.
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'.
We use the term “prefix argument” as well as “numeric argument,” to emphasize that you type these argument before the command, and to distinguish them from minibuffer arguments that come after the 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 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.
The minibuffer is where Emacs commands read complicated arguments (anything more a single number). We call it the “minibuffer” because it's a special-purpose buffer with a small amount of screen space. Minibuffer arguments can be file names, buffer names, Lisp function names, Emacs command names, Lisp expressions, and many other things—whatever the command wants to read. You can use the usual Emacs editing commands in the minibuffer to edit the argument text.
When the minibuffer is in use, it appears in the echo area, with a cursor. The minibuffer display starts with a prompt in a distinct color; it says what kind of input is expected and how it will be used. Often the prompt is derived from the name of the command that is reading the argument. The prompt normally ends with a colon.
Sometimes a default argument appears in the prompt, inside parentheses before the colon. The default will be used as the argument value if you just type <RET>. For example, commands that read buffer names show a buffer name as the default. You can type <RET> to operate on that default buffer.
The simplest way to enter a minibuffer argument is to type the text, then <RET> to exit the minibuffer. You can cancel the minibuffer, and the command that wants the argument, by typing C-g.
Since the minibuffer appears in the echo area, it can conflict with other uses of the echo area. Here is how Emacs handles such conflicts:
The error message hides the minibuffer for a few seconds, or until you type something. Then the minibuffer comes back.
The message hides the minibuffer for a few seconds, or until you type something. Then the minibuffer comes back.
When you use the minibuffer to enter a file name, it starts out with some initial text—the default directory, ending in a slash. The file you specify will be in this directory unless you alter or replace it.
For example, if the minibuffer starts out with these contents:
Find File: /u2/emacs/src/
(where `Find File: ' is the prompt), and you type buffer.c as input, that specifies the file /u2/emacs/src/buffer.c. You can specify the parent directory by adding ..; thus, if you type ../lisp/simple.el, you will get /u2/emacs/lisp/simple.el. Alternatively, you can use M-<DEL> to kill the directory names you don't want (see Words).
You can kill the entire default with C-a C-k, but there's no need to do that. It's easier to ignore the default, and enter an absolute file name starting with a slash or a tilde after the default directory. For example, to specify /etc/termcap, just type that name:
Find File: /u2/emacs/src//etc/termcap
GNU Emacs interprets a double slash (which is not normally useful in file names) as, “ignore everything before the second slash in the pair.” In the example above. `/u2/emacs/src/' is ignored, so you get /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 (a minor mode) with the command M-x file-name-shadow-mode.
If the variable insert-default-directory is nil, the
default directory is never inserted in the minibuffer—so the
minibuffer starts out empty. Nonetheless, relative file name
arguments are still interpreted based on the same default directory.
The minibuffer is an Emacs buffer (albeit a peculiar one), and the usual Emacs commands are available for editing the argument text.
Since <RET> in the minibuffer is defined to exit the minibuffer, you can't use it to insert a newline in the minibuffer. To do that, type C-o or C-q C-j. (The newline character is really the ASCII character control-J.)
The minibuffer has its own window, which normally has space in the frame at all times, but it only acts like an Emacs window when the minibuffer is active. When active, this window is much like any other 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 then yank the text into the argument. See Windows.
There are some restrictions on the minibuffer window, however: you cannot kill it, or split it, or switch buffers in it—the minibuffer and its window are permanently attached.
The minibuffer window expands vertically as necessary to hold the
text that you put in the minibuffer. If resize-mini-windows is
t (the default), the window always resizes as needed by its
contents. If its value is the symbol grow-only, the window
grows automatically as needed, but shrinks (back to the normal size)
only when the minibuffer becomes inactive. If its value is
nil, you have to adjust the height yourself.
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. M-<PAGEUP> and M-<PAGEDOWN> also operate on that help text. This is especially useful with long lists of possible completions. See Other Window.
Emacs normally disallows most commands that use the minibuffer while
the minibuffer is active. (Entering the minibuffer from the
minibuffer can be confusing.) To allow such commands in the
minibuffer, set the variable enable-recursive-minibuffers to
t.
Some arguments allow completion to enter their value. This means that after you type part of the argument, Emacs can fill in the rest, or some of it, based on what you have typed so far.
When completion is available, certain keys—<TAB>, <RET>, and <SPC>—are rebound to complete the text in the minibuffer before point into a longer string chosen from a set of completion alternatives provided by the command that requested the argument. (<SPC> does not do completion in reading file names, because it is common to use spaces in file names on some systems.) ? displays a list of the possible completions at any time.
For example, M-x uses the minibuffer to read the name of a command, so it provides a list of all Emacs command names for completion candidates. The completion keys match the minibuffer text against these candidates, find any additional name characters implied by the text already present in the minibuffer, and add those characters. This makes it possible to type M-x ins <SPC> b <RET> instead of M-x insert-buffer <RET>, for example.
Case is significant in completion when it is significant in the argument you are entering (buffer names, file names, command names, for instance). Thus, `fo' does not complete to `Foo'. Completion ignores case distinctions for certain arguments in which case does not matter.
Completion acts only on the text before point. If there is text in the minibuffer after point—i.e., if you move point backward after typing some text into the minibuffer—it remains unchanged.
A concrete example may help here. If you type M-x au
<TAB>, the <TAB> looks for alternatives (in this case,
command names) that start with `au'. There are several,
including auto-fill-mode and auto-save-mode, but they
all begin with auto-, so the `au' in the minibuffer
completes to `auto-'.
If you type <TAB> again immediately, it cannot determine the next character; it could be any of `cfilrs'. So it does not add any characters; instead, <TAB> displays a list of all possible completions in another window.
Now type f <TAB>. This <TAB> sees `auto-f'. The
only command name starting with that is auto-fill-mode, so
completion fills in the rest of that. You have been able to enter
`auto-fill-mode' by typing just au <TAB> f <TAB>.
Here is a list of the completion commands defined in the minibuffer when completion is allowed.
minibuffer-complete).
minibuffer-complete-word). <SPC> for completion is not
available when entering a file name, since file names often include
spaces.
minibuffer-complete-and-exit). See Strict Completion.
minibuffer-completion-help).
<SPC> 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'. The command that implements this behavior is
called minibuffer-complete-word.
When you display a list of possible completions, you can choose one from it:
mouse-choose-completion). You must click in the
list of completions, not in the minibuffer.
switch-to-completions). This paves the way for using the
commands below. (Selecting that window in other ways has the same
effect.)
choose-completion). To
use this command, you must first switch to the completion list window.
next-completion).
previous-completion).
There are three different ways that <RET> can do completion, depending on how the argument will be used.
Cautious completion is used for reading file names for files that must already exist, for example.
The completion commands display a list of all possible completions whenever they can't determine even one more character by completion. Also, typing ? explicitly requests such a list. You can scroll the list with C-M-v (see Other Window).
When completing file names, certain file names are usually ignored.
The variable completion-ignored-extensions contains a list of
strings; a file name ending in any of those strings is ignored as a
completion candidate. The standard value of this variable has several
elements including ".o", ".elc", ".dvi" and
"~". The effect is that, for example, `foo' can complete
to `foo.c' even though `foo.o' exists as well. However, if
all the possible completions end in “ignored” strings, then
they are not ignored. Displaying a list of possible completions
disregards completion-ignored-extensions; it shows them all.
If an element of completion-ignored-extensions ends in a
slash (/), it's a subdirectory name; then that directory and
its contents are ignored. Elements of
completion-ignored-extensions which do not end in a slash are
ordinary file names, and do not apply to names of directories.
If completion-auto-help is set to nil, the completion
commands never display a list of possibilities; you must type ?
to display the list.
Partial Completion mode implements a more powerful kind of
completion that can complete multiple words in parallel. For example,
it can complete the command name abbreviation p-b into
print-buffer if no other command starts with two words whose
initials are `p' and `b'.
To enable this mode, use M-x partial-completion-mode, or
customize the variable partial-completion-mode. This mode
binds special partial completion commands to <TAB>, <SPC>,
<RET>, and ? in the minibuffer. The usual completion
commands are available on M-<TAB> (or C-M-i),
M-<SPC>, M-<RET> and M-?.
Partial completion of directories in file names uses `*' to indicate the places for completion; thus, /u*/b*/f* might complete to /usr/bin/foo. For remote files, partial completion enables completion of methods, user names and host names. See Remote Files.
Partial Completion mode also extends find-file so that
`<include>' looks for the file named include in the
directories in the path PC-include-file-path. If you set
PC-disable-includes to non-nil, this feature is
disabled.
Icomplete mode presents a constantly-updated display that tells you what completions are available for the text you've entered so far. The command to enable or disable this minor mode is M-x icomplete-mode.
Every argument that you enter with the minibuffer is saved on a minibuffer history list so you can easily use it again later. Special commands fetch the text of an earlier argument into the minibuffer, replacing the old minibuffer contents. You can think of them as moving through the history of previous arguments.
previous-history-element).
next-history-element).
previous-matching-history-element).
next-matching-history-element).
To move through the minibuffer history list one item at a time, use
M-p or up-arrow (previous-history-element) to fetch the
next earlier minibuffer input, and use M-n or down-arrow
(next-history-element) to fetch the next later input. These
commands don't move the cursor, they pull different saved strings into
the minibuffer. But you can think of them as “moving” through the
history list.
The input that you fetch from the history entirely replaces the contents of the minibuffer. To use it again unchanged, just type <RET>. You can also edit the text before you reuse it; this does not change the history element that you “moved” to, but your new argument does go at the end of the history list in its own right.
For many minibuffer arguments there is a “default” value. You can insert the default value into the minibuffer as text by using M-n. You can think of this as moving “into the future” in the history.
There are also commands to search forward or backward through the
history; they search for history elements that match a regular
expression. M-r (previous-matching-history-element)
searches older elements in the history, while M-s
(next-matching-history-element) searches newer elements. These
commands are unusual; they use the minibuffer to read the regular
expression even though they are invoked from the minibuffer. As with
incremental searching, an upper-case letter in the regular expression
makes the search case-sensitive (see Search Case).
All uses of the minibuffer record your input on a history list, but there are separate history lists for different kinds of arguments. For example, there is a list for file names, used by all the commands that read file names. (As a special feature, this history list records the absolute file name, even if the name you entered was not absolute.)
There are several other specific history lists, including one for
buffer names, one for arguments of commands like query-replace,
one used by M-x for command names, and one used by
compile for compilation commands. Finally, there is one
“miscellaneous” history list that most minibuffer arguments use.
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 of
history-length is t, though, there is no maximum length.
The variable history-delete-duplicates specifies whether to
delete duplicates in history. If it is t, adding a new element
deletes from the list all other elements that are equal to it.
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.
repeat-complex-command).
C-x <ESC> <ESC> is used to re-execute 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 understand Lisp syntax, 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 repeated command is added to the front of the command history unless it is identical to the most recently item.
Once inside the minibuffer for C-x <ESC> <ESC>, you can use the minibuffer history commands (M-p, M-n, M-r, M-s; see Minibuffer History) to move through the history list of saved entire commands. After finding the desired previous command, you can edit its expression as usual and then repeat 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 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 which describes one command and its arguments. Lisp programs
can re-execute a command by calling eval with the
command-history element.
Every Emacs command has a name that you can use to run it. For convenience, many commands also have key bindings. You can run those commands by typing the keys, or run them by name. Most Emacs commands have no key bindings, so the only way to run them is by name. (See Key Bindings, for how to set up key bindings.)
By convention, a command name consists of one or more words,
separated by hyphens; for example, auto-fill-mode or
manual-entry. Command names mostly use complete English words
to make them easier to remember.
To run a command by name, start with M-x, type the command name, then terminate it with <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 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.
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.
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.
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.
Emacs provides extensive help features, all accessible through the help character, C-h. This is a prefix key that is used for commands that display documentation; the next character you type should be a help options, to ask for a particular kind of help. You can cancel the C-h command with C-g. The function key <F1> is equivalent to C-h.
C-h itself is one of the help options; C-h C-h displays
a list of help options, with a brief description of each one
(help-for-help). You can scroll the list with <SPC> and
<DEL>, then type the help option you want. To cancel, type
C-g.
C-h or <F1> means “help” in various other contexts as well. For instance, you can type them after a prefix key to display list of the keys that can follow the prefix key. (A few prefix keys don't support C-h in this way, because they define other meanings for it, but they all support <F1> for help.)
Most help buffers use a special major mode, Help mode, which lets you scroll conveniently with <SPC> and <DEL>. You can also follow hyperlinks to URLs, and to other facilities including Info nodes and customization buffers. See Help Mode.
If you are looking for a certain feature, but don't know what it is called or where to look, we recommend three methods. First, try an apropos command, then try searching the manual index, then look in the FAQ and the package keywords.
Here is a summary of the Emacs interactive help commands. (The character that follows C-h is the “help option.”) See Help Files, for other help commands that display fixed files of information.
apropos-command; see Apropos).
describe-bindings).
describe-key-briefly). Here c stands for
“character.” For more extensive information on key, use
C-h k.
apropos-documentation).
*Messages* buffer
(view-echo-area-messages).
describe-function). Since commands are Lisp functions,
this works for commands too.
info).
The complete Emacs manual is available on-line in Info.
describe-key).
view-lossage).
describe-mode).
finder-by-keyword).
describe-syntax). See Syntax.
help-with-tutorial).
describe-variable).
where-is).
describe-coding-system).
describe-input-method).
describe-language-environment).
Info-goto-emacs-command-node).
Info-goto-emacs-key-command-node).
info-lookup-symbol).
display-local-help). (These include, for example, links in
`*Help*' buffers.)
The help commands to get information about a key sequence are C-h c and C-h k. 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'. Since command names are chosen to describe what the commands do, this gives you a very brief description of what key does.
C-h k key is similar but gives more information: it displays the documentation string of the command as well as its name. It displays this information in a window, since it may not fit in the echo area.
To find the documentation of a key sequence key, type C-h K key. This displays the appropriate manual section which contains the documentation of 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. 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.
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> will describe 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 Variables.
Help buffers that describe Emacs variables and functions normally have hyperlinks to the corresponding source definition, if you have the source files installed. (See Hyperlinking.) If you know Lisp (or C), this provides the ultimate documentation. If you don't know Lisp, you should learn it. (The Introduction to Emacs Lisp Programming, available from the FSF through fsf.org, is a good way to get started.) If Emacs feels you are just using it, treating it as an object program, its feelings may be hurt. For real intimacy, read the Emacs source code.
To find a function'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.
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 apropos command displays a list of items that match the pattern, in a separate buffer.
The simplest kind of apropos pattern is one word. Anything which
contains that word matches the pattern. Thus, to find the 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.
The a in C-h a stands for “Apropos”; C-h a
runs the command apropos-command. This command normally checks
only commands (interactive functions); if you specify a prefix
argument, it checks noninteractive functions as well.
For more information about a function definition, variable or symbol property listed in the 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 Regexps). 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.
Use M-x apropos instead of C-h a to list all the Lisp symbols that match an apropos pattern, not just the symbols that are commands. This command does not list key bindings by default; specify a numeric argument if you want it to list them.
Use M-x apropos-variable to list user-customizable variables that match an apropos pattern. If you specify a prefix argument, it lists all matching variables.
The apropos-documentation command is like apropos
except that it searches documentation strings instead of symbol names
for matches.
The apropos-value command is like apropos except that
it searches variables' values for matches for the apropos pattern.
With a prefix argument, it also checks symbols' function definitions
and property lists.
If the variable apropos-do-all is non-nil, the apropos
commands always behave as if they had been given a prefix argument.
By default, apropos lists the search results in alphabetical order.
If the variable apropos-sort-by-scores is non-nil, the
apropos commands try to guess the relevance of each result, and
display the most relevant ones first.
By default, apropos lists the search results for
apropos-documentation in order of relevance of the match. If
the variable apropos-documentation-sort-by-scores is
nil, apropos lists the symbols found in alphabetical order.
Help buffers provide the same commands as View mode (see Misc File Ops), plus a few special commands of their own.
When a function name (see Running Commands by Name), variable name (see Variables), or face name (see Faces) appears in the documentation, it normally appears inside paired single-quotes. To view the documentation of that command, variable or face, you can click on the name with Mouse-1 or Mouse-2, or move point there and type <RET>. Use C-c C-b to retrace your steps.
You can follow cross references to URLs (web pages) also. This uses
the browse-url command to view the page in the browser you
choose. See Browse-URL.
There are convenient commands to move point to cross references in
the help text. <TAB> (help-next-ref) moves point down to
the next cross reference. S-<TAB> moves up to the previous
cross reference (help-previous-ref).
To view all documentation about any symbol name that appears in the
text, move point to the symbol name and type C-c C-c
(help-follow-symbol). This shows all available documentation
about the symbol as a variable, function and/or face. As above, use
C-c C-b to retrace your steps.
The C-h p command lets you search the standard Emacs Lisp libraries by topic keywords. Here is a partial list of keywords you can use:
| abbrev | abbreviation handling, typing shortcuts, macros.
|
| bib | code related to the bib bibliography processor.
|
| c | support for the C language and related languages.
|
| calendar | calendar and time management support.
|
| comm | communications, networking, remote access to files.
|
| convenience | convenience features for faster editing.
|
| data | support for editing files of data.
|
| docs | support for Emacs documentation.
|
| emulations | emulations of other editors.
|
| extensions | Emacs Lisp language extensions.
|
| faces | support for multiple fonts.
|
| files | support for editing and manipulating files.
|
| frames | support for Emacs frames and window systems.
|
| games | games, jokes and amusements.
|
| hardware | support for interfacing with exotic hardware.
|
| help | support for on-line help systems.
|
| hypermedia | support for links between text or other media types.
|
| i18n | internationalization and alternate character-set support.
|
| internal | code for Emacs internals, build process, defaults.
|
| languages | specialized modes for editing programming languages.
|
| lisp | Lisp support, including Emacs Lisp.
|
| local | code local to your site.
|
| maint | maintenance aids for the Emacs development group.
|
| modes for electronic-mail handling.
| |
| matching | various sorts of searching and matching.
|
| mouse | mouse support.
|
| multimedia | images and sound support.
|
| news | support for netnews reading and posting.
|
| oop | support for object-oriented programming.
|
| outlines | support for hierarchical outlining.
|
| processes | process, subshell, compilation, and job control support.
|
| terminals | support for terminal types.
|
| tex | supporting code for the TeX formatter.
|
| tools | programming tools.
|
| unix | front-ends/assistants for, or emulators of, UNIX-like features.
|
| wp | word processing.
|
You can use the command C-h L
(describe-language-environment) to get information about a
specific language environment. See Language Environments. This
tells you which languages this language environment supports. It also
lists the character sets, coding systems, and input methods that work
with this language environment, and finally shows some sample text to
illustrate scripts.
The command C-h h (view-hello-file) displays the file
etc/HELLO, which shows 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 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 Coding Systems.
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 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
the last 100 characters you typed in Emacs. If you see commands that
you don't know, you can use C-h c 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.
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 Key Bindings). C-h s
displays the contents of the syntax table, with explanations of each
character's syntax (see Syntax).
You can get a list of subcommands for a particular prefix key by typing C-h after the prefix key. (There are a few prefix keys for which this does not work—those that provide their own bindings for C-h. One of these is <ESC>, because <ESC> C-h is actually C-M-h, which marks a defun.)
The Emacs help commands described above display dynamic help based on the current state within Emacs, or refer to manuals. Other help commands display pre-written, static help files. These commands all have the form C-h C-char; that is, C-h followed by a control character.
describe-copying).
These are the rules under which you can copy and redistribute Emacs.
describe-distribution).
view-emacs-problems).
view-emacs-FAQ).
view-emacs-news).
describe-project).
view-todo).
describe-no-warranty).
When a region of text is “active,” so that you can select it with the mouse or a key like RET, it often has associated help text. For instance, most parts of the mode line have help text. On graphical displays, the help text is displayed as a “tooltip” (sometimes known as “balloon help”), when you move the mouse over the active text. See Tooltips. On some systems, it is shown in the echo area. On text-only terminals, if Emacs cannot follow the mouse, it cannot show the help text on mouse-over.
You can also access text region help info using the keyboard. The
command C-h . (display-local-help) displays any help text
associated with the text at point, using the echo area. If you want
help text to be displayed automatically whenever it is available at
point, set the variable help-at-pt-display-when-idle to
t.
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. Emacs highlights the region whenever there is one, if you enable Transient Mark mode (see Transient Mark).
Certain Emacs commands set the mark; other editing commands do not affect it, so the mark remains where you set it last. Each Emacs buffer has its own mark, and setting the mark in one buffer has no effect on other buffers' marks. When you return to a buffer that was current earlier, its mark is at the same place as before.
The ends of the region are always point and the mark. It doesn't matter which of them was put in its current place first, or which one comes earlier in the text—the region starts from point or the mark (whichever comes first), and ends at point or the mark (whichever comes last). Every time you move point, or set the mark in a new place, the region changes.
Many commands that insert text, such as C-y (yank) and
M-x insert-buffer, position point and the mark at opposite ends
of the inserted text, so that the region consists of the text just
inserted.
Aside from delimiting the region, the mark is also useful for remembering a spot that you may want to go back to. To make this feature more useful, each buffer remembers 16 previous locations of the mark in the mark ring.
Here are some commands for setting the mark:
set-mark-command).
exchange-point-and-mark).
mouse-save-then-kill).
For example, suppose you wish to convert part of the buffer to
upper case, using the C-x C-u (upcase-region) command,
which operates on the text in the region. You can first go to the
beginning of the text to be capitalized, type C-<SPC> to put
the mark there, move to the end, and then type C-x C-u. Or, you
can set the mark at the end of the text, move to the beginning, and then
type C-x C-u.
The most common way to set the mark is with the C-<SPC> command
(set-mark-command). This sets the mark where point is. Then you
can move point away, leaving the mark behind.
There are two ways to set the mark with the mouse. You can drag mouse button one across a range of text; that puts point where you release the mouse button, and sets the mark at the other end of that range. Or you can click mouse button three, which sets the mark at point (like C-<SPC>) and then moves point where you clicked (like Mouse-1).
Using the mouse to mark a region copies the region into the kill ring in addition to setting the mark; that gives behavior consistent with other window-driven applications. If you don't want to modify the kill ring, you must use keyboard commands to set the mark. See Mouse Commands.
When Emacs was developed, terminals had only one cursor, so Emacs does not show where the mark is located–you have to remember. If you enable Transient Mark mode (see below), then the region is highlighted when it is active; you can tell mark is at the other end of the highlighted region. But this only applies when the mark is active.
The usual solution to this problem is to set the mark and then use
it soon, before you forget where it is. Alternatively, you can see
where the mark is with the command C-x C-x
(exchange-point-and-mark) which puts the mark where point was
and point where the mark was. The extent of the region is unchanged,
but the cursor and point are now at the previous position of the mark.
In Transient Mark mode, this command also reactivates the mark.
C-x C-x is also useful when you are satisfied with the position of point but want to move the other end of the region (where the mark is); do C-x C-x to put point at that end of the region, and then move it. Using C-x C-x a second time, if necessary, puts the mark at the new position with point back at its original position.
For more facilities that allow you to go to previously set marks, see Mark Ring.
There is no such character as C-<SPC> in ASCII;
when you type <SPC> while holding down <CTRL> on a text
terminal, what you get is the character C-@. This key is also
bound to set-mark-command–so unless you are unlucky enough to
have a text terminal where typing C-<SPC> does not produce
C-@, you might as well think of this character as
C-<SPC>.
On a terminal that supports colors, Emacs has the ability to highlight the current region. But normally it does not. Why not?
In the normal mode of use, every command that sets the mark also activates it, and nothing ever deactivates it. Thus, once you have set the mark in a buffer, there is always a region in that buffer. Highlighting the region all the time would be a nuisance. So normally Emacs highlights the region only immediately after you have selected one with the mouse.
If you want region highlighting, you can use Transient Mark mode. This is a more rigid mode of operation in which the region “lasts” only until you use it; operating on the region text deactivates the mark, so there is no region any more. Therefore, you must explicitly set up a region for each command that uses one.
When Transient Mark mode is enabled, Emacs highlights the region, whenever there is a region. In Transient Mark mode, most of the time there is no region; therefore, highlighting the region when it exists is useful and not annoying.
To enable Transient Mark mode, type M-x transient-mark-mode. This command toggles the mode; you can use the same command to turn the mode off again.
Here are the details of Transient Mark mode:
set-mark-command).
This makes the mark active and thus begins highlighting of the region.
As you move point, you will see the highlighted region grow and
shrink.
exchange-point-and-mark).
The highlighting of the region uses the region face; you can
customize the appearance of the highlighted region by changing this
face. See Face Customization.
When multiple windows show the same buffer, they can have different
regions, because they can have different values of point (though they
all share one common mark position). Ordinarily, only the selected
window highlights its region (see Windows). However, if the
variable highlight-nonselected-windows is non-nil, then
each window highlights its own region (provided that Transient Mark mode
is enabled and the mark in the window's buffer is active).
If the variable mark-even-if-inactive is non-nil in
Transient Mark mode, then commands can use the mark and the region
even when it is inactive. Region highlighting appears and disappears
just as it normally does in Transient Mark mode, but the mark doesn't
really go away when the highlighting disappears, so you can still use
region commands.
Transient Mark mode is also sometimes known as “Zmacs mode” because the Zmacs editor on the MIT Lisp Machine handled the mark in a similar way.
If you don't like Transient Mark mode in general, you might still want to use it once in a while. To do this, type C-<SPC> C-<SPC> or C-u C-x C-x. These commands set or activate the mark, and enable Transient Mark mode only until the mark is deactivated.
exchange-point-and-mark, with a prefix argument.)
One of the secondary features of Transient Mark mode is that certain commands operate only on the region, when there is an active region. If you don't use Transient Mark mode, the region once set never becomes inactive, so there is no way for these commands to make such a distinction. Enabling Transient Mark mode momentarily gives you a way to use these commands on the region.
Momentary use of Transient Mark mode is also a way to highlight the region for the time being.
Once you have a region and the mark is active, here are some of the ways you can operate on the region:
Most commands that operate on the text in the region have the word
region in their names.
Here are the commands for placing point and the mark around a textual object such as a word, list, paragraph or page.
mark-word). This command and
the following one do not move point.
mark-sexp).
mark-paragraph).
mark-defun).
mark-whole-buffer).
mark-page).
M-@ (mark-word) puts the mark at the end of the next
word, while C-M-@ (mark-sexp) puts it at the end of the
next balanced expression (see Expressions). These commands handle
arguments just like M-f and C-M-f. Repeating these
commands extends the region. For example, you can type either
C-u 2 M-@ or M-@ M-@ to mark the next two words. These
commands also extend the region in Transient Mark mode, regardless of
the last command.
Other commands set both point and mark, to delimit an object in the
buffer. For example, M-h (mark-paragraph) moves point to
the beginning of the paragraph that surrounds or follows point, and
puts the mark at the end of that paragraph (see Paragraphs). It
prepares the region so you can indent, case-convert, or kill a whole
paragraph. With a prefix argument, if the argument's value is positive,
M-h marks that many paragraphs starting with the one surrounding
point. If the prefix argument is −n, M-h also
marks n paragraphs, running back form the one surrounding point.
In that last case, point moves forward to the end of that paragraph,
and the mark goes at the start of the region. Repeating the M-h
command extends the region to subsequent paragraphs.
C-M-h (mark-defun) similarly puts point before, and the
mark after, the current (or following) major top-level definition, or
defun (see Moving by Defuns). Repeating C-M-h extends
the region to subsequent defuns.
C-x C-p (mark-page) puts point before the current page,
and mark at the end (see Pages). The mark goes after the
terminating page delimiter (to include it in the region), while point
goes after the preceding page delimiter (to exclude it). A numeric
argument specifies a later page (if positive) or an earlier page (if
negative) instead of the current page.
Finally, 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. (In some programs this is called “select all.”)
In Transient Mark mode, all of these commands activate the mark.
Aside from delimiting the region, the mark is also useful for
remembering a spot that you may want to go back to. To make this
feature more useful, each buffer remembers 16 previous locations of the
mark, in the mark ring. Commands that set the mark also push the
old mark onto this ring. To return to a marked location, use C-u
C-<SPC> (or C-u C-@); this is the command
set-mark-command given a numeric argument. It moves point to
where the mark was, and restores the mark from the ring of former
marks.
If you set set-mark-command-repeat-pop to non-nil,
then when you repeat the character C-<SPC> after typing
C-u C-<SPC>, each repetition moves point to a previous mark
position from the ring. The mark positions you move through in this
way are not lost; they go to the end of the ring.
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.
Many commands that can move long distances, such as M-<
(beginning-of-buffer), start by setting the mark and saving the
old mark on the mark ring. This is to make it easier for you to move
back later. Searches set the mark if they move point. However, in
Transient Mark mode, these commands do not set the mark when the mark
is already active. You can tell when a command sets the mark because
it displays `Mark set' in the echo area.
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 Saving Positions in Registers).
The variable mark-ring-max specifies the maximum number of
entries to keep in the mark ring. 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.
The variable mark-ring holds the mark ring itself, as a list of
marker objects, with the most recent first. This variable is local in
every buffer.
In addition to the ordinary mark ring that belongs to each buffer, Emacs has a single global mark ring. It records a sequence of buffers in which you have recently set the mark, so you can go back to those buffers.
Setting the mark always makes an entry on the current buffer's mark ring. If you have switched buffers since the previous mark setting, the new mark position makes an entry on the global mark ring also. The result is that 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 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 and earlier buffers.
Killing means erasing text and copying it into the kill ring, from which you can bring it back into the buffer by yanking it. (Some systems use the terms “cutting” and “pasting” for these operations.) This is the most common way of moving or copying text within Emacs. Killing and yanking is very safe because Emacs remembers several recent kills, not just the last one. It is versatile, because the many commands for killing syntactic units can also be used for moving those units. But there are other ways of copying text for special purposes.
Most commands which erase text from the buffer save it in the kill
ring. These commands are known as kill commands. The commands
that erase text but do not save it in the kill ring are known as
delete commands. The C-x u (undo) command
(see Undo) can undo both kill and delete commands; the importance
of the kill ring is that you can also yank the text in a different
place or places. Emacs has only one kill ring for all buffers, so you
can kill text in one buffer and yank it in another buffer.
The delete commands 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. The commands' names and
individual descriptions use the words `kill' and `delete' to
say which kind of operation they perform.
You cannot kill read-only text, since such text does not allow any
kind of modification. But some users like to use the kill commands to
copy read-only text into the kill ring, without actually changing it.
Therefore, 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, kill commands 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.
You can also use the mouse to kill and yank. See Cut and Paste.
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.
delete-char). If your keyboard has a
<DELETE> function key (usually located in the edit keypad), Emacs
binds it to delete-char as well.
delete-backward-char).
delete-horizontal-space).
just-one-space).
delete-blank-lines).
delete-indentation).
The most basic delete commands are C-d (delete-char) and
<DEL> (delete-backward-char). C-d deletes the
character after point, the one the cursor is “on top of.” This
doesn't move point. <DEL> deletes the character before the cursor,
and moves point back. You can delete newlines like any other characters
in the buffer; deleting a newline joins two lines. Actually, C-d
and <DEL> aren't always delete commands; when given arguments, they
kill instead, since they can erase more than one character this way.
Every keyboard has a large key which is a short distance above the <RET> or <ENTER> key and is normally used for erasing what you have typed. It may be labeled <DEL>, <BACKSPACE>, <BS>, <DELETE>, or even with a left arrow. Regardless of the label on the key, in Emacs it called <DEL>, and it should delete one character backwards.
Many keyboards (including standard PC keyboards) have a <BACKSPACE> key a short ways above <RET> or <ENTER>, and a <DELETE> key elsewhere. In that case, the <BACKSPACE> key is <DEL>, and the <DELETE> key is equivalent to C-d—or it should be.
Why do we say “or it should be”? When Emacs starts up using a graphical display, it determines automatically which key or keys should be equivalent to <DEL>. As a result, <BACKSPACE> and/or <DELETE> keys normally do the right things. But in some unusual cases Emacs gets the wrong information from the system. If these keys don't do what they ought to do, you need to tell Emacs which key to use for <DEL>. See DEL Does Not Delete, for how to do this.
On most text-only terminals, Emacs cannot tell which keys the keyboard really has, so it follows a uniform plan which may or may not fit your keyboard. The uniform plan is that the ASCII <DEL> character deletes, and the ASCII <BS> (backspace) character asks for help (it is the same as C-h). If this is not right for your keyboard, such as if you find that the key which ought to delete backwards enters Help instead, see DEL Does Not Delete.
The other delete commands are those which 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 after
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 after point.
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 M-^.
kill-line).
kill-whole-line)
The simplest kill command is C-k. If given at the beginning of a line, it kills all the text on the line, leaving it blank. When used on a blank line, it kills the whole line including its newline. To kill an entire non-blank line, go to the beginning and type C-k twice.
More generally, C-k kills from point up to the end of the line, unless it is at the end of a line. In that case it kills the newline following point, thus merging the next line into the current one. Spaces and tabs that you can't see at the end of the line are ignored when deciding which case applies, so if point appears to be at the end of the line, you can be sure C-k will kill the newline.
When C-k is given a positive argument, it kills that many lines and the newlines that follow them (however, 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). Thus, C-u - 2 C-k at the front of a line kills the two previous lines.
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) will kill a whole line
including its newline regardless of the position of point within the
line. Note that many character terminals will prevent you from typing
the key sequence C-S-backspace.
kill-region).
kill-word). See Words.
backward-kill-word).
backward-kill-sentence).
See Sentences.
kill-sentence).
kill-sexp). See Expressions.
zap-to-char).
The most general kill command is C-w (kill-region),
which kills everything between point and the mark. With this command,
you can kill any contiguous sequence of characters, if you first set
the region around them.
A convenient way of killing is combined with searching: M-z
(zap-to-char) 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.
Other syntactic units can be killed: words, with M-<DEL> and M-d (see Words); balanced expressions, with C-M-k (see Expressions); and sentences, with C-x <DEL> and M-k (see Sentences).
Yanking means reinserting text previously killed. This is what some systems call “pasting.” The usual way to move or copy text is to kill it and then yank it elsewhere one or more times. This is very safe because Emacs remembers many recent kills, not just the last one.
yank).
yank-pop).
kill-ring-save). Some systems call this “copying.”
append-next-kill).
On graphical displays with window systems, if there is a current selection in some other application, and you selected it more recently than you killed any text in Emacs, C-y copies the selection instead of text killed within Emacs.
All killed text is recorded in the kill ring, a list of blocks of text that have been 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 file to another. (See Accumulating Text, for some other ways.)
The command C-y (yank) reinserts the text of the most recent
kill. It leaves the cursor at the end of the text. It sets the mark at
the beginning of the text. See Mark.
C-u C-y leaves the cursor in front of the text, and sets the mark after it. This happens only if the argument is specified with just a C-u, precisely. Any other sort of argument, including C-u and digits, specifies an earlier kill to yank (see Earlier Kills).
The yank commands discard certain text properties from the text that
is yanked, those that might lead to annoying results. For instance,
they discard text properties that respond to the mouse or specify key
bindings. The variable yank-excluded-properties specifies the
properties to discard. Yanking of register contents and rectangles
also discard these properties.
To copy a block of text, you can use M-w
(kill-ring-save), which copies the region into the kill ring
without removing it from the buffer. This is approximately equivalent
to C-w followed by C-x u, except that M-w does not
alter the undo history and does not temporarily change the screen.
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 append by first typing the command
C-M-w (append-next-kill) right before it. The C-M-w
tells the following command, if it is a kill command, to append the text
it kills to the last killed text, instead of starting a new entry. With
C-M-w, you can kill several separated pieces of text and
accumulate them to be yanked back in one place.
A kill command following M-w does not append to the text that M-w copied into the kill ring.
To recover killed text that is no longer the most recent kill, use the
M-y command (yank-pop). It takes the text previously
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.
If you know how many M-y commands it would take to find the text you want, you can yank that text in one step using C-y with a numeric argument. C-y with an argument restores the text from the specified kill ring entry, counting back from the most recent as 1. Thus, C-u 2 C-y gets the next-to-the-last block of killed text—it is equivalent to C-y M-y. C-y with a numeric argument starts counting from the “last yank” pointer, and sets the “last yank” pointer to the entry that it yanks.
The length of the kill ring is controlled by the variable
kill-ring-max; no more than that many blocks of killed text are
saved.
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
the command C-h v kill-ring.
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. To copy one block to many places, store it in a register (see Registers). Here we describe the commands to accumulate scattered pieces of text into a buffer or into a file.
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 prependings 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.
To retrieve the accumulated text from another buffer, use the command M-x insert-buffer; this too takes buffername as an argument. It inserts a copy of the whole text in buffer buffername into the current buffer at point, and sets the mark after the inserted text. Alternatively, you can select the other buffer for editing, then copy text from it by killing. See Buffers, for background information on buffers.
Instead of accumulating text within Emacs, in a buffer, you can append text directly into a file with M-x append-to-file, which takes filename as an argument. It 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.
The rectangle commands operate on rectangular areas of the text: all the characters between a certain pair of columns, in a certain range of lines. Commands are provided 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.
When you must specify a rectangle for a command to work on, you do it by putting the mark at one corner and point at the opposite corner. The rectangle thus specified is called the region-rectangle because you control it 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.
If point and the mark are in the same column, the rectangle they delimit is empty. If they are in the same line, the rectangle is one line high. This asymmetry between lines and columns comes about because point (and likewise the mark) is between two columns, but within a line.
kill-rectangle).
delete-rectangle).
yank-rectangle).
open-rectangle). This pushes the previous contents of the
region-rectangle rightward.
clear-rectangle).
string-rectangle).
The rectangle operations fall into two classes: commands for deleting and inserting rectangles, and commands for blank rectangles.
There are two ways to get rid of the text in a rectangle: you can
discard the text (delete it) or save it as the “last killed”
rectangle. The commands for these two ways are C-x r d
(delete-rectangle) and C-x r k (kill-rectangle). In
either case, the portion of each line that falls inside the rectangle's
boundaries is deleted, causing any following text on the line to
move left into the gap.
Note that “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 can only record 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. It is hard to define yank-popping for rectangles, so we do not try.
To yank the last killed rectangle, type C-x r y
(yank-rectangle). Yanking a rectangle is the opposite of killing
one. Point specifies where to put the rectangle's upper left corner.
The rectangle's first line is inserted there, the rectangle's second
line is inserted at the same horizontal position, but one line
vertically down, and so on. The number of lines affected is determined
by the height of the saved rectangle.
You can convert single-column lists into double-column lists using rectangle killing and yanking; kill the second half of the list as a rectangle and then yank it beside the first line of the list. See Two-Column, for another way to edit multi-column text.
You can also copy rectangles into and out of registers with C-x r r r and C-x r i r. See Rectangle Registers.
There are two commands you can use for making blank rectangles:
C-x r c (clear-rectangle) which blanks out existing text,
and C-x r o (open-rectangle) which inserts a blank
rectangle. Clearing a rectangle is equivalent to deleting it and then
inserting a blank rectangle of the same size.
The command 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 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 M-x cua-mode sets up key bindings that are
compatible with the Common User Access (CUA) system used in many other
applications. C-x means cut (kill), C-c copy, C-v
paste (yank), and C-z undo. Standard Emacs commands like
C-x C-c still work, because C-x and C-c only take
effect when the mark is active (and the region is highlighted).
However, if you don't want to override these bindings in Emacs at all,
set cua-enable-cua-keys to nil.
In CUA mode, using Shift together with the movement keys activates and highlights the region over which they move. The standard (unshifted) movement keys deactivate the mark, and typed text replaces the active region as in Delete-Selection mode (see Mouse Commands).
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.
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).
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>.
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; you can move point to a position saved in a register once, or many times.
Each register has a name, which consists of a single character. A register can store a number, a piece of text, a rectangle, a position, 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 a register r contains, use M-x view-register.
Bookmarks record files and positions in them, so you can return to those positions when you look at the file again. Bookmarks are similar enough in spirit to registers that they seem to belong in this chapter.
Saving a position records a place in a buffer so that you can move back there later. Moving to a saved position switches to that buffer and moves point to that place in it.
point-to-register).
jump-to-register).
To save the current position of point in a register, choose a name r and type C-x r <SPC> r. The register r retains the position thus saved until you store something else in that register.
The command C-x r j r moves point to the position recorded in register r. The register is not affected; it continues to hold the same position. 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.
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.
copy-to-register).
insert-register).
C-x r s r stores a copy of the text of the region into the register named r. C-u C-x r s r, the same command with a numeric argument, 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 numeric 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, rather than
appending it.
C-x r i r inserts in the buffer the text from register r. Normally it leaves point before the text and places the mark after, but with a numeric argument (C-u) it puts point after the text and the mark before.
A register can contain a rectangle instead of linear text. The rectangle is represented as a list of strings. See Rectangles, for basic information on how to specify a rectangle in the buffer.
copy-rectangle-to-register). With numeric argument, delete it as
well.
insert-register).
The C-x r i r command inserts a text string if the register contains one, and inserts a rectangle if the register contains one.
See also the command sort-columns, which you can think of
as sorting a rectangle. See Sorting.
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.
window-configuration-to-register).
frame-configuration-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.
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 Keyboard Macros).
number-to-register).
increment-register).
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.
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 in a register:
(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.)
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.
bookmark-set).
bookmark-jump).
list-bookmarks).
The prototypical use for bookmarks is to record one current position in each of several files. So the command C-x r m, which sets a bookmark, uses 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.
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 offers to save your bookmark values in your default bookmark file, ~/.emacs.bmk, if you have changed any bookmark values. You can also save the bookmarks at any time with the M-x bookmark-save command. 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, then 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.)
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:
bookmark-write, to
work with other files of bookmark values in addition to your default
bookmark file.
Since only part of a large buffer fits in the window, Emacs tries to show a part that is likely to be interesting. Display-control commands allow you to specify which part of the text you want to see, and how to display it. Many variables also affect the details of redisplay. Unless otherwise stated, the variables described in this chapter have their effect by customizing redisplay itself; therefore, their values only make a difference at the time of redisplay.
If a buffer contains text that is too large to fit entirely within a window that is displaying the buffer, Emacs shows a contiguous portion of the text. The portion shown always contains point.
Scrolling means moving text up or down in the window so that different parts of the text are visible. Scrolling “forward” or “up” means that text moves up, and new text appears at the bottom. Scrolling “backward” or “down” moves text down, and new text appears at the top.
Scrolling happens automatically if you move point past the bottom or top of the window. You can also scroll explicitly with the commands in this section.
recenter).
scroll-up).
scroll-down).
recenter).
reposition-window).
The most basic scrolling command is C-l (recenter) with
no argument. It scrolls the selected window so that point is halfway
down from the top of the window. On a text terminal, it also clears
the screen and redisplays all windows. That is useful in case the
screen is garbled (see Screen Garbled).
To read the buffer a windowful at a time, use C-v
(scroll-up) with no argument. This 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 nearly a
whole windowful of lines that were not previously visible. If point
was in the text that scrolled off the top, it ends up at the new top
of the window.
M-v (scroll-down) with no argument scrolls backward in
a similar way, also with overlap. The number of lines of overlap that
the C-v or M-v commands leave is controlled by the
variable next-screen-context-lines; by default, it is 2. The
function keys <NEXT> and <PRIOR>, or <PAGEDOWN> and
<PAGEUP>, are equivalent to C-v and M-v.
The commands C-v and M-v with a numeric argument scroll the text in the selected window up or down a few lines. C-v with an argument moves the text and point up, together, that many lines; it brings the same number of new lines into view at the bottom of the window. M-v with numeric argument scrolls the text downward, bringing that many new lines into view at the top of the window. C-v with a negative argument is like M-v and vice versa.
The names of scroll commands are based on the direction that the
text moves in the window. Thus, the command to scroll forward is
called scroll-up because it moves the text upward on the
screen. The keys <PAGEDOWN> and <PAGEUP> derive their names
and customary meanings from a different convention that developed
elsewhere; hence the strange result that <PAGEDOWN> runs
scroll-up.
Some users like the full-screen scroll commands to keep point at the
same screen line. To enable this behavior, set the variable
scroll-preserve-screen-position to a non-nil value. In
this mode, when these commands would scroll the text around point off
the screen, or within scroll-margin lines of the edge, they
move point to keep the same vertical position within the window.
This mode is convenient for browsing through a file by scrolling by
screenfuls; if you come back to the screen where you started, point
goes back to the line where it started. However, this mode is
inconvenient when you move to the next screen in order to move point
to the text there.
Another way to do scrolling is with C-l with a numeric argument. C-l does not clear the screen when given an argument; it only scrolls the selected window. With a positive argument n, it repositions text to put point n lines down from the top. An argument of zero puts point on the very top line. Point does not move with respect to the text; rather, the text and point move rigidly on the screen. C-l with a negative argument puts point that many lines from the bottom of the window. For example, C-u - 1 C-l puts point on the bottom line, and C-u - 5 C-l puts it five lines from the bottom. C-u C-l scrolls to put point at the center (vertically) of the selected window.
The C-M-l command (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.
Redisplay scrolls the buffer automatically when point moves out of the visible portion of the text. The purpose of automatic scrolling is to make point visible, but you can customize many aspects of how this is done.
Normally, automatic scrolling centers point vertically within the
window. However, if you set scroll-conservatively to a small
number n, then if you move point just a little off the
screen—less than n lines—then Emacs scrolls the text just
far enough to bring point back on screen. By default,
scroll-conservatively is 0.
When the window does scroll by a longer distance, you can control
how aggressively it scrolls, by setting the variables
scroll-up-aggressively and scroll-down-aggressively.
The value of scroll-up-aggressively should be either
nil, or a fraction f between 0 and 1. A fraction
specifies where on the screen to put point when scrolling upward.
More precisely, when a window scrolls up because point is above the
window start, the new start position is chosen to put point f
part of the window height from the top. The larger f, the more
aggressive the scrolling.
nil, which is the default, scrolls to put point at the center.
So it is equivalent to .5.
Likewise, scroll-down-aggressively is used for scrolling
down. The value, f, specifies how far point should be placed
from the bottom of the window; thus, as with
scroll-up-aggressively, a larger value is more aggressive.
The variable scroll-margin restricts how close point can come
to the top or bottom of a window. Its value is a number of screen
lines; if point comes within that many lines of the top or bottom of the
window, Emacs recenters the window. By default, scroll-margin is
0.
Horizontal scrolling means shifting all the lines sideways within a window—so that some of the text near the left margin is not displayed at all. When the text in a window is scrolled horizontally, text lines are truncated rather than continued (see Line Truncation). Whenever a window shows truncated lines, Emacs automatically updates its horizontal scrolling whenever point moves off the left or right edge of the screen. You can also use these commands to do explicit horizontal scrolling.
scroll-left).
scroll-right).
The command C-x < (scroll-left) scrolls the selected
window to the left by n columns with argument n. This moves
part of the beginning of each line off the left edge of the window.
With no argument, it scrolls by almost the full width of the window (two
columns less, to be precise).
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.
The value of the variable hscroll-margin controls how close
to the window's edges point is allowed to get before the window will
be automatically scrolled. It is measured in columns. If the value
is 5, then moving point within 5 columns of the 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. If it's
zero, horizontal scrolling centers point horizontally within the
window. If it's a positive integer, it specifies the number of
columns to scroll by. If it's a floating-point number, it specifies
the fraction of the window's width to scroll by. The default is zero.
To disable automatic horizontal scrolling, set the variable
auto-hscroll-mode to nil.
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.
You can specify various styles for displaying text using faces. Each face can specify various face attributes, such as the font family, the height, weight and slant of the characters, the foreground and background color, and underlining or overlining. A face does not have to specify all of these attributes; often it inherits most of them from another face.
On graphical display, all the Emacs face attributes are meaningful. On a text-only terminal, only some of them work. Some text-only terminals support inverse video, bold, and underline attributes; some support colors. Text-only terminals generally do not support changing the height and width or the font family.
Emacs uses faces automatically for highlighting, through the work of
Font Lock mode. See Font Lock, for more information about Font
Lock mode and syntactic highlighting. You can print out the buffer
with the highlighting that appears on your screen using the command
ps-print-buffer-with-faces. See PostScript.
You control the appearance of a part of the text in the buffer by
specifying the face or faces to use for it. The style of display used
for any given character is determined by combining the attributes of
all the applicable faces specified for that character. Any attribute
that isn't specified by these faces is taken from the default face,
whose attributes reflect the default settings of the frame itself.
Enriched mode, the mode for editing formatted text, includes several commands and menus for specifying faces for text in the buffer. See Format Faces, for how to specify the font for text in the buffer. See Format Colors, for how to specify the foreground and background color.
To alter the appearance of a face, use the customization buffer.
See Face Customization. You can also use X resources to specify
attributes of particular faces (see Resources). Alternatively,
you can change the foreground and background colors of a specific 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
name, with completion, and then set that face to use the specified
color. Changing the colors of the default face also changes
the foreground and background colors on all frames, both existing and
those to be created in the future. (You can also set foreground and
background colors for the current frame only; see Frame Parameters.)
If you want to alter the appearance of all Emacs frames, you need to
customize the frame parameters in the variable
default-frame-alist; see default-frame-alist.
Emacs can correctly display variable-width fonts, but Emacs commands that calculate width and indentation do not know how to calculate variable widths. This can sometimes lead to incorrect results when you use variable-width fonts. In particular, indentation commands can give inconsistent results, so we recommend you avoid variable-width fonts for editing program source code. Filling will sometimes make lines too long or too short. We plan to address these issues in future Emacs versions.
To see what faces are currently defined, and what they look like, type M-x list-faces-display. It's possible for a given face to look different in different frames; this command shows the appearance in the frame in which you type it. With a prefix argument, this prompts for a regular expression, and displays only faces with names matching that regular expression.
Here are the standard faces for specifying text appearance. You can apply them to specific text when you want the effects they produce.
defaultbolditalicbold-italicunderlinefixed-pitchvariable-pitchshadowHere'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.)
highlightisearchquery-replacelazy-highlightregionsecondary-selectiontrailing-whitespaceshow-trailing-whitespace is non-nil; see
Useless Whitespace.
nobreak-spaceescape-glyph When Transient Mark mode is enabled, the text of the region is
highlighted when the mark is active. This uses the face named
region; you can control the style of highlighting by changing the
style of this face (see Face Customization). See Transient Mark,
for more information about Transient Mark mode and activation and
deactivation of the mark.
These faces control the appearance of parts of the Emacs frame. They exist as faces to provide a consistent way to customize the appearance of these parts of the frame.
mode-linemodelinemodeline is an alias for the mode-line face, for
compatibility with old Emacs versions.
mode-line-inactivemode-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-highlighthighlight, but used for portions of text on mode lines.
mode-line-buffer-idheader-linemode-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.
vertical-bordermode-line-inactive face
on character terminals. On graphical displays the foreground color of
this face is used for the vertical line between windows without
scrollbars.
minibuffer-promptminibuffer-prompt-properties, which is a list of text
properties used to display the prompt text. (This variable takes
effect when you enter the minibuffer.)
fringescroll-barbordercursormousetool-bartooltipmenuFont Lock mode is a minor mode, always local to a particular buffer, which highlights (or “fontifies”) the buffer contents according to the syntax of the text you are editing. It can recognize comments and strings in most languages; in several languages, it can also recognize and properly highlight various other important constructs—for example, names of functions being defined or reserved keywords. Some special modes, such as Occur mode and Info mode, have completely specialized ways of assigning fonts for Font Lock mode.
Font Lock mode is turned on by default in all modes which support it. You can toggle font-lock for each buffer with the command M-x font-lock-mode. Using a positive argument unconditionally turns Font Lock mode on, and a negative or zero argument turns it off.
If you do not wish Font Lock mode to be turned on by default,
customize the variable global-font-lock-mode using the Customize
interface (see Easy Customization), or use the function
global-font-lock-mode in your .emacs file, like this:
(global-font-lock-mode 0)
This variable, like all the variables that control Font Lock mode, take effect whenever fontification is done; that is, potentially at any time.
If you have disabled Global Font Lock mode, you can still enable Font
Lock for specific major modes by adding the function
turn-on-font-lock to the mode hooks (see Hooks). For
example, to enable Font Lock mode for editing C files, you can do this:
(add-hook 'c-mode-hook 'turn-on-font-lock)
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 Face Customization.
You can also customize these faces using M-x set-face-foreground or M-x set-face-background. See Faces.
The variable font-lock-maximum-decoration specifies the
preferred level of fontification, for modes that provide multiple
levels. Level 1 is the least amount of fontification; some modes
support levels as high as 3. The normal default is “as high as
possible.” You can specify an integer, which applies to all modes, or
you can specify different numbers for particular major modes; for
example, to use level 1 for C/C++ modes, and the default level
otherwise, use this:
(setq font-lock-maximum-decoration
'((c-mode . 1) (c++-mode . 1)))
Fontification can be too slow for large buffers, so you can suppress
it for buffers above a certain size. The variable
font-lock-maximum-size specifies a buffer size, beyond which
buffer fontification is suppressed.
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. (See Left Margin Paren.) If you don't follow this convention, Font Lock mode can misfontify the text that follows an open-parenthesis or open-brace in the leftmost column that is inside a string or comment.
The variable font-lock-beginning-of-syntax-function (always
buffer-local) specifies how Font Lock mode can find a position
guaranteed to be outside any comment or string. In modes which use the
leftmost column parenthesis convention, the default value of the variable
is beginning-of-defun—that tells Font Lock mode to use the
convention. If you set this variable to nil, Font Lock no longer
relies on the convention. This avoids incorrect results, but the price
is that, in some cases, fontification for a changed text must rescan
buffer text from the beginning of the buffer. This can considerably
slow down redisplay while scrolling, particularly if you are close to
the end of a large buffer.
Font Lock highlighting patterns already exist for many 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:
(font-lock-add-keywords
'c-mode
'(("\\<\\(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, for
documentation of the format of this list.
Fontifying large buffers can take a long time. To avoid large delays when a file is visited, Emacs 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. The parts of the buffer that are not displayed are fontified “stealthily,” in the background, i.e. when Emacs is idle. You can control this background fontification, also called Just-In-Time (or JIT) Lock, by customizing variables in the customization group `jit-lock'. See Specific Customization.
Use M-x highlight-changes-mode to enable (or disable) Highlight Changes mode, a minor mode that uses faces (colors, typically) to indicate which parts of the buffer were changed most recently.
Hi Lock mode highlights text that matches regular expressions you
specify. For example, you might wish to see all the references to a
certain variable in a program source file, highlight certain parts in
a voluminous output of some program, or make certain names stand out
in an article. Use the M-x hi-lock-mode command to enable (or
disable) 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 Font Lock), except that you specify explicitly the regular expressions to highlight. You control them with these commands:
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)
C-x w h whim <RET> <RET>. Any face can be used for
highlighting, Hi Lock provides several of its own and these are
pre-loaded into a history list. While being prompted for a face use
M-p and M-n to cycle through them.
You can use this command multiple times, specifying various regular
expressions to highlight in different ways.
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-p to show the next older expression and
M-n 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.
highlight-lines-matching-regexp).
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).
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), t (highlight the patterns), 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 nil. 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.
On a graphical display, each Emacs window normally has narrow fringes on the left and right edges. The fringes display indications about the text in the window.
The most common use of the fringes is to indicate a continuation line, when one line of text is split into multiple lines on the screen. 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.”
The fringes indicate 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 empty lines, or where a program you are debugging is executing (see Debuggers).
You can enable and disable the fringes for all frames using M-x fringe-mode. To enable and disable the fringes for the selected frame, use M-x set-fringe-style.
On a graphical display, Emacs can indicate the buffer boundaries in the fringes. It indicates the first line and the last line 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 up and down.
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, 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)).
The value of the variable default-indicate-buffer-boundaries
is the default value for indicate-buffer-boundaries in buffers
that do not override it.
It is easy to leave unnecessary spaces at the end of a line, or empty lines at the end of a file, without realizing it. In most cases, this trailing whitespace has no effect, but there are special circumstances where it matters. It can also be a nuisance that the line has “changed,” when the change is just spaces added or removed at the end.
You can make trailing whitespace at the end of a line visible on the
screen by setting the buffer-local variable
show-trailing-whitespace to t. Then Emacs displays
trailing whitespace in 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.
To delete all trailing whitespace within the current buffer's accessible portion (see Narrowing), type M-x delete-trailing-whitespace <RET>. (This command does not remove the form-feed characters.)
Emacs can indicate unused lines at the end of the window with a small image in the left fringe (see Fringes). The image appears for window lines that do not correspond to any buffer text. Blank lines at the end of the buffer then stand out because they do not have this image in the fringe.
To enable this feature, set the buffer-local variable
indicate-empty-lines to a non-nil value. The default
value of this variable is controlled by the variable
default-indicate-empty-lines; by setting that variable, you
can enable or disable this feature for all new buffers. (This feature
currently doesn't work on text-only terminals.)
Emacs has the ability to hide lines indented more than a certain number of columns (you specify how many 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.
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.
If you have narrowed the buffer (see Narrowing), the size of the accessible part of the buffer is shown.
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. See Minor Modes, for more information about minor modes and about how to use this command.
If you have narrowed the buffer (see 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), then the line number doesn't appear.
Emacs doesn't compute the line number when the buffer is large, because
that would be too slow. Set it to nil to remove the limit.
Line-number computation can also be slow if the lines in the buffer
are too long. For this reason, Emacs normally doesn't display line
numbers if the average width, in characters, of lines near point is
larger than the value of the variable
line-number-display-limit-width. The default value is 200
characters.
You can also display the current column number by turning on Column Number mode. It displays the current column number preceded by the letter `C'. Type M-x column-number-mode to toggle this mode.
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 usually appears after the buffer name, before the mode names and
their parentheses. It 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 of running
processes in the whole system recently. (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 a graphical display 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 as “newly arrived mail”).
By default, the mode line is drawn on graphics displays with
3D-style highlighting, like that of a button when it is not being
pressed. If you don't like this effect, you can disable the 3D
highlighting of the mode line, by customizing the attributes of the
mode-line face. See Face Customization.
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.
ASCII printing characters (octal codes 040 through 0176) in Emacs buffers are displayed with their graphics, as are non-ASCII multibyte printing characters (octal codes above 0400).
Some ASCII control characters are displayed in special ways. The newline character (octal code 012) is displayed by starting a new line. The tab character (octal code 011) is displayed by moving to the next tab stop column (normally every 8 columns).
Other ASCII control characters are normally displayed as a caret
(`^') followed by the non-control version of the character; thus,
control-A is displayed as `^A'. The caret appears in face
escape-glyph.
Non-ASCII characters 0200 through 0237 (octal) are
displayed with octal escape sequences; thus, character code 0230
(octal) is displayed as `\230'. The backslash appears in face
escape-glyph.
If the variable ctl-arrow is nil, control characters in
the buffer are displayed with octal escape sequences, except for newline
and tab. Altering the value of ctl-arrow makes it local to the
current buffer; until that time, the default value is in effect. The
default is initially t.
The display of character codes 0240 through 0377 (octal) may be either as escape sequences or as graphics. They do not normally occur in multibyte buffers, but if they do, they are displayed as Latin-1 graphics. In unibyte mode, if you enable European display they are displayed using their graphics (assuming your terminal supports them), otherwise as escape sequences. See Unibyte Mode.
Some character sets define “no-break” versions of the space and
hyphen characters, which are used where a line should not be broken.
Emacs normally displays these characters with special faces
(respectively, nobreak-space and escape-glyph) to
distinguish them from ordinary spaces and hyphens. You can turn off
this feature by setting the variable nobreak-char-display to
nil. If you set the variable to any other value, that means to
prefix these characters with an escape character.
Normally, a tab character in the buffer is displayed as whitespace which
extends to the next display tab stop position, and display tab stops come
at intervals equal to eight spaces. The number of spaces per tab is
controlled by the variable tab-width, which is made local by
changing it. Note that how the tab character
in the buffer is displayed has nothing to do with the definition of
<TAB> as a command. The variable tab-width must have an
integer value between 1 and 1000, inclusive. The variable
default-tab-width controls the default value of this variable
for buffers where you have not set it locally.
You can customize the way any particular character code is displayed by means of a display table. See Display Tables.
You can customize the cursor's color, and whether it blinks, using
the cursor Custom group (see Easy Customization). On
a graphical display, the command M-x blink-cursor-mode enables
or disables the blinking of the cursor. (On text terminals, the
terminal itself blinks the cursor, and Emacs has no control over it.)
You can control how the cursor appears when it blinks off by setting
the variable blink-cursor-alist.
Some text terminals offer two different cursors: the normal cursor
and the very visible cursor, where the latter may be e.g. bigger or
blinking. 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
doesn't switch, so it uses the normal cursor.
Normally, the cursor appears in non-selected windows in the “off”
state, with the same appearance as when the blinking cursor blinks
“off.” For a box cursor, this is a hollow box; for a bar cursor,
this is a thinner bar. To turn off cursors in non-selected windows,
customize the variable cursor-in-non-selected-windows and assign
it a nil value.
On graphical displays, Emacs can optionally draw the block cursor
as wide as the character under the cursor—for example, if the cursor
is on a tab character, it would cover the full width occupied by that
tab character. To enable this feature, set the variable
x-stretch-cursor to a non-nil value.
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.
As an alternative to continuation, 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-only terminals, `$' appears in the first column when there is text truncated to the left, and in the last column when there is text truncated to the right.
Horizontal scrolling automatically causes line truncation
(see 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 is in effect. The default value is normally nil.
If the variable truncate-partial-width-windows is
non-nil, it forces truncation rather than continuation in any
window less than the full width of the screen or frame, regardless of
the value of truncate-lines. For information about side-by-side
windows, see Split Window. See also Display.
If the variable overflow-newline-into-fringe is
non-nil on a graphical display, then Emacs does not continue or
truncate a line which is exactly as wide as the window. Instead, the
newline overflows into the right fringe, and the cursor appears in the
fringe when positioned on that newline.
This section describes variables (see Variables) that you can change to customize how Emacs displays. Beginning users can skip it.
If the variable inverse-video is non-nil, Emacs attempts
to invert all the lines of the display from what they normally are.
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 someting to echo. See Echo Area.
The variable baud-rate holds the output
speed of the terminal, as far as Emacs knows. Setting this variable
does not change the speed of actual data transmission, but the value
is used for calculations. On text-only terminals, it affects padding,
and decisions about whether to scroll part of the screen or redraw it
instead. It also affects the behavior of incremental search.
On graphical displays, baud-rate is only used to determine
how frequently to look for pending input during display updating. A
higher value of baud-rate means that check for pending input
will be done less frequently.
On graphical display, Emacs can optionally display the mouse pointer
in a special shape to say that Emacs is busy. To turn this feature on
or off, customize the group cursor. You can also control the
amount of time Emacs must remain busy before the busy indicator is
displayed, by setting the variable hourglass-delay.
On graphical display, this variables specifies the vertical position of an overline above the text, including the height of the overline itself (1 pixel). The default value is 2 pixels.
On graphical display, Emacs normally draws an underline at the
baseline level of the font. If x-underline-at-descent-line is
non-nil, Emacs draws the underline at the same height as the
font's descent line.
On some text-only 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.
On a text-only terminal, when you reenter Emacs after suspending, Emacs
normally clears the screen and redraws the entire display. On some
terminals with more than one page of memory, it is possible to arrange
the termcap entry so that the `ti' and `te' strings (output
to the terminal when Emacs is entered and exited, respectively) switch
between pages of memory so as to use one page for Emacs and another
page for other output. On such terminals, you might want to set the variable
no-redraw-on-reenter non-nil; this tells Emacs to
assume, when resumed, that the screen page it is using still contains
what Emacs last wrote there.
Like other editors, Emacs has commands for searching for occurrences of a string. The principal search command is unusual in that it is incremental; it begins to search before you have finished typing the search string. There are also nonincremental search commands more like those of other editors.
Besides the usual replace-string command that finds all
occurrences of one string and replaces them with another, Emacs has a
more flexible replacement command called query-replace, which
asks interactively which occurrences to replace. There are also
commands to find and operate on all matches for a pattern.
You can also search multiple files under control of a tags
table (see Tags Search) or through the Dired A command
(see Operating on Files), or ask the grep program to do it
(see Grep Searching).
An incremental search 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>.
isearch-forward).
isearch-backward).
C-s starts a forward incremental search. It reads characters from the keyboard, and moves point past the next occurrence of those characters. If you type C-s and then F, that puts the cursor after the first `F' (the first following the starting point, since this is a forward search). Then if you type an O, you will see the cursor move to just after the first `FO' (the `F' in that `FO' may or may not be the first `F'). After another O, the cursor moves to just after the first `FOO' after the place where you started the search. At each step, the buffer text that matches the search string is highlighted, if the terminal can do that; the current search string is always displayed in the echo area.
If you make a mistake in typing the search string, you can cancel characters with <DEL>. Each <DEL> cancels the last character of search string. This does not happen until Emacs is ready to read another input character; first it must either find, or fail to find, the character you want to erase. If you do not want to wait for this to happen, use C-g as described below.
When you are satisfied with the place you have reached, you can type <RET>, which 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 would exit the search and then move to the beginning of the line. <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 other meta-characters).
When you exit the incremental search, it sets the mark where point was before the search. That is convenient for moving back there. In Transient Mark mode, incremental search sets the mark without activating it, and does so only if the mark is not already active.
Sometimes you search for `FOO' and find one, but not the one you expected to find. There was a second `FOO' that you forgot about, before the one you were aiming for. 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>.
After you exit 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 “search again.”
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. To edit the current search string in the minibuffer without replacing it with items from the search ring, type M-e. Type C-s or C-r to terminate editing the string and search for it.
You can change to searching backwards with C-r. For instance, if you are searching forward but you realize you were looking for something above the starting point, you can do this. Repeated C-r keeps looking for more occurrences backwards. A C-s starts going forwards again. C-r in a search can be canceled with <DEL>.
If you know initially that you want to search backwards, you can use
C-r instead of C-s to start the search, because C-r
as a key runs a command (isearch-backward) to search backward.
A backward search finds matches that end before the starting point,
just as a forward search finds matches that begin after it.
If your string is not found at all, the echo area says `Failing I-Search'. The cursor is after 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'. At this point there are several things you can do. If your string was mistyped, you can rub some of it out and correct it. If you like the place you have found, you can type <RET> or some other Emacs command 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 C-g “quit” character 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. The cursor moves 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.
An upper-case letter in the search string makes the search case-sensitive. If you delete the upper-case character from the search string, it ceases to have this effect. See Search Case.
To search for a newline, type C-j. To search for another control character, such as control-S or carriage return, you must quote it by typing C-q first. This function of C-q is analogous to its use for insertion (see Inserting Text): it causes the following character to be treated the way any “ordinary” character is treated in the same context. You can also specify a character by its octal code: enter C-q followed by a sequence of octal digits.
M-% typed 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. See Query Replace.
Entering <RET> when the search string is empty launches nonincremental search (see Nonincremental Search).
To customize the special characters that incremental search understands,
alter their bindings in the keymap isearch-mode-map. For a list
of bindings, look at the documentation of isearch-mode with
C-h f isearch-mode <RET>.
To enter non-ASCII characters in an incremental search, you can use C-q (see the previous section), but it is easier to use an input method (see Input Methods). If an input method is enabled in the current buffer when you start the search, you can use it in the search string also. Emacs indicates that by including the input method mnemonic in its prompt, like this:
I-search [im]:
where im is the mnemonic of the active input method.
You can toggle (enable or disable) the input method while you type
the search string with C-\ (isearch-toggle-input-method).
You can turn on a certain (non-default) input method with C-^
(isearch-toggle-specified-input-method), which prompts for the
name of the input method. The input method you enable during
incremental search remains enabled in the current buffer afterwards.
The characters C-w and C-y can be used in incremental search to grab text from the buffer into the search string. This makes it convenient to search for another occurrence of text at point. C-w copies the character or word after point as part of the search string, advancing point over it. (The decision, whether to copy a character or a word, is heuristic.) Another C-s to repeat the search will then search for a string including that character or word.
C-y is similar to C-w but copies all the rest of the current line into the search string. If point is already at the end of a line, it grabs the entire next line. Both C-y and C-w convert the text they copy to lower case if the search is currently not case-sensitive; this is so the search remains case-insensitive.
C-M-w and C-M-y modify the search string by only one character at a time: C-M-w deletes the last character from the search string and C-M-y copies the character after point to the end of the search string. An alternative method to add the character after point into the search string is to enter the minibuffer by M-e and to type C-f at the end of the search string in the minibuffer.
The character M-y copies text from the kill ring into the search string. It uses the same text that C-y as a command would yank. Mouse-2 in the echo area does the same. See Yanking.
When you pause for a little while during incremental search, it
highlights all other possible matches for the search string. This
makes it easier to anticipate where you can get to by typing C-s
or C-r to repeat the search. The short delay before highlighting
other matches helps indicate which match is the current one.
If you don't like this feature, you can turn it off by setting
isearch-lazy-highlight to nil.
You can control how this highlighting looks by customizing the faces
isearch (used for the current match) and lazy-highlight
(for all the other matches).
You can enable the use of vertical scrolling during incremental
search (without exiting the search) by setting the customizable
variable isearch-allow-scroll to a non-nil value. This
applies to using the vertical scroll-bar and to certain keyboard
commands such as <PRIOR> (scroll-down),
<NEXT> (scroll-up) and C-l (recenter).
You must run these commands via their key sequences to stay in the
search—typing M-x will terminate 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 feature also affects some other commands, such as C-x 2
(split-window-vertically) and C-x ^
(enlarge-window) which don't exactly scroll but do affect where
the text appears on the screen. In general, 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. (You type C-h c C-h l; it says view-lossage.)
Then you can put the following line in your .emacs file
(see Init 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.
Incremental search on a slow terminal uses a modified style of display that is designed to take less time. Instead of redisplaying the buffer at each place the search gets to, it creates a new single-line window and uses that to display the line that the search has found. The single-line window comes into play as soon as point moves outside of the text that is already on the screen.
When you terminate the search, the single-line window is removed. Emacs then redisplays the window in which the search was done, to show its new position of point.
The slow terminal style of display is used when the terminal baud rate is
less than or equal to the value of the variable search-slow-speed,
initially 1200. See also the discussion of the variable baud-rate
(see Customization of Display).
The number of lines to use in slow terminal search display is controlled
by the variable search-slow-window-lines. Its normal value is 1.
Emacs also has conventional nonincremental search commands, which require you to type the entire search string before searching begins.
To do 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
nonincremental search, search-forward, if the string you
specify is empty. (Such an empty argument would otherwise be
useless.) But it does not call search-forward right away. First
it checks the next input character to see if is C-w,
which specifies a word search.
See Word Search.
C-r <RET> does likewise, for a reverse incremental search.
Forward and backward nonincremental searches are implemented by the
commands search-forward and search-backward. These
commands may be bound to keys in the usual manner. The feature that you
can get to them via the incremental search commands exists for
historical reasons, and to avoid the need to find separate key sequences
for them.
Word search searches for a sequence of words without regard to how the words are separated. More precisely, you type a string of many words, using single spaces to separate them, and the string can be found even if there are multiple spaces, newlines, or other punctuation characters between these words.
Word search is useful for editing a printed document made with a text formatter. If you edit while looking at the printed, formatted version, you can't tell where the line breaks are in the source file. With word search, you can search without having to know them.
Word search as a special case of nonincremental search is invoked with C-s <RET> C-w. This is followed by the search string, which must always be terminated with <RET>. Being nonincremental, this search does not start until the argument is terminated. It works by constructing a regular expression and searching for that; see Regexp Search.
Use C-r <RET> C-w to do backward word search.
You can also invoke word search with C-s M-e C-w or C-r M-e C-w followed by the search string and terminated with <RET>, C-s or C-r. This puts word search into incremental mode where you can use all keys available for incremental search. However, when you type more words in incremental word search, it will fail until you type complete words.
Forward and backward word searches are implemented by the commands
word-search-forward and word-search-backward. These
commands may be bound to keys in the usual manner. They are available
via the incremental search commands both for historical reasons and
to avoid the need to find separate key sequences for them.
A regular expression (regexp, for short) is a pattern that denotes a class of alternative strings to match, possibly infinitely many. GNU Emacs provides both incremental and nonincremental ways to search for a match for a regexp. The syntax of regular expressions is explained in the following section.
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 control characters that do special things within an ordinary incremental search have the same function in incremental regexp search. Typing C-s or C-r immediately after starting the search retrieves the last incremental search regexp used; that is to say, incremental regexp and non-regexp searches have independent defaults. They also have separate search rings that you can access with M-p and M-n.
If you type <SPC> in incremental regexp search, it matches any
sequence of whitespace characters, including newlines. If you want to
match just a space, type C-q <SPC>. You can control what a
bare space matches by setting the variable
search-whitespace-regexp to the desired regexp.
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'.
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 by the functions
re-search-forward and re-search-backward. You can invoke
these with M-x, or bind them to keys, or invoke them by way of
incremental regexp search with C-M-s <RET> and C-M-r
<RET>.
If you use the incremental regexp search commands with a prefix
argument, they perform ordinary string search, like
isearch-forward and isearch-backward. See Incremental Search.
This manual describes regular expression features that users typically want to use. There are additional features that are mainly used in Lisp programs; see Regular Expressions.
Regular expressions have a syntax in which a few characters are special constructs and the rest are ordinary. An ordinary character is a simple regular expression which matches that same character and nothing else. The special characters are `$', `^', `.', `*', `+', `?', `[', and `\'. The character `]' is special if it ends a character alternative (see later). 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 simple example, we can concatenate the regular expressions `f' and `o' to get the regular expression `fo', which matches only the string `fo'. Still trivial. To do something nontrivial, you need to use one of the special characters. Here is a list of them.
`*' 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.
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.
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), from which 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.
Note that the usual regexp special characters are not special inside a character set. A completely different set of special characters exists inside character sets: `]', `-' and `^'.
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.
`^' 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.
For historical compatibility reasons, `^' can be used with this
meaning only at the beginning of the regular expression, or after
`\(' or `\|'.
For historical compatibility reasons, `$' can be used with this
meaning only at the end of the regular expression, or before `\)'
or `\|'.
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.
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.
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 `\|'.
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.
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.
`\b' matches at the beginning or end of the buffer
regardless of what text appears next to it.
The constructs that pertain to words and syntax are controlled by the setting of the syntax table (see Syntax).
Here is a complicated regexp—a simplified version of the regexp that Emacs uses, by default, to recognize the end of a sentence together with any whitespace that follows. We show its Lisp syntax to distinguish the spaces from the tab characters. In Lisp syntax, the string constant begins and ends with a double-quote. `\"' stands for a double-quote as part of the regexp, `\\' for a backslash as part of the regexp, `\t' for a tab, and `\n' for a newline.
"[.?!][]\"')]*\\($\\| $\\|\t\\| \\)[ \t\n]*"
This contains four parts in succession: a character set matching period, `?', or `!'; a character set matching close-brackets, quotes, or parentheses, repeated zero or more times; a set of alternatives within backslash-parentheses that matches either end-of-line, a space at the end of a line, a tab, or two spaces; and a character set matching whitespace characters, repeated any number of times.
To enter the same regexp in incremental search, you would type <TAB> to enter a tab, and C-j to enter a newline. You would also type single backslashes as themselves, instead of doubling them for Lisp syntax. In commands that use ordinary minibuffer input to read a regexp, you would quote the C-j by preceding it with a C-q to prevent C-j from exiting the minibuffer.
Incremental searches in Emacs normally ignore the case of the text they are searching through, if you specify the text in lower case. Thus, if you specify searching for `foo', then `Foo' and `foo' are also considered a match. Regexps, and in particular character sets, are included: `[ab]' would match `a' or `A' or `b' or `B'.
An upper-case letter anywhere in the incremental 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 string search. The effect ceases if you delete the upper-case letter from the search string.
Typing M-c within an incremental search toggles the case sensitivity of that search. The effect does not extend beyond the current incremental search to the next one, but it does override the effect of including an upper-case letter in the current search.
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 affects only the current buffer, but
there is a default value in default-case-fold-search that you
can also set. See Locals. This variable applies to nonincremental
searches also, including those performed by the replace commands
(see Replace) and the minibuffer history matching commands
(see Minibuffer History).
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>.
Global search-and-replace operations are not needed often in Emacs,
but they are available. In addition to the simple M-x
replace-string command which replaces all occurrences,
there is M-% (query-replace), which presents each occurrence
of the pattern and asks you whether to replace it.
The replace commands normally operate on the text from point to the
end of the buffer; however, in Transient Mark mode (see Transient Mark), when the mark is active, they operate on the region. The
basic replace commands replace one string (or regexp) with one
replacement string. It is possible to perform several replacements in
parallel using the command expand-region-abbrevs
(see Expanding Abbrevs).
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, narrow to that part of the buffer before doing the replacement (see Narrowing). In Transient Mark mode, when the region is active, replacement is limited to the region (see Transient Mark).
When replace-string exits, it leaves point at the last
occurrence replaced. It sets the mark to the prior position of point
(where the replace-string command was issued); use C-u
C-<SPC> to move back there.
A numeric argument restricts replacement to matches that are surrounded by word boundaries. The argument's value doesn't matter.
See Replacement and Case, for details about case-sensitivity in replace commands.
What if you want to exchange `x' and `y': replace every `x' with a `y' and vice versa? You can do it this way:
M-x replace-string <RET> x <RET> @TEMP@ <RET>
M-< M-x replace-string <RET> y <RET> x <RET>
M-< M-x replace-string <RET> @TEMP@ <RET> y <RET>
This works provided the string `@TEMP@' does not appear in your text.
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 pattern.
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, 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 `\n' refer here, as usual, to the entire
match as a string, and to a submatch as a string. n may be
multiple digits, and the value of `\n' is nil if
subexpression n did not match. You can also use `\#&' and
`\#n' 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). 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>
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.
If you want to change only some of the occurrences of `foo' to
`bar', not all of them, then you cannot use an ordinary
replace-string. Instead, 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. It
preserves case, like replace-string, provided
case-replace is non-nil, as it normally is
(see Replacement and Case). A numeric argument means consider
only occurrences that are bounded by word-delimiter characters.
C-M-% performs regexp search and replace (query-replace-regexp).
It works like replace-regexp except that it queries
like query-replace.
These commands highlight the current match using the face
query-replace. They highlight other matches using
lazy-highlight just like incremental search (see Incremental Search).
The characters you can type when you are shown a match for the string or regexp are:
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 Repetition).
Some other characters are aliases for the ones listed above: y, n and q are equivalent to <SPC>, <DEL> and <RET>.
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.
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 C-x ESC ESC.
See Operating on Files, for the Dired Q command which performs query replace on selected files. See also Transforming File Names, for Dired commands to rename, copy, or link files by replacing regexp matches in file names.
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 occur and its variants, all operate on the text from
point to the end of the buffer, or on the active region in Transient
Mark mode.
occur can not correctly
handle multiline matches.
The buffer `*Occur*' containing the output serves as a menu for finding the occurrences in their original context. Click Mouse-2 on an occurrence listed in `*Occur*', or position point there and type <RET>; this switches to the buffer that was searched and moves point to the original of the chosen occurrence. o and C-o display the match in another window; C-o does not select it.
After using M-x occur, you can use next-error to visit
the occurrences found, one by one. Compilation Mode.
occur, except it is able to search
through multiple buffers. It asks you to specify the buffer names one by one.
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.
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.
If a match is split across lines, this command keeps all those lines.
In this chapter we describe the commands that are especially useful for the times when you catch a mistake in your text just after you have made it, or change your mind while composing text on the fly.
The most fundamental command for correcting erroneous editing is the
undo command, C-x u or C-_ or C-/. This command
undoes a single command (usually), a part of a command (in the case of
query-replace), or several consecutive self-inserting
characters. Consecutive repetitions of the undo command undo earlier
and earlier changes, back to the limit of the undo information
available. See Undo, for more information.
The undo commands undo 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 as back these 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. Meanwhile, self-inserting
characters are usually grouped to make undoing less tedious.
undo).
To begin to undo, type the command C-x u (or its aliases, C-_ or C-/). This undoes the most recent change in the buffer, and moves point back to where it was before that change.
Consecutive repetitions of C-x u (or its aliases) undo earlier and earlier changes in the current buffer, back to the limit of the current buffer's undo records. If all the recorded changes have already been undone, the undo command just signals an error.
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. At this time, all the modifications you made have been canceled. 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 below.
Any command other than an undo command breaks the sequence of undo
commands. Starting from that moment, the previous undo commands
become ordinary changes that you can undo. Thus, to redo changes you
have undone, type C-f or any other command that will harmlessly
break the sequence of undoing, then type undo commands again. On the
other hand, 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.
Ordinary undo applies to all changes made in the current buffer. You can also perform selective undo, limited to the region.
To do this, specify the region you want, then run the undo
command with a prefix argument (the value does not matter): C-u
C-x u or C-u C-_. This undoes the most recent change in the
region. To undo further changes in the same region, repeat the
undo command (no prefix argument is needed). In Transient Mark
mode (see Transient Mark), any use of undo when there is an
active region performs selective undo; you do not need a prefix
argument.
Some specialized buffers do not make undo records. Buffers whose names start with spaces never do; these buffers are used internally by Emacs and its extensions to hold text that users don't normally look at or edit.
When the undo records for a buffer becomes too large, Emacs
discards the oldest undo records from time to time (during garbage
collection). You can specify how much undo records to keep by
setting three variables: undo-limit, undo-strong-limit,
and undo-outer-limit. Their values are expressed in units of
bytes of space.
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 20000. The variable undo-strong-limit sets a
stricter limit: a previous command (not the most recent one) which
pushes the size past this amount is itself forgotten. The default
value of undo-strong-limit is 30000.
Regardless of the values of those variables, the most recent change
is never discarded unless it gets bigger than undo-outer-limit
(normally 3,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 Reporting Bugs.
The reason the undo command has three key bindings, C-x
u, C-_ and C-/, is that it is worthy of a
single-character key, but C-x u is more straightforward for
beginners to remember and type. Meanwhile, C-- on a text-only
terminal is really C-_, which makes it a natural and easily
typed binding for undoing.
delete-backward-char).
backward-kill-word).
backward-kill-sentence).
The <DEL> character (delete-backward-char) is the most
important correction command. It deletes the character before point.
When <DEL> follows a self-inserting character command, you can think
of it as canceling that command. However, avoid the confusion of thinking
of <DEL> as a general way to cancel a command!
When your mistake is longer than a couple of characters, it might be more convenient to use M-<DEL> or C-x <DEL>. M-<DEL> kills back to the start of the last word, and C-x <DEL> kills back to the start of the last sentence. C-x <DEL> is particularly useful when you change your mind about the phrasing of the text you are writing. M-<DEL> and C-x <DEL> save the killed text for C-y and M-y to retrieve. See Yanking.
M-<DEL> is often useful even when you have typed only a few characters wrong, if you know you are confused in your typing and aren't sure exactly what you typed. At such a time, you cannot correct with <DEL> except by looking at the screen to see what you did. Often it requires less thought to kill the whole word and start again.
transpose-chars).
transpose-words).
transpose-sexps).
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 are
a good way of getting there. Otherwise, a reverse search (C-r)
is often the best way. See Search.
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,'.
C-M-t (transpose-sexps) is a similar command for
transposing two expressions (see Expressions), and C-x C-t
(transpose-lines) exchanges lines. They work like M-t
except as regards what 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 (word, expression, line) before or containing point across several other characters (words, expressions, 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 (word, expression, line) ending after point with the one ending after the mark.
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 Case.
This section describes the commands to check the spelling of a single word or of a portion of a buffer. These commands work with the spelling checker programs Aspell and Ispell, which are not part of Emacs. See the Aspell manual.
ispell-word).
ispell-complete-word).
Flyspell mode is a fully-automatic way to check spelling as you edit in Emacs. It operates by checking words as you change or insert them. When it finds a word that it does not recognize, it highlights that word. This does not interfere with your editing, but when you see the highlighted word, you can move to it and fix it. Type M-x flyspell-mode to enable or disable this mode in the current buffer.
When Flyspell mode highlights a word as misspelled, you can click on it with Mouse-2 to display a menu of possible corrections and actions. You can also correct the 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.
The other Emacs spell-checking features check or look up words when you give an explicit command to do so.
To check the spelling of the word around or before point, and
optionally correct it as well, use the command M-$
(ispell-word). If the word is not correct, the command offers
you various alternatives for what to do about it.
To check the entire current buffer, use M-x ispell-buffer. Use M-x ispell-region to check just the current region. 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.
The M-x ispell command spell-checks the active region if the Transient Mark mode is on (see Transient Mark), otherwise it spell-checks the current buffer.
Each time these commands encounter an incorrect word, they ask you what to do. They display a list of alternatives, usually including several “near-misses”—words that are close to the word being checked. Then you must type a single-character response. Here are the valid responses:
query-replace so you
can replace it elsewhere in the buffer if you wish. (The replacements
will be rescanned for more spelling errors.)
The command ispell-complete-word, which is bound to the key
M-<TAB> in Text mode and related modes, shows a list of
completions based on spelling correction. Insert the beginning of a
word, and then type M-<TAB>; the command displays a
completion list window. (If your window manager intercepts
M-<TAB>, type <ESC> <TAB> or C-M-i.) To
choose one of the completions listed, click Mouse-2 or
Mouse-1 fast on it, or move the cursor there in the completions
window and type <RET>. See Text Mode.
Once started, the Aspell or Ispell 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 time except when you do spelling correction.
Ispell and Aspell use two dictionaries together for spell checking: the
standard dictionary and your private dictionary. The variable
ispell-dictionary specifies the file name to use for the
standard dictionary; a value of nil selects the default
dictionary. The command M-x ispell-change-dictionary sets this
variable and then restarts the subprocess, so that it will use
a different standard dictionary.
Aspell and Ispell use a separate dictionary 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 root and affix information. For some languages
there is a spell checking dictionary but no word completion
dictionary.
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.
kmacro-start-macro).
kmacro-end-or-call-macro).
kmacro-end-macro).
kmacro-end-and-call-macro).
First end the definition of the keyboard macro, if currently defining it.
To immediately execute the keyboard macro again, just repeat the e.
apply-macro-to-region-lines).
To start defining a keyboard macro, type the F3 or C-x ( command
(kmacro-start-macro). 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, the F4 or C-x ) command (kmacro-end-macro) terminates the
definition (without becoming part of it!). For example,
C-x ( M-f foo C-x )
defines a macro to move forward a word and then insert `foo'.
The macro thus defined can be invoked again with the C-x e
command (kmacro-end-and-call-macro), which may be given a
repeat count as a numeric argument to execute the macro many times.
If you enter C-x e while defining a macro, the macro is
terminated and executed immediately.
After executing the macro with C-x e, you can use e repeatedly to immediately repeat the macro one or more times. For example,
C-x ( xyz C-x e e e
inserts `xyzxyzxyzxyz' in the current buffer.
C-x ) can also be given a repeat count as an argument, in which case it repeats the macro that many times right after defining it, but defining the macro counts as the first repetition (since it is executed as you define it). Therefore, giving C-x ) an argument of 4 executes the macro immediately 3 additional times. An argument of zero to C-x e or C-x ) means repeat the macro indefinitely (until it gets an error or you type C-g or, on MS-DOS, C-<BREAK>).
The key <F4> is like a combination of C-x ) and C-x e. If you're defining a macro, <F4> ends the definition. Otherwise it executes the last macro. For example,
F3 xyz F4 F4 F4
inserts `xyzxyzxyz' in the current buffer.
If you wish to repeat an operation at regularly spaced places in the text, define a macro and include as part of the macro the commands to move to the next place you want to use it. For example, if you want to change each line, you should position point at the start of a line, and define a macro to change that line and leave point at the start of the next line. Then repeating the macro will operate on successive lines.
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,
C-x ( C-a C-<SPC> C-n M-w C-x b f o o <RET> C-y C-x b <RET> C-x )
defines a macro that copies the current line into the buffer `foo', then returns to the original buffer.
You can use function keys in a keyboard macro, just like keyboard keys. You can even use mouse events, but be careful about that: 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. (Using the current mouse position would be even less predictable.)
One thing that sometimes works badly in a keyboard macro is the
command C-M-c (exit-recursive-edit). When this command
exits a recursive edit that started within the macro, it works as
you'd expect. But if it exits a recursive edit that started before
you invoked the keyboard macro, it also necessarily exits the keyboard
macro as part of the process.
After you have terminated the definition of a keyboard macro, you can add to the end of its definition by typing C-u F3 or C-u C-x (. This is equivalent to plain C-x ( followed by retyping the whole definition so far. As a consequence it re-executes the macro as previously defined.
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 C-x (.
The variable kmacro-execute-before-append specifies whether
a single C-u prefix causes the existing macro to be re-executed
before appending to it.
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.
All defined keyboard macros are recorded in the “keyboard macro ring,” a list of sequences of keys. There is only one keyboard macro ring, shared by all buffers.
kmacro-end-or-call-macro-repeat).
kmacro-cycle-ring-next).
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 C-x ) 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, C-x e 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.
kmacro-insert-counter).
kmacro-set-counter).
kmacro-add-counter).
kmacro-set-format).
Each keyboard macro has an associated counter. Normally, the macro counter is initialized to 0 when you start defining the macro, and incremented by 1 after each insertion of the counter value; that is, if you insert the macro counter twice while defining the macro, the counter will increase by 2 on each repetition of the macro.
The command C-x C-k C-i (kmacro-insert-counter) inserts
the current value of the current keyboard macro's counter, and
increments the counter by 1. You can use a numeric prefix argument to
specify a different increment. If you just specify a C-u
prefix, then the increment is zero, so it repeats the last inserted
counter value. For example, if you enter the following sequence while
defining a macro
C-x C-k C-i C-x C-k C-i C-u C-x C-k C-i C-x C-k C-i
it inserts `0112' in the buffer. The next two iterations of the macro will insert `3445' and `6778'.
This command usually only makes sense while defining a keyboard macro. But its behavior when no keyboard macro is being defined or executed is predictable: 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). 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.
kbd-macro-query).
Using C-x q (kbd-macro-query), you can get an effect
similar to that of query-replace, where the macro asks you each
time around whether to make a change. 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),
<DEL> (or n), <RET> (or q), C-l and C-r.
The answers are the same as in query-replace, though not all of
the query-replace options are meaningful.
These responses include <SPC> to continue, and <DEL> to skip the remainder of this repetition of the macro and start right away with the next repetition. <RET> means to skip the remainder of this repetition and cancel further repetitions. C-l redraws the screen and asks you again for a character to say what to do.
C-r enters 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 Recursive Edit.
Another way to vary the behavior of a keyboard macro is to use a register as a counter, incrementing it on each repetition of the macro. See RegNumbers.
kmacro-name-last-macro).
kmacro-bind-to-key).
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 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 need not
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 Lisp Libraries). If the file you
save in is your init file ~/.emacs (see Init 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.
kmacro-edit-macro).
edit-kbd-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 100 keystrokes as a macro by typing
C-x C-k l (kmacro-edit-lossage).
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:
self-insert-command commands).
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.