Introduction to Emacs

This note is essentially an excerpt from A Tutorial Introduction to Emacs by Keith Waclena.


NOTATION

In the rest of this document I use the standard Emacs notation to describe keystrokes:
C-x
For any x, the character Control-x.
M-x
For any x, the character Meta-x (Meta key is set to be Alt on our server).
C-M-x
For any x, the character Control-Meta-x.

SETTING UP EMACS

To set up emacs, you need to download a gzipped file, emacs.tar.gz, which we customized for the math prefresher. This zip file contains .emacs file as well as various mode files. .emacs file is the configuration file for your emacs. You can modify it to meet your own needs and preferences. The mode files such as ``Emacs Speak Statistics'' will be used in the Government Department quantitative courses as well as in the math prefresher.

Place this gzipped file in your home directory and issue the follow commands to unzip it; gunzip -v emacs.tar.gz and then tar -xvf emacs.tar or alternatively you can do tar -zxvf emacs.tar.gz to do it by one command.


STARTING EMACS

To start emacs, simply type emacs & at the command prompt. You can also type emacs filename & to open an existing file or create a new one.

For the first time you open emacs, you need to compile your configuration. Open emacs at the home directory by typing emacs .emacs & and then compile this file by using the menu bar, Emacs-Lisp, and then choose Byte-compile This file. Close emacs by using the menu bar, Files.


THE SCREEN

The Mode Line

The Emacs screen is completely devoted to the text of your file, except for one line near the bottom of the screen: the Mode Line. This line is displays important information including:

The Minibuffer

The blank line below the mode line is the minibuffer. The minibuffer is used by Emacs to display messages, and also for input when Emacs is prompting you to type something (it may want you to type yes or no in answer to a question, the name of a file to be edited, the long name of a command, etc).

The minibuffer is also known as the echo area, because Emacs echoes keystrokes here if you're typing really slowly. To see this, type any multi-character keystroke (like, ESC q) with a long pause between the keystrokes.


FILES AND BUFFERS

Manipulate Files

C-x C-f
find-file. This is the main command used to read a file into a buffer for editing. It's actually rather subtle. When you execute this command, it prompts you for the name of the file (with completion). Then it checks to see if you're already editing that file in some buffer; if you are, it simply switches to that buffer and doesn't actually read in the file from disk again. If you're not, a new buffer is created, named for the file, and initialized with a copy of the file. In either case the current window is switched to view this buffer.
C-x C-s
save-buffer. This is the main command used to save a file, or, more accurately, to write a copy of the current buffer out to the disk, overwriting the buffer's file, and handling backup versions.

Manipulate Buffers

C-x b
switch-to-buffer. Prompts for a buffer name and switches the buffer of the current window to that buffer. Doesn't change your window configuration. This command will also create a new empty buffer if you type a new name; this new buffer will not be visiting any file, no matter what you name it.
C-x C-b
list-buffers. Pops up a new window which lists all your buffers, giving for each the name, modified or not, size in bytes, major mode and the file the buffer is visiting.
C-x k
kill-buffer. Prompts for a buffer name and removes the entire data structure for that buffer from Emacs. If the buffer is modified you'll be given an opportunity to save it. Note that this in no way removes or deletes the associated file, if any.

Manipulate Windows

C-v
scroll-down. The basic command to scroll forward (towards the end of the file) one screenful. By default Emacs leaves you two lines of context from the previous screen.
M-v
scroll-up. Just like C-v, but scrolls backwards.
C-x o
other-window. Switch to another window, making it the active window. Repeated invocation of this command moves through all the windows, left to right and top to bottom, and then circles around again. Under a windowing system, you can use the left mouse button to switch windows.
C-x 0
delete-window. Deletes the current window.
C-x 1
delete-other-windows. Deletes all other windows except the current one, making one window on the screen. Note that this in no way deletes the buffers or files associated with the deleted windows.
C-x 2
split-window-vertically. Splits the current window in two, vertically. This creates a new window, but not a new buffer: the same buffer will now be viewed in the two windows. This allows you to view two different parts of the same buffer simultaneously.
C-x 3
split-window-horizontally. Splits the current window in two, horizontally. This creates a new window, but not a new buffer: the same buffer will now be viewed in the two windows. This allows you to view two different parts of the same buffer simultaneously.

Completion

To save you typing, Emacs offers various forms of completion: this means Emacs tries to complete for you partially typed file names, command names, etc. To invoke completion, you usually type TAB.

Backups and Auto Save Mode

Emacs never modifies your file on disk until you tell it to, but it's very careful about saving your work for you in a number of ways.
Backup files.
Emacs always saves the previous version of your file when you save. If your file is named foo, the backup will be called foo~ (note the squiggle). Although it is off by default, Emacs will keep any number of previous versions for you, named foo.~1~, foo.~2~, etc. You can decide how many versions are to be kept. (But Unix provides more powerful tools for managing multiple versions of files.)
Auto-Save files.
Emacs also, be default, auto-saves your file while you're editing it. The auto-save file for a file foo is called #foo#. If Emacs (or the system) were to crash before you could save your edits, you can recover almost all of it from this file. Auto-saving happens (by default) every 300 characters, or when a system error is encountered.

Searching and Replacing

Emacs has a variety of unusual and extremely powerful search and replace commands. The most important one is called incremental search. This is what the command isearch-forward, bound to C-s, does: it searches incrementally, one character at a time, as you type the search string. This means that Emacs can often find what you're looking for before you have to type the whole thing. To stop searching, you can either hit RET or type any other Emacs command (which will both stop the search and execute the command). You can search for the next match at any point by typing another C-s at any point; you can reverse the search by typing C-r; and you can use DEL to delete and change what you're searching for.

isearch-backward, bound to C-r, works the same way, but searches backward. (Use C-r to search for the next match and C-s to reverse the search.)

Occasionally you may want to search non-incrementally (though I rarely do). You can do this by typing C-s RET text RET, where text is the text to search for.

Much more useful is word search, which lets you search for a sequence of one or more words, regardless of how they're separated (e.g, by any number and combination of newlines and whitespace). To invoke word search, type C-s RET C-w word word word RET.

Emacs can also search incrementally (or not) by regular expressions; this is an extremely powerful feature, but too complex to describe here.

Replacement

Emacs' most important command for replacing text is called query-replace (bound to M-%). This command prompts you for the text to replace, and the text to replace it with, and then searches and replaces within the current buffer. query-replace is interactive: at each match, you are prompted to decide what to do; you have the following options:
SPC or Y
Perform this replacement.
DEL or N
Don't perform this replacement.
RET
Terminate query-replace without performing this replacement.
ESC
Same as RET.
.
Perform this replacement but then terminate the query-replace.
!
Perform this replacement and all the rest in the buffer without querying (ie unconditionally).

Motion and Objects

One of the main things one does in an editor is move around, in order to apply editing commands. Emacs provides many motion commands, which are arranged around textual objects: for each textual object, there is typically a motion command that moves forward over such an object and backward over it (or you can think of this as moving to the beginning and to the end).

Characters

C-f
forward-char. Moves forward (to the right) over a character.
C-b
backward-char. Moves backward (to the left) over a character.
The f for forward and b for backward mnemonic will reoccur.

Words

M-f
forward-word. Moves forward over a word.
M-b
backward-word. Moves backward over a word.
Note the f/b mnemonic. Also, as another mnemonic, note that M-f is like a "bigger" version of C-f.

Lines (vertically)

C-n
next-line. Moves down to the next line.
C-p
previous-line. Moves up to the previous line.
When moving by lines, the cursor tries to stay in the same column, but if the new line is too short, it will be at the end of the line instead. This is very important: Emacs doesn't insert spaces at the ends of lines (end of line is unambiguous).

Lines (horizontally)

C-a
beginning-of-line. Moves to the beginning of the current line.
C-e
end-of-line. Moves to the end of the current line.
E for end, A for the beginning of the alphabet.

Sentences

M-a
backward-sentence. Moves to the beginning of the current sentence.
M-e
forward-sentence. Moves to the end of the current sentence.
Note the mnemonic relation between C-a / M-a and C-e / M-e.

Paragraphs

M-{
backward-paragraph. Move to the beginning of the current paragraph.
M-}
forward-paragraph. Move to the end of the current paragraph.

Pages

C-x [
backward-page. Moves to the beginning of the current page.
C-x ]
forward-page. Moves to the end of the current page.
Pages are separated by formfeed characters (C-l) in most modes.

Buffers

M-<
beginning-of-buffer. Moves to the beginning of the buffer.
M->
end-of-buffer. Moves to the end of the buffer.

Deleting, Killing, Yanking and Undoing

Emacs' deletion commands are also based on the textual objects above. But first, a terminological distinction: Deletion means to remove text from the buffer without saving it; most deletion commands operate on small amounts of text. Killing means to save the removed text, so that it can be yanked back later someplace else.

Killed text is saved on the kill ring. The kill ring holds the last N kills, where N is 30 by default, but you can change it to anything you like by changing the value of the variable kill-ring-max. The kill ring acts like a fifo when you're killing things (after the 30th kill, kill number one is gone), but like a ring when you're yanking things back (you can yank around the ring circularly). kill-ring-max doesn't apply to the amount of text (in bytes) that can be saved in the kill ring (there's no limit), only to the number of distinct kills.

Characters

C-d
delete-char. Deletes the character to the right of (under, if the cursor is a block that covers a character) the cursor.
DEL
delete-backward-char. Deletes the character to the left of the cursor.
Remember, Emacs does not use C-h (aka Backspace) for deletion, but for help! Depending on your cultural background, this may well be the single hardest thing to learn about Emacs. Why does Emacs make this choice? Well, since there's no need for two commands to delete one character backward, and since DEL (aka Delete) can only be mnemonic for deletion while C-h is a nice mnemonic for help, the choice was made. Me, I've never used C-h to delete, so it suits me fine.

Words

M-d
kill-next-word. Kills to the end of the word to the right of the cursor (forward).
M-DEL
kill-last-word. Kills to the beginning of the word to the left of the cursor (backward).

Lines (horizontally)

C-k
kill-forward-line. Kills to the end of the current line, not including the newline. Thus, if you're at the beginning of a line it takes two C-k's to kill the whole line and close up the whitespace.
C-u 0 C-k
kill-back-line. Kills to the beginning of the current line, not including the newline.
You might think that C-u -1 C-k would be used to kill to the beginning of the line, and it does, but it includes the newline before the line as well.

Sentences

M-k
kill-forward-sentence. Kills to the end of the current sentence, including any newline within the sentence.
C-u -1 M-k
kill-back-sentence. Kills to the beginning of the current sentence, including any newlines within the sentence.

Paragraphs

The commands forward-kill-paragraph and backward-kill-paragraph exist, but are not bound to any keys by default.

Yanking

Once you've killed some text, how do you get it back? You can yank back the most recently killed text with C-y (yank). Since Emacs has only one kill ring (as opposed to one per buffer), you can kill in one buffer, switch to another and yank the text there.

Copying and Moving Text

Emacs has no need for special commands to copy or move text; you've already learned them! To move text, just kill it and yank it back elsewhere. To copy text, kill it, yank it back immediately (so it's as if you haven't killed it, except it's now in the kill ring), move elsewhere and yank it back again. For commands to copy and move arbitrary regions of text, as opposed to textual objects, see The Mark and The Region.

Infinite Undo with Redo

One of the most important Emacs commands is undo, invoked with C-_ (control underscore using space key). C-_ is a valid ASCII character, but some keyboards don't generate it, so you can also use C-x u -- but it's more awkward to type, since it's a two-character command.

The undo command allows you to undo your editing, back in time. It's handy when you accidentally convert all of a huge file to uppercase, say, or delete a huge amount of text. One keystroke changes everything back to normal.

We say Emacs has infinite undo because, unlike some editors, you can undo a long chain of commands, not only one previous one, even undoing through saves. We say Emacs has redo because you can reverse direction while undoing, thereby undoing the undo.

It's very important to get comfortable with undo as soon as possible; I recommend reading the undo section of the manual carefully and practising.


The Mark and The Region

Emacs can manipulate arbitrary chunks of text as well as distinct textual objects. The way this is done is to define a region of text; many commands will operate on this region.

The region is the text between point and mark. Point is actually the Emacs term for what we've been calling the cursor up to now. The mark, on the other hand, is set with a special command C-@ (set-mark-command). This sets the mark exactly where point is, but now you can move point backwards or forwards, and any text between constitutes the region.

Each buffer has a distinct point and mark at any moment (though you can always change them--just by moving the cursor changes the point), and therefore a distinct region. (It's also possible for there to be no mark in a buffer, and therefore no region.)

The region is unaffected by whether it begins with point or mark (that is, whether the cursor is currently located somewhere before mark in the textm, or somewhere after it) ; it makes no difference, just do what's convenient.

The region is normally invisible (but see C-x C-x), so don't forget where you place mark. You'll get used to this. However, if you're running Emacs under a windowing system, you can make the region visible by executing M-x transient-mark-mode.

Many commands that move point a significant distance (like M-< and C-s, for example) leave the mark set at the spot they moved from. You'll see "Mark set" in the echo area when this happens.

When using Emacs under a windowing system like X, the mouse can be used to sweep out the region, but many Emacsers find it faster to keep their hands on the keyboard and use the familiar motion commands.

There are some special commands that are specifically designed to set the region around some interesting text.

M-@
mark-word. Sets the region around the next word, or from point to the end of the current word, if you're in the middle of one.
M-h
mark-paragraph. Sets the region around the current paragraph.
C-M-@
mark-sexp. Sets the region around the same sexp that C-M-f would move to.
C-M-h
mark-defun. Sets the region around the current defun.
C-x C-p
mark-page. Sets the region around the current page.
C-x h
mark-whole-buffer. Sets the region around the entire buffer.

So now you know how to define the region: what can you do with it?

C-x C-x
exchange-point-and-mark. Swaps mark and point. Repeated rapid execution of this command makes it easy to see the extent of the region.
C-w
kill-region. Kills the region. It goes on the kill ring, of course.
M-w
kill-ring-save. Saves the region to the kill ring without removing it from the buffer (like a "copy" command). This is exactly equivalent to typing C-w C-y.
C-x C-i
indent-rigidly. Rigidly indents the region by as many characters (columns) as you provide as a numeric argument (default is 1 column).
C-x C-l
downcase-region. Convert the entire region to lowercase. This command is disabled by default.
C-x C-u
upcase-region. Convert the entire region to uppercase. This command is disabled by default.
M-x fill-region
fill-region. Fills, i.e., justifies with a ragged right margin, all the paragraphs within the region.
There are many, many more.

Help

Emacs has extensive online help, most of which is available via the help key, C-h. Type C-h twice to see a list of subcommands; type it three times to get a window describing all these commands (a SPC will scroll this window). Some of the most useful help commands are:
C-h a
command-apropos. Prompts for a keyword and then lists all the commands with that keyword in their long name.
C-h k
describe-key. Prompts for a keystroke and describes the command bound to that key, if any.
C-h i
info. Enters the Info hypertext documentation reader.
C-h m
describe-mode. Describes the current major mode and its particular key bindings.
C-h p
finder-by-keyword. Runs an interactive subject-oriented browser of Emacs packages.
C-h t
help-with-tutorial. Run the Emacs tutorial. This is very helpful for beginners.

Kosuke Imai
Last modified: Wed Aug 28 14:24:36 EDT 2002