Introduction to Emacs

Andy Harris

(originally appeared in Install, Configure, and Customize Slackware Linux

–Prima Tech 2000.  Reprinted with Permission.)

In this chapter, we willyou examine Emacs, a powerful and popular text editor.  We willYou look at many of the features available in Emacs, and explore how you can use it to enhance your text development efforts whether you are working on simple text documents, managing a web server, or writing complex programs.

Why a tText eEditor?

For those raised on GUI interfaces, it might seem strange to even need a text editor.  After all, Star Office and some of the other commercial materials available can do all that a text editor can and much more.  Modern word processors can handle text with formatting, graphics, and a host of special features.  All these things would factors make a program which simply edits text seem to be out of date, or even a little quaint.

Text editing was originally a very large part of computing, and it has never really gone away.  Most computer programs still ultimately start out as text files, no matter how elaborate they will beare when compiled.  WeYou might use fancy editors for writing code or for designing web pages, but eventually it all comes back to text editing.  Computer users find themselves constantly needing to edit text files.

Text editors really come into their own when you find yourself needing to access your computer remotely, or when you do not have access to all the graphical features of your editor.  This is especially common when you are using your computer as a web server or when you are doing some kind of programming.

Why cChoose Emacs?

Emacs is not the only choice of text editor in the linuxLinux world.  A number of other editors are usually included with linuxLinux or unixUnix installs.  These other editors, especially vi (Visual Editor) are also extremely popular.  Linux people are prone to have 'religious wars' about which editor they prefer, but it probably makes sense to know more than one.  Golfers have a lot of clubs in their bag, because every shot is a little bit different.  If you do a lot of text editing, you should know a number of editors, because some jobs require a very powerful editor such as Emacs, and some don't.  If you think you are going to be needing some high-powered text editing, it makes a lot of sense to add Emacs to your list of skills.

Emacs is especially useful if you will find yourself writing HTML pages or programs in languages likesuch as C, Java, or Perl.  We willIn this chapter, you learn examine how it can help you to efficiently write, test, and debug programs. We willYou also look at some of its exceptionally powerful features, including facilities for searching and replacing text,  features that aid in writing, editing and running macros, modes that let you interact with the linuxLinux environment without leaving your editor, and customization features that let you configure Emacs however you wish.

It is not my goal to turn you into an Emacs fanatic, feeling somehow superior to those unfortunate souls doomed to an eternity with vi or (shudder) pico.  I simply want to introduce you to a program that can radically change the way you do certain jobs.  Emacs is not a simple application. It has a learning curve, and it will requires some effort to master.  If you are willing to spend some time with it, you will probably find that it profoundly improves the way you do some of your work.

Understanding Emacs cConventions

It will make my job a lot easier if I startI’ll begin by describing some of the assumptions and conventions about Emacs.  Emacs assumes the same things about its users that linuxLinux does in general:  Emacs users are smart, they don't mind learning things, but they want excellent performance, solid reliability, and oh, yeah, they want it to be free. In all these ways, Emacs is very much in the same spirit as Linux itself.  Although Emacs is available in many forms, including some with GUIs, it is at its heart a text-based program. The assumption is that the user might want to use menus occaisonallyoccasionally for obscure commands, but will usually uses keyboard commands.

We willDo not assume any particular graphics shell, because they are largely irrelevant when you are doing text editing.  In fact, one of the primary reasons you may be interested in Emacs is because it gives you such tremendous power in text mode.  This can be very handy if you are using your computer remotely through telnet.  If your computer will be functioning as a web server, many of your clients will never see your graphic shell, but will only have access through telnet, which is a text-only interface.  Emacs is quite often run from a remote computer, or even from a dumb terminal.  For this reason, we cannot make any assumptions about how the user is connected, how the keyboard is mapped, or even what kinds of keys the user has on the keyboard.  This would seem to be a huge barrier, but Emacs has some clever solutions to this issue, as you will see soon.

This is shows how Emacs looks when run from a Telnet session.  Notice that it is text-only.

Here is the same file being edited under a graphical shell.

Emacs is heavily reliant on keyboard commands for control. Keyboard commands can be difficult to memorize, but this tends to not be as big a barrier as you might think.  First of all, most of the common commands have reasonably easy mnemonics, such as 'control-f' for 'forward a character' and 'control-b' for 'back a character'. Secondly, Emacs has a menu system, which you can use when you cannot remember a control sequence.  Thirdly, you will find that using keyboard commands can be self-reinforcing, because they are so much quicker than using a mouse or a menu.  If you are a touch typist, your hands will never need to leave the keyboard, even when you are sending complex commands to your editor.  Finally, you will find that you won't really ever need to make yourself a set of 'Emacs flash cards' to learn your command sequences, because the ones you use frequently will just etch themselves into your brain and your fingers. After you've had enough practice, you won't even have to think about a particular sequence, because it will just be automatic.

Caution

Before we get much farther here, there are a few is an important keystrokes you should know in case you get into trouble.  Emacs has a habit of opening windows on you, and occasionally giving you a strange window or prompt that you don’t know what to do with.  When you find yourself stuck, try ‘control-g’.  This is the ‘get me out of here’ command.  It is used much like the escape key is often used in other programs. 

 Control cCombinations

Many of the Emacs commands utilize the 'control' key.  As I mentioned before, Emacs is designed to work on a variety of different keyboards.  Fortunately, almost every keyboard made has a control key.  (Even my ancient 'first love', the TRS-80 model I, had a control key.  I was the envy of my neighborhood with that awesome 16K of memory!!   Sigh....). In any case, it is reasonable to assume a control key. In Emacs documentation, a control sequence is marked with a capital C followed by a dash, so Control + g would look like this: C-g

It is not surprising that all the most common commands are control commands.  The commands that are used for cursor movement, cutting and pasting, and all the other things that you do the most often are all simple control combinations.  Of course, with a standard keyboard, you still have a limited number of control combinations.  Emacs has a lot of commands, more than can be called with the control key and a single character, so Emacs uses a number of other tricks for controlling the program.  In addition to the normal control sequences, there are special multi-key sequences.  For example, all the file management commands start with C-x.  Finding (opening) a file is C-x C-f, and saving a file is C-x C-s.

Meta Combinations

Even these multi-key sequences are not enough to control the many commands that Emacs supports.  In addition to the control sequences, Emacs supports a second control key, called the 'meta' key.  Here's where things get just a little strange.  Most keyboards have a secondary control key, but they aren't all called the same thing. The keyboards in the Intel tradition have an 'Alt' key, Macintoshes have a 'Flower' key, and Sun workstations have a 'Diamond' key.  All of these keys have a common purpose, to invoke another set of control sequences.  The problem is that Emacs cannot always recognize these keys.  If, for example, the user is running Emacs from a windows-based telnet program, the alt key is mapped to the local telnet client, and will not be sent across the telnet connection. To avoid this kind of problem, Emacs has multiple ways of reading the meta key.  In a linuxLinux install, you will probably be able to use the 'alt' key as your meta key.  If that does not work, you can use the escape key instead.

Caution

One important thing about using the escape key as a meta key:  It does not act exactly like the control key.  When you activate a control sequence, you press the control key down and hold it down as you press another key.  If you are using 'alt' as your meta key, you can do pretty much the same thing.  If you are using the escape key, it must be pressed and released before you press the next key.

 

 

In any case, the meta key is used for a lot of commands, and in the Emacs documentation, it often looks like this:

  M-b

stands for

Meta key and b

One very interesting characteristic of meta sequences is that they tend to amplify control sequences.  For example, C-f means 'go forward one character', and M-f means 'go forward one word.'  Likewise, C-y means to yank (or paste) whatever was last cut.  M-y means to pull an earlier cut and paste it.  I'll explain these commands later, but the main point here is that control commands and meta commands are often related, and the meta command is usually a more powerful version of the control command.

M-x cCommands

There's a couple of other ways to get to commands in the Emacs environment.  One of the most powerful is by knowing a command's name.  For example, I can never remember what the command sequence for 'interactively spell the current buffer' is.  For me, it is easier to remember the name of the command, ispell-buffer.  When you can remember the name of a command, you can invoke it directly, with M-x. So, to start the spell checker, I type 'M-x ispell-buffer.' This will work even for commands that do not have a keystroke combination bound to them.

Using the mMenus

In addition to all these techniques, Emacs has a set of menus, which contain all the most useful commands.  In the GUI world, online menus are not anything shocking, but they are very unusual in text-based programs in the unixUnix tradition.  Most unixUnix editors do not have them.

Here is how the menus might look under a graphical shell.

If you are running Emacs in some kind of graphical shell, you can use your mouse to access the menus in the normal way.  If you are in a text mode, the mouse may not work correctly.  In most setups, you can use the F10 key to invoke the online menus.  If that doesn't work, you can try M-`  (Note that ` is the backtick, not the apostrophe.  It is often on the same key as the ~ tilde character).  If that doesn't work, you can always call up a crude form of menus with this command:

M-x tmm-menubar.

In any case, you should see a set of menu items pop up.  In text mode, the menus will look unusual, because they will be at the bottom of the screen, but after you play around, you will see that they act pretty typically.

In figure 13-04, you will see Emacs run with a text mode menu active.  Note that the menu is on the bottom, but all the same commands are available (Compare with figure 13-03).  You can access this kind of menu even when you are on a system without a GUI interface.

Example of text mode menu

 Here is the text-mode menu.  Note that the menu is on the bottom, but all the same commands are available.  You can access this kind of menu even with non-graphical systems or connections.

The oOnline hHelp sSystems

Emacs is also unusual in the amount of online help it provides. Unix-style programs are not generally known for excellent help systems, but Emacs has many kinds of help, some of which are pretty useful.  All the help commands can be accessed by  C-h, and the first one to learn is C-h ?, which will bring up a list of other help options.  There are a number of choices here, but we'll go through the most useful for beginners.

C-h t is a tutorial.  This brings up a window with a text file in it. The text file is instructions in how to get around in Emacs.  If you haven't already done so, you should take a break from reading, and run this tutorial.  It will get you up and running quickly.  You can't hurt anything, so just play around with it to get the basic ideas. The rest of this chapter will make a lot more sense when you've done a little playing on your own.  You will find that the tutorial takes you through many of the same topics as this chapter, and touches on a few other interesting things.

Getting aApropos hHelp

If you want help on some particular topic, you can invoke the apropos help feature with

C-h a

This will ask you for a particular keyword, and will search for any command name that contains that word.  It is kind of like an index system in a more traditional help system.  Like those indices, the results can sometimes be exactly what you are looking for, or they can be overwhelming and useless.

Finding all the cCurrent kKeystrokes

As you have already seen, Emacs has a bewildering number of commands. You can use the C-h b command to describe the current key bindings. This will open up a little window that will contain a list of all the keystroke commands Emacs recognizes, and what commands will be invoked by that sequence.

Getting mMore dDetailed hHelp

C-h i invokes info mode, which is a full-fledged, hypertext help system.  It has a lot of information.  It can be overwhelming, but it is as good a help system as you will find in the unixUnix editor world.

help commands

Key

command

what it does

C-h ?

help-for-help

shows a list of the help commands

C-h t

help-with-tutorial

runs the online tutorial

C-h a

command-apropos

allows user to search for a command containing a word

C-h m

describe-mode

describes anything special about the current setup

C-h b

describe-bindings

gives a list of the current key commands

C-h i

info

runs the special info help system

M-` (F10)

tmm-menubar

opens the menu in text mode

 

Basic eEditing

Well, the point of all this was to edit some text, so let's get going. As complicated as Emacs can be, editing text is very easy.  You just type it in, and it goes on the screen.

Cursor mMovement

You will usually want to be able to move around in your document, and Emacs gives you a number of ways to do that.  You can probably use your arrow keys in the normal way, but you might want to learn some other techniques as well.  These other techniques can be used without your hands ever leaving the main keyboard, and they allow for some more flexible options.

Character mMovement

The easiest kind of movement is a character at a time.  Use the arrows to go left, right, up, and down.  You can also use control characters, because the arrow commands are not available on every terminal.  C-f is forward, C-b is back, C-p is previous line, and C-n is next line.

If it's easier for you, remember that p is the last letter in 'up' and n is the last letter in 'down.'

Word and lLine mMovement

If you want to move more quickly through a file, you can move a word at a time.  To go forward a word, you can use M-f, and M-b goes back a word at a time.  Notice the relationship between the control combination and the meta combination.

To go to the beginning of the current line, use C-a.  C-e goes to the end of the current line.

Semantic mMovement

Emacs has the ability to move in even more powerful ways.  You can go forward or back in increments of a sentence, a paragraph, or a

screen. The following summarizes the various movement commands.

Adding an aArgument to a cCommand

You can also modify the movement commands by adding an argument to the command.  Precede the command with C-u and a number to make the command execute that number of times.  For example,

C-u 8 C-f

moves forward eight characters

C-u 4 M-b

moves back four words.

 

Movement commands

Key

command

what it does

C-f (right arrow)

forward-char

move forward one character

C-b (left arrow)

backward-char

move backwards one character

C-p (up arrow)

previous-line

move up one line

C-n (down arrow)

next-line

move down one line

M-f

forward-word

move forward one word

M-b

backward-word

move backwards one word

C-v

scroll-up

move cursor DOWN one screen in the document

M-v

scroll-down

move cursor UP one screen in the document

M-<

beginning-of-buffer

Go to the beginning of the document

M->

end-of-buffer

Go to the end of the document

C-a

beginning-of-line

go to beginning of line. (surprise.)

C-e

end-of-line

go to the end of the line

 

 Deleting Stuff

It is surprising how often the destructive commands come in play when creating text files.  Fortunately, Emacs provides a number of ways to delete text.

Characters

For the most part, you can use the normal delete and backspace keys to delete text a character at a time, but these commands will not always work as you suspect when you are accessing Emacs through a telnet session. Sometimes in this case you will need to explicitly set up your telnet program to send delete and backspace characters correctly.  In any case, you can always use C-d to delete the current character.  C-d acts like the typical delete key.  It deletes the character directly under the cursor, moving all following characters one character to the left.  The backspace key deletes the character to the left of the cursor.  The characters deleted by using the del key, the C-d command, or the backspace key are really gone, and cannot be 'yanked' back (more on the yank command in a few minutes.)  They can be retrieved by the undo command (C-x u.)

Deleting wWords, lLines, and sSentences

Often you will be manipulating larger units of text, and you will find yourself wanting to delete words, sentences, lines, or paragraphs at a time.  Emacs supports a number of commands for doing exactly this:

***{Begin Table]***

Deletion commands

Key Command What it Does

C-d (Del) delete-character Delete current char

M-d kill-word Delete current word

BackSpace(Del) backward-delete-character Delete previous char

M-Backspace backward-kill-word Delete previous word

C-k kill-line Delete rest of line

M-k kill-sentence Delete rest of sentence

C-x Backspace backward-kill-sentence Delete previous sentence

***{End Table]***

One note about killing a line:  A line usually goes until it reaches a carriage return character.  In Emacs, if you hit the C-k command, you will delete the entire line, but not the newline character.  If you hit C-k again, you will delete the newline character as well.

Marking a rRegion

Sometimes, you will want to delete things that do not exactly fit within the definitions of the above commands.  You can also mark an entire region and kill it all in one command.  There are a number of Emacs commands that operate on a region, so it is a good skill to have.  Unfortunately, Emacs does not display in any obvious way which text is in a region, so it can be a tricky concept to get used to.

Basically, here's how it works.  You're used to the cursor, which is visible, and indicates where the next character you type will go. In addition to this visible cursor, Emacs supports another cursor which is not visible.  This second cursor is called the mark. To work with a region, you move the visible cursor until it is at the beginning or end of some text you want to work with (for now, we'll just assume we want to delete the text.)  Use the C-space or C-@ command to set the mark at the current cursor position.  The two commands mean exactly the same thing, but not all  keyboards will support C-space.  At the bottom of the screen, you will see a 'mark set' message.

Now you can move the cursor to the other end of the text you wish to manipulate, and you can activate a region command, such as C-w kill-region).  Everything between the current cursor position and the mark will be deleted. 

TIP

Sadly, Emacs does not put a visible cursor where the mark is, but there is a terrific command for figuring out where the mark currently is.  It is C-x C-x, which means exchange-point-and-mark.  What this command does is move the cursor to wherever the mark was, and move the mark to where the cursor was. Use this command twice in a row to see the beginning and the end of a region.  It's a really good idea to do this before you run region commands like kill-region, because some of the other commands might move the mark without you knowing it has happened.

Yanking (pPasting) sStuff bBack

Deleting things can be therapeutic, but often you will not want something simply destroyed, but moved to another place in the document.  Most text editors provide some sort of cut, copy, and paste mechanism.  Emacs provides this capability, with a few twists.

Essentially, all of the kill commands (the ones with 'kill' in their Emacs name) are cut commands. What this means is if you delete a word, sentence, line, or paragraph, that text is automatically stored in a buffer which you will be able to access later.  The only deletion commands that do not have this behavior are the ones that work on only one character at a time.  In Emacs, pasting is called 'yanking'. (The authors of Emacs apparently loved mnemonics so much that they often changed the names of commands so they could make a keystroke that matched!)  The standard yank command is C-y.  This command causes the last element that was cut to be pasted back into the document at the current cursor position.

What makes this interesting is the way that things are added to the kill buffer.  Imagine the following line:

one two three four five

If we were to go to the beginning of the line, and hit M-d, we would delete one word (the word 'one') and it would be put in the kill buffer.  Now, if we moved somewhere else, and hit the C-y command, the contents of that buffer (the word one) would be pasted.  That's not at all surprising, but here's a twist:

What if we started with the same line, put our cursor at the beginning, and hit M-d 3 times?  Clearly, the line would now contain the values

four five

but the real question is "what is in the buffer?"  When we hit the yank command, we will see

one two three

If you do a series of identical kill commands, Emacs treats them all as one command, and places them together.  This is very handy, because most of the time you will want to move a series of words, lines, or sentences.

The kill ring

The kill buffer of Emacs is flexible in another way.  In many systems, there is only one buffer for copy and paste.  Emacs keeps track of the last thirty deletions! (more or less.  The exact number can be changed by the user)  To yank back earlier text, start with the C-y command, then hit M-y until you see the specific text you are looking for. If you keep hitting M-y, you will originally come back to the last thing killed.  Because of this behavior, the kill buffer in Emacs is more accurately referred to as a kill ring, because it can contain many items, and you can go around the ring to find them.

No doubt one of the reasons for Emacs' popularity is how much it adds to the bizarre vocabulary of techies.  It's fun just to be able to mutter things about 'yanking from the kill ring.'  Sometimes I love being a nerd...

TIP

Here's an interesting way to take advantage of the kill ring: If you have some kind of text that is difficult to type and that you will be using a lot in a document, you can type it once and kill it.  Then, whenever you need that phrase, you can yank it from the kill ring. This way you only have to type it once!

Insertion and deletion commands

Key

command

what it does

C-d (Del)

delete-character

Delete current char

BackSpace(Del)

backward-delete-character

Delete previous char

M-Backspace

backward-kill-word

Delete previous word

C-k

kill-line

Delete rest of line

M-k

kill-sentence

Delete rest of sentence

C-x Backspace

backward-kill-sentence

Delete previous sentence

C-@ (C-SPACE)

set-mark

set a boundary for copying or deleting

M-d

kill-word

remove next word, keep it in buffer

C-w

kill-region

cut from mark to here, keep in buffer

C-k

kill-line

cut from here to end of line, keep in buffer

C-y

yank

paste last thing put in buffer

M-y

yank-pop

paste previous buffer (C-y must happen first)

Files, wWindows, and bBuffers

Basic file management is a critical part of any text editor.  Emacs provides all the typical functionality, but adds some special features, such as the ability to work with multiple files at the same time, and the ability to have multiple windows open at once, even in a text-based environment.

Files

Of course, you will rarely write text without it being stored somehow in a file.  Emacs provides a number of ways to manipulate files, including features for managing multiple files at the same time.

Opening an eExisting fFile

When you are on the linuxLinux command line, you can open up Emacs with a file by typing 'Emacs filename' If the file already exists, Emacs will start with the file loaded in.  If the file does not already exist, you will get a blank screen associated with the filename you chose.

If you are already in Emacs, and you want to load in a file, you can use the 'find-file' command C-x f.

You will be prompted for a file name.  Enter the name of the file, and it will be loaded if it exists, or you will get a blank screen to write in if the file does not yet exist.  If you want to import a file into your current document, you can use C-x i to insert the file. The contents of the file will be inserted wherever the cursor currently is.

Saving a fFile

Saving a file is very simple.  The main way to do this is through the save-file command, C-x s.  This command will save the file using whatever name you have assigned.  Note that in Emacs, your files will always have a name, even if you have never saved them before.  If you want to save the file to another name (like a save as command in Windows) you can use C-x w, which stands for 'write-file'.

Editing Modes

By now you might have noticed that Emacs sometimes changes its behavior.  For example, if you use Emacs to edit an HTML file, you will see an HTML menu appear.  If you use Emacs to edit a java or perl program, Emacs might put all the comment characters in one color, and the keywords in another.  Also, if you are in a programming language, you might notice that Emacs automatically indents the code whenever you press a semicolon (the end-of-line character for many programming languages).  Emacs is capable of changing its behavior to manage special forms of editing.  This is one of the things that makes it so endearing to high-end users.  It keeps much of the same general characteristics, but it customizes itself to be useful in many contexts.  This is done through a technique called 'modes.'  Emacs has two kinds of modes, major and minor modes.

Major mModes

The major modes are generally related to kinds of editing.  There is a major mode for writing plain text (... and it's called ...   text mode!!!) There are also major modes for html, c language programming, typesetting with the Tex and LaTex languages, and even modes for reading email and playing games!  We will generally stick to text mode in this chapter, although it is certainly worth exploring the other modes.  You will probably find some very entertaining and useful modes in your implementation of Emacs.  To find out which modes are installed in your version of Emacs, use C-h p.  You will see a list of packages. If you select a package, you will see the modes in that package. In my version, I found 34 packages, most with at least a couple of modes.  That should keep you busy on a rainy day.  Most of the time, though, people only use a few standard modes.  Most of the modes are related to very specific programming languages or other kinds of specialized editing.

Once you are in a particular mode, you will see its name on the bottom line of the editor.  You can get more information about that mode by typing C-h m (describe-mode).  This will give you an overview of the mode you are in and any special key bindings that might be a part of this mode.

There are two major ways to get into a specific mode.  The first way is to simply open up a file.  Emacs recognizes a large number of file extensions and automatically opens up the correct mode most of the time.  Occasionall