Emacs Tutorial

Table of Contents

1 About Emacs

Emacs is a text editor, not a word processor.

Word processor users are concerned with producing documents. They want to produce something that looks good, with correctly formatted titles,

Text editor users are concerned with editing text quickly and efficiently. They realise that using the keyboard is faster than using a mouse; they know that it’s quicker to jump to a word they can see by searching for it rather than scrolling down the page; they appreciate the fact that they can select everything between two quote marks quickly, they understand that difference between opening a line beneath the cursor and hitting return and they know why this can make editing quicker.

Text editor users don't want to format documents themselves, they want to mark them up so that other some other process will do the formatting.

Emacs was around a long time before Windows, it does things in slightly different way to Windows and new users can find this confusing. Many of the standard Windows shortcuts are different in Emacs, for example Control C doesn't copy in Emacs, Control V doesn't paste. Even the idea of copy and paste is different in Emacs. Many things in Emacs seem harder to do at first, but there is a reason for this: Emacs makes things easier for power users. Word processors are great for casual users, Emacs is for serious users.

Emacs is hard to learn, but it's worth learning.

2 License

Copyright (C) 2014 Tony Ballantyne. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

Code in this document is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

3 Conventions

Emacs commands generally involve the CONTROL key (sometimes labeled CTRL or CTL) or the META key (sometimes labelled EDIT or ALT). Rather than write that in full each time, we'll use the following abbreviations:

C-<chr> means hold the CONTROL key while typing the character <chr> Thus, C-f would be: hold the CONTROL key and type f.

M-<chr> means hold the META or EDIT or ALT key down while typing <chr>. If there is no META, EDIT or ALT key, instead press and release the ESC key and then type <chr>. We write <ESC> for the ESC key.

Important note: to end the Emacs session, type C-x C-c.

To quit a partially entered command, type C-g.

4 Files and Buffers

Even starting a new file seems overly complicated on Emacs…

Note that Emacs distinguishes between a File (saved to disk) and a buffer (a temporary store).

4.1 Buffers

Open Emacs and press

C-x b

The command <Switch to buffer (default <something>)> appears in the minibuffer at the bottom of Emacs.

Enter spoons in the minibuffer and hit enter.

An empty buffer appears. Enter some text: This is the spoons buffer

Press

C-x b

and enter knives in the minibuffer.

Enter some text in this buffer: This is the knives buffer

You've now created two buffers.

Press

C-x (right arrow)
C-x (left arrow)

repeatedly to move back and forth through the buffers. Note the different buffers Emacs has opened in addition to the two you have created.

4.2 Files

The buffers you have created so far aren't attached to any files. Close down Emacs, and all your work will be forgotten.

Enter

C-x b forks

to create a buffer named forks

Enter

C-x C-w

to write the buffer to a file. You enter the file's name and location in the minibuffer

This is a roundabout way to create and save a file. Here's an easier way:

C-x C-f         Visit a file
C-x C-s         Save a file

Try this now

  • Hit C-x C-f to visit a new file. Call this file pepper.
  • Enter some text on the screen: This is the pepper file.
  • Hit C-x C-s to save the file
  • You've now created a file.
  • Hit C-x c to close and exit emacs
  • Now open emacs again and revisit your pepper file:
  • C-x C-f and enter the path to pepper in the minibuffer
  • Change the text in the pepper file: This is now salt and pepper
  • Hit C-x C-w to save a copy of the edited file with a different name. Call this one cruet

4.3 Summary

You can now create buffers and files. You can open existing files and save them under different names. Here are the keybindings you've used so far:

C-x b Create Buffer
C-x C-w Write Buffer to File
C-x (right arrow) Move to next Buffer
c-x (left arrow) Move to previous Buffer
C-x C-f Visit File
C-x C-s Save File

5 Moving Around

The following commands are used for moving around the text.

C-f     Move forward a character
C-b     Move backward a character

C-n     Move to next line
C-p     Move to previous line

These are a hangover from the old days when keyboards didn't have arrow keys. Use the arrow keys instead if you find them easier.

The following commands are very useful. Practice using them.

C-a     Move to beginning of line
C-e     Move to end of line

M-a     Move back to beginning of sentence
M-e     Move forward to end of sentence

M-f     Move forward a word
M-b     Move backward a word

You can also use

M-(right arrow) Move forward a word
M-(left arrow)  Move backward a word

There are two more useful commands

M-<     Move to start of text
M->     Move to end of text

6 Editing

You can now create, open and save files and buffers. You can also move around the text. You're probably thinking that it would be easier to do these things in a normal text editor. This section introduces some commands that make editing faster and more efficient.

<Del> means the delete key <Backspace> means the backspace key

6.1 Deleting

C-<Del>                 Delete next word
C-<Backspace>           Delete previous word
C-k                     Kill all text to the end of the line
C-M-SHIFT-<Backspace>   Kill entire line

Don't forget to use C-a, C-e and so on to move around the text.

6.2 Undoing Mistakes

C-/ 
or
C-x u

You'll probably find C-/ the easiest to use on a standard UK English keyboard.

6.3 Transposing

Learn these, they save a surprising amount of time

C-t             Transpose two characters
M-t             Transpose two words 
C-x C-t         Transpose two lines
Practice using them to make the following sentences look like these ones.  

Don't forget the M-a, M-e etc commands when moving around. 

Don't forget the M-a, M-e etc commands when moving around. 

Practice uising thme make to the following look sentence like these ones.

6.4 Changing Case

M-u             Convert to uppercase to the end of the word
M-l             Convert to lowercase to the end of the word
M-c             Capitalize word

There is more to the above commands than meets the eye.

First, note how the point jumps to the end of the word when each command is called. This makes it easy to jump through a string of words, changing case or capitalizing as you wish.

Second, note that to capitalize a whole word you need to be at the start of the word. You can either use M-b to jump back a word, or you can use the following:

M-- M-u         Convert previous word to uppercase
M-- M-l         Convert previous word to lowercase
M-- M-c         Capitalize previous word

M– means (Alt) and -

The above are very useful, they work even if the point is already in the word.

6.5 Miscellaneous

M-^             Join this line with the previous line;
                Removes the newline between the two lines.
C-x C-o         Delete white space after line up to next line.  Close the gap.
M-SPACE         Delete all spaces but one between two characters

7 Three Important Things

7.1 If Emacs stops responding

Whilst you're learning Emacs you might find that it seems to freeze. This is probably because you've unwittingly entered a command and Emacs is waiting for you. You can escape from whatever Emacs is doing by pressing C-g a few times

C-g      Escape

7.2 Disabled Commands

Some Emacs commands are "disabled" so that beginning users cannot use them by accident.

If you type one of the disabled commands, Emacs displays a message saying what the command was, and asking you whether you want to go ahead and execute the command.

If you really want to try the command, type <SPC> (the Space bar) in answer to the question.

As a beginner you probably won't want to execute the disabled command. Answer the question with "n".

Type C-x C-l (which is a disabled command), then type n to answer the question.

7.3 Windows

Somewhat confusingly, what Emacs calls a window is not what most people nowadays think of as a window. Try the following commands to see what Emacs thinks a window is.

C-x 2    Split the frame into two horizontal windows
C-x 3    Split the frame into two vertical windows

You probably won't need to use these two commands so much when you first start using Emacs. You will need the following commands though.

C-x 1    Get rid of all the windows apart from the current window. 
C-x 0    Get rid of the current window

8 Copying and Pasting

Copying and pasting is a little more complicated on Emacs, but a lot more powerful. First note that Emacs talks of killing and yanking, rather than copying and pasting (remember these words predate the Windows terms!)

8.1 Commands

C-k    Kill to the end of the line
M-k    Kill to the end of the sentence 
C-w    Kill the region (the selected area)
M-w    Copy the region (the selected area)
C-y    Yank (or paste)
M-y    Yank from the kill ring

You will also need to know how to select a region. You can do this using a mouse drag or using shift and the arrow keys, just like in windows, but Emacs has its own way of doing things. Note the terminology: a region in Emacs exists between the mark (the beginning of the region) and the point, the end of the region.

C-<Space>    Set the mark at the point (turn on region select)
Use the standard movement keys (for example C-e, or the arrow keys) to define the region
C-g          Turn off the region
C-x C-x      Swap the mark and the point.  Useful for moving back to the beginning of selected text
M-h          Select a paragraph
C-x h        Select all

The above may seem a little complicated. An exercise follows to help this make more sense.

8.2 Yank and Kill: more intelligent Copy and Paste

Here is an exercise to demonstrate. We're going to enter the following rhyme

Here we go round the mulberry bush
the mulberry bush
the mulberry bush
Here we go round the mulberry bush
On a cold and frosty morning
Type in the first line:

Here we go round the mulberry bush

Now C-a to move the point to the front of the line
C-<Space> to turn on selection
C-e to move to the end of the line

The first line should now be highlighted. 

M-w to copy the highlighted region to the kill ring.  We're keeping this for later... 
C-g to turn off the highlighted region
M-f a few times to move the cursor to just before 'the'
C-k to kill the rest of the line. 'the mulberry bush' should vanish
C-y to yank back the mulberry bush
Press enter and C-y to yank back a copy of the mulberry bush
Press enter and C-y again

You should now have the first three lines of the verse.

Move to a new line and C-y.  This should yank back the 'mulberry bush' again. 
But we want the whole first line, the first thing you copied to the kill ring...
Press M-y to move to the previous item in the kill ring

Finally type in 'on a cold and frosty morning'

8.3 Copying and Pasting from other Programs

This is can be a nuisance, especially for beginners. The simplest way to begin with is to use the mouse and the menu commands to copy and paste from and to Emacs.

9 Sexps

A Sexp is is short for s-expression, an old LISP term. A sexp is a pair of balanced parentheses.

"Another sexp"

(This is also a sexp)

[Here's another one]

You may have noticed how Emacs flashes the cursor when you type a closing parenthesis, just so you can check that they balance.

C-M-b           Moves backward over the next sexp. 
C-M-f           Moves forward over the next sexp. 
C-M-u           Move backward up one level of parens. 
C-M-d           Move down one level of parens.
C-M-SPACE       Select sexp

C-M-SPACE is particularly useful

(Outer brackets (inner brackets 1) (inner brackets 2(inner inner brackets)))(More outer brackets)

10 Searching and Replacing

10.1 Searching

Use searching on Emacs as often as possible. It's often faster to search for a word half way down the screen than to scroll there directly.

C-s    Search forward
C-r    Search backward (reverse)

Press C-s to start a search.  You will see I-search: appear in the echo area. 

Type in the word reindeer and watch what happens as you press each letter.  
Press C-s repeatedly to cycle through all the reindeer.  
Press C-r to go through backwards.  
Don't forget you can use C-g to cancel the search.

reindeer
Tall reindeer
A reindeer pulling a sleigh

The best way to see how search works is to do it.

10.2 Replacing

M-%             Query replace

Note that Emacs will search from the point forward. Use M-< to jump to the start of the buffer if you want to do a whole buffer search and replace.

Type y to replace one match, ! to replace all, ? for more options

10.3 Regexp Search and Replace

C-M-s           Regexp Search
C-M-%           Regexp Search and Replace

If you know how to use regexps, this is very powerful. Read the Emacs manual for more details

11 Universal Modifier

C-u             modifies the following command.
C-u 5 p         prints ppppp
C-u 5 C-f       moves the cursor 5 spaces forward
C-u 3 C-k       kills the following 3 lines

If you don't type a number, C-u defaults to 4

You can also use M-(number), so M-6 F prints FFFFFF which saves time when entering Hex.

12 Basic LISP

LISP is derived from the term LISt Processing. A list in LISP looks like this

(Knife Fork Spoon)

or like these two

(set-background-color "yellow")

(set-background-color "white")

If the first item in the list is a function you can evaluate the list by placing the cursor at the end of the list and pressing C-x C-e. Try it with the two lists above to turn the background yellow and then to set it white again.

If you try to evalute the (Knife Fork Spoon) list you'll get an error telling you that Knife is a void function.

Try evaluating the following lists:

  • (linum-mode) (C-x C-e, remember?)
  • (* 2 3) -look in the echo area at the bottom of the window to see the result
  • (+ 4 5)
  • (message "Hello! This is the echo area!")

It's worth noting that you can also evaluate a function by typing M-x (function name). So M-x visual-line-mode will turn word wrap on and off. Emacs supports TAB completion, so typing M-x visu and pressing TAB is enough to fill in the function name.

You can set a variable as follows

(set 'name 'John)

name

Press C-x C-e after the first line to set the variable, then after the second to see the contents of the variable "name"

Press C-x C-e after the following

(name)

and you'll get an error. name is a variable, (name) is a function, and you haven't defined a function called name.

It's a nuisance typing in ' all the time, so the following is often used

(setq animal 'cat)

Evaluate the above and then evaluate animal …

C-u C-x C-e will insert any output directly in the text area, rather than in the echo area.

Here is a list of cheeses called cheese:

(setq cheese '(Stilton Wensleydale Cheddar Cheshire))

Evaluate the list.

The first item in a list is called the car, the remaining items are called the cdr (pronounced could-er) The Emacs Lisp tutorial will tell you why. Evaluate the following

(car cheese) (cdr cheese)

13 The .emacs File

The .emacs file is loaded when Emacs is first run. It's used to configure Emacs. In case you don't know, the . at the front means the file is hidden on linux systems - hidden so that it doesn't clutter up your directories, not hidden to keep it a secret.

The .emacs file is found in your home directory. You can easily find this by evaluating (getenv "HOME") (C-x C-e, remember)

An even easier way is to use the linux shortcut ~. Type C-x C-f ~\.emacs will open the .emacs file. This works even on Windows systems.

A good way to see .emacs in action is to place (set-background-color "yellow") at the start of it. Close emacs and open it. If the screen is yellow, you know that you've done everything right.

14 Modes

Emacs can operate in different modes according to what you're editing. This is useful if you're editing something in a particular programming language, for example. Some modes are

  • java-mode
  • html-mode
  • python-mode

Emacs is usually clever enough to switch to the correct mode if you open a file with a recognised extension, so opening foo.java will switch to java mode.

You can also switch modes by typing, for example.

M-x java-mode

The above are all examples of major modes. Emacs also has a number of minor modes. A major mode can have more than one minor mode attached to it.

14.1 Useful Major Modes

14.1.1 Calculator Mode

  1. Calculator Mode
    M-x calc or C-x * c             for Calculator Mode
    C-x * k                         for Keypad Mode
    

    Hit q to quit

    Quick Demo: RPN calculation. In RPN, you type the input number(s) first, then the command to operate on the numbers.

    Type 2 <RET> 3 + Q to compute the square root of 2+3, which is 2.2360679775.

    Type P 2 ^ to compute the value of `pi' squared, 9.86960440109.

    Type <TAB> to exchange the order of these two results.

    Type - I H S to subtract these results and compute the Inverse Hyperbolic sine of the difference, 2.72996136574.

    Type <DEL> to erase this result.

    Algebraic calculation. You can also enter calculations using conventional “algebraic” notation. To enter an algebraic formula, use the apostrophe key.

    Type ' sqrt(2+3) <RET> to compute the square root of 2+3.

    Type ' pi ^ 2 <RET> to enter `pi' squared. To evaluate this symbolic formula as a number, type =.

    Type ' arcsinh($ - $$) <RET> to subtract the second-most-recent result from the most-recent and compute the Inverse Hyperbolic sine.

  2. Grab Mode

    Type C-x * g to “grab” these numbers into Calc.

    1.23 1.97 1.6 2 1.19 1.08

    The result '[1.23, 1.97, 1.6, 2, 1.19, 1.08]' is a Calc vector. Type V R + to compute the sum of these numbers. (V for Vector, R for Reduce)

    Type U to Undo this command, then type V R * to compute the product of the numbers.

    You can also grab data as a rectangular matrix. Place the cursor on the upper-leftmost '1' and set the mark, then move to just after the lower-right '8' and press C-x * r.

    Type v t to transpose this 3x2 matrix into a 2x3 matrix. Type v u to unpack the rows into two separate vectors. Now type V R + <TAB> V R + to compute the sums of the two original columns.

    Read the documentation for more details

14.1.2 Picture Modes

You can draw pictures in emacs using text. Try picture-mode and artist-mode. artist-mode is the most fun…

14.1.3 Org Mode

Org Mode is so important it gets a tutorial to itself…

14.2 Useful Minor Modes

Use M-x (mode name) to toggle the following on and off

  • M-x linum-mode: display line numbers
  • M-x whitespace-mode: Show spaces, tabs and new lines
  • M-x visual-line-mode: Wrap the text like a word processor
  • M-x flyspell-mode: Spell checking

15 What Now?

This tutorial only scratches the surface of what Emacs can do. Here's some ways you can find out more…

  1. Experiment with the commands on the menu bar. Find out other features and their shortcuts
  2. Revise what you've learned by doing the Emacs online tutorial. Open Emacs and type C-h t.
  3. Read the Emacs online manual. C-h r.
  4. Look online. There's a great Emacs community on the web. Some places to get you started are:

http://emacswiki.org/

http://ergoemacs.org/emacs/emacs.html

And finally, and most importantly, learn org-mode

Date: <2013-08-01 Thu>

Author: Tony Ballantyne

Created: 2014-02-15 Sat 12:57

Emacs 23.3.1 (Org mode 8.0.2)

Validate XHTML 1.0