====== Emacs Tutorial ======
===== Getting Started =====
Emacs is an extensible, customizable, full-screen text editor. You can learn enough to be productive in Emacs in 30 minutes, but there is enough to learn about Emacs to keep you busy for years. The goal of this tutorial is to show you enough so that you are comfortable using Emacs as a work environment, not just as a text editor. This document refers to GNU Emacs version 23 (the latest version, and the one installed on SDF).
Start by typing "emacs" at the shell prompt, read the splash screen and hit any key to clear it. You'll be in a so-called //scratch buffer//. A //buffer// is a place in Emacs that usually contains the text of a file for editing (but can contain other text, like error messages, command output or directory contents). Anyway, the scratch buffer is just that - a place to scratch notes or otherwise put temporary snippets of text you don't care to save. When you exit Emacs, the contents of the scratch buffer are discarded.
You will see a white or grey line at the bottom of the Emacs window, with some information displayed like the name of the buffer or file you are viewing, the line number your cursor is on, and whether or not the current buffer has been modified (indicated by two asterisks to the left of the buffer name). This is called the //modeline//. Like everything else in Emacs, what is displayed in the modeline is configurable, but the defaults should work fine for most people.
Just below the modeline is a blank line called the //echo area// or //minibuffer//. The minibuffer is used when Emacs has to gather data from the user, like which filename to edit, or when Emacs has to display information to the user, like error messages. You will also see Emacs command sequences echoed here as you type them.
===== Basic Commands =====
Emacs is a non-modal editor, meaning when you have a file loaded into a buffer, you can type text and it will appear directly in the buffer. You don't need to be in a special insert mode as in vi. That also means cursor movement and other text manipulation commands are not mapped to single alphabetic characters as in vi. Commands in Emacs are typically entered with a two- or three-key sequence, either Control- or Alt- followed by a one- or two-key sequence. The Control key in the Emacs documentation is denoted by "C" and Alt by "M" (Emacs documentation refers to the Alt key as Meta, hence the "M". The Esc key on most keyboards acts as an Alt or Meta key as well). For example, to quit Emacs, you type "C-x C-c", meaning you hold down the Control key, hit the "x" key and release it, then hit the "c" key and release it. To move up a screenfull of text, you type "M-v", meaning hold down the Alt key and type "v". With that in mind, here are a few useful key sequences:
| C-x C-f | Find file and load into buffer (Emacs prompts for filename) |
| C-x C-s | Save the current buffer |
| C-x C-w | Save the current buffer under a different name (Emacs prompts for the new name) |
| C-x C-c | Quit Emacs, prompting if you have not saved any buffers |
| Arrow keys or C-f, C-b, C-n, C-p | Right (forward), left (back), down (next), up (previous), respectively |
| C-k | Delete from cursor to end of line |
| C-a | Go to start of line |
| C-e | Go to end of line |
| C-v | Go down a page |
| M-v | Go up a page |
| C-x u | Undo |
| C-g | Abort the current command |
| C-l | Redraw and center screen at cursor |
| M-< | Go to start of buffer |
| M-> | Go to end of buffer |
| Backspace | Delete previous character |
===== Getting Help =====
GNU Emacs has excellent help facilities. Most of them are accessed with the prefix "C-h". The Emacs tutorial is an interactive introduction you can work through fairly quickly to learn the most common key bindings. "C-h i" accesses the GNU hypertext info browser from within Emacs, displaying system info pages (including the Emacs manual itself). Here are some of the help-related key bindings:
| C-h t | Emacs tutorial |
| C-h i | Load info browser |
| C-h m | Display help on current mode |
| C-h f | Display help on function (Emacs prompts for function) |
| C-h k | Display help on key (Emacs prompts for key) |
| M-x man | Display a man page in a new buffer (Emacs prompts for man page) |
===== Extended Commands and Command Completion =====
Emacs has the concept of //extended commands//, which consist of "M-x" followed by the name of the command. As an example of a useful extended command, sometimes the backspace key gets mapped to C-h (I find this happens sometimes under remote screen sessions, you'll know this is the case if you hit the backspace key twice and the emacs help buffer pops up, just hit "C-g" to clear the help window). To get the backspace key to act as it should (i.e., it deletes the previous character), you enter "M-x normal-erase-is-backspace-mode". That's a lot to type, so you can take advantage of Emacs' //command-completion// by typing a partial command and hitting the "Tab" key one or more times. In this case, you type "M-x normal-e" and hit "Tab", and Emacs will complete the command for you. You can then just hit "Enter" to execute the command. If you don't type enough of the command to make it unique, Emacs will display a list of alternatives for you to choose from. For example, if you type "M-x normal-" and hit the "Tab" key, Emacs will pop up a buffer named *Completion* with with two alternatives for you to choose from: normal-mode and mormal-erase-is-backspace-mode. Just type a bit more of the command you want and hit tab again to narrow the completion list or to complete the command if it is the only one left.
===== Kill & Yank (Cut/Copy and Paste) =====
Most Emacs commands operate on the region defined by the //point//, which is the location of the cursor at any given time, and the //mark//, which is set with the command "C-space". To copy or cut a region of text, move the cursor to the start of the text area you are interested in and type "C-space". You will see "Mark set" in the echo area. Now move the cursor to the end of the text region (which moves the point) and type "M-w" for copy or "C-w" for cut (both called killing text). The text you copy or cut is stored by Emacs in the //kill-ring//, which is a circular buffer that stores the text snippets you kill in a last-in-first-out order. To paste the most recently stored text, move the cursor to where the text should be inserted, and type "C-y". The "y" stands for yank, what you'll see paste referred to in the Emacs help documentation (remember Emacs pre-dated modern windowing systems and other full-screen editors, so the terms cut and paste were not in use yet). After a yank ("C-y") command, you can replace the inserted text with earlier kills in turn by typing "M-y" one or more times. Each time you press "M-y" the next block of killed text is popped off of the kill ring and inserted into your buffer, replacing the last insert at the same time.
Here are the commands we discussed above, and a few other useful ones:
| C-space | Set the mark |
| C-w | Cut (kill) |
| M-w | Copy (kill) |
| C-y | Paste (yank) |
| M-y | Paste (yank) next saved selection |
| C-x h | Set point to start of buffer and mark to end of buffer (select the entire buffer) |
| C-x C-x | Go back to the last mark that was set |
===== Search & Replace =====
Emacs has a nice search mode called //incremental search//. To use it, type "C-s". The text "I-search:" will appear in the echo area. Now start typing a search string. As you type, Emacs will search for your string in real-time (starting at point), highlighting any matches it finds. You can backspace and re-type text, and the search will continue to change with the text you type. When you find a match, you can hit "C-s" to search again and jump to the next match, or you can just hit "Enter" to exit the search mode and leave the cursor at the last match. "C-g" will abort the search and put your cursor back where you started. Searches will re-start at the top of a buffer if they hit the bottom. You can search backwards in a similar fashion with "C-r".
To replace text that matches a search pattern, type "M-%". You'll see "Query replace:" in the echo area. Type a search string, and hit "Enter". The echo area will now display "Query replace with:". Type the replacement string, and hit "Enter" again. Emacs will search through your buffer, looking for the search string. When it finds it, it will display "Query replacing with : (? for help)". Type "y" to replace this match and move onto the next, or "n" to skip this match. Type "!" to replace this occurrence of the search string and all other occurrences in your buffer without prompting. As usual, you can type "C-g" to abort a search/replace operation.
All searches in Emacs are case-insensitive by default, unless you type at least one capital letter in your search string - in that case, the search becomes case-sensitive.
One nice feature you'll notice is that Emacs remembers the search and replacement strings you've used, so if you type "M-%" again, the last search/replace operation can be repeated by just hitting the "Enter" key. Prior search and replacement strings can be accessed with up- or down-arrow keys or "M-p" and "M-n" (for previous- and next-, respectively) - this is like the history mechanism in the Bash shell.
Another nice tip during searches is that "C-w" will highlight the word around the cursor, then successive words each time it's pressed during a search (so the highlighted area will grow with each press of "C-w"). You can search again by typing "C-s", this time the search string is whatever was highlighted.
Here are the search and replace commands we discussed:
| C-s | Search forward |
| C-r | Search backward |
| M-% | Search and replace |
| C-g | Abort a search |
| C-w | During a search, highlight the word around the cursor |
| Up, down arrow keys or M-p, M-n | Access search string history |
===== Emacs Modes =====
Emacs buffers are associated with one so-called //major mode// and one or more //minor modes//. Major modes typically denote a type of file, and are associated with special command sequences and syntax highlighting just for that file type. Minor modes change the behavior of an associated major mode in small ways. For example, the major mode for editing text is called text-mode, while the one for editing HTML is called html-mode. Both text and html modes have a minor mode called refill-mode that automatically formats paragraphs of text as you type (similar to the behavior you expect from a word processor). You can switch modes by just typing "M-x modename", so "M-x html-mode" would switch you into html-mode. Emacs can usually figure out the mode to use by the file extension, so if you visit (load with "C-x C-f") a file ending in .html or .htm, html-mode will be selected for you, and if you visit a file ending in .txt, text mode will be selected.
As an example, say you want to create a new text document. You type "C-x C-f foo.txt" and Emacs creates an empty buffer for you named "foo.txt". Notice the modeline displays "(Text)" to indicate the major mode. Now type "M-x refi" and hit the Tab key. Emacs will complete "refill-mode". Hit enter, now the modeline displays "(Text Refill)" to indicate the major and minor modes in effect. Experiment with refill mode by typing some text and watch as Emacs wraps the lines for you. Now go back and add or delete some text and notice how the paragraph re-formats itself. Modes toggle on and off, so a second "M-x refill-mode" will turn refilling off. Type some text and notice Emacs no longer wraps lines or formats paragraphs for you. The mode for buffers not associated with any special file type is called fundamental-mode. This is the mode your scratch buffer is put in at startup.
There are lots of Emacs major modes, many of which are useful for programmers. There is c-mode, perl-mode, and c++-mode, for example. Each mode has its own key bindings and syntax highlighting rules. You can see the details of the currently selected major mode by typing "C-h m". To enable syntax highlighting on a source-code file, you can type "M-x global-font-lock-mode" (on some operating systems, packaged versions of Emacs will enable font lock [syntax highlighting] for you automatically).
As an example of special key bindings, in html-mode, the key sequence "C-c C-c h" will insert a properly formatted hyperlink into the text, prompting you for the URL first. In other modes this key sequence will have no effect.
Here are some of the most useful mode commands:
| M-x modename | Toggle the given major or minor mode |
| C-h m | Display help on the current major mode, including any special key bindings in effect |
| M-q | Used in text-mode to reformat a paragraph of text manually |
| M-x global-font-lock-mode | Toggle syntax highlighting |
===== Buffers =====
When you visit a file with "C-x C-f", Emacs loads the file into a new buffer created just for that file. Existing buffers are not destroyed, but persist and can be switched to with "C-x b". Emacs will prompt you for a buffer name to switch to; tab-completion works here as it does in other places. One tip that I wish I had known when I first started using Emacs is to use a special mode called //iswitch mode// to help manage buffers. Since it's not uncommon to have dozens of buffers in an Emacs editing session, you can easily forget buffer names. With iswitch mode enabled, a "C-x b" displays a list of buffers in the echo area that changes in real-time as you type characters. You don't even have to type the first few letters of a buffer name, any substring of a buffer name will do. To enable iswitch mode, type the extended command "M-x iswitchb-mode" (we'll see later how to permanently enable modes like this in a startup file). To see a list of all buffers, type "C-x C-b". The buffer list will appear in a new window. Here is a list of some useful buffer commands:
| C-x b | Switch to another buffer |
| C-x C-b | Display buffer list |
| C-x k | Kill current buffer (Emacs prompts for confirmation) |
| M-x iswitchb-mode | Enable iswitch mode, for smart buffer name completion with C-x b |
===== Windows =====
The Emacs screen area can be divided into multiple //windows//. Each window contains one buffer, so the contents of a window can change depending on the buffer it contains. The most common way to create new windows is to split the screen into two regions with "C-x 2" or "C-x 3". The first splits the screen in half horizontally, the second splits it vertically. Any Emacs window can be split multiple times, so if you have a large display, you could have lots of windows open. You can cycle through visible windows with "C-x o" (think of the "o" as meaning "other window"). When you do have another window open, it's sometimes useful to scroll the other window without leaving your current one. You can do this with "C-M-v". This is particularly useful for when Emacs pops up a completion or help buffer in a new window that you would like to scroll through.
You can close a window with "C-x 0" or "C-x 1". The first closes the window you are currently in, the second closes all the other windows, but leaves the window you are currently in open for you. Closing a window does not destroy the buffer it contains, so you can think of a window as a view into a buffer (in fact you can have multiple windows visiting different parts of the same buffer). Here is a list of the most useful window commands:
| C-x 0 | Close this window |
| C-x 1 | Close all other visible windows |
| C-x 2 | Split horizontally |
| C-x 3 | Split vertically |
| C-x o | Switch to other window |
| C-M-v | Scroll other window |
===== Dired Mode =====
If you type the name of a directory after a "C-x C-f" command, Emacs will display the directory contents in a new buffer. By default, Emacs displays the file name, permissions, owner/group, size and timestamp of each file on a line by itself. You can visit a file by just moving the cursor to it and hitting "Enter". Dired mode is unlike other modes in that single keys are used to effect commands. Here is a list of the most useful dired commands:
| Left, right arrow keys or p, n | Previous and next file, respectively |
| Enter | Visit this file in this window |
| o | Visit this file in a new window |
| g | Refresh directory view |
| m | Mark file |
| u | Un-mark file |
| d | Mark a file for later deletion |
| x | Delete all files marked for deletion (Emacs prompts for confirmation) |
| D | Delete this file right now (Emacs prompts for confirmation) |
| C | Copy this file, or copy currently marked files (Emacs prompts for destination) |
| R | Rename/move this file, or rename/move currently marked files (Emacs prompts for destination) |
| M | Chmod this file, or chmod currently marked files (Emacs prompts for new permissions) |
| O | Chown this file, or chown currently marked files (Emacs prompts for new owner) |
| G | Chgrp this file, or chgrp currently marked files (Emacs prompts for new group) |
| + | Create directory (Emacs prompts for directory name) |
| ! | Execute shell command on this file, or currently marked files (Emacs prompts for command) |
===== Shell Modes =====
It is possible to run a shell from within Emacs; there are a few different ways to do so. The easiest way is to type "M-x shell". This creates a a buffer called *shell* with a shell prompt. Shell commands you type are sent to a system shell and the output displayed in the shell buffer. One thing you'll notice in shell mode is that the arrow keys move you around the buffer - they don't access command history as they do in most shells. To access command history, use "M-p" and "M-n" for previous and next, respectively.
One of the drawbacks of shell-mode is that it is not suitable for full-screen applications (like less, lynx, mutt or pine), to run these inside of Emacs, you need to use a terminal mode. Type "M-x ansi-term", and specify which shell you would like to run (your default will be the shell you are using, e.g. "/usr/pkg/bin/bash").
On platforms without an underlying shell (e.g., Windows), Emacs has a terminal emulator written entirely in Emacs Lisp. To enter it, type "M-x eshell". While not suitable for full-screen applications, it does emulate a limited subset of shell features rather nicely. In this shell mode, the arrow keys work as you would expect, and most shell builtins and shell aliases work as well. Some external commands such as grep work, although input/output redirection is not yet implemented.
Here are the commands we discussed above:
| M-x shell | Shell mode, use M-p and M-n for command history |
| M-x eshell | Emacs Lisp shell emulator, use arrow keys for command history |
| M-x ansi-term | Full terminal emulator, suitable for full-screen applications. |
===== Emacs Startup and Configuration =====
When Emacs starts it will load a file named ".emacs" in your home directory and execute the commands found in it. This file is written in Emacs Lisp, but you can use it without knowing any Lisp, by copying other people's sample files. It is mainly useful for making certain extended commands a permanent part of your Emacs experience, so you don't have to type them every time you start Emacs. In the example below, comment lines start with one or more semi-colons, so you would delete the semi-colons to enable the given feature.
;; Sample ~/.emacs file
;;
;; Un-comment what you want to enable and re-start Emacs
;;
;;Load iswitch mode
;;(require 'iswitchb)
;;Make text mode the default for new buffers
;;(setq default-major-mode 'text-mode)
;;Turn on refill-mode whenever text mode is entered
;;(add-hook 'text-mode-hook
;; '(lambda () (refill-mode 1)))
;;Enable syntax highlighting when it's allowed
;;(when (fboundp 'global-font-lock-mode)
;; (global-font-lock-mode t))
;;Fix the backspace key
;;(normal-erase-is-backspace-mode 1)
;;Use cperl-mode for editing Perl code, it is better than perl-mode
;;(defalias 'perl-mode 'cperl-mode)
;;Don't blink my cursor, please
;;(blink-cursor-mode nil)
;;Display the current time in the modeline
;;(display-time-mode t)
;;Start the emacs server
;;
;;When this is running, programs calling emacsclient open a buffer
;;in the already running emacs. Useful in mutt or pine for composing
;;mail in Emacs. Type C-x # to exit client buffer and send the text
;;back to the application that called it.
;;(server-start)
The above example gives you a good idea of what can be done in a ".emacs" file, for more in-depth configuration Emacs has a customization mode that can be accessed with the extended command "M-x customize". Running it will put you in a curses-style application where you can choose from customization menus and have your changes written to your ".emacs" file automatically.
===== Browsing the Web in Emacs with w3m =====
[[http://sourceforge.net/projects/w3m/files/|Emacs w3m mode]] will use the excellent [[http://w3m.sourceforge.net|w3m]] text-mode browser and allow you to surf the web in an Emacs buffer.
To get started, add the following to your .emacs file:
(require 'w3m-load)
Then restart emacs, or place the cursor at the end of each line in turn and press C-x e. Then you can open a new w3m buffer with M-x w3m. The basic key bindings are as follows (note that these are taken from the w3m-mode help page, which can be accessed at any time in a new window with C-h m):
| M-x w3m | Start browsing web with emacs-w3m. |
| q | Close all emacs-w3m windows, without deleting buffers. |
| Q | Exit browsing web. All emacs-w3m buffers will be deleted. |
| RET | Display the page pointed to by the link under point. |
| C-c C-c | Submit the form at point. |
| R | Reload the current page. |
| r | Redisplay the current page. |
| TAB | Move the point to the next anchor. |
| M-TAB | Move the point to the previous anchor. |
| B | Move back to the previous page in the history. |
| N | Move forward to the next page in the history. |
| U | Visit the web page. |
| H | Go to the Home page. |
| M-d | Download the URL. |
| d | Download the URL under point. |
| \ | Display the html source of the current page. |
| SPC | Scroll up the current window, or go to the next page. |
| b | Scroll down the current window, or go to the previous page. |
| > | Scroll to the left. |
| < | Scroll to the right. |
| . | Shift to the left. |
| , | Shift to the right. |
| M-l | Recenter horizontally. |
| j | Next line. |
| k | Previous line. |
| l | Forward char. |
| h | Backward char. |
| s | Display the history of pages you have visited in the session. |
| S | Prompt for a search query and submit it to google. |
| v | Display the bookmarks list. |
| a | Add a url of the current page to a new bookmark. |
| M-a | Add the url under point to a new bookmark. |
There are many more features in w3m-mode, the mode help text details them all with keybindings. To end your session and close all w3m buffers, just press Q and answer y when prompted.
===== Where to Go From Here =====
Below are some links to resources and useful Emacs Lisp packages. Many Linux and BSD-based operating systems have packages for most of these, so check there before you attempt to install by hand:
* [[http://www.gnu.org/software/emacs/tour/|Emacs Tour]]: Guided tour of GNU Emacs with lots of screenshots.
* [[http://mwolson.org/projects/EmacsMuse.html|Muse]]: A publishing and authoring environment that converts simple text markup into HTML, PDF, Texinfo, Docbook, LaTeX, Blosxom blog entries and more. This tutorial was written using muse-mode.
* [[http://www.emacswiki.org/cgi-bin/wiki|Emacs Wiki]]: Loads of tips and howtos.
$Id: emacs-tutorial.html,v 1.14 2012/05/02 13:42:40 slugmax Exp $