\documentclass[11pt,twoside]{handout}
%\documentstyle[11pt,twoside]{handout}

\author{P. N. Hilfinger}
\title{Highlights of GNU Emacs}
\course{CS61A}
\semester{}

\newcommand {\caret} {{\tt \^{ }}}
\newcommand {\bs} {$\backslash$}
\newcommand {\ARG} {{\it ARG}}

\advance\oddsidemargin18pt
\advance\evensidemargin-6pt

%\pageno=179

\begin{document}

\setcounter{page}{57}

\maketitle

This document describes the major features of GNU Emacs (called ``Emacs''
hereafter), a
customizable, self-documenting text editor.  In the
interests of truth, beauty, and justice---and to undo, in some small
part, the damage Berkeley has done by foisting {\tt vi} on an
already-unhappy world---Emacs will be the official CS61A text
editor this semester.
%  I have spoken.

Emacs carries with it on-line documentation of most of its
commands, along with a tutorial for first-time users (see
\S\ref{sec:doc}).  Because
this documentation is available, I have not attempted to present
a complete Emacs reference manual here.

To run Emacs, simply enter the command {\tt emacs} to the shell.
Within Emacs, as described below, you can edit any number of files
simultaneously, run UNIX shells, read and send mail, and run the
Scheme interpreter to execute your programs.
As a result, {\it it should seldom be necessary to leave Emacs before you
are ready to logout and seldom necessary to create new windows.}

\section{Basic Concepts}\label{sec:concepts}
We'll begin with some fundamental definitions and notational conventions.

\subsection{Buffers, windows, and what's in them}
At any given time, Emacs
maintains one or more {\it buffers} containing text.  Each buffer may,
but need not, be
associated with a file.  A buffer may be associated with a UNIX
process, in which case the buffer generally contains input and output produced
by that process (see, for example, sections~\ref{sec:shell}
and~\ref{sec:compilation}).
Within each buffer, there is a position called the {\it point},
where most of the action takes place.

Emacs displays one or more {\it windows} into its buffers, each
showing some portion of the text of some buffer.
A buffer's text is retained even when no window displays it;
it can be displayed at any time by giving it a window.
Each window has its own point (as just described); when only one
window displays a buffer, its point is the same as the buffer's point.
Two windows can simultaneously display text (not necessarily the same text)
from the same buffer with a different point in each window,
although it is most often useful
to use multiple windows to display multiple files.  At the bottom of
each window, Emacs displays a {\it mode line}, which generally
identifies the buffer being displayed and (if applicable) the file
associated with it.
At any given time, the {\it cursor}, which generally marks the point
of text insertion, is in one of the windows (called the {\it current window})
at that window's point.

\subsection{Commands}
At the bottom of Emacs' display is a single {\it echo area},
displaying the contents of the {\it minibuffer}.  This is a one-line
buffer in which one types commands.  It is, for many purposes, an
ordinary Emacs buffer; standard Emacs text-editing commands for moving
left or right and for inserting or deleting characters generally work
in it.  To issue a command by name, one types {\tt M-x} (``meta-x'';
this notation is
described below) followed by
the name of the command and {\tt RET} (the return key);
the echo area displays the command as it is typed.
It is only necessary to type
as much of the command name as suffices to identify it uniquely.  For
example, to run the command for looking at a UNIX manual entry---for
which the full command is {\tt M-x manual-entry}---it suffices to type
{\tt M-x~man}, followed by a {\tt RET}.

All Emacs commands have names, and you can issue them with {\tt M-x}.
You'll invoke most commands, however, by using
control characters and escape sequences to which these commands are
{\it bound}.  Almost every character typed to Emacs actually executes
a command.
By default, typing any of the printable characters executes a command
that inserts that character at the cursor.
Many of the control characters are bound to commonly-used
commands (see the quick-reference guide at the end
for a summary of particularly
important ones).
At any time, it is possible to bind an
arbitrary key or sequence of keys to an arbitrary command,
thus {\it customizing} Emacs to
your own tastes.   Hence, all descriptions of key bindings in
this document are actually descriptions of standard or default bindings.

\subsection{Notations for special keys}
In referring to non-graphic keys (control characters and the like),
we'll use the following notations.
\begin{description}
\item[{\tt ESC}] denotes the escape character.

\item[{\tt DEL}] denotes the delete character.  On HP workstations, as
we've set them up for this class, the
`{\tt Backspace}' key has the same effect.

\item[{\tt SPC}] denotes the space character.

\item[{\tt RET}] denotes the result of pressing the `Return' key.
(Confusingly, the result of typing this into a file is not a return
character (ASCII code 13), but rather a linefeed character (ASCII code
10). Nevertheless, Emacs distinguishes the two keys.)
On the HP workstations, this is the wide key labelled ``Enter'' in
the main section of the keyboard.

\item[{\tt LFD}] denotes the result of typing the linefeed key.
On the HP workstations, this is the tall key labelled ``Enter'' in the
numeric keypad at the far right of the keyboard.

\item[{\tt TAB}] denotes the tab (also {\tt C-i}) key.

\item[{\tt C-}$\alpha$] denotes ``control-$\alpha$''---the result of
holding down the {\tt Control} (or {\tt Ctrl}) key while typing $\alpha$.

\item[{\tt M-}$\alpha$] denotes ``meta-$\alpha$,'' which one gets either by
typing the two-character sequence {\tt ESC}
followed by $\alpha$, or (on our HP workstations when running the
X~window system) holding down either {\tt Alt} key while typing $\alpha$.

\item[{\tt C-M-}$\alpha$] denotes the result of typing the
two-character sequence {\tt ESC~C-}$\alpha$, or
(on HP workstations when running~X)
holding down both {\tt Control} and {\tt Alt}
simultaneously with typing $\alpha$).
\end{description}

\subsection{Command arguments}\label{sec:arguments}
Certain commands take arguments, and take these arguments from a
variety of sources.  Any command may be given a numeric argument. To
enter the number comprising the digits $d_0d_1\cdots d_n$ as a numeric
argument ($d_0$ may also be a minus sign), type either `{\tt
M-}$d_0d_1\cdots d_n$' or  `{\tt C-u}$d_0d_1\cdots d_n$' before the command.
When using {\tt C-u}, the digits may be omitted, in which case `4' is
assumed.
The most
common use for numeric arguments is as  repetition counts.  Thus,
{\tt M-4~C-n} moves down four lines and {\tt M-72~*} inserts a line
of~72 asterisks in the file.  Other commands give other
interpretations, as described below.  In describing commands, we will
use the notation \ARG{} to refer to the value of the numeric argument,
if present.

When commands prompt for arguments, Emacs will often allow provide a
{\it completion} facility.  When entering a file name on the echo
line, you can usually save time by typing  {\tt TAB}, which
fills in as much of the file name as possible, or
{\tt SPC} which fills in as much as possible up to a punctuation mark
in the file name.   Here, ``as much as possible'' means as much as is
possible without having to guess which of several possible names you
must have meant.  A similar facility will attempt to complete the
names of functions or buffers that are prompted for in the echo line.


\subsection{Modes}\label{sec:modes}
The binding of keys to commands depends on the buffer that currently
contains the cursor.  This allows different buffers to respond to
characters in different ways.   In this document, we will refer to the
set of key bindings in effect within a given buffer as the {\it (major) mode}
of that buffer (the term ``{\it mode\/}'' is actually somewhat
ill-defined in Emacs).
A set of key bindings that simply modifies a few
characteristics is called a {\tt minor mode}.

Emacs will
automatically establish a mode for buffers containing
certain files depending on the name of their
associated file.  Thus, buffers start out in `C' mode for files whose
names end in
`{\tt .c}' or `{\tt.h}'; `C++' mode for {\tt.cc} or {\tt.C}; or `Scheme'
mode (see \S\ref{sec:Scheme}) for {\tt.scm}.
These modes affect the behavior of the {\tt TAB} key, for example,
causing program text to be indented according to the conventions for a
particular programming language.
The shell buffer runs in Shell
mode, which (among many other things) causes the {\tt RET} key to send
the last line typed to the shell.
Files with unclassifiable names generally start in Fundamental mode.

There is one useful minor mode that's worth knowing about.
\begin{description}
\item[{\tt M-x auto-fill-mode}] toggles (reverses the setting) of
auto-fill mode, which by default is usually off.  In auto-fill mode,
lines get broken automatically as they are being typed when they get
too long.  When you are typing comments in C programs, auto-fill mode
will automatically start a new comment on the next line when the
current line gets near to filling up.
\end{description}

\section{Important special-purpose commands}\label{sec:special-purpose}
\begin{description}
\item[{\tt C-g}] quits the current command.  Generally useful for
cancelling a {\tt M-x}-style command or other multi-character command
that you have started entering.  When in doubt, use it.
\item[{\tt C-x C-c}] exits from Emacs.  It prompts (in the echo area)
if there are any buffers that have not been properly saved.
\item[{\tt C-x u}] undoes the effects of
the last editing command.  If repeated, it undoes
each of the preceding commands in reverse order (there is a limit).
This is an extremely important command; be sure to master it.
This does not undo other kinds of commands; the cursor may end up at
some rather odd places.
\item[{\tt C-l}] redraws the screen, and positions the current line to
the center of the current window.
\end{description}

\section{Basic Editing}\label{sec:editing}

The simple commands in this section will enable you to do most of the
text entering and editing that you'll ordinarily need.  Periodic
browsing through the on-line documentation (see
section~\ref{sec:info}) will uncover many more.

\subsection{Simple text.}
To enter text, simply position the cursor to the desired buffer and
character position (using the commands to be described) and type the
desired text.
Carriage return behaves as you would expect.
To enter control characters and other special characters as if they
were ordinary characters, precede them with a {\tt C-q}.

\subsection{Navigation within a buffer.}\label{sec:navigation}
The following commands move the cursor within a given buffer.  Later
sections describe how to move around between buffers.
\begin{description}
\item[{\tt C-f}] moves forward one character (at the end of a line,
this goes to the next).
\item[{\tt C-b}] moves  backward one character.
\item[{\tt M-f}] moves  forward one ``word.''
\item[{\tt M-b}] moves  backward one word.
\item[{\tt C-e}] moves to the end of the current line.
\item[{\tt C-a}] moves to the beginning of the current line.
\item[{\tt C-M-f}] moves forward one Lisp (Scheme) S-expression.
\item[{\tt C-M-b}] moves backward one Lisp (Scheme) S-expression.
\item[{\tt M-a}] moves backward to next beginning-of-sentence.  The
precise meaning of ``sentence'' depends on the mode.
\item[{\tt M-\{}] moves backward to next beginning-of-paragraph. The
precise meaning of ``paragraph'' depends on the mode.
\item[{\tt M-e}] moves to the next end-of-sentence.
\item[{\tt M-\}}] moves to the next end-of-paragraph.
\item[{\tt C-n}] moves  down to the next line (at roughly the
same horizontal position, if possible).
\item[{\tt C-p}] moves  up to the previous line.
\item[{\tt C-v}] scrolls the text of the current window up roughly one
window-full (i.e., exposes text {\it later} in the buffer).  If \ARG{}
is supplied, it scrolls up \ARG{} lines.
\item[{\tt M-v}] scrolls the text of the current window down roughly
one window-full (i.e., exposes text {\it earlier} in the buffer).
If \ARG{}
is supplied, it scrolls down \ARG{} lines.
\item[{\tt C-M-v}] scrolls up the text in another window (if any)
roughly one window-full.
If \ARG{}
is supplied, it scrolls up \ARG{} lines.
\end{description}

\begin{description}
\item[{\tt M-<}] moves to the beginning of the current buffer, after
setting the mark (see \S\ref{sec:regions}) to the current point.  If \ARG{} is
supplied, it
moves to a point $\ARG/10$ of the way through the buffer, instead of
the beginning.
\item[{\tt M->}] moves to the end of the current buffer.  If \ARG{} is
supplied, it
moves to a point $\ARG/10$ of the way back from the end of the buffer, instead
of the end.
\item[{\tt M-g}] goes to the line number given by the argument (prompts
for a number in the echo line, if you haven't supplied an argument).
\item[{\tt M-x what-line}] displays the number of the current line in
the current buffer.
\end{description}

\subsection{Regions}\label{sec:regions}
In addition to a point (marked by the cursor in the current window),
each buffer may contain a {\it mark}.  Everything between the point
and mark is called the {\it current region}.   The current region
typically delimits text to be manipulated by certain commands.
% We have set up Emacs so that the current region is shaded.
\begin{description}
\item[{\tt C-@}] sets the mark at the current point, and pushes the
previous mark on a ring of marks.  If \ARG{} is present, it instead
puts the point at the current mark and pops a new mark
off this ring.
\item[{\tt C-SPC}] is the same as {\tt C-@}.
\item[{\tt C-x C-x}] exchanges the point and the mark.
\item[{\tt M-@}] sets the mark after the end of the next word.
\item[{\tt M-h}] sets the region (point and mark) around the current paragraph.
\item[{\tt C-x h}] sets the region (point and mark) around the entire
current  buffer.
\end{description}


\subsection{Deletion}\label{sec:deletion}
\begin{description}
\item[{\tt DEL}] deletes the character preceding the cursor.  At
the beginning of a line, it deletes the preceding end-of-line
character, thus joining the current and preceding lines.
\item[{\tt M-DEL}] deletes the word preceding the cursor.
The deleted word moves to the kill buffer, described later.
\item[{\tt C-d}] deletes the character under the cursor (which can be
the end-of-line).
\item[{\tt M-d}] deletes the word following the cursor.
\item[{\tt C-k}] deletes the rest of the line following the cursor.  If
the cursor is on the end-of-line, delete the end-of-line.  The deleted
line moves to the kill buffer.
\item[{\tt M-\bs}] deletes all horizontal blank space on either side of
the cursor.
\item[{\tt M-SPC}] deletes all but one horizontal blank space
surrounding the cursor.
\item[{\tt C-x C-o}] on non-blank line, deletes all immediately
following blank lines;
on isolated blank line, deletes the line; on other blank lines,
deletes all but one.
\item[{\tt C-w}] deletes everything between the point and
the mark, moving the deleted text to the kill buffer.
\item[{\tt M-w}] copies everything between point and mark to the
kill buffer, without actually deleting it.
\end{description}

\subsection{Insertion and the kill buffer}\label{sec:insertion}
Several of the preceding commands mention the {\it kill buffer}.  Text
that is deleted is appended to the end of the current kill buffer, and
can later be retrieved and inserted (``pasted'' or ``yanked'')
elsewhere in the text (even in another buffer different
from its original source).
Normally, each time a command that does not append to the kill buffer is
executed, the current kill buffer is saved in a ring of kill buffers,
and the next deletion command starts with an empty kill buffer.
Hence, to move a sequence of lines, one can issue a sequence of {\tt
C-k} commands, with no intervening commands,
move to the desired destination, and yank them back (with {\tt C-y}).
\begin{description}
\item[{\tt C-y}] inserts the contents of the current kill buffer at
the cursor, and moves cursor to end of inserted text.
If a numeric value of \ARG{} is supplied, inserts the $\ARG^{\rm th}$
most recent kill buffer in the ring.
\item[{\tt C-u C-y}] inserts current kill buffer, as for {\tt C-y},
but leaves point unchanged.
\item[{\tt M-y}] when issued {\it immediately} after a {\tt C-y} or
{\tt M-y},
deletes the text inserted by the {\tt C-y} or {\tt M-y} and
substitutes the text from the next kill buffer in sequence in the kill ring.
\item[{\tt C-M-w}] causes the next command, if a kill command, to
append to the end of previous kill buffer, rather than starting with a
new one.  This allows you, for example,  to delete lines from several different
places and then yank them back into one place.
\end{description}

\subsection{Indentation}\label{sec:indenting}
Indentation generally depends on the mode of the buffer.  When a
buffer is associated with a `.scm' file, in particular, it is by default
in Scheme mode, in which the standard indentation referred to below is
appropriate for Scheme source programs.
\begin{description}
\item[{\tt TAB}] indents as appropriate for the current mode.  In text
files, this is just an ordinary typewriter-style tab command.  In Scheme
source files, it indents to the appropriate point for a standard set
of indentation conventions.
\item[{\tt LFD}] is the same as {\tt RET TAB}.  Thus, if in typing in a
Scheme program, you end each line with {\tt LFD} instead of {\tt RET}, your
program will be indented as you enter it.
\item[{\tt M-;}] indents for a comment according to the current mode.
In Scheme mode, this inserts {\tt ;}.
\item[{\tt M-LFD}] when used inside a comment, will close the
comment, if necessary, go to a new line, and start a properly-indented
comment on that line.
\item[{\tt C-x TAB}] indents the current region ``rigidly''
by \ARG\ spaces to the right
(default 4).  Negative arguments indent to the left.  Tabs are
correctly counted as the appropriate number of blanks.
\item[{\tt C-M-\bs}] indents the current region according to the current
mode.  For an improperly-indented Scheme program, for example, this will
correct all the indentation within the region.
\end{description}

\subsection{Miscellaneous manipulations}
\begin{description}
\item[{\tt C-o}] inserts a newline after the cursor.  This has the
same effect as {\tt RET~C-b} (return and then back up one character).
\item[{\tt C-t}] transposes the character under the cursor with the
preceding character.
If an end-of-line is under the cursor, transposes the preceding
two characters.
\item[{\tt M-t}]  transposes the next word that begins left of the cursor
with the word following.
\item[{\tt C-x C-t}] transposes the current and preceding lines.
\item[{\tt M-c}] capitalizes the next word (making all characters
other than the first lower case).
\item[{\tt M-u}] converts the next word to all upper case.
\item[{\tt M-l}] converts the next word to all lower case.
\end{description}

\subsection{Using the mouse}\label{sec:Mouse}
When you are using Emacs with the X window system, you may use the
mouse for simple positioning, text deletion, and text insertion.
The
three mouse buttons indicate the operation to be performed, and the
mouse pointer (the slanting arrow, which we'll usually just call the
{\it pointer\/}) usually indicates the position at
which to perform it.  In the following, the mouse buttons are called
`LB', `MB', and `RB', for left button, middle button, and right button.
We'll use {\tt C-$B$} to indicate the result of holding down
``Control'' while pushing button $B$.
\begin{description}
\item[{\tt LB}] places the point and mark at the position (and in the buffer)
indicated by the pointer.  You may then drag the mouse with LB depressed;
this leaves the mark at the point you pressed {\tt LB} and moves the
point (and cursor) to
the point at which you release {\tt LB}, thus defining a new current region.
\item[{\tt RB}] first extends the current region to include all the
text between the existing current region (or the point, if there is no current
region) and the pointer.  Next, it copies
the text in the current region into the kill buffer, as for
{\tt M-w} above.  When clicked twice for the same text, it also deletes the
text.
Finally, it also copies the text into something
called the {\it window-system cut
buffer}.  Text in the window-system cut buffer may be
``pasted'' (inserted) by {\tt MB}, as described below, not only into
Emacs buffers, but also into any other X-windows buffer.
\item[{\tt MB}] pastes (inserts) text from the window system cut buffer
at the point indicated
by the mouse, and puts the cursor at the beginning and the
mark at the end of the inserted text.  This is somewhat like a mouse
version of {\tt C-y}.  However, since it takes its text from the
window system cut buffer (common to all windows on the screen), it
allows the insertion of text from or to a window other than the one running
Emacs.
\item[{\tt C-LB}] Displays a menu of buffers to move to and allows you to
select one (a mouse version of {\tt C-x~b}, described later).
\end{description}

You may also use the mouse to select from menus that sprout from the
menu bar at the top of your Emacs screen.  The content of these menus
depends on the kind of buffer you are in.

\section{Context searches}\label{sec:search}
The search commands provide a convenient way to position the cursor
quickly over long distances.  One can search either for specific
strings or for patterns specified by {\it regular expressions}.
Both kinds of searches are carried out {\it incrementally\/}; that is,
as you type in the target string or pattern, the cursor's position is
continually changed to point to the first point in the buffer (if any)
that matches what you have typed so far.

\begin{description}
\item[{\tt C-s}] searches forward incrementally.
\item[{\tt C-s C-s}] is as for {\tt C-s},  but initialize
the search string to the one used in the last string search.
\item[{\tt C-M-s}] is as for {\tt C-s},
but searches
for a regular expression.
\item[{\tt C-M-s C-s}] As for {\tt C-M-s}, but initialize the search
pattern to the last pattern used.
\item[{\tt C-r}] Search backward incrementally.
\item[{\tt C-r C-r}] As for {\tt C-r}, but initialize the search
string as for {\tt C-s~C-s}.
\item[{\tt M-x occur}] prompts for a regular expression and
lists each line that follows the point and contains a match for
the expression in a buffer.
If you give an \ARG, it will list that number of lines of context
around each match.
\item[{\tt M-x count-matches}] prompts for a regular expression and
displays in the echo area the number of lines following the point that
contain a match for it.
\item[{\tt M-x grep}] prompts for arguments to the UNIX {\tt grep} utility
(which searches files for
lines matching a given regular expression) and runs it asynchronously,
allowing other editing while the search continues.  See the command
{\tt C-x~`} in \S\ref{sec:compile} for a description of how to
look at each of the lines found in turn.
\item[{\tt M-x kill-grep}] stops a {\tt grep} that was started by {\tt
M-x~grep}.
\end{description}

As you type the  search string or pattern, the cursor
moves in the appropriate direction to the first matching string, if any
(specifically, to the right end of that string for a forward search
and to the left end for a reverse search).
By default, the case (upper or lower) of characters is ignored as long
as the pattern you type contains no upper-case characters; `a'
will each match either `a' or `A'.  When the pattern contains at least
one upper-case character, the search becomes case-sensitive; `a' will
not match `A', nor will `A' match `a'.
If matching fails at any point, you will receive a message to that
effect in the echo area.
While entering a search string or pattern, certain command characters
have altered effects, as follows.
\begin{description}
\item[{\tt RET}] ends the search, leaving the point at the string
found, and setting the mark at the original position of the point.
\item[{\tt DEL}] undoes the effect of the last character typed (and
not previously DELed),
moving the search back to wherever it was previously.
\item[{\tt C-g}] aborts the search and returns the cursor to where it was
at the beginning of the search.
\item[{\tt C-q}] quotes the next character.  That is, it causes the
next character to be added to the search string or pattern as an
ordinary character, ignoring any control action it might normally
have.  Use this, for example to search for a {\tt C-g} character or,
in a regular-expression search, to search for a `.'.
\item[{\tt C-s}] begins searching forward at the point of the cursor for the
next string satisfying the search string or pattern.  If used in a
reverse search, therefore,
this reverses the sense of the search.  If used at the
point of a failing search, this starts the search over at the
beginning of the buffer (``wraps around'').
\item[{\tt C-r}] is like {\tt C-s}, but searches in the reverse
direction, and can reverse the direction of a forward search.
\item[{\tt C-w}] adds the next word beginning at the cursor to the end
of the search string or pattern.
It follows that this has the effect of moving
the cursor forward over that word.
\item[{\tt LFD}] adds the rest of the line to the end of the current
search string or pattern.
\end{description}
Other control characters terminate the search, and then have their
ordinary effect.

Ordinary searches ({\tt C-s} and {\tt C-r})
treat all ordinary characters as search characters.  For
regular-expression searches, several of these characters have
special significance.  See also the on-line documentation.
\begin{description}
\item[.] matches any character, except end-of-line.
\item[\caret] matches the beginning of a line (that is, it matches
the empty string, and only at the beginning of a line.)
\item[\$] matches the end of a line.
\item[{\tt [$\cdots$]}] matches any of the characters between the
square brackets.  A range of characters may be denoted using `{\tt
-}', as in {\tt [a-z0-9]}, which denotes any digit or letter.  To
include `{\tt ]}' as one of the characters, put it first.  To include
{\tt `-'}, use {\tt `---'}.  To include `\caret', do {\it not}
make it the first character.
\item[{\tt [\caret$\cdots$]}] matches any of the characters {\tt
not} included in the `$\cdots$'.   Thus, if end-of-line is not one of
the characters, this will match it.
\item[{\tt *}] when following another regular expression, denotes
zero or more occurrences of that regular expression---in other words,
an optional occurrence.  This character
applies to the immediately preceding regular expression; it has
``highest precedence.''  There are special parentheses (see below) for
cases where this is not what you want.
Hence, the
pattern `{\tt .*}' denotes any number of characters, other than end-of-line.
The pattern `{\tt [a-z][a-z0-9\_]*}' denotes a letter optionally
followed by string of letters, digits, and underscores.
\item[{\tt +}] is like `{\tt *}', but denotes at least one occurrence.
Thus, `{\tt [0-9]+}' denotes an integer literal.
\item[{\tt ?}] is like `{\tt *}', but denotes zero or one
occurrence.  Hence, the pattern `{\tt [0-9]+,?}' denotes an integer
literal optionally followed by a comma.
\item[{\tt \bs($\cdots$\bs)}] groups the items `$\cdots$'.  Hence,
`{\tt \bs([0-9]+,\bs)?}' denotes an optional string consisting of an
integer literal followed by a comma.  The pattern `{\tt \bs(01\bs)*} denotes
zero or more occurrences of the two-character string `{\tt 01}'.
\item[{\tt \bs{}b}] matches the empty string at the beginning or end
of a word.  Hence, `{\tt \bs{}bring\bs{}b}' matches ``ring'' standing
alone, but not ``string'' or ``rings''.
\item[{\tt \bs{}B}] matches the empty string, provided that it is
not at the beginning or end of a word.
\item[{\tt \bs$|$}] matches a string matching
either the regular expression to its left or to its right.  Use
`\bs(\bs)' to limit what regular expressions it applies to.  Thus,
`{\tt \bs{}bf[a-z]+\bs$|$[0-9]+}' matches any integer literal or any word
that begins with `f', while `{\tt \bs{}bf\bs([a-z]+\bs$|$[0-9]+\bs)}'
matches any ``word'' that begins with `f' and continues with either
all letters or with all digits.
\item[\bs{\it n}] where $n$ is any digit, denotes the string that
matched the pattern within the $n^{\mbox{th}}$ set of
`\bs(\bs)' brackets in the current regular expression.  Thus,
`{\tt \bs{}b\bs([0-9]+\bs),~*\bs1}' matches any integer literal that
is followed by a comma, an optional space, and a repetition of the
same literal; it matches ``23, 23'' and ``10,10'', but not ``23, 24''.
\end{description}

\section{Replacement}\label{sec:replacement}
The following commands allow you to do systematic replacement of one
string or pattern with another within a given buffer.
\begin{description}
\item[{\tt M-\%}] performs a query-replace operation.  It prompts for a
search string and a replacement string.  Terminate each of the two
with a {\tt RET}.  The command will then display each instance of the
search string found, and prompt for its disposal.  The options are
described below.  If \ARG{} is supplied, it will only match things
surrounded by word boundaries, so that if the search string is
``top'', there will be no replacement inside the string ``stop'' or
``topping''.
\item[{\tt M-X query-replace-regexp}] is the same as {\tt M-\%}, but replaces patterns
designated by regular expressions, rather than just simple strings.
The replacement string may contain instances of `\bs{\it n}', for $n$
a digit,
which, as described in the section on regular expressions, denotes the
string matched by the $n^{\rm th}$ regular expression in `\bs(\bs)'
braces in the search string.  Thus, for example, the search pattern
`{\tt (\bs([a-z\_][a-z0-9\_]+\bs))}' with  the replacement pattern
`{\tt [\bs1]}' will replace each  C identifier surrounded by
parentheses by the same identifier surrounded by square brackets.
\end{description}
By default, the replacement will preserve the case of the letters
replaced if the search string or pattern has no upper-case letters, and
otherwise will use the case supplied in the replacement string.

At each instance of the search string or pattern, you are prompted for
an action.  Here are some common ones.
\begin{description}
\item[{\tt SPC}] replaces the indicated occurrence and goes to the next.
\item[{\tt DEL}] keeps the indicated occurrence unchanged and go to the next.
\item[{\tt RET}] exits with no further replacements.
\item[{\tt ,}] makes one replacement, but waits for another {\tt SPC}
or {\tt DEL} before moving to the next match.
\item[{\tt .}] makes one replacement and then exits.
\item[{\tt !}] replaces all remaining occurrences without prompting again.
\item[{\tt ?}] prints a help message.
\item[{\tt C-r}] enters a recursive edit level.  That is, you are put back
in ordinary Emacs at the point of the current occurrence and can edit
in the usual manner.  Typing {\tt C-M-c} then goes back to the
query-replace command.
\item[{\tt y}] same as {\tt SPC}.
\item[{\tt n}] same as {\tt DEL}.
\item[{\tt q}] same as {\tt RET}.
\end{description}

In addition to replacement, there are two often-useful commands for
deleting selected lines.
\begin{description}
\item[{\tt M-x delete-matching-lines}] prompts for a regular
expression and deletes ({\it without\/} prompting)
each line after the point that contains a match
for it.
\item[{\tt M-x delete-non-matching-lines}] prompts for a regular
expression and deletes each line after the point that does not contain
a match for it.
\end{description}

\section{Files, buffers, and windows}\label{sec:buffers_files_windows}
Each buffer has a name.  By default, buffers that are associated with
particular files have the name of that file (not including the name of
the directory containing it), possibly followed by a number in angle
brackets to distinguish multiple files (from different directories
with the same name.

\subsection{Loading into and storing from buffers}\label{sec:files}

\begin{description}
\item[{\tt C-x C-f}] prompts for a file name
and sets the current window to displaying that file
in a buffer having the same
name.  If a buffer displaying that file already exists, this command
merely switches the window to that buffer.  If the file does not
exist, the buffer is initially empty.  The buffer is subsequently
associated with the file.
This process is called {\it finding}
the file.
\item[{\tt C-x 4 C-f}] prompts for a file name, goes to the next window
on the screen (creating a new one, if there is only one), and then
acts like {\tt C-x C-f}.
\item[{\tt C-x C-s}] saves the current buffer in its associated file,
if the buffer has been modified.  If the file being saved exists, then
the old version is first renamed to have a tilde ({\tt \~{\ }}) appended to
its name, if no such file yet exists.
\item[{\tt C-x C-w}] prompts for a file name and saves the current
buffer into that file.  Generally, it is preferable and safer
to use {\tt C-x~C-f} or
{\tt C-x~4~C-f} and then use {\tt C-x~C-s}, but
sometimes this command is handy.
\item[{\tt C-x i}] prompts for a file name and inserts that file at
the point.  It does not associate the inserted file with the current buffer.
\item[{\tt M-x revert-buffer}] throws away the contents of the current
buffer and restores the contents of the associated file.  It will ask
you to confirm these actions before taking them.
\end{description}

\subsection{Manipulating buffers and windows}\label{sec:buffers_windows}
\begin{description}
\item[{\tt C-x o}] makes another window on the screen (if any) the
current window.
\item[{\tt C-x 0}] deletes the current window, expanding another window
to take its place.  The buffer being displayed in the current window
is not affected.
\item[{\tt C-x 1}] makes the current window the only window on the
screen, deleting all others.  The buffers being displayed in the
deleted windows are not affected.
\item[{\tt C-x 2}] splits the current window into two vertically (one
on top of the other), both displaying the same buffer.
\item[{\tt C-x 3}] splits the current window into two horizontally
(beside each other), each displaying the same buffer.
\item[{\tt C-x b}] prompts for a buffer name and switches the current
window to that buffer.  When trying to move to a buffer associated
with a file, it is better to use the file finding commands.
\item[{\tt C-x C-b}] lists the active buffers in a window.
\item[{\tt C-x k}] prompts for a buffer name
and deletes that buffer, displaying some other buffer in the current
window.  You will be warned if the contents of the buffer have been
modified and not yet saved.
\end{description}

\subsection{Auto-saving and recovery}\label{sec:autosave}
Buffers that are associated with files are periodically saved (``auto-saved'')
in
files whose names begin and end with `{\tt \#}'.  After a crash, you
can return yourself to the point at which the last auto-save of a
given file took place by using the following command in place of {\tt
C-x~C-f} or {\tt C-x~4~C-f}.
\begin{description}
\item[{\tt M-x recover-file}] prompts for a file name, $F$.  It then
tries to recover the contents of that file from an auto-save file
(named {\tt \#$F$\#}) in
the same directory, if such a file exists and is younger than the any
file named $F$ in the directory.  After completing this command, {\tt
C-x~C-s} will save the recovered file to $F$.
\end{description}

\section{On-line documentation}\label{sec:doc}

\subsection{UNIX documentation}\label{sec:man}
Emacs has a simple interface to the standard UNIX `{\tt
man}' command, which provides documentation to UNIX commands:
\begin{description}
\item[{\tt M-x manual-entry}] prompts for a topic (a UNIX command or
subprogram name, usually), and displays the man page for it, if any,
in a buffer.  The buffer is a perfectly ordinary buffer; you may put
the cursor in it and move around using ordinary Emacs navigational commands.
\end{description}

\subsection{Basic Emacs help}\label{sec:help}
The help command, {\tt C-h}, provides a variety of useful documentation.
The character following {\tt C-h}
indicates the specific kind of
service desired; the descriptions of several of these follow.
\begin{description}
\item[{\tt C-h a}] prompts for a pattern (regular expression) and
displays a buffer containing all commands whose name contains a match
to that pattern, together with a short description and the key
sequence to which the command is bound, if any.
\item[{\tt C-h b}] displays a buffer containing all
bindings of commands to keys.  The display is in two parts: the {\it
global bindings} that apply by default in any buffer, and the {\it
local bindings} that apply only when one is in the current buffer, and
override any global binding in that buffer.
\item[{\tt C-h f}] prompts for a function name and then displays its
full documentation in  a buffer.
\item[{\tt C-h C-h}] documents the help command itself.
\item[{\tt C-h i}] runs the `info' documentation reader (see below).
\item[{\tt C-h k}] prompts for a command key sequence
and describes the function invoked by that sequence.
\item[{\tt C-h m}] prints documentation about the mode of the current buffer.
\item[{\tt C-h t}] puts you into an Emacs tutorial.
\item[{\tt C-h w}] prompts for a function name and tells what key, if
any, invokes it.
\end{description}

\subsection{The info browser}\label{sec:info}
The key sequence {\tt C-h i} invokes the documentation browsing
system, {\tt info}.  Actually, this is little more than a buffer with some
special bindings to the keys.  Aside from the special bindings, the
ordinary Emacs commands will work while inside the {\tt info} buffer.
At any time, the {\tt info} buffer, whose name is {\tt *info*},
contains a {\it node}, a section of text documenting something.  These
nodes are connected to each other in such a way that one can move
quickly from one node to another that covers a related topic.  Some
nodes contain {\it menus}, indicated by lines that begin
\begin{verbatim}
  * Menu:
\end{verbatim}
The lines after this give the names of other nodes, and descriptions
of their contents.  One such entry reads as follows.
\begin{verbatim}
  * Commands::      Named functions run by key sequences to do editing.
\end{verbatim}
The word(s) between the asterisk and the double-colon name another node.
The following key commands, defined only when in the buffer {\tt *info*},
allow one to move through the documentation.  They are only a few of the ones provided.
\begin{description}
\item[{\tt m}] prompts for the name of a node from the menu in the
current buffer and
displays that node.  You need
only enter enough to identify the desired entry unambiguously; case is
ignored.
\item[{\tt f}] follows a cross-reference.  Cross references are
indicated in the text of a node by a phrase of the form
``{\tt *~Note~}{\it foo}{\tt ::}''.  One follows them by typing `f'
followed by the name ({\it foo}) of the referenced node, as for the
`m' command.
\item[{\tt l}] goes back to the last-visited node.
\item[{\tt u}] goes up to the parent of this node.  The definition
of parent is actually arbitrary, but is usually a node that contains
the current one in its menu.
\item[{\tt d}] returns to the top (initial) node of the Info system.
\item[{\tt q}] suspends the browser and goes back to where you were
when you issued {\tt C-h~i}.
\item[{\tt .}] returns to the beginning of the text of the current node.
\item[{\tt ?}] furnishes help about the browser commands.
\end{description}

\section{The shell}\label{sec:shell}
It is possible to run a UNIX shell under Emacs, and this allows any
number of useful effects.
The command {\tt M-x shell} moves to a buffer named {\tt *shell*}
that is running a UNIX shell
(creating it if necessary).  Anything typed into this buffer is sent
to the shell, just it would be outside of Emacs.  Any output
produced as a result of the commands sent to the shell is placed at
the end of the shell buffer.
Because the
shell is running in an Emacs window, the contents of the shell can be
edited and navigated
freely, and the entire record of the input and output to the
shell is available at all times.
A few keys have slightly different-from-usual meanings in the shell buffer.
\begin{description}
\item[{\tt RET}] sends whatever line the cursor is on to the shell and moves
to the end of the shell buffer.  Hence, one can repeat a command by
placing the cursor anywhere in it and typing {\tt RET}.
\item[{\tt TAB}] attempts to complete the immediately preceding file name.
\item[{\tt C-c C-c}] is the same as a single {\tt C-c} outside Emacs.
\item[{\tt C-c C-d}] is the same as {\tt C-d} (end-of-file) outside Emacs.
\item[{\tt C-c C-z}] is the same as {\tt C-z} outside Emacs.
\item[{\tt C-c C-u}] kills the current line of input to the shell.
\end{description}

\noindent It is sometimes useful to run a single shell command over
a region of text in a buffer.
\begin{description}
\item[{\tt M-$|$}] prompts for a shell command and executes it,
giving the current region as the standard input.  If the {\tt M-$|$}
is preceded by {\tt C-u}, the output of the command replaces the
region.  Otherwise, the output goes to a separate buffer.
For example, to sort the lines in the current region, enter the command {\tt
C-u~M-$|$~sort}.
\end{description}

\section{Running Scheme under Emacs}\label{sec:Scheme}
The best way to run Scheme from a workstation is to do so through
Emacs.  Just as you can create an Emacs buffer for communicating with
a UNIX shell (\S\ref{sec:shell}), you can also do so to communicate
with a Scheme interpreter.  Not only can you interact with the
interpreter, but you can also feed files or definitions that you are
editing to a running interpreter conveniently without having to load
them explicitly.

The command {\tt M-x run-scheme} moves to a buffer named {\tt
*scheme*} that is running the Scheme interpreter, creating this buffer if
necessary.  Each line that you type into this buffer gets sent to the
interpreter, just as if you had typed it in while running the
interpreter outside of Emacs.  Any output from the interpreter in
response to your input is appended to the {\tt *scheme*} buffer.

The usual way to create and execute a Scheme program is as follows.
\begin{itemize}
\item Using Emacs, create a file to contain your program (or load one
that you've already started) using {\tt C-x~C-f} or {\tt C-x~4~C-f}; let's
suppose the file is named {\tt something.scm} (so that within Emacs,
it lives in a buffer of the same name).
We have configured Emacs so
that any file ending in {\tt .scm} gets edited in Scheme mode, which
gives a special meaning to the keys {\tt TAB}, {\tt LFD}, and
others described below.

\item  Edit or add to your file as needed.
When typing definitions into the Emacs buffer for {\tt
something.scm}, using the {\tt TAB} key at the beginning of each line will
automatically indent that line properly.  Alternatively, you can end
each line by typing {\tt LFD} instead of {\tt RET};  in Scheme mode,
{\tt LFD} is short for {\tt RET TAB}.  If in the process of editing
the buffer, you mess up the indentation of a definition, place the
cursor at the beginning of the definition (on or before the opening
`(') and type {\tt M-C-q}, which will correctly indent the entire definition.

\item Make sure you have a Scheme buffer (named {\tt *scheme*})
running under Emacs ({\tt M-x
run-scheme}) will create one if you don't).

\item In the buffer for {\tt something.scm}, type {\tt C-c~M-l} to
load your program into the running Scheme interpreter.  Emacs
will ask you for a file name; just type {\tt RET}, which will use {\tt
something.scm}.  If you haven't saved your changes to {\tt
something.scm}, Emacs will ask if it should do it for you.  The effect
of
{\tt C-c~M-l} is to send the command {\tt (load "something.scm")} to
the Scheme interpreter and also to put the cursor in the {\tt
*scheme*} buffer, ready to enter Scheme expressions.  You'll see the
usual response to the {\tt load} command in the {\tt *scheme*} buffer.

\item Sometimes---especially when you are correcting a file whose contents
you've already loaded into Scheme---it is convenient to send just a
single revised definition to the Scheme interpreter.  To so do, place
the cursor at the beginning of the definition (on or before the
opening `(') and type {\tt C-c~M-e}.  This also puts you into the
Scheme buffer.
\end{itemize}

Here is a concise summary of the Scheme-related
commands.  These commands are also available from the menu bar.  With
the exception of {\tt M-x} commands, all of these commands are in
effect only in buffers that are in Scheme mode (normally, those
containing files whose name ends in {\tt .scm}).
\begin{description}
\item[{\tt M-x run-scheme}] when used for the first time, creates a
buffer named {\tt *scheme*} and runs the Scheme interpreter in it,
displaying input from you and output from the interpreter.  If the
buffer already exists, this command simply moves to that buffer.
\item[{\tt C-c~C-z}] puts the cursor in the {\tt *scheme*} buffer.
\item[{\tt C-c~M-e}] sends the definition after the cursor to Scheme
(that is, it copies it the {\tt*scheme*} buffer and then sends it to
the Scheme interpreter that attached to that buffer).  The command
also places the cursor at the end of the {\tt*scheme*} buffer.
\item[{\tt C-c~C-e}] is the same as {\tt C-c~M-e}, but leaves the cursor
where it is.
\item[{\tt C-c~M-l}] loads an entire file into Scheme
Prompts for a file name; the
default is the current buffer's file.  Puts the cursor at the end of
the {\tt
*scheme*} buffer.
\item[{\tt C-c~C-l}] is the same as {\tt C-c~M-l}, but leaves the cursor
where it is.
\item[{\tt C-c~M-r}] sends all the text in the current region to
Scheme and puts the cursor at the end of the {\tt *scheme*} buffer.
\item[{\tt C-c~C-r}] is the same as {\tt C-c~M-r}, but leaves the cursor
where it is.
\item[{\tt M-C-q}] indents the definition after the cursor according to
the usual rules for indenting Scheme expressions.
\item[{\tt M-C-\bs}] indents all Scheme expressions in the current
region.
\item[{\tt TAB}] indents the current line of Scheme code as appropriate for the
surrounding context.
\item[{\tt LFD}] is the same as {\tt RET}~{\tt TAB}.
\end{description}


\section{Compiling, debugging, and tags}\label{sec:compilation}
[This section is not relevant to CS61A.]
Emacs provides rather nice ways of compiling programs, correcting
any compilation errors, and debugging the results.
It is so much more convenient than entering compilation commands
directly from a shell that there is no excuse not to use it.

\subsection{Compilation}\label{sec:compile}
\begin{description}
\item[{\tt M-x compile}] prompts for a shell command, and then executes that
command in a special buffer, named {\tt *compilation*}.  The current
file at the time the {\tt M-x~compile} is issued determines the
directory in which the shell command executes.
The default
command is simply {\tt make~-k}.   Assuming you follow the convention
of putting an appropriate {\tt make} input file named {\tt makefile}
or {\tt Makefile} in each source directory, this command will
generally do the right thing.  While the compilation proceeds, you are
free to edit or use the {\tt *shell*} buffer.
\item[{\tt C-x `}] finds the next error message in the buffer {\tt
*compilation*} (if any), finds the source files and line referred to by the
error message, and displays the error message in one window and the
source file in another.  Thus, after a compilation is complete
(actually, even while it proceeds), you can step through the error
messages produced, going automatically to the offending points in the
source file so that they can be corrected.  The buffer {\tt
*compilation*} also contains the output from the {\tt M-x~grep} command
described in \S\ref{sec:search}.
\item[{\tt M-x kill-compiler}] cancels a
compilation started by {\tt M-x~compile}, if any.
\end{description}

\subsection{Using GDB under Emacs}
[This section is not relevant to CS61A.]
The GNU debugger, GDB, is an interactive source-level
debugger for C and several other languages.  It can be run under
Emacs, which provides a few rather nifty additional features.
Full on-line documentation of gdb is available using the {\tt C-h~i}
command in Emacs.
The command {\tt M-x~gdb} will prompt for an executable file name, and
then run GDB on that file, displaying the interaction in a
buffer that acts much like a shell buffer described previously.
Within that buffer, however, several commands have a slightly
different meaning.
In addition, whenever GDB displays the current position in the program
(for example, after a step, at a breakpoint, or after an interrupt),
Emacs will try to display the indicated source file and line in
another window, with an arrow (`{\tt =>}') pointing at the
corresponding line in the source text (this arrow is not actually in
the file being displayed).

The following commands are peculiar to GDB buffers.
\begin{description}
\item[{\tt C-c C-n}] performs a GDB `next' command (step to next
    line in the source program).
\item[{\tt C-c C-s}] performs a GDB `step' command (step to next line
    in the source program to be executed, stopping at the
    beginning of any procedure that gets called.)
\item[{\tt C-c C-i}] performs a GDB `stepi' command (step to next
    machine-language instruction---not usually used unless you are
    programming in assembly language.
\item[{\tt C-c <}] performs a GDB `up' command (go up to procedure
    that called current one).
\item[{\tt C-c >}] performs a GDB `down' command (opposite of `up').
\item[{\tt C-c C-r}] performs a GDB `finish' command (continues from
last breakpoint).
\item[{\tt C-c C-b}] set a breakpoint at the current position in the
program (as indicated by the position of the `{\tt =>}' arrow).
\item[{\tt C-c C-d}] delete a breakpoint (if any) at the current position in
the program (as indicated by the position of the `{\tt =>}' arrow).
\end{description}
In addition, within any source file buffer, there is the following command.
\begin{description}
\item[{\tt C-x SPC}] puts a break point at the point in the program
indicated by the cursor.
\end{description}

\subsection{Tags}
In UNIX terminology, a {\it tag table} is an index that tells how to
find the definition of any certain identifiers
(`tags') defined in some collection
of source files.  In effect, it provides a smart, multi-file search
that is particularly useful when navigating in non-trivial
directories of source files.  Typically, you set things up by
going into the directory
containing the source text to be indexed and issuing the UNIX command
\begin{quotation}
{\tt etags} {\it options files}
\end{quotation}
where {\it files} is a list of all the source files that need to be
indexed.  This creates a file named `TAGS' containing the tag table.
For C programs, the tags are the names of functions defined in the
named source files.
The {\tt -t} option causes {\tt etags} to record {\bf typedef}
declarations as well.  The tag table produced is organized in such a way that
simple edits to a source file will not invalidate it.
The following Emacs commands deal with tag tables.
\begin{description}
\item[{\tt M-x visit-tags-table}] prompts for the name of a tags table
file, and uses its contents in future tag-related searches.
\item[{\tt M-.}] prompts for a tag and then positions the current
window in the file containing its first definition and puts the cursor
on that definition.  You may also give a null response (just {\tt RET}), in
which case the word
before or around the point is used as the tag.
\item[{\tt C-u M-.}] finds the next alternate definition of the last
tag specified.
\item[{\tt C-x 4 .}] is the same as {\tt M-.}, but displays the text
containing the tag in the other window instead of the current one.
\item[{\tt M-x tags-search}] prompts and searches for a regular expression
as for {\tt C-M-s}, but is does a non-incremental
search through all the files given in the
currently-visited tag table.
\item[{\tt M-x tags-query-replace}] acts like {\tt M-Q}, but looks
through all the files given in the currently-visited tag table.
\item[{\tt M-,}] restarts the last {\tt tags-search} or {\tt
tags-query-replace} from the current location of the point.
\item[{\tt M-x tags-apropos}] prompts for a regular expression and
displays a list of all tags in the
currently-visited table that match it.
\end{description}

\section{But wait; there's more!}
As indicated at the beginning, this is not a complete reference
manual.   It has not covered
scrolling sideways,
tab setting, the mail system, the Emacs internal Lisp dialect,
automatic abbreviation, the spelling checker, the directory editor,
the change-log editor, or how to replace all groups of lines of your program
that are indented more than \ARG{} spaces by `$\ldots$'\footnote{You
probably think I'm kidding, don't you?   Guess again.}.
You can learn about these and other topics by using {\tt C-h~i}.  You
might also try typing {\tt C-h~f~SPC~C-x~o}, which creates a buffer
containing the names of all Emacs functions and then puts the cursor
there so that you can scroll through and look for likely-sounding names.

Just use it.  Every session is an adventure.



\end{document}
