Welcome to the Slackware Documentation Project

This is an old revision of the document!


Emacs

What is Emacs?

vi and its clones are very functional and powerful editors. However, they are often considered not particularly extensible. vim is a successful and powerful vi variant that shrugs this trend, being both extremely extensible and lightweight. However, many users prefer a more “heavy” and extensible editor. This is why many people (including the author of this chapter) prefer Emacs.

Emacs takes extensibility up to eleven. Outside of a core of C, the rest of Emacs is written in a Lisp variant, nearly all of which is exposed to you, so that you may configure it or even extend it at will (many good Emacs Lisp tutorials can be found on the Internet). People have written all sorts of extensions in Emacs Lisp, from syntax highlighting for an obscure language, to a built-in terminal. In fact, there's even a vi emulation mode within Emacs (called viper), so you can still get the modal editing that comes with vi, while having access to the power of the Emacs core.

Like vi, there are many variants of Emacs (termed “emacsen”). However, the one most commonly used (and the only one in Slackware) is GNU Emacs. When people reference “Emacs” directly, they almost always mean GNU Emacs.

Unlike vi, Emacs operates more like a traditional editor by default. This means that most keyboard shortcuts can be performed without repeatedly changing modes. You can open up a file and start typing away without having to learn what the modes do, or forgetting which one you are currently using.

Starting Out

Emacs can be started simply by running the emacs command in your terminal. When you first start it in a console without arguments, you will see something that resembles this:

Starting Out

If you are in X windows, Emacs may start a GUI instead of running in your console. If this is the case and you don't want a GUI, you can invoke it with the flag '-nw'.

While here, you can browse around using the keyboard arrow keys. Underlined elements are links, and you can activate them by moving over them and pressing Enter. The documentation mentioned is very good, and can help you get your bearings should you have any problems. Also note how they describe key sequences such as Ctrl+H, meaning press the h key while holding down the CTRL key. Same deal with M-`, meaning to hold the the Meta key (usually Alt) and press the backtick ` key. When they say (e.g.) Ctrl+X Ctrl+C, this means to press the x key while holding down the CTRL key, then press the x key while also holding down the CTRL key. Conveniently, this is also one of the more important commands in Emacs: to close it.

Alternatively, if you call emacs with a file name as an argument, it will open that file, just like vi. Upon doing this, you will be presented with the contents of the file in question. Here, you can navigate the document using traditional arrow keys and type in information at will without any issues.

Say you make some edits, and you now want to save your file. The following key sequence will do that: Ctrl+XCtrl+S. If you made a new file, you will be prompted for this in what is called the “minibuffer”, the blank line below the gray line at the bottom of the screen. Type in the file name of your choice, then hit Enter. If you don't want to save the file, you can press Ctrl+G, which aborts operations that ask for input. Do note that tab-completion is usually available for operations that use the minibuffer.

Should you want to open a new file within your same Emacs session, type in Ctrl+XCtrl+F. You will be prompted for a file name in the minibuffer. Emacs doesn't care whether it exists or not. If it doesn't exist, a new buffer will be created for it (the file will be created upon saving with Ctrl+XCtrl+S), or it will be opened as expected. However, the old file will still be open! You can switch back to it using Ctrl+XCtrl+B, entering in the file's name (or more technically, the buffer's name), then hitting Enter.

How to Move Around

Like vi, Emacs is also older than the arrow keys on your keyboard. Also, like in vi, using the arrow keys to navigate files is also supported. While the vi movement keys are more ergonomic, emacs's are more “mnemonic”. However, it is still very possible to operate using the main Emacs keybindings quickly and efficiently. Here is a table of the basic movement keybindings:

Emacs Cursor Movement

CommandResult
Ctrl+FMove the cursor one character to the right (forward)
Ctrl+BMove the cursor one character to the left (backward)
Ctrl+NMove the cursor one line down (next)
Ctrl+PMove the cursor one line up (previous)

Of course, like with vi it is also possible to repeat these commands with a numeric argument. If you type in M-1 M-0 Ctrl+P, or Ctrl+U 10 Ctrl+P, the cursor will move ten lines up. If you type in M-5 Ctrl+F or Ctrl+U 5 Ctrl+F, the cursor will move five characters to the right.

Getting Help

Emacs contains a great deal of documentation, to the point that it is often called a “self-documenting” editor. This is because it provides mechanisms for providing users with documentation while you are using it.

Here are some useful functions that display documentation (they all start with Ctrl+H):

Accessing Emacs Documentation

CommandResult
Ctrl+H f FUNCTION-NAME EnterShow documentation for function FUNCTION-NAME
Ctrl+H k Ctrl+X Ctrl+CShow documentation for the function bound to the keysCtrl+X Ctrl+C
Ctrl+H tShow the Emacs tutorial
Ctrl+H ?Show all help-related functions

Ctrl+H t is especially useful if you want or need practice using Emacs.

Calling Functions

As noted earlier, Emacs exports a large number of functions to for interactive use. Some of these, like those opening and saving files, are mapped to keys. Others (like the ones for moving to the beginning and end of lines) are not. To call them, you have to invoke them. Say we want to call the function “end-of-line”. We would do this:

M-x end-of-line Enter

And the cursor would move to the end of the line, as the function name suggests.

Emacs Cheat Sheet

While Emacs can be simple to use, its scope can easily be overwhelming. Below are some useful Emacs commands. Some aspects have been simplified, most notably regarding text selection. These concepts, and more, are described the Emacs manual, and various on-line tutorials. Decent summaries can also be gleaned from web searches.

Emacs Cheat Sheet

CommandResult
Ctrl+F Move the cursor one character to the right (forward)
Ctrl+B Move the cursor one character to the left (backward)
Ctrl+N Move the cursor one line down (next)
Ctrl+P Move the cursor one line up (previous)
Ctrl+H f FUNCTION-NAME Enter Show documentation for function FUNCTION-NAME
Ctrl+H k Ctrl+X Ctrl+C Show documentation for the function bound to the keys Ctrl+X Ctrl+C
Ctrl+H T Show the Emacs tutorial
Ctrl+H ? Show all help-related functions
M-` Access the Menu Bar
Ctrl+G Cancel the current operation. This is most useful when in the minibuffer.
M-X FUNCTION-NAME Enter Call the interactive function FUNCTION-NAME
M-1 M-0 Ctrl+N Move the cursor ten lines down
Ctrl+U 10 Ctrl+N Move the cursor ten lines down (same as above)
M-x beginning-of-line Move the cursor to the beginning of the current line
M-x end-of-line Move the cursor to the end of the current line
M-> Move the cursor to the end of the buffer
M-< Move the cursor to the beginning of the buffer
Ctrl+K Remove text from the cursor to the end of the line and place it into the kill ring
Ctrl+Space Enter selection mode (use normal motion keys to move around). Press C-space again to leave it.
Ctrl+W While in selection mode, delete the selected region, and store the result into the kill ring
M-W While in selection mode, store the selected region into the kill ring.
C-Y “Yanks” the contents of the kill ring and places them at the cursor's location
Ctrl+/ Undo the previous action. Unlike most other editors, this includes previous undo actions.
Insert Enable or disable overwriting characters
Ctrl+S asdf Enter Forward incremental search for the string “asdf”. Repeat Ctrl+S as needed to search for future items, or Ctrl+R (below) to search backwards.
Ctrl+R asdf Enter Backward incremental search for the string “asdf”. Repeat Ctrl+R as needed to search for future items, or Ctrl+S (above) to search forwards.
M-% old Enter new Enter Search for each instance of “old” and prompt you to replace it with “new”. You can force replacement of all items by typing ! at the replacement prompt.
Ctrl+X Ctrl+C Exit Emacs, prompting you to save each unsaved buffer before doing so
Ctrl+X Ctrl+S Save the currrent buffer to its file
Ctrl+X Ctrl+W new-file.txt Enter Save the current buffer to a file “new-file.txt”

Starting Emacs

Emacs can be started from the shell by simply typing emacs. When you are running X, emacs will (normally) come up with its own X window, usually with a menu bar at the top, where you can find the most important functions. On startup, emacs will first show a welcome message, and then after a few seconds will drop you in the *scratch* buffer. (See Section 17.2.)

You can also start emacs on an existing file by typing

%  emacs
/etc/resolv.conf

This will cause emacs to load the specified file when it starts up, skipping the welcome message.

Command Keys

As mentioned above, emacs uses Ctrl and Alt combinations for commands. The usual convention is to write these with Ctrl-letter and M-letter, respectively. So Ctrl+X means Ctrl+X, and M+X means Alt+X.

The letter M is used instead of A because originally the key was not the Alt key but the Meta key. The Meta key has all but disappeared from computer keyboards, and in emacs the Alt key has taken over its function.

Many emacs commands consist of sequences of keys and key combinations. For example, Ctrl+X Ctrl+C (that is Ctrl+X followed by Ctrl+C) quits Emacs, Ctrl+X Ctrl+S saves the current file. Keep in mind that Ctrl+X Ctrl+B is not the same as Ctrl+X b. The former means Ctrl+X followed by Ctrl+B, while the latter means Ctrl+X followed by just B.

Buffers

In emacs, the concept of 'buffers' is essential. Every file that you open is loaded into its own buffer. Furthermore, emacs has several special buffers, which do not contain a file but are used for other things. Such special buffers usually have a name that starts and ends with an asterisk. For example, the buffer that emacs shows when it is first started, is the so-called *scratch* buffer. In the *scratch* buffer, you can type text in the normal way, but text that is typed there is not saved when emacs is closed.

There is one other special buffer you need to know about, and that is the minibuffer. This buffer consists of only one line, and is always on the screen: it is the very last line of the emacs window, below the status bar for the current buffer. The minibuffer is where emacs shows messages for the user, and it is also the place where commands that require some user input are executed. For example, when you open a file, emacs will ask for its name in the minibuffer.

Switching from one buffer to another can be done with the command Ctrl+X b. This will prompt you for the name of a buffer (a buffer's name is usually the name of the file you are editing in it), and it gives a default choice, which is normally the buffer that you were in before you switched to or created the current buffer. Just hitting Enter will switch to that default buffer.

If you want to switch to another buffer than the default offered by Emacs, just type its name. Note that you can use so-called Tab-completion here: type the first few letters of the buffer's name and hit Tab; emacs will then complete the name of the buffer. Tab completion works everywhere in emacs where it makes sense.

You can get a list of open buffers by hitting Ctrl+X Ctrl+B. This command will usually split the screen in two, displaying the buffer you were working in in the top half, and a new buffer called *Buffer List* in the bottom half. This buffer contains a list of all the buffers, their sizes and modes, and the files, if any, that those buffers are visiting (as it is called in emacs). You can get rid of this split screen by typing Ctrl+X 1.

Modes

Every buffer in emacs has an associated mode. This mode is very different from the idea of modes in vi: a mode tells you what kind of buffer you are in. For example, there is text-mode for normal text files, but there are also modes such as c-mode for editing C programs, sh-mode for editing shell scripts, latex-mode for editing LaTeX files, mail-mode for editing email and news messages, etc. A mode provides special customizations and functionality that is useful for the kind of file you are editing. It is even possible for a mode to redefine keys and key commands. For example, in Text mode, the Tab key simply jumps to the next tab stop, but in many programming language modes, the Tab key indents the current line according to the depth of the block that line is in.

The modes mentioned above are called major modes. Each buffer has exactly one major mode. Additionally, a buffer can have one or more minor modes. A minor mode provides additional features that may be useful for certain editing tasks. For example, if you hit the Insert key, you invoke overwrite-mode, which does what you'd expect. There is also an auto-fill-mode, which is handy in combination with text-mode or latex-mode: it causes each line that you type to be automatically wrapped once the line reaches a certain number of characters. Without auto-fill-mode, you have to type M+Q to fill out a paragraph. (Which you can also use to reformat a paragraph after you've edited some text in it and it is no longer nicely filled out.)

Opening Files

To open a file in emacs, type Ctrl+X Ctrl+F

Emacs will ask you for the name of the file, filling in some default path for you (which is usually ~/ ). After you type the filename (you can use Tab completion) and hit ENTER, emacs will open the file in a new buffer and display that buffer on the screen.

Emacs will automatically create a new buffer, it will not load the file into the current buffer.

In order to create a new file in emacs, you cannot just go typing right away. You first have to create a buffer for it, and come up with a filename. You do this by typing Ctrl+X Ctrl+F and typing a filename, just as if you were opening an existing file. Emacs will notice that the file you typed doesn't exist, and will create a new buffer and report “(New file)” in the minibuffer.

When you type Ctrl+X Ctrl+F and then enter a directory name instead of a filename, emacs will create a new buffer in which you will find a list of all the files in that directory. You can move the cursor to the file that you are looking for and type , and emacs will open it.

There are in fact a lot more actions you can perform here, such as deleting, renaming and moving files, and so on. This is the dired-mode of emacs, which is basically a simple file manager.

When you have typed Ctrl+X Ctrl+F and suddenly change your mind, you can type Ctrl+G to cancel the action. Ctrl+G works almost everywhere where you want to cancel an action or command that you've started but don't want to finish.

Basic Editing

When you have opened a file, you can of course move around in it with the cursor. The cursor keys and PgUp, PgDn do what you'd expect. Home and End jump to the beginning and end of the line. (In older versions, they would actually jump to the beginning and end of the buffer.) However, there are also Ctrl and Meta (Alt) key combos that move the cursor around. Because you do not need to move your hands to another part of the keyboard for these, they are much quicker once you get used to them.

Basic emacs Editing Commands

Command Result
Ctrl+Bgo one character back
Ctrl+Fgo one character forward
Ctrl+Ngo one line down
Ctrl+Pgo one line up
Ctrl+Ago to the beginning of the line
Ctrl+Ego to the end of the line
M+Bgo one word back
M+Fgo one word forward
M+}go one paragraph forward
M+{go one paragraph backward
M+Ago one sentence backward
M+Ego one sentence forward
Ctrl+Ddelete the character under the cursor
M+Ddelete until the end of the current word
Ctrl+Vgo down one screen (i.e., PgDn)
M+Vgo up one screen (i.e., PgUp)
M+<go to the beginning of the buffer
M+>go to the end of the buffer
Ctrl+_undo the last change (can be repeated); note that you actually have to type SHIFT+CTRL+hyphen for this.
Ctrl+Kdelete to end of line
Ctrl+Sforward search
Ctrl+Rreverse search

Note that many Meta commands are parallel to the Ctrl commands except that they operate on larger units: while Ctrl+F goes forward one character, M+F goes forward an entire word, etc.

Also note that M+< and M+> require you to type Shift+ALT+, and Shift+Alt+. respectively, since < and > are on Shift+, and Shift+.. (Unless of course you have a different keyboard layout from the standard US layout.)

Note that Ctrl+K deletes (kills, as it is commonly called) all the text after the cursor to the end of the line, but doesn't delete the line itself (i.e., it doesn't delete the final newline). It only deletes the line if there was no text after the cursor. In other words, in order to delete a complete line, you have to put the cursor at the beginning of the line, and then hit Ctrl+K twice: once to delete the text on the line, and once to delete the line itself.

Saving Files

In order to save a file, you type Ctrl+X Ctrl+S

Emacs will not ask you for a filename, the buffer will just be saved to the file it was loaded from. If you want to save your text to another file, type Ctrl+X Ctrl+W

When you save the file for the first time in this session, emacs will normally save the old version of your file to a backup file, which has the same name appended with a tilde: so if you're editing a file cars.txt, emacs will create a backup cars.txt~.

This backup file is a copy of the file that you opened. While you are working, emacs will also regularly create an auto-save copy of the work you are doing, to a file named with hash signs: #cars.txt#. This backup is deleted when you save the file with Ctrl+X Ctrl+S.

When you are done editing a file, you can kill the buffer that holds it by typing Ctrl+X k

Emacs will then ask you which buffer you want to kill, with the current buffer as default, which you can select by hitting Enter. If you haven't saved your file yet, emacs will ask you if you really want to kill the buffer.

If you'd prefer to save the file with a new name so that you don't overwrite the original version, use Ctrl+X Ctrl+W instead. You may then give a new name for the file, and the buffer will be updated to reflect the contents of this new file, leaving the old file unchanged.

Quitting Emacs

When you are done with emacs altogether, you can type Ctrl+X Ctrl+C

This quits emacs. If you have any unsaved files, emacs will tell you so, and ask if you want to save them each in turn. If you answer no to any of these, emacs will ask for one final confirmation and then quit.

Chapter Navigation

Previous Chapter: vi

Next Chapter: Networking

Sources


In Other Languages
Translations of this page?:
QR Code
QR Code slackbook:emacs (generated for current page)