This is ../../info/emacs, produced by makeinfo version 4.13 from
emacs.texi.

This is the Sixteenth edition of the `GNU Emacs Manual',
updated for Emacs version 23.4.

   Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998,
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012  Free Software Foundation, Inc.

     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 the Invariant Sections being "The GNU Manifesto,"
     "Distribution" and "GNU GENERAL PUBLIC LICENSE," with the
     Front-Cover texts being "A GNU Manual," and with the Back-Cover
     Texts as in (a) below.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."

     (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
     modify this GNU manual.  Buying copies from the FSF supports it in
     developing GNU and promoting software freedom."

INFO-DIR-SECTION Emacs
START-INFO-DIR-ENTRY
* Emacs: (emacs).       The extensible self-documenting text editor.
END-INFO-DIR-ENTRY


File: emacs,  Node: Operating on Files,  Next: Shell Commands in Dired,  Prev: Marks vs Flags,  Up: Dired

37.7 Operating on Files
=======================

This section describes the basic Dired commands to operate on one file
or several files.  All of these commands are capital letters; all of
them use the minibuffer, either to read an argument or to ask for
confirmation, before they act.  All of them let you specify the files
to manipulate in these ways:

   * If you give the command a numeric prefix argument N, it operates
     on the next N files, starting with the current file.  (If N is
     negative, the command operates on the -N files preceding the
     current line.)

   * Otherwise, if some files are marked with `*', the command operates
     on all those files.

   * Otherwise, the command operates on the current file only.

Certain other Dired commands, such as `!' and the `%' commands, use the
same conventions to decide which files to work on.

   Commands which ask for a destination directory, such as those which
copy and rename files or create links for them, try to guess the default
target directory for the operation.  Normally, they suggest the Dired
buffer's default directory, but if the variable `dired-dwim-target' is
non-`nil', and if there is another Dired buffer displayed in the next
window, that other buffer's directory is suggested instead.

   Here are the file-manipulating Dired commands that operate on files.

`C NEW <RET>'
     Copy the specified files (`dired-do-copy').  The argument NEW is
     the directory to copy into, or (if copying a single file) the new
     name.  This is like the shell command `cp'.

     If `dired-copy-preserve-time' is non-`nil', then copying with this
     command preserves the modification time of the old file in the
     copy, like `cp -p'.

     The variable `dired-recursive-copies' controls whether to copy
     directories recursively (like `cp -r').  The default is `nil',
     which means that directories cannot be copied.

`D'
     Delete the specified files (`dired-do-delete').  This is like the
     shell command `rm'.

     Like the other commands in this section, this command operates on
     the _marked_ files, or the next N files.  By contrast, `x'
     (`dired-do-flagged-delete') deletes all "flagged" files.

`R NEW <RET>'
     Rename the specified files (`dired-do-rename').  If you rename a
     single file, the argument NEW is the new name of the file.  If you
     rename several files, the argument NEW is the directory into which
     to move the files (this is like the shell command `mv').

     Dired automatically changes the visited file name of buffers
     associated with renamed files so that they refer to the new names.

`H NEW <RET>'
     Make hard links to the specified files (`dired-do-hardlink').
     This is like the shell command `ln'.  The argument NEW is the
     directory to make the links in, or (if making just one link) the
     name to give the link.

`S NEW <RET>'
     Make symbolic links to the specified files (`dired-do-symlink').
     This is like `ln -s'.  The argument NEW is the directory to make
     the links in, or (if making just one link) the name to give the
     link.

`M MODESPEC <RET>'
     Change the mode (also called "permission bits") of the specified
     files (`dired-do-chmod').  This uses the `chmod' program, so
     MODESPEC can be any argument that `chmod' can handle.

`G NEWGROUP <RET>'
     Change the group of the specified files to NEWGROUP
     (`dired-do-chgrp').

`O NEWOWNER <RET>'
     Change the owner of the specified files to NEWOWNER
     (`dired-do-chown').  (On most systems, only the superuser can do
     this.)

     The variable `dired-chown-program' specifies the name of the
     program to use to do the work (different systems put `chown' in
     different places).

`T TIMESTAMP <RET>'
     Touch the specified files (`dired-do-touch').  This means updating
     their modification times to the present time.  This is like the
     shell command `touch'.

`P COMMAND <RET>'
     Print the specified files (`dired-do-print').  You must specify the
     command to print them with, but the minibuffer starts out with a
     suitable guess made using the variables `lpr-command' and
     `lpr-switches' (the same variables that `lpr-buffer' uses; *note
     Printing::).

`Z'
     Compress the specified files (`dired-do-compress').  If the file
     appears to be a compressed file already, uncompress it instead.

`L'
     Load the specified Emacs Lisp files (`dired-do-load').  *Note Lisp
     Libraries::.

`B'
     Byte compile the specified Emacs Lisp files
     (`dired-do-byte-compile').  *Note Byte Compilation: (elisp)Byte
     Compilation.

`A REGEXP <RET>'
     Search all the specified files for the regular expression REGEXP
     (`dired-do-search').

     This command is a variant of `tags-search'.  The search stops at
     the first match it finds; use `M-,' to resume the search and find
     the next match.  *Note Tags Search::.

`Q REGEXP <RET> TO <RET>'
     Perform `query-replace-regexp' on each of the specified files,
     replacing matches for REGEXP with the string TO
     (`dired-do-query-replace-regexp').

     This command is a variant of `tags-query-replace'.  If you exit the
     query replace loop, you can use `M-,' to resume the scan and
     replace more matches.  *Note Tags Search::.


File: emacs,  Node: Shell Commands in Dired,  Next: Transforming File Names,  Prev: Operating on Files,  Up: Dired

37.8 Shell Commands in Dired
============================

The Dired command `!' (`dired-do-shell-command') reads a shell command
string in the minibuffer and runs that shell command on one or more
files.  The files that the shell command operates on are determined in
the usual way for Dired commands (*note Operating on Files::).  The
command `X' is a synonym for `!'.

   The command `&' (`dired-do-async-shell-command') does the same,
except that it runs the shell command asynchronously.  You can also do
this with `!', by appending a `&' character to the end of the shell
command.

   For both `!' and `&', the working directory for the shell command is
the top-level directory of the Dired buffer.

   If you tell `!' or `&' to operate on more than one file, the shell
command string determines how those files are passed to the shell
command:

   * If you use `*' surrounded by whitespace in the command string,
     then the command runs just once, with the list of file names
     substituted for the `*'.  The order of file names is the order of
     appearance in the Dired buffer.

     Thus, `! tar cf foo.tar * <RET>' runs `tar' on the entire list of
     file names, putting them into one tar file `foo.tar'.

     If you want to use `*' as a shell wildcard with whitespace around
     it, write `*""'.  In the shell, this is equivalent to `*'; but
     since the `*' is not surrounded by whitespace, Dired does not
     treat it specially.

   * Otherwise, if the command string contains `?' surrounded by
     whitespace, Emacs runs the shell command once _for each file_,
     substituting the current file name for `?' each time.  You can use
     `?' more than once in the command; the same file name replaces
     each occurrence.

   * If the command string contains neither `*' nor `?', Emacs runs the
     shell command once for each file, adding the file name is added at
     the end.  For example, `! uudecode <RET>' runs `uudecode' on each
     file.

   To iterate over the file names in a more complicated fashion, use an
explicit shell loop.  For example, here is how to uuencode each file,
making the output file name by appending `.uu' to the input file name:

     for file in * ; do uuencode "$file" "$file" >"$file".uu; done

   The `!' and `&' commands do not attempt to update the Dired buffer
to show new or modified files, because they don't know what files will
be changed.  Use the `g' command to update the Dired buffer (*note
Dired Updating::).

   *Note Single Shell::, for information about running shell commands
outside Dired.


File: emacs,  Node: Transforming File Names,  Next: Comparison in Dired,  Prev: Shell Commands in Dired,  Up: Dired

37.9 Transforming File Names in Dired
=====================================

This section describes Dired commands which alter file names in a
systematic way.  Each command operates on some or all of the marked
files, using a new name made by transforming the existing name.

   Like the basic Dired file-manipulation commands (*note Operating on
Files::), the commands described here operate either on the next N
files, or on all files marked with `*', or on the current file.  (To
mark files, use the commands described in *note Marks vs Flags::.)

   All of the commands described in this section work _interactively_:
they ask you to confirm the operation for each candidate file.  Thus,
you can select more files than you actually need to operate on (e.g.,
with a regexp that matches many files), and then filter the selected
names by typing `y' or `n' when the command prompts for confirmation.

`% u'
     Rename each of the selected files to an upper-case name
     (`dired-upcase').  If the old file names are `Foo' and `bar', the
     new names are `FOO' and `BAR'.

`% l'
     Rename each of the selected files to a lower-case name
     (`dired-downcase').  If the old file names are `Foo' and `bar',
     the new names are `foo' and `bar'.

`% R FROM <RET> TO <RET>'
`% C FROM <RET> TO <RET>'
`% H FROM <RET> TO <RET>'
`% S FROM <RET> TO <RET>'
     These four commands rename, copy, make hard links and make soft
     links, in each case computing the new name by regular-expression
     substitution from the name of the old file.

   The four regular-expression substitution commands effectively
perform a search-and-replace on the selected file names.  They read two
arguments: a regular expression FROM, and a substitution pattern TO;
they match each "old" file name against FROM, and then replace the
matching part with TO.  You can use `\&' and `\DIGIT' in TO to refer to
all or part of what the pattern matched in the old file name, as in
`replace-regexp' (*note Regexp Replace::).  If the regular expression
matches more than once in a file name, only the first match is replaced.

   For example, `% R ^.*$ <RET> x-\& <RET>' renames each selected file
by prepending `x-' to its name.  The inverse of this, removing `x-'
from the front of each file name, is also possible: one method is `% R
^x-\(.*\)$ <RET> \1 <RET>'; another is `% R ^x- <RET> <RET>'.  (Use `^'
and `$' to anchor matches that should span the whole file name.)

   Normally, the replacement process does not consider the files'
directory names; it operates on the file name within the directory.  If
you specify a numeric argument of zero, then replacement affects the
entire absolute file name including directory name.  (A non-zero
argument specifies the number of files to operate on.)

   You may want to select the set of files to operate on using the same
regexp FROM that you will use to operate on them.  To do this, mark
those files with `% m FROM <RET>', then use the same regular expression
in the command to operate on the files.  To make this more convenient,
the `%' commands to operate on files use the last regular expression
specified in any `%' command as a default.


File: emacs,  Node: Comparison in Dired,  Next: Subdirectories in Dired,  Prev: Transforming File Names,  Up: Dired

37.10 File Comparison with Dired
================================

Here are two Dired commands that compare specified files using `diff'.
They show the output in a buffer using Diff mode (*note Comparing
Files::).

`='
     Compare the current file (the file at point) with another file (the
     file at the mark) using the `diff' program (`dired-diff').  The
     file at the mark is the first argument of `diff', and the file at
     point is the second argument.  This refers to the ordinary Emacs
     mark, not Dired marks; use `C-<SPC>' (`set-mark-command') to set
     the mark at the first file's line (*note Setting Mark::).

`M-='
     Compare the current file with its latest backup file
     (`dired-backup-diff').  If the current file is itself a backup,
     compare it with the file it is a backup of; this way, you can
     compare a file with any one of its backups.

     The backup file is the first file given to `diff'.


File: emacs,  Node: Subdirectories in Dired,  Next: Subdir Switches,  Prev: Comparison in Dired,  Up: Dired

37.11 Subdirectories in Dired
=============================

A Dired buffer displays just one directory in the normal case; but you
can optionally include its subdirectories as well.

   The simplest way to include multiple directories in one Dired buffer
is to specify the options `-lR' for running `ls'.  (If you give a
numeric argument when you run Dired, then you can specify these options
in the minibuffer.)  That produces a recursive directory listing showing
all subdirectories at all levels.

   More often, you will want to show only specific subdirectories.  You
can do this with the `i' command:

`i'
     Insert the contents of a subdirectory later in the buffer.

   Use the `i' (`dired-maybe-insert-subdir') command on a line that
describes a file which is a directory.  It inserts the contents of that
directory into the same Dired buffer, and moves there.  Inserted
subdirectory contents follow the top-level directory of the Dired
buffer, just as they do in `ls -lR' output.

   If the subdirectory's contents are already present in the buffer, the
`i' command just moves to it.

   In either case, `i' sets the Emacs mark before moving, so `C-u
C-<SPC>' takes you back to the old position in the buffer (the line
describing that subdirectory).  You can also use `^' to return to the
parent directory in the same Dired buffer.

   Use the `l' command (`dired-do-redisplay') to update the
subdirectory's contents.  Use `C-u k' on the subdirectory header line
to delete the subdirectory (*note Dired Updating::).  You can also hide
and show inserted subdirectories (*note Hiding Subdirectories::).


File: emacs,  Node: Subdir Switches,  Next: Subdirectory Motion,  Prev: Subdirectories in Dired,  Up: Dired

37.12 Subdirectory Switches in Dired
====================================

You can insert subdirectories with specified `ls' switches in Dired
buffers using `C-u i'.  You can change the `ls' switches of an already
inserted subdirectory using `C-u l'.

   Dired preserves the switches if you revert the buffer.  Deleting a
subdirectory forgets about its switches.

   Using `dired-undo' (usually bound to `C-_' and `C-x u') to reinsert
or delete subdirectories that were inserted with explicit switches can
bypass Dired's machinery for remembering (or forgetting) switches.
Deleting a subdirectory using `dired-undo' does not forget its
switches.  When later reinserted using `i', it will be reinserted using
its old switches.  Using `dired-undo' to reinsert a subdirectory that
was deleted using the regular Dired commands (not `dired-undo') will
originally insert it with its old switches.  Reverting the buffer,
however, will relist it using the buffer's default switches.  If any of
this yields problems, you can easily correct the situation using `C-u
i' or `C-u l'.

   Dired does not remember the `R' switch.  Inserting a subdirectory
with switches that include the `R' switch is equivalent to inserting
each of its subdirectories using all remaining switches.  For instance,
updating or killing a subdirectory that was inserted with the `R'
switch will not update or kill its subdirectories.

   The buffer's default switches do not affect subdirectories that were
inserted using explicitly specified switches.  In particular, commands
such as `s' that change the buffer's switches do not affect such
subdirectories.  (They do, however, affect subdirectories without
explicitly assigned switches.)

   You can make Dired forget about all subdirectory switches and relist
all subdirectories with the buffer's default switches using `M-x
dired-reset-subdir-switches'.  This also reverts the Dired buffer.


File: emacs,  Node: Subdirectory Motion,  Next: Hiding Subdirectories,  Prev: Subdir Switches,  Up: Dired

37.13 Moving Over Subdirectories
================================

When a Dired buffer lists subdirectories, you can use the page motion
commands `C-x [' and `C-x ]' to move by entire directories (*note
Pages::).

   The following commands move across, up and down in the tree of
directories within one Dired buffer.  They move to "directory header
lines", which are the lines that give a directory's name, at the
beginning of the directory's contents.

`C-M-n'
     Go to next subdirectory header line, regardless of level
     (`dired-next-subdir').

`C-M-p'
     Go to previous subdirectory header line, regardless of level
     (`dired-prev-subdir').

`C-M-u'
     Go up to the parent directory's header line (`dired-tree-up').

`C-M-d'
     Go down in the directory tree, to the first subdirectory's header
     line (`dired-tree-down').

`<'
     Move up to the previous directory-file line (`dired-prev-dirline').
     These lines are the ones that describe a directory as a file in its
     parent directory.

`>'
     Move down to the next directory-file line (`dired-prev-dirline').


File: emacs,  Node: Hiding Subdirectories,  Next: Dired Updating,  Prev: Subdirectory Motion,  Up: Dired

37.14 Hiding Subdirectories
===========================

"Hiding" a subdirectory means to make it invisible, except for its
header line.

`$'
     Hide or show the subdirectory that point is in, and move point to
     the next subdirectory (`dired-hide-subdir').  This is a toggle.  A
     numeric argument serves as a repeat count.

`M-$'
     Hide all subdirectories in this Dired buffer, leaving only their
     header lines (`dired-hide-all').  Or, if any subdirectory is
     currently hidden, make all subdirectories visible again.  You can
     use this command to get an overview in very deep directory trees
     or to move quickly to subdirectories far away.

   Ordinary Dired commands never consider files inside a hidden
subdirectory.  For example, the commands to operate on marked files
ignore files in hidden directories even if they are marked.  Thus you
can use hiding to temporarily exclude subdirectories from operations
without having to remove the Dired marks on files in those
subdirectories.

   *Note Dired Updating::, for how to insert or delete a subdirectory
listing.


File: emacs,  Node: Dired Updating,  Next: Dired and Find,  Prev: Hiding Subdirectories,  Up: Dired

37.15 Updating the Dired Buffer
===============================

This section describes commands to update the Dired buffer to reflect
outside (non-Dired) changes in the directories and files, and to delete
part of the Dired buffer.

`g'
     Update the entire contents of the Dired buffer (`revert-buffer').

`l'
     Update the specified files (`dired-do-redisplay').  You specify the
     files for `l' in the same way as for file operations.

`k'
     Delete the specified _file lines_--not the files, just the lines
     (`dired-do-kill-lines').

`s'
     Toggle between alphabetical order and date/time order
     (`dired-sort-toggle-or-edit').

`C-u s SWITCHES <RET>'
     Refresh the Dired buffer using SWITCHES as
     `dired-listing-switches'.

   Type `g' (`revert-buffer') to update the contents of the Dired
buffer, based on changes in the files and directories listed.  This
preserves all marks except for those on files that have vanished.
Hidden subdirectories are updated but remain hidden.

   To update only some of the files, type `l' (`dired-do-redisplay').
Like the Dired file-operating commands, this command operates on the
next N files (or previous -N files), or on the marked files if any, or
on the current file.  Updating the files means reading their current
status, then updating their lines in the buffer to indicate that status.

   If you use `l' on a subdirectory header line, it updates the
contents of the corresponding subdirectory.

   If you use `C-x d' or some other Dired command to visit a directory
that is already being shown in a Dired buffer, Dired switches to that
buffer but does not update it.  If the buffer is not up-to-date, Dired
displays a warning telling you to type <g> to update it.  You can also
tell Emacs to revert each Dired buffer automatically when you revisit
it, by setting the variable `dired-auto-revert-buffer' to a non-`nil'
value.

   To delete the specified _file lines_ from the buffer--not delete the
files--type `k' (`dired-do-kill-lines').  Like the file-operating
commands, this command operates on the next N files, or on the marked
files if any; but it does not operate on the current file as a last
resort.

   If you use `k' with a numeric prefix argument to kill the line for a
file that is a directory, which you have inserted in the Dired buffer
as a subdirectory, it deletes that subdirectory from the buffer as
well.  Typing `C-u k' on the header line for a subdirectory also
deletes the subdirectory from the Dired buffer.

   The `g' command brings back any individual lines that you have
killed in this way, but not subdirectories--you must use `i' to
reinsert a subdirectory.

   The files in a Dired buffers are normally listed in alphabetical
order by file names.  Alternatively Dired can sort them by date/time.
The Dired command `s' (`dired-sort-toggle-or-edit') switches between
these two sorting modes.  The mode line in a Dired buffer indicates
which way it is currently sorted--by name, or by date.

   `C-u s SWITCHES <RET>' lets you specify a new value for
`dired-listing-switches'.


File: emacs,  Node: Dired and Find,  Next: Wdired,  Prev: Dired Updating,  Up: Dired

37.16 Dired and `find'
======================

You can select a set of files for display in a Dired buffer more
flexibly by using the `find' utility to choose the files.

   To search for files with names matching a wildcard pattern use `M-x
find-name-dired'.  It reads arguments DIRECTORY and PATTERN, and
chooses all the files in DIRECTORY or its subdirectories whose
individual names match PATTERN.

   The files thus chosen are displayed in a Dired buffer, in which the
ordinary Dired commands are available.

   If you want to test the contents of files, rather than their names,
use `M-x find-grep-dired'.  This command reads two minibuffer
arguments, DIRECTORY and REGEXP; it chooses all the files in DIRECTORY
or its subdirectories that contain a match for REGEXP.  It works by
running the programs `find' and `grep'.  See also `M-x grep-find', in
*note Grep Searching::.  Remember to write the regular expression for
`grep', not for Emacs.  (An alternative method of showing files whose
contents match a given regexp is the `% g REGEXP' command, see *note
Marks vs Flags::.)

   The most general command in this series is `M-x find-dired', which
lets you specify any condition that `find' can test.  It takes two
minibuffer arguments, DIRECTORY and FIND-ARGS; it runs `find' in
DIRECTORY, passing FIND-ARGS to tell `find' what condition to test.  To
use this command, you need to know how to use `find'.

   The format of listing produced by these commands is controlled by the
variable `find-ls-option', whose default value specifies using options
`-ld' for `ls'.  If your listings are corrupted, you may need to change
the value of this variable.

   The command `M-x locate' provides a similar interface to the
`locate' program.  `M-x locate-with-filter' is similar, but keeps only
files whose names match a given regular expression.

   These buffers don't work entirely like ordinary Dired buffers: file
operations work, but do not always automatically update the buffer.
Reverting the buffer with `g' deletes all inserted subdirectories, and
erases all flags and marks.


File: emacs,  Node: Wdired,  Next: Image-Dired,  Prev: Dired and Find,  Up: Dired

37.17 Editing the Dired Buffer
==============================

Wdired is a special mode that allows you to perform file operations by
editing the Dired buffer directly (the "W" in "Wdired" stands for
"writable.")  To enter Wdired mode, type `C-x C-q'
(`dired-toggle-read-only') while in a Dired buffer.  Alternatively, use
the `Immediate / Edit File Names' menu item.

   While in Wdired mode, you can rename files by editing the file names
displayed in the Dired buffer.  All the ordinary Emacs editing
commands, including rectangle operations and `query-replace', are
available for this.  Once you are done editing, type `C-c C-c'
(`wdired-finish-edit').  This applies your changes and switches back to
ordinary Dired mode.

   Apart from simply renaming files, you can move a file to another
directory by typing in the new file name (either absolute or relative).
To mark a file for deletion, delete the entire file name.  To change
the target of a symbolic link, edit the link target name which appears
next to the link name.

   The rest of the text in the buffer, such as the file sizes and
modification dates, is marked read-only, so you can't edit it.
However, if you set `wdired-allow-to-change-permissions' to `t', you
can edit the file permissions.  For example, you can change
`-rw-r--r--' to `-rw-rw-rw-' to make a file world-writable.  These
changes also take effect when you type `C-c C-c'.


File: emacs,  Node: Image-Dired,  Next: Misc Dired Features,  Prev: Wdired,  Up: Dired

37.18 Viewing Image Thumbnails in Dired
=======================================

Image-Dired is a facility for browsing image files.  It provides viewing
the images either as thumbnails or in full size, either inside Emacs or
through an external viewer.

   To enter Image-Dired, mark the image files you want to look at in
the Dired buffer, using `m' as usual.  Then type `C-t d'
(`image-dired-display-thumbs').  This creates and switches to a buffer
containing image-dired, corresponding to the marked files.

   You can also enter Image-Dired directly by typing `M-x image-dired'.
This prompts for a directory; specify one that has image files.  This
creates thumbnails for all the images in that directory, and displays
them all in the "thumbnail buffer."  This takes a long time if the
directory contains many image files, and it asks for confirmation if
the number of image files exceeds
`image-dired-show-all-from-dir-max-files'.

   With point in the thumbnail buffer, you can type `RET'
(`image-dired-display-thumbnail-original-image') to display a sized
version of it in another window.  This sizes the image to fit the
window.  Use the arrow keys to move around in the buffer.  For easy
browsing, use `SPC' (`image-dired-display-next-thumbnail-original') to
advance and display the next image.  Typing `DEL'
(`image-dired-display-previous-thumbnail-original') backs up to the
previous thumbnail and displays that instead.

   To view and the image in its original size, either provide a prefix
argument (`C-u') before pressing `RET', or type `C-<RET>'
(`image-dired-thumbnail-display-external') to display the image in an
external viewer.  You must first configure
`image-dired-external-viewer'.

   You can delete images through Image-Dired also.  Type `d'
(`image-dired-flag-thumb-original-file') to flag the image file for
deletion in the Dired buffer.  You can also delete the thumbnail image
from the thumbnail buffer with `C-d' (`image-dired-delete-char').

   More advanced features include "image tags", which are metadata used
to categorize image files.  The tags are stored in a plain text file
configured by `image-dired-db-file'.

   To tag image files, mark them in the dired buffer (you can also mark
files in Dired from the thumbnail buffer by typing `m') and type `C-t
t' (`image-dired-tag-files').  This reads the tag name in the
minibuffer.  To mark files having a certain tag, type `C-t f'
(`image-dired-mark-tagged-files').  After marking image files with a
certain tag, you can use `C-t d' to view them.

   You can also tag a file directly from the thumbnail buffer by typing
`t t' and you can remove a tag by typing `t r'.  There is also a
special "tag" called "comment" for each file (it is not a tag in the
exact same sense as the other tags, it is handled slightly different).
That is used to enter a comment or description about the image.  You
comment a file from the thumbnail buffer by typing `c'.  You will be
prompted for a comment.  Type `C-t c' to add a comment from Dired
(`image-dired-dired-comment-files').

   Image-Dired also provides simple image manipulation.  In the
thumbnail buffer, type `L' to rotate the original image 90 degrees anti
clockwise, and `R' to rotate it 90 degrees clockwise.  This rotation is
lossless, and uses an external utility called JpegTRAN.


File: emacs,  Node: Misc Dired Features,  Prev: Image-Dired,  Up: Dired

37.19 Other Dired Features
==========================

The command `+' (`dired-create-directory') reads a directory name, and
creates the directory if it does not already exist.

   The command `M-s a C-s' (`dired-do-isearch') begins a "multi-file"
incremental search on the marked files.  If a search fails at the end
of a file, typing `C-s' advances to the next marked file and repeats
the search; at the end of the last marked file, the search wraps around
to the first marked file.  The command `M-s a M-C-s'
(`dired-do-isearch-regexp') does the same with a regular expression
search.  *Note Repeat Isearch::, for information about search
repetition.

   The command `w' (`dired-copy-filename-as-kill') puts the names of
the marked (or next N) files into the kill ring, as if you had killed
them with `C-w'.  The names are separated by a space.

   With a zero prefix argument, this uses the absolute file name of
each marked file.  With just `C-u' as the prefix argument, it uses file
names relative to the Dired buffer's default directory.  (This can
still contain slashes if in a subdirectory.)  As a special case, if
point is on a directory headerline, `w' gives you the absolute name of
that directory.  Any prefix argument or marked files are ignored in
this case.

   The main purpose of this command is so that you can yank the file
names into arguments for other Emacs commands.  It also displays what
it added to the kill ring, so you can use it to display the list of
currently marked files in the echo area.

   If the directory you are visiting is under version control (*note
Version Control::), then the normal VC diff and log commands will
operate on the selected files.

   The command `M-x dired-compare-directories' is used to compare the
current Dired buffer with another directory.  It marks all the files
that are "different" between the two directories.  It puts these marks
in all Dired buffers where these files are listed, which of course
includes the current buffer.

   The default comparison method (used if you type <RET> at the prompt)
is to compare just the file names--each file name that does not appear
in the other directory is "different."  You can specify more stringent
comparisons by entering a Lisp expression, which can refer to the
variables `size1' and `size2', the respective file sizes; `mtime1' and
`mtime2', the last modification times in seconds, as floating point
numbers; and `fa1' and `fa2', the respective file attribute lists (as
returned by the function `file-attributes').  This expression is
evaluated for each pair of like-named files, and if the expression's
value is non-`nil', those files are considered "different."

   For instance, the sequence `M-x dired-compare-directories <RET> (>
mtime1 mtime2) <RET>' marks files newer in this directory than in the
other, and marks files older in the other directory than in this one.
It also marks files with no counterpart, in both directories, as always.

   On the X window system, Emacs supports the "drag and drop" protocol.
You can drag a file object from another program, and drop it onto a
Dired buffer; this either moves, copies, or creates a link to the file
in that directory.  Precisely which action is taken is determined by
the originating program.  Dragging files out of a Dired buffer is
currently not supported.


File: emacs,  Node: Calendar/Diary,  Next: Document View,  Prev: Dired,  Up: Top

38 The Calendar and the Diary
*****************************

Emacs provides the functions of a desk calendar, with a diary of
planned or past events.  It also has facilities for managing your
appointments, and keeping track of how much time you spend working on
certain projects.

   To enter the calendar, type `M-x calendar'; this displays a
three-month calendar centered on the current month, with point on the
current date.  With a numeric argument, as in `C-u M-x calendar', it
prompts you for the month and year to be the center of the three-month
calendar.  The calendar uses its own buffer, whose major mode is
Calendar mode.

   `Mouse-3' in the calendar brings up a menu of operations on a
particular date; `Mouse-2' brings up a menu of commonly used calendar
features that are independent of any particular date.  To exit the
calendar, type `q'.

* Menu:

* Calendar Motion::     Moving through the calendar; selecting a date.
* Scroll Calendar::     Bringing earlier or later months onto the screen.
* Counting Days::       How many days are there between two dates?
* General Calendar::    Exiting or recomputing the calendar.
* Writing Calendar Files:: Writing calendars to files of various formats.
* Holidays::            Displaying dates of holidays.
* Sunrise/Sunset::      Displaying local times of sunrise and sunset.
* Lunar Phases::        Displaying phases of the moon.
* Other Calendars::     Converting dates to other calendar systems.
* Diary::               Displaying events from your diary.
* Appointments::        Reminders when it's time to do something.
* Importing Diary::     Converting diary events to/from other formats.
* Daylight Saving::     How to specify when daylight saving time is active.
* Time Intervals::      Keeping track of time intervals.

* Advanced Calendar/Diary Usage:: Advanced Calendar/Diary customization.


File: emacs,  Node: Calendar Motion,  Next: Scroll Calendar,  Up: Calendar/Diary

38.1 Movement in the Calendar
=============================

Calendar mode provides commands to move through the calendar in logical
units of time such as days, weeks, months, and years.  If you move
outside the three months originally displayed, the calendar display
"scrolls" automatically through time to make the selected date visible.
Moving to a date lets you view its holidays or diary entries, or
convert it to other calendars; moving by long time periods is also
useful simply to scroll the calendar.

* Menu:

* Calendar Unit Motion::      Moving by days, weeks, months, and years.
* Move to Beginning or End::  Moving to start/end of weeks, months, and years.
* Specified Dates::           Moving to the current date or another
                                specific date.


File: emacs,  Node: Calendar Unit Motion,  Next: Move to Beginning or End,  Up: Calendar Motion

38.1.1 Motion by Standard Lengths of Time
-----------------------------------------

The commands for movement in the calendar buffer parallel the commands
for movement in text.  You can move forward and backward by days,
weeks, months, and years.

`C-f'
     Move point one day forward (`calendar-forward-day').

`C-b'
     Move point one day backward (`calendar-backward-day').

`C-n'
     Move point one week forward (`calendar-forward-week').

`C-p'
     Move point one week backward (`calendar-backward-week').

`M-}'
     Move point one month forward (`calendar-forward-month').

`M-{'
     Move point one month backward (`calendar-backward-month').

`C-x ]'
     Move point one year forward (`calendar-forward-year').

`C-x ['
     Move point one year backward (`calendar-backward-year').

   The day and week commands are natural analogues of the usual Emacs
commands for moving by characters and by lines.  Just as `C-n' usually
moves to the same column in the following line, in Calendar mode it
moves to the same day in the following week.  And `C-p' moves to the
same day in the previous week.

   The arrow keys are equivalent to `C-f', `C-b', `C-n' and `C-p', just
as they normally are in other modes.

   The commands for motion by months and years work like those for
weeks, but move a larger distance.  The month commands `M-}' and `M-{'
move forward or backward by an entire month.  The year commands `C-x ]'
and `C-x [' move forward or backward a whole year.

   The easiest way to remember these commands is to consider months and
years analogous to paragraphs and pages of text, respectively.  But the
commands themselves are not quite analogous.  The ordinary Emacs
paragraph commands move to the beginning or end of a paragraph, whereas
these month and year commands move by an entire month or an entire
year, keeping the same date within the month or year.

   All these commands accept a numeric argument as a repeat count.  For
convenience, the digit keys and the minus sign specify numeric
arguments in Calendar mode even without the Meta modifier.  For example,
`100 C-f' moves point 100 days forward from its present location.


File: emacs,  Node: Move to Beginning or End,  Next: Specified Dates,  Prev: Calendar Unit Motion,  Up: Calendar Motion

38.1.2 Beginning or End of Week, Month or Year
----------------------------------------------

A week (or month, or year) is not just a quantity of days; we think of
weeks (months, years) as starting on particular dates.  So Calendar mode
provides commands to move to the beginning or end of a week, month or
year:

`C-a'
     Move point to start of week (`calendar-beginning-of-week').  

`C-e'
     Move point to end of week (`calendar-end-of-week').  

`M-a'
     Move point to start of month (`calendar-beginning-of-month').  

`M-e'
     Move point to end of month (`calendar-end-of-month').  

`M-<'
     Move point to start of year (`calendar-beginning-of-year').  

`M->'
     Move point to end of year (`calendar-end-of-year').

   These commands also take numeric arguments as repeat counts, with the
repeat count indicating how many weeks, months, or years to move
backward or forward.

   By default, weeks begin on Sunday.  To make them begin on Monday
instead, set the variable `calendar-week-start-day' to 1.


File: emacs,  Node: Specified Dates,  Prev: Move to Beginning or End,  Up: Calendar Motion

38.1.3 Specified Dates
----------------------

Calendar mode provides commands for moving to a particular date
specified in various ways.

`g d'
     Move point to specified date (`calendar-goto-date').

`g D'
     Move point to specified day of year (`calendar-goto-day-of-year').

`g w'
     Move point to specified week of year (`calendar-iso-goto-week').

`o'
     Center calendar around specified month (`calendar-other-month').

`.'
     Move point to today's date (`calendar-goto-today').

   `g d' (`calendar-goto-date') prompts for a year, a month, and a day
of the month, and then moves to that date.  Because the calendar
includes all dates from the beginning of the current era, you must type
the year in its entirety; that is, type `1990', not `90'.

   `g D' (`calendar-goto-day-of-year') prompts for a year and day
number, and moves to that date.  Negative day numbers count backward
from the end of the year.  `g w' (`calendar-iso-goto-week') prompts for
a year and week number, and moves to that week.

   `o' (`calendar-other-month') prompts for a month and year, then
centers the three-month calendar around that month.

   You can return to today's date with `.' (`calendar-goto-today').


File: emacs,  Node: Scroll Calendar,  Next: Counting Days,  Prev: Calendar Motion,  Up: Calendar/Diary

38.2 Scrolling in the Calendar
==============================

The calendar display scrolls automatically through time when you move
out of the visible portion.  You can also scroll it manually.  Imagine
that the calendar window contains a long strip of paper with the months
on it.  Scrolling the calendar means moving the strip horizontally, so
that new months become visible in the window.

`>'
     Scroll calendar one month forward (`calendar-scroll-left').

`<'
     Scroll calendar one month backward (`calendar-scroll-right').

`C-v'
`<next>'
     Scroll calendar three months forward
     (`calendar-scroll-left-three-months').

`M-v'
`<prior>'
     Scroll calendar three months backward
     (`calendar-scroll-right-three-months').

   The most basic calendar scroll commands scroll by one month at a
time.  This means that there are two months of overlap between the
display before the command and the display after.  `>' scrolls the
calendar contents one month forward in time.  `<' scrolls the contents
one month backwards in time.

   The commands `C-v' and `M-v' scroll the calendar by an entire
"screenful"--three months--in analogy with the usual meaning of these
commands.  `C-v' makes later dates visible and `M-v' makes earlier
dates visible.  These commands take a numeric argument as a repeat
count; in particular, since `C-u' multiplies the next command by four,
typing `C-u C-v' scrolls the calendar forward by a year and typing `C-u
M-v' scrolls the calendar backward by a year.

   The function keys <next> and <prior> are equivalent to `C-v' and
`M-v', just as they are in other modes.


File: emacs,  Node: Counting Days,  Next: General Calendar,  Prev: Scroll Calendar,  Up: Calendar/Diary

38.3 Counting Days
==================

`M-='
     Display the number of days in the current region
     (`calendar-count-days-region').

   To determine the number of days in the region, type `M-='
(`calendar-count-days-region').  The numbers of days shown is
_inclusive_; that is, it includes the days specified by mark and point.


File: emacs,  Node: General Calendar,  Next: Writing Calendar Files,  Prev: Counting Days,  Up: Calendar/Diary

38.4 Miscellaneous Calendar Commands
====================================

`p d'
     Display day-in-year (`calendar-print-day-of-year').

`C-c C-l'
     Regenerate the calendar window (`calendar-redraw').

`SPC'
     Scroll the next window up (`scroll-other-window').

`DEL'
     Scroll the next window down (`scroll-other-window-down').

`q'
     Exit from calendar (`calendar-exit').

   To display the number of days elapsed since the start of the year, or
the number of days remaining in the year, type the `p d' command
(`calendar-print-day-of-year').  This displays both of those numbers in
the echo area.  The count of days elapsed includes the selected date.
The count of days remaining does not include that date.

   If the calendar window text gets corrupted, type `C-c C-l'
(`calendar-redraw') to redraw it.  (This can only happen if you use
non-Calendar-mode editing commands.)

   In Calendar mode, you can use `SPC' (`scroll-other-window') and
`DEL' (`scroll-other-window-down') to scroll the other window (if there
is one) up or down, respectively.  This is handy when you display a
list of holidays or diary entries in another window.

   To exit from the calendar, type `q' (`calendar-exit').  This buries
all buffers related to the calendar, selecting other buffers.  (If a
frame contains a dedicated calendar window, exiting from the calendar
deletes or iconifies that frame depending on the value of
`calendar-remove-frame-by-deleting'.)


File: emacs,  Node: Writing Calendar Files,  Next: Holidays,  Prev: General Calendar,  Up: Calendar/Diary

38.5 Writing Calendar Files
===========================

You can write calendars and diary entries to HTML and LaTeX files.

   The Calendar HTML commands produce files of HTML code that contain
calendar and diary entries.  Each file applies to one month, and has a
name of the format `YYYY-MM.html', where YYYY and MM are the four-digit
year and two-digit month, respectively.  The variable
`cal-html-directory' specifies the default output directory for the
HTML files.

   Diary entries enclosed by `<' and `>' are interpreted as HTML tags
(for example: this is a diary entry with <font color="red">some red
text</font>).  You can change the overall appearance of the displayed
HTML pages (for example, the color of various page elements, header
styles) via a stylesheet `cal.css' in the directory containing the HTML
files (see the value of the variable `cal-html-css-default' for
relevant style settings).

`H m'
     Generate a one-month calendar (`cal-html-cursor-month').

`H y'
     Generate a calendar file for each month of a year, as well as an
     index page (`cal-html-cursor-year').  By default, this command
     writes files to a YYYY subdirectory - if this is altered some
     hyperlinks between years will not work.

   If the variable `cal-html-print-day-number-flag' is non-`nil', then
the monthly calendars show the day-of-the-year number. The variable
`cal-html-year-index-cols' specifies the number of columns in the
yearly index page.

   The Calendar LaTeX commands produce a buffer of LaTeX code that
prints as a calendar.  Depending on the command you use, the printed
calendar covers the day, week, month or year that point is in.

`t m'
     Generate a one-month calendar (`cal-tex-cursor-month').

`t M'
     Generate a sideways-printing one-month calendar
     (`cal-tex-cursor-month-landscape').

`t d'
     Generate a one-day calendar (`cal-tex-cursor-day').

`t w 1'
     Generate a one-page calendar for one week (`cal-tex-cursor-week').

`t w 2'
     Generate a two-page calendar for one week (`cal-tex-cursor-week2').

`t w 3'
     Generate an ISO-style calendar for one week
     (`cal-tex-cursor-week-iso').

`t w 4'
     Generate a calendar for one Monday-starting week
     (`cal-tex-cursor-week-monday').

`t f w'
     Generate a Filofax-style two-weeks-at-a-glance calendar
     (`cal-tex-cursor-filofax-2week').

`t f W'
     Generate a Filofax-style one-week-at-a-glance calendar
     (`cal-tex-cursor-filofax-week').

`t y'
     Generate a calendar for one year (`cal-tex-cursor-year').

`t Y'
     Generate a sideways-printing calendar for one year
     (`cal-tex-cursor-year-landscape').

`t f y'
     Generate a Filofax-style calendar for one year
     (`cal-tex-cursor-filofax-year').

   Some of these commands print the calendar sideways (in "landscape
mode"), so it can be wider than it is long.  Some of them use Filofax
paper size (3.75in x 6.75in).  All of these commands accept a prefix
argument which specifies how many days, weeks, months or years to print
(starting always with the selected one).

   If the variable `cal-tex-holidays' is non-`nil' (the default), then
the printed calendars show the holidays in `calendar-holidays'.  If the
variable `cal-tex-diary' is non-`nil' (the default is `nil'), diary
entries are included also (in monthly, filofax, and iso-week calendars
only).  If the variable `cal-tex-rules' is non-`nil' (the default is
`nil'), the calendar displays ruled pages in styles that have
sufficient room.  Consult the documentation of the individual cal-tex
functions to see which calendars support which features.

   You can use the variable `cal-tex-preamble-extra' to insert extra
LaTeX commands in the preamble of the generated document if you need to.


File: emacs,  Node: Holidays,  Next: Sunrise/Sunset,  Prev: Writing Calendar Files,  Up: Calendar/Diary

38.6 Holidays
=============

The Emacs calendar knows about many major and minor holidays, and can
display them.  You can add your own holidays to the default list.

`h'
     Display holidays for the selected date
     (`calendar-cursor-holidays').

`Mouse-3 Holidays'
     Display any holidays for the date you click on.

`x'
     Mark holidays in the calendar window (`calendar-mark-holidays').

`u'
     Unmark calendar window (`calendar-unmark').

`a'
     List all holidays for the displayed three months in another window
     (`calendar-list-holidays').

`M-x holidays'
     List all holidays for three months around today's date in another
     window.

`M-x list-holidays'
     List holidays in another window for a specified range of years.

   To see if any holidays fall on a given date, position point on that
date in the calendar window and use the `h' command.  Alternatively,
click on that date with `Mouse-3' and then choose `Holidays' from the
menu that appears.  Either way, this displays the holidays for that
date, in the echo area if they fit there, otherwise in a separate
window.

   To view the distribution of holidays for all the dates shown in the
calendar, use the `x' command.  This displays the dates that are
holidays in a different face.  *Note calendar-holiday-marker: Calendar
Customizing.    The command applies both to the currently visible
months and to other months that subsequently become visible by
scrolling.  To turn marking off and erase the current marks, type `u',
which also erases any diary marks (*note Diary::).  If the variable
`calendar-mark-holidays-flag' is non-`nil', creating or updating the
calendar marks holidays automatically.

   To get even more detailed information, use the `a' command, which
displays a separate buffer containing a list of all holidays in the
current three-month range.  You can use <SPC> and <DEL> in the calendar
window to scroll that list up and down, respectively.

   The command `M-x holidays' displays the list of holidays for the
current month and the preceding and succeeding months; this works even
if you don't have a calendar window.  If the variable
`calendar-view-holidays-initially-flag' is non-`nil', creating the
calendar displays holidays in this way.  If you want the list of
holidays centered around a different month, use `C-u M-x holidays',
which prompts for the month and year.

   The holidays known to Emacs include United States holidays and the
major Baha'i, Chinese, Christian, Islamic, and Jewish holidays; also the
solstices and equinoxes.

   The command `M-x holiday-list' displays the list of holidays for a
range of years.  This function asks you for the starting and stopping
years, and allows you to choose all the holidays or one of several
categories of holidays.  You can use this command even if you don't have
a calendar window.

   The dates used by Emacs for holidays are based on _current
practice_, not historical fact.  For example Veteran's Day began in
1919, but is shown in earlier years.


File: emacs,  Node: Sunrise/Sunset,  Next: Lunar Phases,  Prev: Holidays,  Up: Calendar/Diary

38.7 Times of Sunrise and Sunset
================================

Special calendar commands can tell you, to within a minute or two, the
times of sunrise and sunset for any date.

`S'
     Display times of sunrise and sunset for the selected date
     (`calendar-sunrise-sunset').

`Mouse-3 Sunrise/sunset'
     Display times of sunrise and sunset for the date you click on.

`M-x sunrise-sunset'
     Display times of sunrise and sunset for today's date.

`C-u M-x sunrise-sunset'
     Display times of sunrise and sunset for a specified date.

`M-x calendar-sunrise-sunset-month'
     Display times of sunrise and sunset for the selected month.

   Within the calendar, to display the _local times_ of sunrise and
sunset in the echo area, move point to the date you want, and type `S'.
Alternatively, click `Mouse-3' on the date, then choose
`Sunrise/sunset' from the menu that appears.  The command `M-x
sunrise-sunset' is available outside the calendar to display this
information for today's date or a specified date.  To specify a date
other than today, use `C-u M-x sunrise-sunset', which prompts for the
year, month, and day.

   You can display the times of sunrise and sunset for any location and
any date with `C-u C-u M-x sunrise-sunset'.  This asks you for a
longitude, latitude, number of minutes difference from Coordinated
Universal Time, and date, and then tells you the times of sunrise and
sunset for that location on that date.

   Because the times of sunrise and sunset depend on the location on
earth, you need to tell Emacs your latitude, longitude, and location
name before using these commands.  Here is an example of what to set:

     (setq calendar-latitude 40.1)
     (setq calendar-longitude -88.2)
     (setq calendar-location-name "Urbana, IL")

Use one decimal place in the values of `calendar-latitude' and
`calendar-longitude'.

   Your time zone also affects the local time of sunrise and sunset.
Emacs usually gets time zone information from the operating system, but
if these values are not what you want (or if the operating system does
not supply them), you must set them yourself.  Here is an example:

     (setq calendar-time-zone -360)
     (setq calendar-standard-time-zone-name "CST")
     (setq calendar-daylight-time-zone-name "CDT")

The value of `calendar-time-zone' is the number of minutes difference
between your local standard time and Coordinated Universal Time
(Greenwich time).  The values of `calendar-standard-time-zone-name' and
`calendar-daylight-time-zone-name' are the abbreviations used in your
time zone.  Emacs displays the times of sunrise and sunset _corrected
for daylight saving time_.  *Note Daylight Saving::, for how daylight
saving time is determined.

   As a user, you might find it convenient to set the calendar location
variables for your usual physical location in your `.emacs' file.  And
when you install Emacs on a machine, you can create a `default.el' file
which sets them properly for the typical location of most users of that
machine.  *Note Init File::.


File: emacs,  Node: Lunar Phases,  Next: Other Calendars,  Prev: Sunrise/Sunset,  Up: Calendar/Diary

38.8 Phases of the Moon
=======================

These calendar commands display the dates and times of the phases of
the moon (new moon, first quarter, full moon, last quarter).  This
feature is useful for debugging problems that "depend on the phase of
the moon."

`M'
     Display the dates and times for all the quarters of the moon for
     the three-month period shown (`calendar-lunar-phases').

`M-x lunar-phases'
     Display dates and times of the quarters of the moon for three
     months around today's date.

   Within the calendar, use the `M' command to display a separate
buffer of the phases of the moon for the current three-month range.  The
dates and times listed are accurate to within a few minutes.

   Outside the calendar, use the command `M-x lunar-phases' to display
the list of the phases of the moon for the current month and the
preceding and succeeding months.  For information about a different
month, use `C-u M-x lunar-phases', which prompts for the month and year.

   The dates and times given for the phases of the moon are given in
local time (corrected for daylight saving, when appropriate).  See the
discussion in the previous section.  *Note Sunrise/Sunset::.


File: emacs,  Node: Other Calendars,  Next: Diary,  Prev: Lunar Phases,  Up: Calendar/Diary

38.9 Conversion To and From Other Calendars
===========================================

The Emacs calendar displayed is _always_ the Gregorian calendar,
sometimes called the "new style" calendar, which is used in most of the
world today.  However, this calendar did not exist before the sixteenth
century and was not widely used before the eighteenth century; it did
not fully displace the Julian calendar and gain universal acceptance
until the early twentieth century.  The Emacs calendar can display any
month since January, year 1 of the current era, but the calendar
displayed is the Gregorian, even for a date at which the Gregorian
calendar did not exist.

   While Emacs cannot display other calendars, it can convert dates to
and from several other calendars.

* Menu:

* Calendar Systems::       The calendars Emacs understands
                             (aside from Gregorian).
* To Other Calendar::      Converting the selected date to various calendars.
* From Other Calendar::    Moving to a date specified in another calendar.
* Mayan Calendar::         Moving to a date specified in a Mayan calendar.


File: emacs,  Node: Calendar Systems,  Next: To Other Calendar,  Up: Other Calendars

38.9.1 Supported Calendar Systems
---------------------------------

The ISO commercial calendar is used largely in Europe.

   The Julian calendar, named after Julius Caesar, was the one used in
Europe throughout medieval times, and in many countries up until the
nineteenth century.

   Astronomers use a simple counting of days elapsed since noon, Monday,
January 1, 4713 B.C. on the Julian calendar.  The number of days elapsed
is called the "Julian day number" or the "Astronomical day number".

   The Hebrew calendar is used by tradition in the Jewish religion.  The
Emacs calendar program uses the Hebrew calendar to determine the dates
of Jewish holidays.  Hebrew calendar dates begin and end at sunset.

   The Islamic calendar is used in many predominantly Islamic countries.
Emacs uses it to determine the dates of Islamic holidays.  There is no
universal agreement in the Islamic world about the calendar; Emacs uses
a widely accepted version, but the precise dates of Islamic holidays
often depend on proclamation by religious authorities, not on
calculations.  As a consequence, the actual dates of observance can vary
slightly from the dates computed by Emacs.  Islamic calendar dates begin
and end at sunset.

   The French Revolutionary calendar was created by the Jacobins after
the 1789 revolution, to represent a more secular and nature-based view
of the annual cycle, and to install a 10-day week in a rationalization
measure similar to the metric system.  The French government officially
abandoned this calendar at the end of 1805.

   The Maya of Central America used three separate, overlapping calendar
systems, the _long count_, the _tzolkin_, and the _haab_.  Emacs knows
about all three of these calendars.  Experts dispute the exact
correlation between the Mayan calendar and our calendar; Emacs uses the
Goodman-Martinez-Thompson correlation in its calculations.

   The Copts use a calendar based on the ancient Egyptian solar
calendar.  Their calendar consists of twelve 30-day months followed by
an extra five-day period.  Once every fourth year they add a leap day
to this extra period to make it six days.  The Ethiopic calendar is
identical in structure, but has different year numbers and month names.

   The Persians use a solar calendar based on a design of Omar Khayyam.
Their calendar consists of twelve months of which the first six have 31
days, the next five have 30 days, and the last has 29 in ordinary years
and 30 in leap years.  Leap years occur in a complicated pattern every
four or five years.  The calendar implemented here is the arithmetical
Persian calendar championed by Birashk, based on a 2,820-year cycle.
It differs from the astronomical Persian calendar, which is based on
astronomical events.  As of this writing the first future discrepancy
is projected to occur on March 20, 2025.  It is currently not clear
what the official calendar of Iran will be that far into the future.

   The Chinese calendar is a complicated system of lunar months arranged
into solar years.  The years go in cycles of sixty, each year containing
either twelve months in an ordinary year or thirteen months in a leap
year; each month has either 29 or 30 days.  Years, ordinary months, and
days are named by combining one of ten "celestial stems" with one of
twelve "terrestrial branches" for a total of sixty names that are
repeated in a cycle of sixty.

   The Baha'i calendar system is based on a solar cycle of 19 months
with 19 days each.  The four remaining "intercalary" days are placed
between the 18th and 19th months.


File: emacs,  Node: To Other Calendar,  Next: From Other Calendar,  Prev: Calendar Systems,  Up: Other Calendars

38.9.2 Converting To Other Calendars
------------------------------------

The following commands describe the selected date (the date at point)
in various other calendar systems:

`Mouse-3  Other calendars'
     Display the date that you click on, expressed in various other
     calendars.  

`p o'
     Display the selected date in various other calendars.
     (`calendar-print-other-dates').  

`p c'
     Display ISO commercial calendar equivalent for selected day
     (`calendar-iso-print-date').  

`p j'
     Display Julian date for selected day
     (`calendar-julian-print-date').  

`p a'
     Display astronomical (Julian) day number for selected day
     (`calendar-astro-print-day-number').  

`p h'
     Display Hebrew date for selected day
     (`calendar-hebrew-print-date').  

`p i'
     Display Islamic date for selected day
     (`calendar-islamic-print-date').  

`p f'
     Display French Revolutionary date for selected day
     (`calendar-french-print-date').  

`p b'
     Display Baha'i date for selected day (`calendar-bahai-print-date').  

`p C'
     Display Chinese date for selected day
     (`calendar-chinese-print-date').  

`p k'
     Display Coptic date for selected day
     (`calendar-coptic-print-date').  

`p e'
     Display Ethiopic date for selected day
     (`calendar-ethiopic-print-date').  

`p p'
     Display Persian date for selected day
     (`calendar-persian-print-date').  

`p m'
     Display Mayan date for selected day (`calendar-mayan-print-date').

   If you are using a graphic display, the easiest way to translate a
date into other calendars is to click on it with `Mouse-3', then choose
`Other calendars' from the menu that appears.  This displays the
equivalent forms of the date in all the calendars Emacs understands, in
the form of a menu.  (Choosing an alternative from this menu doesn't
actually do anything--the menu is used only for display.)

   Otherwise, move point to the date you want to convert, then type the
appropriate command starting with `p' from the table above.  The prefix
`p' is a mnemonic for "print," since Emacs "prints" the equivalent date
in the echo area. `p o' displays the date in all forms known to Emacs.


File: emacs,  Node: From Other Calendar,  Next: Mayan Calendar,  Prev: To Other Calendar,  Up: Other Calendars

38.9.3 Converting From Other Calendars
--------------------------------------

You can use the other supported calendars to specify a date to move to.
This section describes the commands for doing this using calendars
other than Mayan; for the Mayan calendar, see the following section.

`g c'
     Move to a date specified in the ISO commercial calendar
     (`calendar-iso-goto-date').

`g w'
     Move to a week specified in the ISO commercial calendar
     (`calendar-iso-goto-week').

`g j'
     Move to a date specified in the Julian calendar
     (`calendar-julian-goto-date').

`g a'
     Move to a date specified with an astronomical (Julian) day number
     (`calendar-astro-goto-day-number').

`g b'
     Move to a date specified in the Baha'i calendar
     (`calendar-bahai-goto-date').

`g h'
     Move to a date specified in the Hebrew calendar
     (`calendar-hebrew-goto-date').

`g i'
     Move to a date specified in the Islamic calendar
     (`calendar-islamic-goto-date').

`g f'
     Move to a date specified in the French Revolutionary calendar
     (`calendar-french-goto-date').

`g C'
     Move to a date specified in the Chinese calendar
     (`calendar-chinese-goto-date').

`g p'
     Move to a date specified in the Persian calendar
     (`calendar-persian-goto-date').

`g k'
     Move to a date specified in the Coptic calendar
     (`calendar-coptic-goto-date').

`g e'
     Move to a date specified in the Ethiopic calendar
     (`calendar-ethiopic-goto-date').

   These commands ask you for a date on the other calendar, move point
to the Gregorian calendar date equivalent to that date, and display the
other calendar's date in the echo area.  Emacs uses strict completion
(*note Strict Completion::) whenever it asks you to type a month name,
so you don't have to worry about the spelling of Hebrew, Islamic, or
French names.

   One common question concerning the Hebrew calendar is the computation
of the anniversary of a date of death, called a "yahrzeit."  The Emacs
calendar includes a facility for such calculations.  If you are in the
calendar, the command `M-x calendar-hebrew-list-yahrzeits' asks you for
a range of years and then displays a list of the yahrzeit dates for
those years for the date given by point.  If you are not in the
calendar, this command first asks you for the date of death and the
range of years, and then displays the list of yahrzeit dates.


File: emacs,  Node: Mayan Calendar,  Prev: From Other Calendar,  Up: Other Calendars

38.9.4 Converting from the Mayan Calendar
-----------------------------------------

Here are the commands to select dates based on the Mayan calendar:

`g m l'
     Move to a date specified by the long count calendar
     (`calendar-mayan-goto-long-count-date').

`g m n t'
     Move to the next occurrence of a place in the tzolkin calendar
     (`calendar-mayan-next-tzolkin-date').

`g m p t'
     Move to the previous occurrence of a place in the tzolkin calendar
     (`calendar-mayan-previous-tzolkin-date').

`g m n h'
     Move to the next occurrence of a place in the haab calendar
     (`calendar-mayan-next-haab-date').

`g m p h'
     Move to the previous occurrence of a place in the haab calendar
     (`calendar-mayan-previous-haab-date').

`g m n c'
     Move to the next occurrence of a place in the calendar round
     (`calendar-mayan-next-calendar-round-date').

`g m p c'
     Move to the previous occurrence of a place in the calendar round
     (`calendar-mayan-previous-calendar-round-date').

   To understand these commands, you need to understand the Mayan
calendars.  The "long count" is a counting of days with these units:

     1 kin = 1 day   1 uinal = 20 kin   1 tun = 18 uinal
     1 katun = 20 tun   1 baktun = 20 katun

Thus, the long count date 12.16.11.16.6 means 12 baktun, 16 katun, 11
tun, 16 uinal, and 6 kin.  The Emacs calendar can handle Mayan long
count dates as early as 7.17.18.13.3, but no earlier.  When you use the
`g m l' command, type the Mayan long count date with the baktun, katun,
tun, uinal, and kin separated by periods.

   The Mayan tzolkin calendar is a cycle of 260 days formed by a pair of
independent cycles of 13 and 20 days.  Since this cycle repeats
endlessly, Emacs provides commands to move backward and forward to the
previous or next point in the cycle.  Type `g m p t' to go to the
previous tzolkin date; Emacs asks you for a tzolkin date and moves point
to the previous occurrence of that date.  Similarly, type `g m n t' to
go to the next occurrence of a tzolkin date.

   The Mayan haab calendar is a cycle of 365 days arranged as 18 months
of 20 days each, followed a 5-day monthless period.  Like the tzolkin
cycle, this cycle repeats endlessly, and there are commands to move
backward and forward to the previous or next point in the cycle.  Type
`g m p h' to go to the previous haab date; Emacs asks you for a haab
date and moves point to the previous occurrence of that date.
Similarly, type `g m n h' to go to the next occurrence of a haab date.

   The Maya also used the combination of the tzolkin date and the haab
date.  This combination is a cycle of about 52 years called a _calendar
round_.  If you type `g m p c', Emacs asks you for both a haab and a
tzolkin date and then moves point to the previous occurrence of that
combination.  Use `g m n c' to move point to the next occurrence of a
combination.  These commands signal an error if the haab/tzolkin date
combination you have typed is impossible.

   Emacs uses strict completion (*note Strict Completion::) whenever it
asks you to type a Mayan name, so you don't have to worry about
spelling.


File: emacs,  Node: Diary,  Next: Appointments,  Prev: Other Calendars,  Up: Calendar/Diary

38.10 The Diary
===============

The Emacs diary keeps track of appointments or other events on a daily
basis, in conjunction with the calendar.  To use the diary feature, you
must first create a "diary file" containing a list of events and their
dates.  Then Emacs can automatically pick out and display the events
for today, for the immediate future, or for any specified date.

   The name of the diary file is specified by the variable
`diary-file'; `~/diary' is the default.  Here's an example showing what
that file looks like:

     12/22/1988  Twentieth wedding anniversary!!
     &1/1.       Happy New Year!
     10/22       Ruth's birthday.
     * 21, *:    Payday
     Tuesday--weekly meeting with grad students at 10am
              Supowit, Shen, Bitner, and Kapoor to attend.
     1/13/89     Friday the thirteenth!!
     &thu 4pm    squash game with Lloyd.
     mar 16      Dad's birthday
     April 15, 1989 Income tax due.
     &* 15       time cards due.

This format is essentially the same as the one used by the system's
`calendar' utility.  This example uses extra spaces to align the event
descriptions of most of the entries.  Such formatting is purely a
matter of taste.

   Although you probably will start by creating a diary manually, Emacs
provides a number of commands to let you view, add, and change diary
entries.

* Menu:

* Displaying the Diary::   Viewing diary entries and associated calendar dates.
* Format of Diary File::   Entering events in your diary.
* Date Formats::           Various ways you can specify dates.
* Adding to Diary::        Commands to create diary entries.
* Special Diary Entries::  Anniversaries, blocks of dates, cyclic entries, etc.


File: emacs,  Node: Displaying the Diary,  Next: Format of Diary File,  Up: Diary

38.10.1 Displaying the Diary
----------------------------

Once you have created a diary file, you can use the calendar to view
it.  You can also view today's events outside of Calendar mode.  In the
following, key bindings refer to the Calendar buffer.

`d'
     Display all diary entries for the selected date
     (`diary-view-entries').

`Mouse-3 Diary'
     Display all diary entries for the date you click on.

`s'
     Display the entire diary file (`diary-show-all-entries').

`m'
     Mark all visible dates that have diary entries
     (`diary-mark-entries').

`u'
     Unmark the calendar window (`calendar-unmark').

`M-x diary-print-entries'
     Print hard copy of the diary display as it appears.

`M-x diary'
     Display all diary entries for today's date.

`M-x diary-mail-entries'
     Mail yourself email reminders about upcoming diary entries.

   Displaying the diary entries with `d' shows in a separate window the
diary entries for the selected date in the calendar.  The mode line of
the new window shows the date of the diary entries.  Holidays are shown
either in the buffer or in the mode line, depending on the display
method you choose (*note Diary Display::).  If you specify a numeric
argument with `d', it shows all the diary entries for that many
successive days.  Thus, `2 d' displays all the entries for the selected
date and for the following day.

   Another way to display the diary entries for a date is to click
`Mouse-3' on the date, and then choose `Diary entries' from the menu
that appears.  If the variable `calendar-view-diary-initially-flag' is
non-`nil', creating the calendar lists the diary entries for the
current date (provided the current date is visible).

   To get a broader view of which days are mentioned in the diary, use
the `m' command.  This marks the dates that have diary entries in a
different face.  *Note diary-entry-marker: Calendar Customizing.

   The command applies both to the currently visible months and to
other months that subsequently become visible by scrolling.  To turn
marking off and erase the current marks, type `u', which also turns off
holiday marks (*note Holidays::).  If the variable
`calendar-mark-diary-entries-flag' is non-`nil', creating or updating
the calendar marks diary dates automatically.

   To see the full diary file, rather than just some of the entries, use
the `s' command.

   The command `M-x diary' displays the diary entries for the current
date, independently of the calendar display, and optionally for the next
few days as well; the variable `diary-number-of-entries' specifies how
many days to include.  *Note diary-number-of-entries: Diary Customizing.

   If you put `(diary)' in your `.emacs' file, this automatically
displays a window with the day's diary entries, when you enter Emacs.

   Many users like to receive notice of events in their diary as email.
To send such mail to yourself, use the command `M-x
diary-mail-entries'.  A prefix argument specifies how many days
(starting with today) to check; otherwise, the variable
`diary-mail-days' says how many days.


File: emacs,  Node: Format of Diary File,  Next: Date Formats,  Prev: Displaying the Diary,  Up: Diary

38.10.2 The Diary File
----------------------

Your "diary file" is a file that records events associated with
particular dates.  The name of the diary file is specified by the
variable `diary-file'; `~/diary' is the default.  The `calendar'
utility program supports a subset of the format allowed by the Emacs
diary facilities, so you can use that utility to view the diary file,
with reasonable results aside from the entries it cannot understand.

   Each entry in the diary file describes one event and consists of one
or more lines.  An entry always begins with a date specification at the
left margin.  The rest of the entry is simply text to describe the
event.  If the entry has more than one line, then the lines after the
first must begin with whitespace to indicate they continue a previous
entry.  Lines that do not begin with valid dates and do not continue a
preceding entry are ignored.

   You can also use a format where the first line of a diary entry
consists only of the date or day name (with no following blanks or
punctuation).  For example:

     02/11/1989
           Bill B. visits Princeton today
           2pm Cognitive Studies Committee meeting
           2:30-5:30 Liz at Lawrenceville
           4:00pm Dentist appt
           7:30pm Dinner at George's
           8:00-10:00pm concert

This entry will have a different appearance if you use the simple diary
display (*note Diary Display::).  The simple diary display omits the
date line at the beginning; only the continuation lines appear.  This
style of entry looks neater when you display just a single day's
entries, but can cause confusion if you ask for more than one day's
entries.

   You can inhibit the marking of certain diary entries in the calendar
window; to do this, insert an ampersand `diary-nonmarking-symbol'
(default `&') at the beginning of the entry, before the date.  This has
no effect on display of the entry in the diary window; it affects only
marks on dates in the calendar window.  Nonmarking entries are
especially useful for generic entries that would otherwise mark many
different dates.


File: emacs,  Node: Date Formats,  Next: Adding to Diary,  Prev: Format of Diary File,  Up: Diary

38.10.3 Date Formats
--------------------

Here are some sample diary entries, illustrating different ways of
formatting a date.  The examples all show dates in American order
(month, day, year), but Calendar mode supports European order (day,
month, year) and ISO order (year, month, day) as options.

     4/20/93  Switch-over to new tabulation system
     apr. 25  Start tabulating annual results
     4/30  Results for April are due
     */25  Monthly cycle finishes
     Friday  Don't leave without backing up files

   The first entry appears only once, on April 20, 1993.  The second and
third appear every year on the specified dates, and the fourth uses a
wildcard (asterisk) for the month, so it appears on the 25th of every
month.  The final entry appears every week on Friday.

   You can use just numbers to express a date, as in `MONTH/DAY' or
`MONTH/DAY/YEAR'.  This must be followed by a nondigit.  In the date
itself, MONTH and DAY are numbers of one or two digits.  The optional
YEAR is also a number, and may be abbreviated to the last two digits;
that is, you can use `11/12/1989' or `11/12/89'.

   Dates can also have the form `MONTHNAME DAY' or `MONTHNAME DAY,
YEAR', where the month's name can be spelled in full or abbreviated
(with or without a period).  The preferred abbreviations for month and
day names can be set using the variables `calendar-abbrev-length',
`calendar-month-abbrev-array', and `calendar-day-abbrev-array'.  The
default is to use the first three letters of a name as its
abbreviation.  Case is not significant.

   A date may be "generic"; that is, partially unspecified.  Then the
entry applies to all dates that match the specification.  If the date
does not contain a year, it is generic and applies to any year.
Alternatively, MONTH, DAY, or YEAR can be a `*'; this matches any
month, day, or year, respectively.  Thus, a diary entry `3/*/*' matches
any day in March of any year; so does `march *'.

   If you prefer the European style of writing dates (in which the day
comes before the month), or the ISO style (in which the order is year,
month, day), type `M-x calendar-set-date-style' while in the calendar,
or customize the variable `calendar-date-style'.  This affects how
diary dates are interpreted, date display, and the order in which some
commands expect their arguments to be given.

   You can use the name of a day of the week as a generic date which
applies to any date falling on that day of the week.  You can abbreviate
the day of the week as described above, or spell it in full; case is not
significant.


File: emacs,  Node: Adding to Diary,  Next: Special Diary Entries,  Prev: Date Formats,  Up: Diary

38.10.4 Commands to Add to the Diary
------------------------------------

While in the calendar, there are several commands to create diary
entries.  The basic commands are listed here; more sophisticated
commands are in the next section (*note Special Diary Entries::).
Entries can also be based on non-Gregorian calendars.  *Note
Non-Gregorian Diary::.

`i d'
     Add a diary entry for the selected date (`diary-insert-entry').

`i w'
     Add a diary entry for the selected day of the week
     (`diary-insert-weekly-entry').

`i m'
     Add a diary entry for the selected day of the month
     (`diary-insert-monthly-entry').

`i y'
     Add a diary entry for the selected day of the year
     (`diary-insert-yearly-entry').

   You can make a diary entry for a specific date by selecting that date
in the calendar window and typing the `i d' command.  This command
displays the end of your diary file in another window and inserts the
date; you can then type the rest of the diary entry.

   If you want to make a diary entry that applies to a specific day of
the week, select that day of the week (any occurrence will do) and type
`i w'.  This inserts the day-of-week as a generic date; you can then
type the rest of the diary entry.  You can make a monthly diary entry in
the same fashion: select the day of the month, use the `i m' command,
and type the rest of the entry.  Similarly, you can insert a yearly
diary entry with the `i y' command.

   All of the above commands make marking diary entries by default.  To
make a nonmarking diary entry, give a numeric argument to the command.
For example, `C-u i w' makes a nonmarking weekly diary entry.

   When you modify the diary file, be sure to save the file before
exiting Emacs.  Saving the diary file after using any of the above
insertion commands will automatically update the diary marks in the
calendar window, if appropriate.  You can use the command
`calendar-redraw' to force an update at any time.


File: emacs,  Node: Special Diary Entries,  Prev: Adding to Diary,  Up: Diary

38.10.5 Special Diary Entries
-----------------------------

In addition to entries based on calendar dates, the diary file can
contain "sexp entries" for regular events such as anniversaries.  These
entries are based on Lisp expressions (sexps) that Emacs evaluates as
it scans the diary file.  Instead of a date, a sexp entry contains `%%'
followed by a Lisp expression which must begin and end with
parentheses.  The Lisp expression determines which dates the entry
applies to.

   Calendar mode provides commands to insert certain commonly used sexp
entries:

`i a'
     Add an anniversary diary entry for the selected date
     (`diary-insert-anniversary-entry').

`i b'
     Add a block diary entry for the current region
     (`diary-insert-block-entry').

`i c'
     Add a cyclic diary entry starting at the date
     (`diary-insert-cyclic-entry').

   If you want to make a diary entry that applies to the anniversary of
a specific date, move point to that date and use the `i a' command.
This displays the end of your diary file in another window and inserts
the anniversary description; you can then type the rest of the diary
entry.  The entry looks like this:

     %%(diary-anniversary 10 31 1948) Arthur's birthday

This entry applies to October 31 in any year after 1948; `10 31 1948'
specifies the date.  (If you are using the European or ISO calendar
style, the input order of month, day and year is different.)  The
reason this expression requires a beginning year is that advanced diary
functions can use it to calculate the number of elapsed years.

   A "block" diary entry applies to a specified range of consecutive
dates.  Here is a block diary entry that applies to all dates from June
24, 1990 through July 10, 1990:

     %%(diary-block 6 24 1990 7 10 1990) Vacation

The `6 24 1990' indicates the starting date and the `7 10 1990'
indicates the stopping date.  (Again, if you are using the European or
ISO calendar style, the input order of month, day and year is
different.)

   To insert a block entry, place point and the mark on the two dates
that begin and end the range, and type `i b'.  This command displays
the end of your diary file in another window and inserts the block
description; you can then type the diary entry.

   "Cyclic" diary entries repeat after a fixed interval of days.  To
create one, select the starting date and use the `i c' command.  The
command prompts for the length of interval, then inserts the entry,
which looks like this:

     %%(diary-cyclic 50 3 1 1990) Renew medication

This entry applies to March 1, 1990 and every 50th day following; `3 1
1990' specifies the starting date.  (If you are using the European or
ISO calendar style, the input order of month, day and year is
different.)

   All three of these commands make marking diary entries.  To insert a
nonmarking entry, give a numeric argument to the command.  For example,
`C-u i a' makes a nonmarking anniversary diary entry.

   Marking sexp diary entries in the calendar is _extremely_
time-consuming, since every date visible in the calendar window must be
individually checked.  So it's a good idea to make sexp diary entries
nonmarking (with `&') when possible.

   Another sophisticated kind of sexp entry, a "floating" diary entry,
specifies a regularly occurring event by offsets specified in days,
weeks, and months.  It is comparable to a crontab entry interpreted by
the `cron' utility.  Here is a nonmarking, floating diary entry that
applies to the fourth Thursday in November:

     &%%(diary-float 11 4 4) American Thanksgiving

The 11 specifies November (the eleventh month), the 4 specifies Thursday
(the fourth day of the week, where Sunday is numbered zero), and the
second 4 specifies the fourth Thursday (1 would mean "first," 2 would
mean "second," -2 would mean "second-to-last," and so on).  The month
can be a single month or a list of months.  Thus you could change the
11 above to `'(1 2 3)' and have the entry apply to the last Thursday of
January, February, and March.  If the month is `t', the entry applies
to all months of the year.

   Each of the standard sexp diary entries takes an optional parameter
specifying the name of a face or a single-character string to use when
marking the entry in the calendar.  Most generally, sexp diary entries
can perform arbitrary computations to determine when they apply.  *Note
Sexp Diary Entries::.


File: emacs,  Node: Appointments,  Next: Importing Diary,  Prev: Diary,  Up: Calendar/Diary

38.11 Appointments
==================

If you have a diary entry for an appointment, and that diary entry
begins with a recognizable time of day, Emacs can warn you several
minutes beforehand that that appointment is pending.  Emacs alerts you
to the appointment by displaying a message in your chosen format, as
specified by the variable `appt-display-format'.  If the value of
`appt-audible' is non-`nil', the warning includes an audible reminder.
In addition, if `appt-display-mode-line' is non-`nil', Emacs displays
the number of minutes to the appointment on the mode line.

   If `appt-display-format' has the value `window', then the variable
`appt-display-duration' controls how long the reminder window is
visible for; and the variables `appt-disp-window-function' and
`appt-delete-window-function' give the names of functions used to
create and destroy the window, respectively.

   To enable appointment notification, type `M-x appt-activate'.  With
a positive argument, it enables notification; with a negative argument,
it disables notification; with no argument, it toggles.  Enabling
notification also sets up an appointment list for today from the diary
file, giving all diary entries found with recognizable times of day,
and reminds you just before each of them.

   For example, suppose the diary file contains these lines:

     Monday
       9:30am Coffee break
      12:00pm Lunch

Then on Mondays, you will be reminded at around 9:20am about your
coffee break and at around 11:50am about lunch.  The variable
`appt-message-warning-time' specifies how many minutes (default 12) in
advance to warn you.

   You can write times in am/pm style (with `12:00am' standing for
midnight and `12:00pm' standing for noon), or 24-hour European/military
style.  You need not be consistent; your diary file can have a mixture
of the two styles.  Times must be at the beginning of diary entries if
they are to be recognized.

   Emacs updates the appointments list from the diary file
automatically just after midnight.  You can force an update at any time
by re-enabling appointment notification.  Both these actions also
display the day's diary buffer, unless you set `appt-display-diary' to
`nil'.  The appointments list is also updated whenever the diary file
(or a file it includes; see *note Fancy Diary Display::) is saved.

   You can also use the appointment notification facility like an alarm
clock.  The command `M-x appt-add' adds entries to the appointment list
without affecting your diary file.  You delete entries from the
appointment list with `M-x appt-delete'.


File: emacs,  Node: Importing Diary,  Next: Daylight Saving,  Prev: Appointments,  Up: Calendar/Diary

38.12 Importing and Exporting Diary Entries
===========================================

You can transfer diary entries between Emacs diary files and a variety
of other formats.

   You can import diary entries from Outlook-generated appointment
messages.  While viewing such a message in Rmail or Gnus, do `M-x
diary-from-outlook' to import the entry.  You can make this command
recognize additional appointment message formats by customizing the
variable `diary-outlook-formats'.

   The icalendar package allows you to transfer data between your Emacs
diary file and iCalendar files, which are defined in "RFC
2445--Internet Calendaring and Scheduling Core Object Specification
(iCalendar)" (as well as the earlier vCalendar format).

   The command `icalendar-import-buffer' extracts iCalendar data from
the current buffer and adds it to your (default) diary file.  This
function is also suitable for automatic extraction of iCalendar data;
for example with the Rmail mail client one could use:

     (add-hook 'rmail-show-message-hook 'icalendar-import-buffer)

   The command `icalendar-import-file' imports an iCalendar file and
adds the results to an Emacs diary file.  For example:

     (icalendar-import-file "/here/is/calendar.ics"
                            "/there/goes/ical-diary")

You can use an `#include' directive to add the import file contents to
the main diary file, if these are different files.  *Note Fancy Diary
Display::.

   Use `icalendar-export-file' to interactively export an entire Emacs
diary file to iCalendar format.  To export only a part of a diary file,
mark the relevant area, and call `icalendar-export-region'.  In both
cases the result is appended to the target file.


File: emacs,  Node: Daylight Saving,  Next: Time Intervals,  Prev: Importing Diary,  Up: Calendar/Diary

38.13 Daylight Saving Time
==========================

Emacs understands the difference between standard time and daylight
saving time--the times given for sunrise, sunset, solstices, equinoxes,
and the phases of the moon take that into account.  The rules for
daylight saving time vary from place to place and have also varied
historically from year to year.  To do the job properly, Emacs needs to
know which rules to use.

   Some operating systems keep track of the rules that apply to the
place where you are; on these systems, Emacs gets the information it
needs from the system automatically.  If some or all of this
information is missing, Emacs fills in the gaps with the rules
currently used in Cambridge, Massachusetts.  If the resulting rules are
not what you want, you can tell Emacs the rules to use by setting
certain variables: `calendar-daylight-savings-starts' and
`calendar-daylight-savings-ends'.

   These values should be Lisp expressions that refer to the variable
`year', and evaluate to the Gregorian date on which daylight saving
time starts or (respectively) ends, in the form of a list `(MONTH DAY
YEAR)'.  The values should be `nil' if your area does not use daylight
saving time.

   Emacs uses these expressions to determine the starting date of
daylight saving time for the holiday list and for correcting times of
day in the solar and lunar calculations.

   The values for Cambridge, Massachusetts are as follows:

     (calendar-nth-named-day 2 0 3 year)
     (calendar-nth-named-day 1 0 11 year)

That is, the second 0th day (Sunday) of the third month (March) in the
year specified by `year', and the first Sunday of the eleventh month
(November) of that year.  If daylight saving time were changed to start
on October 1, you would set `calendar-daylight-savings-starts' to this:

     (list 10 1 year)

   If there is no daylight saving time at your location, or if you want
all times in standard time, set `calendar-daylight-savings-starts' and
`calendar-daylight-savings-ends' to `nil'.

   The variable `calendar-daylight-time-offset' specifies the
difference between daylight saving time and standard time, measured in
minutes.  The value for Cambridge, Massachusetts is 60.

   Finally, the two variables `calendar-daylight-savings-starts-time'
and `calendar-daylight-savings-ends-time' specify the number of minutes
after midnight local time when the transition to and from daylight
saving time should occur.  For Cambridge, Massachusetts both variables'
values are 120.


File: emacs,  Node: Time Intervals,  Next: Advanced Calendar/Diary Usage,  Prev: Daylight Saving,  Up: Calendar/Diary

38.14 Summing Time Intervals
============================

The timeclock package adds up time intervals, so you can (for instance)
keep track of how much time you spend working on particular projects.

   Use the `M-x timeclock-in' command when you start working on a
project, and `M-x timeclock-out' command when you're done.  Each time
you do this, it adds one time interval to the record of the project.
You can change to working on a different project with `M-x
timeclock-change'.

   Once you've collected data from a number of time intervals, you can
use `M-x timeclock-workday-remaining' to see how much time is left to
work today (assuming a typical average of 8 hours a day), and `M-x
timeclock-when-to-leave' which will calculate when you're "done."

   If you want Emacs to display the amount of time "left" of your
workday in the mode line, either customize the
`timeclock-modeline-display' variable and set its value to `t', or
invoke the `M-x timeclock-modeline-display' command.

   Terminating the current Emacs session might or might not mean that
you have stopped working on the project and, by default, Emacs asks
you.  You can, however, set customize the value of the variable
`timeclock-ask-before-exiting' to `nil' to avoid the question; then,
only an explicit `M-x timeclock-out' or `M-x timeclock-change' will
tell Emacs that the current interval is over.

   The timeclock functions work by accumulating the data in a file
called `.timelog' in your home directory.  You can specify a different
name for this file by customizing the variable `timeclock-file'.  If
you edit the timeclock file manually, or if you change the value of any
of timeclock's customizable variables, you should run the command `M-x
timeclock-reread-log' to update the data in Emacs from the file.


File: emacs,  Node: Advanced Calendar/Diary Usage,  Prev: Time Intervals,  Up: Calendar/Diary

38.15 Customizing the Calendar and Diary
========================================

There are many customizations that you can use to make the calendar and
diary suit your personal tastes.

* Menu:

* Calendar Customizing::   Calendar layout and hooks.
* Holiday Customizing::    Defining your own holidays.
* Date Display Format::    Changing the format.
* Time Display Format::    Changing the format.
* Diary Customizing::      Defaults you can set.
* Non-Gregorian Diary::    Diary entries based on other calendars.
* Diary Display::          A choice of ways to display the diary.
* Fancy Diary Display::    Sorting diary entries, using included diary files.
* Sexp Diary Entries::     More flexible diary entries.


File: emacs,  Node: Calendar Customizing,  Next: Holiday Customizing,  Up: Advanced Calendar/Diary Usage

38.15.1 Customizing the Calendar
--------------------------------

The calendar display unfortunately cannot be changed from three months,
but you can customize the whitespace used by setting the variables:
`calendar-left-margin', `calendar-day-header-width',
`calendar-day-digit-width', `calendar-column-width', and
`calendar-intermonth-spacing'.  To display text _between_ the months,
for example week numbers, customize the variables
`calendar-intermonth-header' and `calendar-intermonth-text' as
described in their documentation.

   The variable `calendar-holiday-marker' specifies how to mark a date
as being a holiday.  Its value may be a single-character string to
insert next to the date, or a face name to use for displaying the date.
Likewise, the variable `diary-entry-marker' specifies how to mark a
date that has diary entries, and `calenday-today-marker' is used by the
function `calendar-mark-today' to mark today's date.  By default, the
calendar uses faces named `holiday', `diary', and `calendar-today' for
these purposes.

   The variable `calendar-load-hook' is a normal hook run when the
calendar package is first loaded (before actually starting to display
the calendar).

   Starting the calendar runs the normal hook
`calendar-initial-window-hook'.  Recomputation of the calendar display
does not run this hook.  But if you leave the calendar with the `q'
command and reenter it, the hook runs again.

   The variable `calendar-today-visible-hook' is a normal hook run
after the calendar buffer has been prepared with the calendar when the
current date is visible in the window.  One use of this hook is to mark
today's date; to do that use either of the functions
`calendar-mark-today' or `calendar-star-date':

     (add-hook 'calendar-today-visible-hook 'calendar-mark-today)

A similar normal hook, `calendar-today-invisible-hook' is run if the
current date is _not_ visible in the window.

   Each of the calendar cursor motion commands runs the hook
`calendar-move-hook' after it moves the cursor.


File: emacs,  Node: Holiday Customizing,  Next: Date Display Format,  Prev: Calendar Customizing,  Up: Advanced Calendar/Diary Usage

38.15.2 Customizing the Holidays
--------------------------------

Emacs knows about holidays defined by entries on one of several lists.
The lists of holidays that Emacs uses are for general holidays
(`holiday-general-holidays'), local holidays (`holiday-local-holidays'),
sun- and moon-related holidays (`holiday-solar-holidays'), Baha'i
holidays (`holiday-bahai-holidays'), Christian holidays
(`holiday-christian-holidays'), Hebrew (Jewish) holidays
(`holiday-hebrew-holidays'), Islamic (Muslim) holidays
(`holiday-islamic-holidays'), Oriental holidays
(`holiday-oriental-holidays'), and other holidays
(`holiday-other-holidays').

   You can customize these lists of holidays to your own needs,
deleting or adding holidays as described below.  Set any of them to
`nil' to eliminate the associated holidays.

   The general holidays are, by default, holidays common throughout the
United States.

   There are no default local holidays, but your site may supply some.

   By default, Emacs does not include all the holidays of the religions
that it knows, only those commonly found in secular calendars.  For a
more extensive collection of religious holidays, you can set any (or
all) of the variables `calendar-bahai-all-holidays-flag',
`calendar-christian-all-holidays-flag',
`calendar-hebrew-all-holidays-flag', or
`calendar-islamic-all-holidays-flag' to `t'.

   You can set the variable `holiday-other-holidays' to any list of
holidays.  This list, normally empty, is intended for individual use.

   Each of the holiday variables is a list of "holiday forms", each
form describing a holiday (or sometimes a list of holidays).

   Here is a table of the possible kinds of holiday form.  Day numbers
and month numbers count starting from 1, but "dayname" numbers count
Sunday as 0.  The element STRING is always the description of the
holiday, as a string.

`(holiday-fixed MONTH DAY STRING)'
     A fixed date on the Gregorian calendar.

`(holiday-float MONTH DAYNAME K STRING'
     &optional DAY) The Kth DAYNAME (DAYNAME=0 for Sunday, and so on)
     after or before Gregorian date MONTH, DAY.  Negative K means count
     back from the end of the month.  Optional DAY defaults to 1 if K
     is positive, and the last day of MONTH otherwise.

`(holiday-chinese MONTH DAY STRING)'
     A fixed date on the Chinese calendar.

`(holiday-hebrew MONTH DAY STRING)'
     A fixed date on the Hebrew calendar.

`(holiday-islamic MONTH DAY STRING)'
     A fixed date on the Islamic calendar.

`(holiday-julian MONTH DAY STRING)'
     A fixed date on the Julian calendar.

`(holiday-sexp SEXP STRING)'
     A date calculated by the Lisp expression SEXP.  The expression
     should use the variable `year' to compute and return the date of a
     holiday in the form of a list `(MONTH DAY YEAR)', or `nil' if the
     holiday doesn't happen this year.

`(if CONDITION HOLIDAY-FORM)'
     A holiday that happens only if CONDITION is true.

`(FUNCTION [ARGS])'
     A list of dates calculated by the function FUNCTION, called with
     arguments ARGS.

   For example, suppose you want to add Bastille Day, celebrated in
France on July 14 (i.e., the fourteenth day of the seventh month).  You
can do this as follows:

     (setq holiday-other-holidays '((holiday-fixed 7 14 "Bastille Day")))

   Many holidays occur on a specific day of the week, at a specific time
of month.  Here is a holiday form describing Hurricane Supplication Day,
celebrated in the Virgin Islands on the fourth Monday in August:

     (holiday-float 8 1 4 "Hurricane Supplication Day")

Here the 8 specifies August, the 1 specifies Monday (Sunday is 0,
Tuesday is 2, and so on), and the 4 specifies the fourth occurrence in
the month (1 specifies the first occurrence, 2 the second occurrence,
-1 the last occurrence, -2 the second-to-last occurrence, and so on).

   You can specify holidays that occur on fixed days of the Baha'i,
Chinese, Hebrew, Islamic, and Julian calendars too.  For example,

     (setq holiday-other-holidays
           '((holiday-hebrew 10 2 "Last day of Hanukkah")
             (holiday-islamic 3 12 "Mohammed's Birthday")
             (holiday-julian 4 2 "Jefferson's Birthday")))

adds the last day of Hanukkah (since the Hebrew months are numbered with
1 starting from Nisan), the Islamic feast celebrating Mohammed's
birthday (since the Islamic months are numbered from 1 starting with
Muharram), and Thomas Jefferson's birthday, which is 2 April 1743 on the
Julian calendar.

   To include a holiday conditionally, use either Emacs Lisp's `if' or
the `holiday-sexp' form.  For example, American presidential elections
occur on the first Tuesday after the first Monday in November of years
divisible by 4:

     (holiday-sexp '(if (zerop (% year 4))
                        (calendar-gregorian-from-absolute
                         (1+ (calendar-dayname-on-or-before
                               1 (+ 6 (calendar-absolute-from-gregorian
                                       (list 11 1 year)))))))
                   "US Presidential Election")

or

     (if (zerop (% displayed-year 4))
         (holiday-fixed 11
                (calendar-extract-day
                  (calendar-gregorian-from-absolute
                    (1+ (calendar-dayname-on-or-before
                          1 (+ 6 (calendar-absolute-from-gregorian
                                   (list 11 1 displayed-year)))))))
                "US Presidential Election"))

   Some holidays just don't fit into any of these forms because special
calculations are involved in their determination.  In such cases you
must write a Lisp function to do the calculation.  To include eclipses,
for example, add `(eclipses)' to `holiday-other-holidays' and write an
Emacs Lisp function `eclipses' that returns a (possibly empty) list of
the relevant Gregorian dates among the range visible in the calendar
window, with descriptive strings, like this:

     (((6 27 1991) "Lunar Eclipse") ((7 11 1991) "Solar Eclipse") ... )


File: emacs,  Node: Date Display Format,  Next: Time Display Format,  Prev: Holiday Customizing,  Up: Advanced Calendar/Diary Usage

38.15.3 Date Display Format
---------------------------

You can customize the manner of displaying dates in the diary, in mode
lines, and in messages by setting `calendar-date-display-form'.  This
variable holds a list of expressions that can involve the variables
`month', `day', and `year', which are all numbers in string form, and
`monthname' and `dayname', which are both alphabetic strings.  In the
American style, the default value of this list is as follows:

     ((if dayname (concat dayname ", ")) monthname " " day ", " year)

while in the European style this value is the default:

     ((if dayname (concat dayname ", ")) day " " monthname " " year)

The default ISO date representation is:

     ((format "%s-%.2d-%.2d" year (string-to-number month)
              (string-to-number day)))

This specifies a typical American format:

     (month "/" day "/" (substring year -2))


File: emacs,  Node: Time Display Format,  Next: Diary Customizing,  Prev: Date Display Format,  Up: Advanced Calendar/Diary Usage

38.15.4 Time Display Format
---------------------------

The calendar and diary by default display times of day in the
conventional American style with the hours from 1 through 12, minutes,
and either `am' or `pm'.  If you prefer the European style, also known
in the US as military, in which the hours go from 00 to 23, you can
alter the variable `calendar-time-display-form'.  This variable is a
list of expressions that can involve the variables `12-hours',
`24-hours', and `minutes', which are all numbers in string form, and
`am-pm' and `time-zone', which are both alphabetic strings.  The
default value is:

     (12-hours ":" minutes am-pm
               (if time-zone " (") time-zone (if time-zone ")"))

Here is a value that provides European style times:

     (24-hours ":" minutes
               (if time-zone " (") time-zone (if time-zone ")"))

   Note that few calendar functions return a time of day (at present,
only solar functions).


File: emacs,  Node: Diary Customizing,  Next: Non-Gregorian Diary,  Prev: Time Display Format,  Up: Advanced Calendar/Diary Usage

38.15.5 Customizing the Diary
-----------------------------

Ordinarily, the diary window indicates any holidays that fall on the
date of the diary entries, either in the mode line or the buffer itself.
The process of checking for holidays can be slow, depending on the
defined holidays.  In that case, setting `diary-show-holidays-flag' to
`nil' will speed up the diary display.

   The variable `diary-number-of-entries' controls the number of days
of diary entries to be displayed at one time.  It affects the initial
display when `calendar-view-diary-initially-flag' is `t', as well as
the command `M-x diary'.  For example, a value of 1 (the default)
displays only the current day's diary entries, whereas a value of 2
will also show the next day's entries.  The value can also be a vector
of seven integers: for example, if the value is `[0 2 2 2 2 4 1]' then
no diary entries appear on Sunday, the current date's and the next
day's diary entries appear Monday through Thursday, Friday through
Monday's entries appear on Friday, while on Saturday only that day's
entries appear.

   You can customize the form of dates in your diary file by setting the
variable `diary-date-forms'.  This variable is a list of patterns for
recognizing a date.  Each date pattern is a list whose elements may be
regular expressions (*note Regular Expressions: (elisp)Regular
Expressions.) or the symbols `month', `day', `year', `monthname', and
`dayname'.  All these elements serve as patterns that match certain
kinds of text in the diary file.  In order for the date pattern, as a
whole, to match, all of its elements must match consecutively.

   A regular expression in a date pattern matches in its usual fashion,
using the standard syntax table altered so that `*' is a word
constituent.

   The symbols `month', `day', `year', `monthname', and `dayname' match
the month number, day number, year number, month name, and day name of
the date being considered.  The symbols that match numbers allow
leading zeros; those that match names allow capitalization and
abbreviation (as specified by `calendar-month-abbrev-array' and
`calendar-day-abbrev-array').  All the symbols can match `*'; since `*'
in a diary entry means "any day", "any month", and so on, it should
match regardless of the date being considered.

   The default value of `diary-date-forms' in the American style is
provided by `diary-american-date-forms':

     ((month "/" day "[^/0-9]")
      (month "/" day "/" year "[^0-9]")
      (monthname " *" day "[^,0-9]")
      (monthname " *" day ", *" year "[^0-9]")
      (dayname "\\W"))

Other default styles are provided by `diary-european-date-forms' and
`diary-iso-date-forms'.

   The date patterns in the list must be _mutually exclusive_ and must
not match any portion of the diary entry itself, just the date and one
character of whitespace.  If, to be mutually exclusive, the pattern
must match a portion of the diary entry text--beyond the whitespace
that ends the date--then the first element of the date pattern _must_
be `backup'.  This causes the date recognizer to back up to the
beginning of the current word of the diary entry, after finishing the
match.  Even if you use `backup', the date pattern must absolutely not
match more than a portion of the first word of the diary entry.  For
example, the default value of `diary-european-date-forms' is:

     ((day "/" month "[^/0-9]")
      (day "/" month "/" year "[^0-9]")
      (backup day " *" monthname "\\W+\\<\\([^*0-9]\\|\\([0-9]+[:aApP]\\)\\)")
      (day " *" monthname " *" year "[^0-9]")
      (dayname "\\W"))

Notice the use of `backup' in the third pattern, because it needs to
match part of a word beyond the date itself to distinguish it from the
fourth pattern.


File: emacs,  Node: Non-Gregorian Diary,  Next: Diary Display,  Prev: Diary Customizing,  Up: Advanced Calendar/Diary Usage

38.15.6 Diary Entries Using non-Gregorian Calendars
---------------------------------------------------

As well as entries based on the standard Gregorian calendar, your diary
can have entries based on Baha'i, Hebrew, or Islamic dates.
Recognition of such entries can be time-consuming, however, and since
most people don't use them, you must explicitly enable their use.  If
you want the diary to recognize Hebrew-date diary entries, for example,
you must do this:

     (add-hook 'diary-nongregorian-listing-hook 'diary-hebrew-list-entries)
     (add-hook 'diary-nongregorian-marking-hook 'diary-hebrew-mark-entries)

Similarly, for Islamic and Baha'i entries, add
`diary-islamic-list-entries' and `diary-islamic-mark-entries', or
`diary-bahai-list-entries' and `diary-bahai-mark-entries'.

   These diary entries have the same formats as Gregorian-date diary
entries; except that `diary-bahai-entry-symbol' (default `B') must
precede a Baha'i date, `diary-hebrew-entry-symbol' (default `H') a
Hebrew date, and `diary-islamic-entry-symbol' (default `I') an Islamic
date.  Moreover, non-Gregorian month names may not be abbreviated
(because the first three letters are often not unique).  (Note also
that you must use "Adar I" if you want Adar of a common Hebrew year.)
For example, a diary entry for the Hebrew date Heshvan 25 could look
like this:

     HHeshvan 25 Happy Hebrew birthday!

and would appear in the diary for any date that corresponds to Heshvan
25 on the Hebrew calendar.  And here is an Islamic-date diary entry
that matches Dhu al-Qada 25:

     IDhu al-Qada 25 Happy Islamic birthday!

   As with Gregorian-date diary entries, non-Gregorian entries are
nonmarking if preceded by `diary-nonmarking-symbol' (default `&').

   Here is a table of commands used in the calendar to create diary
entries that match the selected date and other dates that are similar in
the Baha'i, Hebrew, or Islamic calendars:

`i h d'
     `diary-hebrew-insert-entry'

`i h m'
     `diary-hebrew-insert-monthly-entry'

`i h y'
     `diary-hebrew-insert-yearly-entry'

`i i d'
     `diary-islamic-insert-entry'

`i i m'
     `diary-islamic-insert-monthly-entry'

`i i y'
     `diary-islamic-insert-yearly-entry'

`i B d'
     `diary-bahai-insert-entry'

`i B m'
     `diary-bahai-insert-monthly-entry'

`i B y'
     `diary-bahai-insert-yearly-entry'

   These commands work much like the corresponding commands for ordinary
diary entries: they apply to the date that point is on in the calendar
window, and what they do is insert just the date portion of a diary
entry at the end of your diary file.  You must then insert the rest of
the diary entry.  The basic commands add an entry for the specific
non-Gregorian date, the `monthly' commands for the given non-Gregorian
day-within-month in every month, and the `yearly' commands for the
given non-Gregorian day and month in every year.


File: emacs,  Node: Diary Display,  Next: Fancy Diary Display,  Prev: Non-Gregorian Diary,  Up: Advanced Calendar/Diary Usage

38.15.7 Diary Display
---------------------

Diary display works by preparing the list of diary entries and then
running the function specified by the variable
`diary-display-function'.  The default value `diary-fancy-display'
displays diary entries and holidays by copying them into a special
buffer that exists only for the sake of display.  Copying diary entries
to a separate buffer provides an opportunity to change the displayed
text to make it prettier--for example, to sort the entries by the dates
they apply to.

   Ordinarily, the fancy diary buffer does not show days for which there
are no diary entries, even if that day is a holiday.  If you want such
days to be shown in the fancy diary buffer, set the variable
`diary-list-include-blanks' to `t'.

   The fancy diary buffer enables View mode, a minor mode that provides
commands for scrolling and searching the text.  For example, <SPC> and
<DEL> scroll forward and backward, and <s> starts an incremental
search.  See the documentation of the function `view-mode' for more
information.

   The alternative display method `diary-simple-display' shows the
actual diary buffer, and uses invisible text to hide entries that don't
apply.  Holidays are shown in the mode line.  The advantage of this
method is that you can edit the buffer and save your changes directly to
the diary file.  This method is not as flexible as the fancy method,
however.  For example, it cannot sort entries.  Another disadvantage is
that invisible text can be confusing.  For example, if you copy a region
of text in order to paste it elsewhere, invisible text may be included.
Similarly, since the diary buffer as you see it is an illusion, simply
printing the buffer may not print what you see on your screen.

   For this reason, there is a special command to print hard copy of the
diary buffer _as it appears_; this command is `M-x
diary-print-entries'.  It works with either display method, although
with the fancy display you can also print the buffer like any other.  To
print a hard copy of a day-by-day diary for a week, position point on
the first day of the week, type `7 d', and then do `M-x
diary-print-entries'.  As usual, the inclusion of the holidays slows
down the display slightly; you can speed things up by setting the
variable `diary-show-holidays-flag' to `nil'.

   This command prepares a temporary buffer that contains only the diary
entries currently visible in the diary buffer.  Unlike with the simple
display, the other irrelevant entries are really absent, not just
hidden.  After preparing the buffer, it runs the hook
`diary-print-entries-hook'.  The default value of this hook sends the
data directly to the printer with the command `lpr-buffer' (*note
Printing::).  If you want to use a different command to do the
printing, just change the value of this hook.  Other uses might include,
for example, rearranging the lines into order by day and time.

   You can edit the diary entries as they appear in the simple diary
window, but it is important to remember that the buffer displayed
contains the _entire_ diary file, with portions of it concealed from
view.  This means, for instance, that the `C-f' (`forward-char')
command can put point at what appears to be the end of the line, but
what is in reality the middle of some concealed line.

   _Be careful when editing the diary entries in the simple display!_
Inserting additional lines or adding/deleting characters in the middle
of a visible line cannot cause problems, but editing at the end of a
line may not do what you expect.  Deleting a line may delete other
invisible entries that follow it.  Before editing the simple diary
buffer, it is best to display the entire file with `s'
(`diary-show-all-entries').


File: emacs,  Node: Fancy Diary Display,  Next: Sexp Diary Entries,  Prev: Diary Display,  Up: Advanced Calendar/Diary Usage

38.15.8 Fancy Diary Display
---------------------------

The following features only work with the fancy diary display.

   You can use the normal hook `diary-list-entries-hook' to sort each
day's diary entries by their time of day.  Here's how:

     (add-hook 'diary-list-entries-hook 'diary-sort-entries t)

For each day, this sorts diary entries that begin with a recognizable
time of day according to their times.  Diary entries without times come
first within each day.  Note how the sort command is placed at the end
of the hook list, in case earlier members of the list change the order
of the diary entries, or add items.

   Your main diary file can include other files.  This permits a group
of people to share a diary file for events that apply to all of them.
Lines in the diary file starting with `diary-include-string':

     #include "FILENAME"

include the diary entries from the file FILENAME in the fancy diary
buffer.  The include mechanism is recursive, so that included files can
include other files, and so on (you must be careful not to have a cycle
of inclusions, of course).  Here is how to enable the include facility:

     (add-hook 'diary-list-entries-hook 'diary-include-other-diary-files)
     (add-hook 'diary-mark-entries-hook 'diary-mark-included-diary-files)

   The include mechanism works only with the fancy diary display,
because simple diary display shows the entries directly from your diary
file.


File: emacs,  Node: Sexp Diary Entries,  Prev: Fancy Diary Display,  Up: Advanced Calendar/Diary Usage

38.15.9 Sexp Entries and the Fancy Diary Display
------------------------------------------------

Sexp diary entries allow you to do more than just have complicated
conditions under which a diary entry applies.  Sexp entries should be
preceded by `diary-sexp-entry-symbol' (default `%%') in the diary file.
With the fancy diary display, sexp entries can generate the text of the
entry depending on the date itself.

   For example, an anniversary diary entry can insert the number of
years since the anniversary date into the text of the diary entry.
Thus the `%d' in this diary entry:

     %%(diary-anniversary 10 31 1948) Arthur's birthday (%d years old)

gets replaced by the age, so on October 31, 1990 the entry appears in
the fancy diary buffer like this:

     Arthur's birthday (42 years old)

If the diary file instead contains this entry:

     %%(diary-anniversary 10 31 1948) Arthur's %d%s birthday

the entry in the fancy diary buffer for October 31, 1990 appears like
this:

     Arthur's 42nd birthday

   Similarly, cyclic diary entries can interpolate the number of
repetitions that have occurred:

     %%(diary-cyclic 50 1 1 1990) Renew medication (%d%s time)

looks like this:

     Renew medication (5th time)

in the fancy diary display on September 8, 1990.

   There is an early reminder diary sexp that includes its entry in the
diary not only on the date of occurrence, but also on earlier dates.
For example, if you want a reminder a week before your anniversary, you
can use

     %%(diary-remind '(diary-anniversary 12 22 1968) 7) Ed's anniversary

and the fancy diary will show `Ed's anniversary' both on December 15
and on December 22.

   The function `diary-date' applies to dates described by a month,
day, year combination, each of which can be an integer, a list of
integers, or `t' (meaning all values).  For example,

     %%(diary-date '(10 11 12) 22 t) Rake leaves

causes the fancy diary to show

     Rake leaves

on October 22, November 22, and December 22 of every year.

   The function `diary-float' allows you to describe diary entries that
apply to dates like the third Friday of November, or the last Tuesday
in April.  The parameters are the MONTH, DAYNAME, and an index N.  The
entry appears on the Nth DAYNAME after the first day of MONTH, where
DAYNAME=0 means Sunday, 1 means Monday, and so on.  If N is negative it
counts backward from the end of MONTH.  The value of MONTH can be a
list of months, a single month, or `t' to specify all months.  You can
also use an optional parameter DAY to specify the Nth DAYNAME on or
after/before DAY of MONTH; the value of DAY defaults to 1 if N is
positive and to the last day of MONTH if N is negative.  For example,

     %%(diary-float t 1 -1) Pay rent

causes the fancy diary to show

     Pay rent

on the last Monday of every month.

   The generality of sexp diary entries lets you specify any diary
entry that you can describe algorithmically.  A sexp diary entry
contains an expression that computes whether the entry applies to any
given date.  If its value is non-`nil', the entry applies to that date;
otherwise, it does not.  The expression can use the variable `date' to
find the date being considered; its value is a list (MONTH DAY YEAR)
that refers to the Gregorian calendar.

   The sexp diary entry applies to a date when the expression's value
is non-`nil', but some values have more specific meanings.  If the
value is a string, that string is a description of the event which
occurs on that date.  The value can also have the form `(MARK .
STRING)'; then MARK specifies how to mark the date in the calendar, and
STRING is the description of the event.  If MARK is a single-character
string, that character appears next to the date in the calendar.  If
MARK is a face name, the date is displayed in that face.  If MARK is
`nil', that specifies no particular highlighting for the date.

   Suppose you get paid on the 21st of the month if it is a weekday, and
on the Friday before if the 21st is on a weekend.  Here is how to write
a sexp diary entry that matches those dates:

     &%%(let ((dayname (calendar-day-of-week date))
              (day (cadr date)))
           (or (and (= day 21) (memq dayname '(1 2 3 4 5)))
               (and (memq day '(19 20)) (= dayname 5)))
              ) Pay check deposited

   The following sexp diary entries take advantage of the ability (in
the fancy diary display) to concoct diary entries whose text varies
based on the date:

`%%(diary-sunrise-sunset)'
     Make a diary entry for today's local times of sunrise and sunset.

`%%(diary-lunar-phases)'
     Make a diary entry for the phases (quarters) of the moon.

`%%(diary-day-of-year)'
     Make a diary entry with today's day number in the current year and
     the number of days remaining in the current year.

`%%(diary-iso-date)'
     Make a diary entry with today's equivalent ISO commercial date.

`%%(diary-julian-date)'
     Make a diary entry with today's equivalent Julian calendar date.

`%%(diary-astro-day-number)'
     Make a diary entry with today's equivalent astronomical (Julian)
     day number.

`%%(diary-bahai-date)'
     Make a diary entry with today's equivalent Baha'i calendar date.

`%%(diary-chinese-date)'
     Make a diary entry with today's equivalent Chinese calendar date.

`%%(diary-coptic-date)'
     Make a diary entry with today's equivalent Coptic calendar date.

`%%(diary-ethiopic-date)'
     Make a diary entry with today's equivalent Ethiopic calendar date.

`%%(diary-french-date)'
     Make a diary entry with today's equivalent date on the French
     Revolutionary calendar.

`%%(diary-hebrew-date)'
     Make a diary entry with today's equivalent Hebrew calendar date.

`%%(diary-islamic-date)'
     Make a diary entry with today's equivalent Islamic calendar date.

`%%(diary-mayan-date)'
     Make a diary entry with today's equivalent Mayan calendar date.

`%%(diary-persian-date)'
     Make a diary entry with today's equivalent Persian calendar date.

For example, including the diary entry

     &%%(diary-hebrew-date)

causes every day's diary display to contain the equivalent date on the
Hebrew calendar, if you are using the fancy diary display.  (With simple
diary display, the literal line `&%%(diary-hebrew-date)' appears in the
diary for any date.)

   This function has been used to construct certain standard Hebrew sexp
diary entries:

`%%(diary-hebrew-rosh-hodesh)'
     Make a diary entry that tells the occurrence and ritual
     announcement of each new Hebrew month.

`%%(diary-hebrew-parasha)'
     Make a Saturday diary entry that tells the weekly synagogue
     scripture reading.

`%%(diary-hebrew-sabbath-candles)'
     Make a Friday diary entry that tells the _local time_ of Sabbath
     candle lighting.

`%%(diary-hebrew-omer)'
     Make a diary entry that gives the omer count, when appropriate.

`%%(diary-hebrew-yahrzeit MONTH DAY YEAR) NAME'
     Make a diary entry marking the anniversary of a date of death.
     The date is the _Gregorian_ (civil) date of death.  The diary
     entry appears on the proper Hebrew calendar anniversary and on the
     day before.  (The order of the parameters changes according to the
     calendar date style; for example in the European style to DAY,
     MONTH, YEAR.)

   All the functions documented above take an optional argument MARK
which specifies how to mark the date in the calendar display.  If one
of these functions decides that it applies to a certain date, it
returns a value that contains MARK, as described above.


File: emacs,  Node: Document View,  Next: Gnus,  Prev: Calendar/Diary,  Up: Top

39 Document Viewing
*******************

DocView mode (`doc-view-mode') is a viewer for DVI, Postscript (PS),
and PDF documents.  It provides features such as slicing, zooming, and
searching inside documents.  It works by converting the document to a
set of images using the `gs' (GhostScript) command, and displaying
those images.

   When you visit a PDF or DVI file, Emacs automatically switches to
DocView mode.  When you visit a Postscript file, Emacs switches to PS
mode, a major mode for editing Postscript files as text; however, it
also enables DocView minor mode, so you can type `C-c C-c' to view the
document with DocView.  (PDF and DVI files, unlike Postscript files,
are not usually human-editable.)  In either case, repeating `C-c C-c'
(`doc-view-toggle-display') toggles between DocView and the file text.

   You can explicitly toggle DocView mode with the command `M-x
doc-view-mode', and DocView minor mode with the command `M-x
doc-view-minor-mode'.

   When DocView mode starts, it displays a welcome screen and begins
formatting the file, page by page.  It displays the first page once
that has been formatted.

   When in DocView mode, you can enlarge or shrink the document with
`+' (`doc-view-enlarge') and `-' (`doc-view-shrink').  To specify the
default size for DocView, set or customize the variable
`doc-view-resolution'.

   To kill the DocView buffer, type `k'
(`doc-view-kill-proc-and-buffer').  To bury it, type `q'
(`quit-window').

* Menu:

* Navigation::  Navigation inside DocView buffers.
* Searching::   Searching inside documents.
* Slicing::     Specifying which part of pages should be displayed.
* Conversion::  Influencing and triggering conversion.


File: emacs,  Node: Navigation,  Next: Searching,  Up: Document View

39.1 Navigation
===============

When in DocView mode, you can scroll the current page using the usual
Emacs movement keys: `C-p', `C-n', `C-b', `C-f', and the arrow keys.

   By default, the line-motion keys `C-p' and `C-n' stop scrolling at
the beginning and end of the current page, respectively.  However, if
you change the variable `doc-view-continuous' to a non-`nil' value,
then `C-p' displays the previous page if you are already at the
beginning of the current page, and `C-n' displays the next page if you
are at the end of the current page.

   You can also display the next page by typing `n', <next> or `C-x ]'
(`doc-view-next-page').  To display the previous page, type `p',
<prior> or `C-x [' (`doc-view-previous-page').

   The <SPC> (`doc-view-scroll-up-or-next-page') key is a convenient
way to advance through the document.  It scrolls within the current
page or advances to the next.  <DEL> moves backwards in a similar way
(`doc-view-scroll-down-or-previous-page').

   To go to the first page, type `M-<' (`doc-view-first-page'); to go
to the last one, type `M->' (`doc-view-last-page').  To jump to a page
by its number, type `M-g M-g' or `M-g g' (`doc-view-goto-page').


File: emacs,  Node: Searching,  Next: Slicing,  Prev: Navigation,  Up: Document View

39.2 Searching
==============

While in DocView mode, you can search the file's text for a regular
expression (*note Regexps::).  The interface for searching is inspired
by `isearch' (*note Incremental Search::).

   To begin a search, type `C-s' (`doc-view-search') or `C-r'
(`doc-view-search-backward').  This reads a regular expression using a
minibuffer, then echoes the number of matches found within the
document.  You can move forward and back among the matches by typing
`C-s' and `C-r'.  DocView mode has no way to show the match inside the
page image; instead, it displays a tooltip (at the mouse position)
listing all matching lines in the current page.  To force display of
this tooltip, type `C-t' (`doc-view-show-tooltip').

   To start a new search, use the search command with a prefix
argument; i.e., `C-u C-s' for a forward search or `C-u C-r' for a
backward search.


File: emacs,  Node: Slicing,  Next: Conversion,  Prev: Searching,  Up: Document View

39.3 Slicing
============

Documents often have wide margins for printing.  They are annoying when
reading the document on the screen, because they use up screen space
and can cause inconvenient scrolling.

   With DocView you can hide these margins by selecting a "slice" of
pages to display.  A slice is a rectangle within the page area; once
you specify a slice in DocView, it applies to whichever page you look
at.

   To specify the slice numerically, type `s s' (`doc-view-set-slice');
then enter the top left pixel position and the slice's width and height.

   A more convenient graphical way to specify the slice is with `s m'
(`doc-view-set-slice-using-mouse'), where you use the mouse to select
the slice.

   To cancel the selected slice, type `s r' (`doc-view-reset-slice').
Then DocView shows the entire page including its entire margins.


File: emacs,  Node: Conversion,  Prev: Slicing,  Up: Document View

39.4 Conversion
===============

For efficiency, DocView caches the images produced by `gs'.  The name
of this directory is given by the variable `doc-view-cache-directory'.
You can clear the cache directory by typing `M-x doc-view-clear-cache'.

   To force a reconversion of the currently viewed document, type `r'
or `g' (`revert-buffer').  To kill the converter process associated
with the current buffer, type `K' (`doc-view-kill-proc').  The command
`k' (`doc-view-kill-proc-and-buffer') kills the converter process and
the DocView buffer.

   The zoom commands `+' (`doc-view-enlarge') and `-'
(`doc-view-shrink') need to reconvert the document at the new size.
The current page is converted first.


File: emacs,  Node: Gnus,  Next: Shell,  Prev: Document View,  Up: Top

40 Gnus
*******

Gnus is an Emacs package primarily designed for reading and posting
Usenet news.  It can also be used to read and respond to messages from a
number of other sources--mail, remote directories, digests, and so on.
Here we introduce Gnus and describe several basic features.  For full
details, see *note Gnus: (gnus)Top.

   To start Gnus, type `M-x gnus <RET>'.

* Menu:

* Buffers of Gnus::     The group, summary, and article buffers.
* Gnus Startup::        What you should know about starting Gnus.
* Summary of Gnus::     A short description of the basic Gnus commands.


File: emacs,  Node: Buffers of Gnus,  Next: Gnus Startup,  Up: Gnus

40.1 Gnus Buffers
=================

Unlike most Emacs packages, Gnus uses several buffers to display
information and to receive commands.  The three Gnus buffers users use
most are the "group buffer", the "summary buffer" and the "article
buffer".

   The "group buffer" contains a list of newsgroups.  This is the first
buffer Gnus displays when it starts up.  It normally displays only the
groups to which you subscribe and that contain unread articles.  Use
this buffer to select a specific group.

   The "summary buffer" lists one line for each article in a single
group.  By default, the author, the subject and the line number are
displayed for each article, but this is customizable, like most aspects
of Gnus display.  The summary buffer is created when you select a group
in the group buffer, and is killed when you exit the group.  Use this
buffer to select an article.

   The "article buffer" displays the article.  In normal Gnus usage,
you see this buffer but you don't select it--all useful
article-oriented commands work in the summary buffer.  But you can
select the article buffer, and execute all Gnus commands from that
buffer, if you want to.


File: emacs,  Node: Gnus Startup,  Next: Summary of Gnus,  Prev: Buffers of Gnus,  Up: Gnus

40.2 When Gnus Starts Up
========================

At startup, Gnus reads your `.newsrc' news initialization file and
attempts to communicate with the local news server, which is a
repository of news articles.  The news server need not be the same
computer you are logged in on.

   If you start Gnus and connect to the server, but do not see any
newsgroups listed in the group buffer, type `L' or `A k' to get a
listing of all the groups.  Then type `u' to toggle subscription to
groups.

   The first time you start Gnus, Gnus subscribes you to a few selected
groups.  All other groups start out as "killed groups" for you; you can
list them with `A k'.  All new groups that subsequently come to exist
at the news server become "zombie groups" for you; type `A z' to list
them.  You can subscribe to a group shown in these lists using the `u'
command.

   When you quit Gnus with `q', it automatically records in your
`.newsrc' and `.newsrc.eld' initialization files the subscribed or
unsubscribed status of all groups.  You should normally not edit these
files manually, but you may if you know how.


File: emacs,  Node: Summary of Gnus,  Prev: Gnus Startup,  Up: Gnus

40.3 Summary of Gnus Commands
=============================

Reading news is a two-step process:

  1. Choose a group in the group buffer.

  2. Select articles from the summary buffer.  Each article selected is
     displayed in the article buffer in a large window, below the
     summary buffer in its small window.

   Each Gnus buffer has its own special commands; the meanings of any
given key in the various Gnus buffers are usually analogous, even if
not identical.  Here are commands for the group and summary buffers:

`q'
     In the group buffer, update your `.newsrc' initialization file and
     quit Gnus.

     In the summary buffer, exit the current group and return to the
     group buffer.  Thus, typing `q' twice quits Gnus.

`L'
     In the group buffer, list all the groups available on your news
     server (except those you have killed).  This may be a long list!

`l'
     In the group buffer, list only the groups to which you subscribe
     and which contain unread articles.

`u'
     In the group buffer, unsubscribe from (or subscribe to) the group
     listed in the line that point is on.  When you quit Gnus by typing
     `q', Gnus lists in your `.newsrc' file which groups you have
     subscribed to.  The next time you start Gnus, you won't see this
     group, because Gnus normally displays only subscribed-to groups.

`C-k'
     In the group buffer, "kill" the current line's group--don't even
     list it in `.newsrc' from now on.  This affects future Gnus
     sessions as well as the present session.

     When you quit Gnus by typing `q', Gnus writes information in the
     file `.newsrc' describing all newsgroups except those you have
     "killed."

`<SPC>'
     In the group buffer, select the group on the line under the cursor
     and display the first unread article in that group.

     In the summary buffer,

        * Select the article on the line under the cursor if none is
          selected.

        * Scroll the text of the selected article (if there is one).

        * Select the next unread article if at the end of the current
          article.

     Thus, you can move through all the articles by repeatedly typing
     <SPC>.

`<DEL>'
     In the group buffer, move point to the previous group containing
     unread articles.

     In the summary buffer, scroll the text of the article backwards.

`n'
     Move point to the next unread group, or select the next unread
     article.

`p'
     Move point to the previous unread group, or select the previous
     unread article.

`C-n'
`C-p'
     Move point to the next or previous item, even if it is marked as
     read.  This does not select the article or group on that line.

`s'
     In the summary buffer, do an incremental search of the current
     text in the article buffer, just as if you switched to the article
     buffer and typed `C-s'.

`M-s REGEXP <RET>'
     In the summary buffer, search forward for articles containing a
     match for REGEXP.



File: emacs,  Node: Shell,  Next: Emacs Server,  Prev: Gnus,  Up: Top

41 Running Shell Commands from Emacs
************************************

Emacs has commands for passing single command lines to inferior shell
processes; it can also run a shell interactively with input and output
to an Emacs buffer named `*shell*' or run a shell inside a terminal
emulator window.

`M-! CMD <RET>'
     Run the shell command line CMD and display the output
     (`shell-command').

`M-| CMD <RET>'
     Run the shell command line CMD with region contents as input;
     optionally replace the region with the output
     (`shell-command-on-region').

`M-& CMD <RET>'
     Run the shell command line CMD asynchronously, and display the
     output (`async-shell-command').

`M-x shell'
     Run a subshell with input and output through an Emacs buffer.  You
     can then give commands interactively.

`M-x term'
     Run a subshell with input and output through an Emacs buffer.  You
     can then give commands interactively.  Full terminal emulation is
     available.

   `M-x eshell' invokes a shell implemented entirely in Emacs.  It is
documented in a separate manual.  *Note Eshell: (eshell)Top.

* Menu:

* Single Shell::           How to run one shell command and return.
* Interactive Shell::      Permanent shell taking input via Emacs.
* Shell Mode::             Special Emacs commands used with permanent shell.
* Shell Prompts::          Two ways to recognize shell prompts.
* History: Shell History.  Repeating previous commands in a shell buffer.
* Directory Tracking::     Keeping track when the subshell changes directory.
* Options: Shell Options.  Options for customizing Shell mode.
* Terminal emulator::      An Emacs window as a terminal emulator.
* Term Mode::              Special Emacs commands used in Term mode.
* Paging in Term::         Paging in the terminal emulator.
* Remote Host::            Connecting to another computer.
* Serial Terminal::        Connecting to a serial port.


File: emacs,  Node: Single Shell,  Next: Interactive Shell,  Up: Shell

41.1 Single Shell Commands
==========================

`M-!' (`shell-command') reads a line of text using the minibuffer and
executes it as a shell command in a subshell made just for that
command.  Standard input for the command comes from the null device.
If the shell command produces any output, the output appears either in
the echo area (if it is short), or in an Emacs buffer named `*Shell
Command Output*', which is displayed in another window but not selected
(if the output is long).

   For instance, one way to decompress a file `foo.gz' from Emacs is to
type `M-! gunzip foo.gz <RET>'.  That shell command normally creates
the file `foo' and produces no terminal output.

   A numeric argument, as in `M-1 M-!', says to insert terminal output
into the current buffer instead of a separate buffer.  It puts point
before the output, and sets the mark after the output.  For instance,
`M-1 M-! gunzip < foo.gz <RET>' would insert the uncompressed
equivalent of `foo.gz' into the current buffer.

   If the shell command line ends in `&', it runs asynchronously.  For
a synchronous shell command, `shell-command' returns the command's exit
status (0 means success), when it is called from a Lisp program.  You
do not get any status information for an asynchronous command, since it
hasn't finished yet when `shell-command' returns.

   You can also type `M-&' (`async-shell-command') to execute a shell
command asynchronously.  This behaves exactly like calling
`shell-command' with `&', except that you do not need to add the `&' to
the shell command line.

   `M-|' (`shell-command-on-region') is like `M-!' but passes the
contents of the region as the standard input to the shell command,
instead of no input.  With a numeric argument, meaning insert the
output in the current buffer, it deletes the old region and the output
replaces it as the contents of the region.  It returns the command's
exit status, like `M-!'.

   One use for `M-|' is to run `gpg' to see what keys are in the
buffer.  For instance, if the buffer contains a GPG key, type `C-x h
M-| gpg <RET>' to feed the entire buffer contents to the `gpg' program.
That program will ignore everything except the encoded keys, and will
output a list of the keys the buffer contains.

   Both `M-!' and `M-|' use `shell-file-name' to specify the shell to
use.  This variable is initialized based on your `SHELL' environment
variable when Emacs is started.  If the file name is relative, Emacs
searches the directories in the list `exec-path'; this list is
initialized based on the environment variable `PATH' when Emacs is
started.  Your init file can override either or both of these default
initializations (*note Init File::).

   Both `M-!' and `M-|' wait for the shell command to complete, unless
you end the command with `&' to make it asynchronous.  To stop waiting,
type `C-g' to quit; that terminates the shell command with the signal
`SIGINT'--the same signal that `C-c' normally generates in the shell.
Emacs then waits until the command actually terminates.  If the shell
command doesn't stop (because it ignores the `SIGINT' signal), type
`C-g' again; this sends the command a `SIGKILL' signal which is
impossible to ignore.

   Asynchronous commands ending in `&' feed their output into the
buffer `*Async Shell Command*'.  Output arrives in that buffer
regardless of whether it is visible in a window.

   To specify a coding system for `M-!' or `M-|', use the command `C-x
<RET> c' immediately beforehand.  *Note Communication Coding::.

   Error output from these commands is normally intermixed with the
regular output.  But if the variable
`shell-command-default-error-buffer' has a string as value, and it's
the name of a buffer, `M-!' and `M-|' insert error output before point
in that buffer.


File: emacs,  Node: Interactive Shell,  Next: Shell Mode,  Prev: Single Shell,  Up: Shell

41.2 Interactive Inferior Shell
===============================

To run a subshell interactively, use `M-x shell'.  This creates (or
reuses) a buffer named `*shell*' and runs a subshell with input coming
from and output going to that buffer.  That is to say, any "terminal
output" from the subshell goes into the buffer, advancing point, and
any "terminal input" for the subshell comes from text in the buffer.
To give input to the subshell, go to the end of the buffer and type the
input, terminated by <RET>.

   Emacs does not wait for the subshell to do anything.  You can switch
windows or buffers and edit them while the shell is waiting, or while
it is running a command.  Output from the subshell waits until Emacs
has time to process it; this happens whenever Emacs is waiting for
keyboard input or for time to elapse.

   Input lines, once you submit them, are displayed using the face
`comint-highlight-input', and prompts are displayed using the face
`comint-highlight-prompt'.  This makes it easier to see previous input
lines in the buffer.  *Note Faces::.

   To make multiple subshells, you can invoke `M-x shell' with a prefix
argument (e.g. `C-u M-x shell'), which will read a buffer name and
create (or reuse) a subshell in that buffer.  You can also rename the
`*shell*' buffer using `M-x rename-uniquely', then create a new
`*shell*' buffer using plain `M-x shell'.  Subshells in different
buffers run independently and in parallel.

   The file name used to load the subshell is the value of the variable
`explicit-shell-file-name', if that is non-`nil'.  Otherwise, the
environment variable `ESHELL' is used, or the environment variable
`SHELL' if there is no `ESHELL'.  If the file name specified is
relative, the directories in the list `exec-path' are searched; this
list is initialized based on the environment variable `PATH' when Emacs
is started.  Your init file can override either or both of these
default initializations.  (*note Init File::).

   Emacs sends the new shell the contents of the file
`~/.emacs_SHELLNAME' as input, if it exists, where SHELLNAME is the
name of the file that the shell was loaded from.  For example, if you
use bash, the file sent to it is `~/.emacs_bash'.  If this file is not
found, Emacs tries to fallback on `~/.emacs.d/init_SHELLNAME.sh'.

   To specify a coding system for the shell, you can use the command
`C-x <RET> c' immediately before `M-x shell'.  You can also change the
coding system for a running subshell by typing `C-x <RET> p' in the
shell buffer.  *Note Communication Coding::.

   Emacs sets the environment variable `INSIDE_EMACS' in the subshell
to a comma-separated list including the Emacs version.  Programs can
check this variable to determine whether they are running inside an
Emacs subshell.

   Emacs also sets the `EMACS' environment variable (to `t') if it is
not already defined.  *Warning:* This environment variable is
deprecated.  Programs that check this variable should be changed to
check `INSIDE_EMACS' instead.


File: emacs,  Node: Shell Mode,  Next: Shell Prompts,  Prev: Interactive Shell,  Up: Shell

41.3 Shell Mode
===============

Shell buffers use Shell mode, which defines several special keys
attached to the `C-c' prefix.  They are chosen to resemble the usual
editing and job control characters present in shells that are not under
Emacs, except that you must type `C-c' first.  Here is a complete list
of the special key bindings of Shell mode:

`<RET>'
     At end of buffer send line as input; otherwise, copy current line
     to end of buffer and send it (`comint-send-input').  Copying a line
     in this way omits any prompt at the beginning of the line (text
     output by programs preceding your input).  *Note Shell Prompts::,
     for how Shell mode recognizes prompts.

`<TAB>'
     Complete the command name or file name before point in the shell
     buffer (`comint-dynamic-complete').  <TAB> also completes history
     references (*note History References::) and environment variable
     names.

     The variable `shell-completion-fignore' specifies a list of file
     name extensions to ignore in Shell mode completion.  The default
     setting is `nil', but some users prefer `("~" "#" "%")' to ignore
     file names ending in `~', `#' or `%'.  Other related Comint modes
     use the variable `comint-completion-fignore' instead.

`M-?'
     Display temporarily a list of the possible completions of the file
     name before point in the shell buffer
     (`comint-dynamic-list-filename-completions').

`C-d'
     Either delete a character or send EOF
     (`comint-delchar-or-maybe-eof').  Typed at the end of the shell
     buffer, `C-d' sends EOF to the subshell.  Typed at any other
     position in the buffer, `C-d' deletes a character as usual.

`C-c C-a'
     Move to the beginning of the line, but after the prompt if any
     (`comint-bol-or-process-mark').  If you repeat this command twice
     in a row, the second time it moves back to the process mark, which
     is the beginning of the input that you have not yet sent to the
     subshell.  (Normally that is the same place--the end of the prompt
     on this line--but after `C-c <SPC>' the process mark may be in a
     previous line.)

`C-c <SPC>'
     Accumulate multiple lines of input, then send them together.  This
     command inserts a newline before point, but does not send the
     preceding text as input to the subshell--at least, not yet.  Both
     lines, the one before this newline and the one after, will be sent
     together (along with the newline that separates them), when you
     type <RET>.

`C-c C-u'
     Kill all text pending at end of buffer to be sent as input
     (`comint-kill-input').  If point is not at end of buffer, this
     only kills the part of this text that precedes point.

`C-c C-w'
     Kill a word before point (`backward-kill-word').

`C-c C-c'
     Interrupt the shell or its current subjob if any
     (`comint-interrupt-subjob').  This command also kills any shell
     input pending in the shell buffer and not yet sent.

`C-c C-z'
     Stop the shell or its current subjob if any (`comint-stop-subjob').
     This command also kills any shell input pending in the shell
     buffer and not yet sent.

`C-c C-\'
     Send quit signal to the shell or its current subjob if any
     (`comint-quit-subjob').  This command also kills any shell input
     pending in the shell buffer and not yet sent.

`C-c C-o'
     Delete the last batch of output from a shell command
     (`comint-delete-output').  This is useful if a shell command spews
     out lots of output that just gets in the way.  This command used
     to be called `comint-kill-output'.

`C-c C-s'
     Write the last batch of output from a shell command to a file
     (`comint-write-output').  With a prefix argument, the file is
     appended to instead.  Any prompt at the end of the output is not
     written.

`C-c C-r'
`C-M-l'
     Scroll to display the beginning of the last batch of output at the
     top of the window; also move the cursor there
     (`comint-show-output').

`C-c C-e'
     Scroll to put the end of the buffer at the bottom of the window
     (`comint-show-maximum-output').

`C-c C-f'
     Move forward across one shell command, but not beyond the current
     line (`shell-forward-command').  The variable
     `shell-command-regexp' specifies how to recognize the end of a
     command.

`C-c C-b'
     Move backward across one shell command, but not beyond the current
     line (`shell-backward-command').

`M-x dirs'
     Ask the shell what its current directory is, so that Emacs can
     agree with the shell.

`M-x send-invisible <RET> TEXT <RET>'
     Send TEXT as input to the shell, after reading it without echoing.
     This is useful when a shell command runs a program that asks for a
     password.

     Please note that Emacs will not echo passwords by default.  If you
     really want them to be echoed, evaluate the following Lisp
     expression:

          (remove-hook 'comint-output-filter-functions
                       'comint-watch-for-password-prompt)

`M-x comint-continue-subjob'
     Continue the shell process.  This is useful if you accidentally
     suspend the shell process.(1)

`M-x comint-strip-ctrl-m'
     Discard all control-M characters from the current group of shell
     output.  The most convenient way to use this command is to make it
     run automatically when you get output from the subshell.  To do
     that, evaluate this Lisp expression:

          (add-hook 'comint-output-filter-functions
                    'comint-strip-ctrl-m)

`M-x comint-truncate-buffer'
     This command truncates the shell buffer to a certain maximum
     number of lines, specified by the variable
     `comint-buffer-maximum-size'.  Here's how to do this automatically
     each time you get output from the subshell:

          (add-hook 'comint-output-filter-functions
                    'comint-truncate-buffer)

   Shell mode is a derivative of Comint mode, a general-purpose mode for
communicating with interactive subprocesses.  Most of the features of
Shell mode actually come from Comint mode, as you can see from the
command names listed above.  The special features of Shell mode include
the directory tracking feature, and a few user commands.

   Other Emacs features that use variants of Comint mode include GUD
(*note Debuggers::) and `M-x run-lisp' (*note External Lisp::).

   You can use `M-x comint-run' to execute any program of your choice
in a subprocess using unmodified Comint mode--without the
specializations of Shell mode.

   ---------- Footnotes ----------

   (1) You should not suspend the shell process.  Suspending a subjob
of the shell is a completely different matter--that is normal practice,
but you must use the shell to continue the subjob; this command won't
do it.


File: emacs,  Node: Shell Prompts,  Next: Shell History,  Prev: Shell Mode,  Up: Shell

41.4 Shell Prompts
==================

A prompt is text output by a program to show that it is ready to accept
new user input.  Normally, Comint mode (and thus Shell mode) considers
the prompt to be any text output by a program at the beginning of an
input line.  However, if the variable `comint-use-prompt-regexp' is
non-`nil', then Comint mode uses a regular expression to recognize
prompts.  In Shell mode, `shell-prompt-pattern' specifies the regular
expression.

   The value of `comint-use-prompt-regexp' also affects many motion and
paragraph commands.  If the value is non-`nil', the general Emacs
motion commands behave as they normally do in buffers without special
text properties.  However, if the value is `nil', the default, then
Comint mode divides the buffer into two types of "fields" (ranges of
consecutive characters having the same `field' text property): input
and output.  Prompts are part of the output.  Most Emacs motion
commands do not cross field boundaries, unless they move over multiple
lines.  For instance, when point is in input on the same line as a
prompt, `C-a' puts point at the beginning of the input if
`comint-use-prompt-regexp' is `nil' and at the beginning of the line
otherwise.

   In Shell mode, only shell prompts start new paragraphs.  Thus, a
paragraph consists of a prompt and the input and output that follow it.
However, if `comint-use-prompt-regexp' is `nil', the default, most
paragraph commands do not cross field boundaries.  This means that
prompts, ranges of input, and ranges of non-prompt output behave mostly
like separate paragraphs; with this setting, numeric arguments to most
paragraph commands yield essentially undefined behavior.  For the
purpose of finding paragraph boundaries, Shell mode uses
`shell-prompt-pattern', regardless of `comint-use-prompt-regexp'.


File: emacs,  Node: Shell History,  Next: Directory Tracking,  Prev: Shell Prompts,  Up: Shell

41.5 Shell Command History
==========================

Shell buffers support three ways of repeating earlier commands.  You
can use keys like those used for the minibuffer history; these work
much as they do in the minibuffer, inserting text from prior commands
while point remains always at the end of the buffer.  You can move
through the buffer to previous inputs in their original place, then
resubmit them or copy them to the end.  Or you can use a `!'-style
history reference.

* Menu:

* Ring: Shell Ring.             Fetching commands from the history list.
* Copy: Shell History Copying.  Moving to a command and then copying it.
* History References::          Expanding `!'-style history references.


File: emacs,  Node: Shell Ring,  Next: Shell History Copying,  Up: Shell History

41.5.1 Shell History Ring
-------------------------

`M-p'
`C-<UP>'
     Fetch the next earlier old shell command.

`M-n'
`C-<DOWN>'
     Fetch the next later old shell command.

`M-r'
     Begin an incremental regexp search of old shell commands.

`C-c C-x'
     Fetch the next subsequent command from the history.

`C-c .'
     Fetch one argument from an old shell command.

`C-c C-l'
     Display the buffer's history of shell commands in another window
     (`comint-dynamic-list-input-ring').

   Shell buffers provide a history of previously entered shell
commands.  To reuse shell commands from the history, use the editing
commands `M-p', `M-n', `M-r' and `M-s'.  These work just like the
minibuffer history commands except that they operate on the text at the
end of the shell buffer, where you would normally insert text to send
to the shell.

   `M-p' fetches an earlier shell command to the end of the shell
buffer.  Successive use of `M-p' fetches successively earlier shell
commands, each replacing any text that was already present as potential
shell input.  `M-n' does likewise except that it finds successively
more recent shell commands from the buffer.  `C-<UP>' works like `M-p',
and `C-<DOWN>' like `M-n'.

   The history search command `M-r' begins an incremental regular
expression search of previous shell commands.  After typing `M-r',
start typing the desired string or regular expression; the last
matching shell command will be displayed in the current line.
Incremental search commands have their usual effects--for instance,
`C-s' and `C-r' search forward and backward for the next match (*note
Incremental Search::).  When you find the desired input, type <RET> to
terminate the search.  This puts the input in the command line.  Any
partial input you were composing before navigating the history list is
restored when you go to the beginning or end of the history ring.

   Often it is useful to reexecute several successive shell commands
that were previously executed in sequence.  To do this, first find and
reexecute the first command of the sequence.  Then type `C-c C-x'; that
will fetch the following command--the one that follows the command you
just repeated.  Then type <RET> to reexecute this command.  You can
reexecute several successive commands by typing `C-c C-x <RET>' over
and over.

   The command `C-c .' (`comint-input-previous-argument') copies an
individual argument from a previous command, like `ESC .' in Bash.  The
simplest use copies the last argument from the previous shell command.
With a prefix argument N, it copies the Nth argument instead.
Repeating `C-c .' copies from an earlier shell command instead, always
using the same value of N (don't give a prefix argument when you repeat
the `C-c .' command).

   These commands get the text of previous shell commands from a special
history list, not from the shell buffer itself.  Thus, editing the shell
buffer, or even killing large parts of it, does not affect the history
that these commands access.

   Some shells store their command histories in files so that you can
refer to commands from previous shell sessions.  Emacs reads the
command history file for your chosen shell, to initialize its own
command history.  The file name is `~/.bash_history' for bash,
`~/.sh_history' for ksh, and `~/.history' for other shells.


File: emacs,  Node: Shell History Copying,  Next: History References,  Prev: Shell Ring,  Up: Shell History

41.5.2 Shell History Copying
----------------------------

`C-c C-p'
     Move point to the previous prompt (`comint-previous-prompt').

`C-c C-n'
     Move point to the following prompt (`comint-next-prompt').

`C-c <RET>'
     Copy the input command at point, inserting the copy at the end of
     the buffer (`comint-copy-old-input').  This is useful if you move
     point back to a previous command.  After you copy the command, you
     can submit the copy as input with <RET>.  If you wish, you can edit
     the copy before resubmitting it.  If you use this command on an
     output line, it copies that line to the end of the buffer.

`Mouse-2'
     If `comint-use-prompt-regexp' is `nil' (the default), copy the old
     input command that you click on, inserting the copy at the end of
     the buffer (`comint-insert-input').  If `comint-use-prompt-regexp'
     is non-`nil', or if the click is not over old input, just yank as
     usual.

   Moving to a previous input and then copying it with `C-c <RET>' or
`Mouse-2' produces the same results--the same buffer contents--that you
would get by using `M-p' enough times to fetch that previous input from
the history list.  However, `C-c <RET>' copies the text from the
buffer, which can be different from what is in the history list if you
edit the input text in the buffer after it has been sent.


File: emacs,  Node: History References,  Prev: Shell History Copying,  Up: Shell History

41.5.3 Shell History References
-------------------------------

Various shells including csh and bash support "history references" that
begin with `!' and `^'.  Shell mode recognizes these constructs, and
can perform the history substitution for you.

   If you insert a history reference and type <TAB>, this searches the
input history for a matching command, performs substitution if
necessary, and places the result in the buffer in place of the history
reference.  For example, you can fetch the most recent command
beginning with `mv' with `! m v <TAB>'.  You can edit the command if
you wish, and then resubmit the command to the shell by typing <RET>.

   Shell mode can optionally expand history references in the buffer
when you send them to the shell.  To request this, set the variable
`comint-input-autoexpand' to `input'.  You can make <SPC> perform
history expansion by binding <SPC> to the command `comint-magic-space'.

   Shell mode recognizes history references when they follow a prompt.
*Note Shell Prompts::, for how Shell mode recognizes prompts.


File: emacs,  Node: Directory Tracking,  Next: Shell Options,  Prev: Shell History,  Up: Shell

41.6 Directory Tracking
=======================

Shell mode keeps track of `cd', `pushd' and `popd' commands given to
the inferior shell, so it can keep the `*shell*' buffer's default
directory the same as the shell's working directory.  It recognizes
these commands syntactically, by examining lines of input that are sent.

   If you use aliases for these commands, you can tell Emacs to
recognize them also.  For example, if the value of the variable
`shell-pushd-regexp' matches the beginning of a shell command line,
that line is regarded as a `pushd' command.  Change this variable when
you add aliases for `pushd'.  Likewise, `shell-popd-regexp' and
`shell-cd-regexp' are used to recognize commands with the meaning of
`popd' and `cd'.  These commands are recognized only at the beginning
of a shell command line.

   If Emacs gets confused about changes in the current directory of the
subshell, use the command `M-x dirs' to ask the shell what its current
directory is.  This command works for shells that support the most
common command syntax; it may not work for unusual shells.

   You can also use `M-x dirtrack-mode' to enable (or disable) an
alternative method of tracking changes in the current directory.  This
method relies on your shell prompt containing the full current working
directory at all times.


File: emacs,  Node: Shell Options,  Next: Terminal emulator,  Prev: Directory Tracking,  Up: Shell

41.7 Shell Mode Options
=======================

If the variable `comint-scroll-to-bottom-on-input' is non-`nil',
insertion and yank commands scroll the selected window to the bottom
before inserting.  The default is `nil'.

   If `comint-scroll-show-maximum-output' is non-`nil', then arrival of
output when point is at the end tries to scroll the last line of text
to the bottom line of the window, showing as much useful text as
possible.  (This mimics the scrolling behavior of most terminals.)  The
default is `t'.

   By setting `comint-move-point-for-output', you can opt for having
point jump to the end of the buffer whenever output arrives--no matter
where in the buffer point was before.  If the value is `this', point
jumps in the selected window.  If the value is `all', point jumps in
each window that shows the Comint buffer.  If the value is `other',
point jumps in all nonselected windows that show the current buffer.
The default value is `nil', which means point does not jump to the end.

   If you set `comint-prompt-read-only', the prompts in the Comint
buffer are read-only.

   The variable `comint-input-ignoredups' controls whether successive
identical inputs are stored in the input history.  A non-`nil' value
means to omit an input that is the same as the previous input.  The
default is `nil', which means to store each input even if it is equal
to the previous input.

   Three variables customize file name completion.  The variable
`comint-completion-addsuffix' controls whether completion inserts a
space or a slash to indicate a fully completed file or directory name
(non-`nil' means do insert a space or slash).
`comint-completion-recexact', if non-`nil', directs <TAB> to choose the
shortest possible completion if the usual Emacs completion algorithm
cannot add even a single character.  `comint-completion-autolist', if
non-`nil', says to list all the possible completions whenever
completion is not exact.

   Command completion normally considers only executable files.  If you
set `shell-completion-execonly' to `nil', it considers nonexecutable
files as well.

   You can configure the behavior of `pushd'.  Variables control
whether `pushd' behaves like `cd' if no argument is given
(`shell-pushd-tohome'), pop rather than rotate with a numeric argument
(`shell-pushd-dextract'), and only add directories to the directory
stack if they are not already on it (`shell-pushd-dunique').  The
values you choose should match the underlying shell, of course.


File: emacs,  Node: Terminal emulator,  Next: Term Mode,  Prev: Shell Options,  Up: Shell

41.8 Emacs Terminal Emulator
============================

To run a subshell in a terminal emulator, use `M-x term'.  This creates
(or reuses) a buffer named `*terminal*', and runs a subshell with input
coming from your keyboard, and output going to that buffer.

   The terminal emulator uses Term mode, which has two input modes.  In
line mode, Term basically acts like Shell mode; see *note Shell Mode::.

   In char mode, each character is sent directly to the inferior
subshell, as "terminal input."  Any "echoing" of your input is the
responsibility of the subshell.  The sole exception is the terminal
escape character, which by default is `C-c' (*note Term Mode::).  Any
"terminal output" from the subshell goes into the buffer, advancing
point.

   Some programs (such as Emacs itself) need to control the appearance
on the terminal screen in detail.  They do this by sending special
control codes.  The exact control codes needed vary from terminal to
terminal, but nowadays most terminals and terminal emulators (including
`xterm') understand the ANSI-standard (VT100-style) escape sequences.
Term mode recognizes these escape sequences, and handles each one
appropriately, changing the buffer so that the appearance of the window
matches what it would be on a real terminal.  You can actually run
Emacs inside an Emacs Term window.

   You can use Term mode to communicate with a device connected to a
serial port of your computer.  *Note Serial Terminal::.

   The file name used to load the subshell is determined the same way
as for Shell mode.  To make multiple terminal emulators, rename the
buffer `*terminal*' to something different using `M-x rename-uniquely',
just as with Shell mode.

   Unlike Shell mode, Term mode does not track the current directory by
examining your input.  But some shells can tell Term what the current
directory is.  This is done automatically by `bash' version 1.15 and
later.


File: emacs,  Node: Term Mode,  Next: Paging in Term,  Prev: Terminal emulator,  Up: Shell

41.9 Term Mode
==============

The terminal emulator uses Term mode, which has two input modes.  In
line mode, Term basically acts like Shell mode; see *note Shell Mode::.
In char mode, each character is sent directly to the inferior subshell,
except for the Term escape character, normally `C-c'.

   To switch between line and char mode, use these commands:

`C-c C-j'
     Switch to line mode.  Do nothing if already in line mode.

`C-c C-k'
     Switch to char mode.  Do nothing if already in char mode.

   The following commands are only available in char mode:

`C-c C-c'
     Send a literal <C-c> to the sub-shell.

`C-c CHAR'
     This is equivalent to `C-x CHAR' in normal Emacs.  For example,
     `C-c o' invokes the global binding of `C-x o', which is normally
     `other-window'.


File: emacs,  Node: Paging in Term,  Next: Remote Host,  Prev: Term Mode,  Up: Shell

41.10 Page-At-A-Time Output
===========================

Term mode has a page-at-a-time feature.  When enabled it makes output
pause at the end of each screenful.

`C-c C-q'
     Toggle the page-at-a-time feature.  This command works in both line
     and char modes.  When page-at-a-time is enabled, the mode-line
     displays the word `page'.

   With page-at-a-time enabled, whenever Term receives more than a
screenful of output since your last input, it pauses, displaying
`**MORE**' in the mode-line.  Type <SPC> to display the next screenful
of output.  Type `?' to see your other options.  The interface is
similar to the `more' program.


File: emacs,  Node: Remote Host,  Next: Serial Terminal,  Prev: Paging in Term,  Up: Shell

41.11 Remote Host Shell
=======================

You can login to a remote computer, using whatever commands you would
from a regular terminal (e.g. using the `telnet' or `rlogin' commands),
from a Term window.

   A program that asks you for a password will normally suppress
echoing of the password, so the password will not show up in the
buffer.  This will happen just as if you were using a real terminal, if
the buffer is in char mode.  If it is in line mode, the password is
temporarily visible, but will be erased when you hit return.  (This
happens automatically; there is no special password processing.)

   When you log in to a different machine, you need to specify the type
of terminal you're using, by setting the `TERM' environment variable in
the environment for the remote login command.  (If you use bash, you do
that by writing the variable assignment before the remote login
command, without separating comma.)  Terminal types `ansi' or `vt100'
will work on most systems.


File: emacs,  Node: Serial Terminal,  Prev: Remote Host,  Up: Shell

41.12 Serial Terminal
=====================

If you have a device connected to a serial port of your computer, you
can use Emacs to communicate with it.  `M-x serial-term' will ask you
for a serial port name and speed and will then open a new window in
*note Term Mode::.

   The speed of the serial port is measured in bits per second.  The
most common speed is 9600 bits per second.  You can change the speed
interactively by clicking on the mode line.

   A serial port can be configured even more by clicking on "8N1" in
the mode line.  By default, a serial port is configured as "8N1", which
means that each byte consists of 8 data bits, No parity check bit, and
1 stopbit.

   When you have opened the serial port connection, you will see output
from the device in the window.  Also, what you type in the window is
sent to the device.

   If the speed or the configuration is wrong, you cannot communicate
with your device and will probably only see garbage output in the
window.


File: emacs,  Node: Emacs Server,  Next: Printing,  Prev: Shell,  Up: Top

42 Using Emacs as a Server
**************************

Various programs such as `mail' can invoke your choice of editor to
edit a particular piece of text, such as a message that you are
sending.  By convention, most of these programs use the environment
variable `EDITOR' to specify which editor to run.  If you set `EDITOR'
to `emacs', they invoke Emacs--but in an inconvenient way, by starting
a new Emacs process.  This is inconvenient because the new Emacs
process doesn't share buffers, a command history, or other kinds of
information with any existing Emacs process.

   You can solve this problem by setting up Emacs as an "edit server",
so that it "listens" for external edit requests and acts accordingly.
There are two ways to start an Emacs server:

   The first is to run the command `server-start' in an existing Emacs
process: either type `M-x server-start', or put the expression
`(server-start)' in your initialization file (*note Init File::).  The
existing Emacs process is the server; when you exit Emacs, the server
dies with the Emacs process.

   The second way to start an Emacs server is to run Emacs as a
"daemon", using the `--daemon' command-line option.  *Note Initial
Options::.  When Emacs is started this way, it calls `server-start'
after initialization, and returns control to the calling terminal
instead of opening an initial frame; it then waits in the background,
listening for edit requests.

   Once an Emacs server is set up, you can use a shell command called
`emacsclient' to connect to the existing Emacs process and tell it to
visit a file.  If you set the `EDITOR' environment variable to
`emacsclient', programs such as `mail' will use the existing Emacs
process for editing.(1)

   You can run multiple Emacs servers on the same machine by giving
each one a unique "server name", using the variable `server-name'.  For
example, `M-x set-variable <RET> server-name <RET> foo <RET>' sets the
server name to `foo'.  The `emacsclient' program can specify a server by
name, using the `-s' option (*note emacsclient Options::).

* Menu:

* Invoking emacsclient:: Connecting to the Emacs server.
* emacsclient Options::  Emacs client startup options.

   ---------- Footnotes ----------

   (1) Some programs use a different environment variable; for example,
to make TeX use `emacsclient', set the `TEXEDIT' environment variable to
`emacsclient +%d %s'.


File: emacs,  Node: Invoking emacsclient,  Next: emacsclient Options,  Up: Emacs Server

42.1 Invoking `emacsclient'
===========================

The simplest way to use the `emacsclient' program is to run the shell
command `emacsclient FILE', where FILE is a file name.  This connects
to an Emacs server, and tells that Emacs process to visit FILE in one
of its existing frames--either a graphical frame, or one in a text-only
terminal (*note Frames::).  You can then select that frame to begin
editing.

   If there is no Emacs server, the `emacsclient' program halts with an
error message.  If the Emacs process has no existing frame--which can
happen if it was started as a daemon (*note Emacs Server::)--then Emacs
opens a frame on the terminal in which you called `emacsclient'.

   You can also force `emacsclient' to open a new frame on a graphical
display, or on a text-only terminal, using the `-c' and `-t' options.
*Note emacsclient Options::.

   If you are running on a single text-only terminal, you can switch
between `emacsclient''s shell and the Emacs server using one of two
methods: (i) run the Emacs server and `emacsclient' on different
virtual terminals, and switch to the Emacs server's virtual terminal
after calling `emacsclient'; or (ii) call `emacsclient' from within the
Emacs server itself, using Shell mode (*note Interactive Shell::) or
Term mode (*note Term Mode::); `emacsclient' blocks only the subshell
under Emacs, and you can still use Emacs to edit the file.

   When you finish editing FILE in the Emacs server, type `C-x #'
(`server-edit') in its buffer.  This saves the file and sends a message
back to the `emacsclient' program, telling it to exit.  Programs that
use `EDITOR' usually wait for the "editor"--in this case
`emacsclient'--to exit before doing something else.

   You can also call `emacsclient' with multiple file name arguments:
`emacsclient FILE1 FILE2 ...' tells the Emacs server to visit FILE1,
FILE2, and so forth.  Emacs selects the buffer visiting FILE1, and
buries the other buffers at the bottom of the buffer list (*note
Buffers::).  The `emacsclient' program exits once all the specified
files are finished (i.e., once you have typed `C-x #' in each server
buffer).

   Finishing with a server buffer also kills the buffer, unless it
already existed in the Emacs session before the server was asked to
create it.  However, if you set `server-kill-new-buffers' to `nil',
then a different criterion is used: finishing with a server buffer
kills it if the file name matches the regular expression
`server-temp-file-regexp'.  This is set up to distinguish certain
"temporary" files.

   Each `C-x #' checks for other pending external requests to edit
various files, and selects the next such file.  You can switch to a
server buffer manually if you wish; you don't have to arrive at it with
`C-x #'.  But `C-x #' is the way to tell `emacsclient' that you are
finished.

   If you set the value of the variable `server-window' to a window or
a frame, `C-x #' always displays the next server buffer in that window
or in that frame.


File: emacs,  Node: emacsclient Options,  Prev: Invoking emacsclient,  Up: Emacs Server

42.2 `emacsclient' Options
==========================

You can pass some optional arguments to the `emacsclient' program, such
as:

     emacsclient -c +12 FILE1 +4:3 FILE2

The `+LINE' or `+LINE:COLUMN' arguments specify line numbers, or line
and column numbers, for the next file argument.  These behave like the
command line arguments for Emacs itself.  *Note Action Arguments::.

   The other optional arguments recognized by `emacsclient' are listed
below:

`-a COMMAND'
`--alternate-editor=COMMAND'
     Specify a command to run if `emacsclient' fails to contact Emacs.
     This is useful when running `emacsclient' in a script.

     As a special exception, if COMMAND is the empty string, then
     `emacsclient' starts Emacs in daemon mode and then tries
     connecting again.

     The environment variable `ALTERNATE_EDITOR' has the same effect as
     the `-a' option.  If both are present, the latter takes precedence.

`-c'
     Create a new graphical frame, instead of using an existing Emacs
     frame.  Emacs 23 can create a graphical frame even if it was
     started in a text-only terminal, provided it is able to connect to
     a graphical display.  If no graphical display is available, Emacs
     creates a new text-only terminal frame (*note Frames::).  If you
     omit a filename argument while supplying the `-c' option, the new
     frame displays the `*scratch*' buffer (*note Buffers::).

`-d DISPLAY'
`--display=DISPLAY'
     Tell Emacs to open the given files on the X display DISPLAY
     (assuming there is more than one X display available).

`-e'
`--eval'
     Tell Emacs to evaluate some Emacs Lisp code, instead of visiting
     some files.  When this option is given, the arguments to
     `emacsclient' are interpreted as a list of expressions to
     evaluate, _not_ as a list of files to visit.

`-f SERVER-FILE'
`--server-file=SERVER-FILE'
     Specify a "server file" for connecting to an Emacs server via TCP.

     An Emacs server usually uses an operating system feature called a
     "local socket" to listen for connections.  Some operating systems,
     such as Microsoft Windows, do not support local sockets; in that
     case, Emacs uses TCP instead.  When you start the Emacs server,
     Emacs creates a server file containing some TCP information that
     `emacsclient' needs for making the connection.  By default, the
     server file is in `~/.emacs.d/server/'.  On Microsoft Windows, if
     `emacsclient' does not find the server file there, it looks in the
     `.emacs.d/server/' subdirectory of the directory pointed to by the
     `APPDATA' environment variable.  You can tell `emacsclient' to use
     a specific server file with the `-f' or `--server-file' option, or
     by setting the `EMACS_SERVER_FILE' environment variable.

     Even if local sockets are available, you can tell Emacs to use TCP
     by setting the variable `server-use-tcp' to `t'.  One advantage of
     TCP is that the server can accept connections from remote machines.
     For this to work, you must (i) set the variable `server-host' to
     the hostname or IP address of the machine on which the Emacs server
     runs, and (ii) provide `emacsclient' with the server file.  (One
     convenient way to do the latter is to put the server file on a
     networked file system such as NFS.)

`-n'
`--no-wait'
     Let `emacsclient' exit immediately, instead of waiting until all
     server buffers are finished.  You can take as long as you like to
     edit the server buffers within Emacs, and they are _not_ killed
     when you type `C-x #' in them.

`-s SERVER-NAME'
`--socket-name=SERVER-NAME'
     Connect to the Emacs server named SERVER-NAME.  The server name is
     given by the variable `server-name' on the Emacs server.  If this
     option is omitted, `emacsclient' connects to the first server it
     finds.  (This option is not supported on MS-Windows.)

`-t'
`--tty'
`-nw'
     Create a new Emacs frame on the current text-only terminal,
     instead of using an existing Emacs frame.  Emacs 23 can open a
     text-only terminal even if it was started in another text-only
     terminal, or on a graphical display.  If you omit a filename
     argument while supplying this option, the new frame displays the
     `*scratch*' buffer.  *Note Buffers::.

   If you type `C-x C-c' (`save-buffers-kill-terminal') in an Emacs
frame created with `emacsclient', via the `-c' or `-t' options, Emacs
deletes the frame instead of killing the Emacs process itself.  On a
text-only terminal frame created with the `-t' option, this returns
control to the terminal.  Emacs also marks all the server buffers for
the client as finished, as though you had typed `C-x #' in all of them.

   When Emacs is started as a daemon, all frames are considered client
frames, so `C-x C-c' will never kill Emacs.  To kill the Emacs process,
type `M-x kill-emacs'.


File: emacs,  Node: Printing,  Next: Sorting,  Prev: Emacs Server,  Up: Top

43 Printing Hard Copies
***********************

Emacs provides commands for printing hard copies of either an entire
buffer or just part of one, with or without page headers.  You can
invoke the printing commands directly, as detailed in the following
section, or using the `File' menu on the menu bar.

   Aside from the commands described in this section, you can also
"print" an Emacs buffer to HTML with `M-x htmlfontify-buffer'.  This
command converts the current buffer to a HTML file, replacing Emacs
faces with CSS-based markup.  In addition, see the hardcopy commands of
Dired (*note Misc File Ops::) and the diary (*note Displaying the
Diary::).

`M-x print-buffer'
     Print hardcopy of current buffer with page headings containing the
     file name and page number.

`M-x lpr-buffer'
     Print hardcopy of current buffer without page headings.

`M-x print-region'
     Like `print-buffer' but print only the current region.

`M-x lpr-region'
     Like `lpr-buffer' but print only the current region.

   The hardcopy commands (aside from the PostScript commands) pass extra
switches to the `lpr' program based on the value of the variable
`lpr-switches'.  Its value should be a list of strings, each string an
option starting with `-'.  For example, to specify a line width of 80
columns for all the printing you do in Emacs, set `lpr-switches' like
this:

     (setq lpr-switches '("-w80"))

   You can specify the printer to use by setting the variable
`printer-name'.

   The variable `lpr-command' specifies the name of the printer program
to run; the default value depends on your operating system type.  On
most systems, the default is `"lpr"'.  The variable
`lpr-headers-switches' similarly specifies the extra switches to use to
make page headers.  The variable `lpr-add-switches' controls whether to
supply `-T' and `-J' options (suitable for `lpr') to the printer
program: `nil' means don't add them.  `lpr-add-switches' should be
`nil' if your printer program is not compatible with `lpr'.

* Menu:

* PostScript::           Printing buffers or regions as PostScript.
* PostScript Variables:: Customizing the PostScript printing commands.
* Printing Package::     An optional advanced printing interface.


File: emacs,  Node: PostScript,  Next: PostScript Variables,  Up: Printing

44 PostScript Hardcopy
**********************

These commands convert buffer contents to PostScript, either printing
it or leaving it in another Emacs buffer.

`M-x ps-print-buffer'
     Print hardcopy of the current buffer in PostScript form.

`M-x ps-print-region'
     Print hardcopy of the current region in PostScript form.

`M-x ps-print-buffer-with-faces'
     Print hardcopy of the current buffer in PostScript form, showing
     the faces used in the text by means of PostScript features.

`M-x ps-print-region-with-faces'
     Print hardcopy of the current region in PostScript form, showing
     the faces used in the text.

`M-x ps-spool-buffer'
     Generate and spool a PostScript image for the current buffer text.

`M-x ps-spool-region'
     Generate and spool a PostScript image for the current region.

`M-x ps-spool-buffer-with-faces'
     Generate and spool a PostScript image for the current buffer,
     showing the faces used.

`M-x ps-spool-region-with-faces'
     Generate and spool a PostScript image for the current region,
     showing the faces used.

`M-x ps-despool'
     Send the spooled PostScript to the printer.

`M-x handwrite'
     Generate/print PostScript for the current buffer as if handwritten.

   The PostScript commands, `ps-print-buffer' and `ps-print-region',
print buffer contents in PostScript form.  One command prints the
entire buffer; the other, just the region.  The corresponding
`-with-faces' commands, `ps-print-buffer-with-faces' and
`ps-print-region-with-faces', use PostScript features to show the faces
(fonts and colors) in the text properties of the text being printed.
The `-with-faces' commands only work if they are used in a window
system, so it has a way to determine color values.

   Interactively, when you use a prefix argument (`C-u'), the command
prompts the user for a file name, and saves the PostScript image in
that file instead of sending it to the printer.

   Noninteractively, the argument FILENAME is treated as follows: if it
is `nil', send the image to the printer.  If FILENAME is a string, save
the PostScript image in a file with that name.

   If you are using a color display, you can print a buffer of program
code with color highlighting by turning on Font-Lock mode in that
buffer, and using `ps-print-buffer-with-faces'.

   The commands whose names have `spool' instead of `print', generate
the PostScript output in an Emacs buffer instead of sending it to the
printer.

   Use the command `ps-despool' to send the spooled images to the
printer.

   This command sends the PostScript generated by  `-spool-' commands
(see commands above) to the printer.

   Interactively, when you use a prefix argument (`C-u'), the command
prompts the user for a file name, and saves the spooled PostScript
image in that file instead of sending it to the printer.

   Noninteractively, the argument FILENAME is treated as follows: if it
is `nil', send the image to the printer.  If FILENAME is a string, save
the PostScript image in a file with that name.

   `M-x handwrite' is more frivolous.  It generates a PostScript
rendition of the current buffer as a cursive handwritten document.  It
can be customized in group `handwrite'.  This function only supports
ISO 8859-1 characters.

   The following section describes variables for customizing these
commands.


File: emacs,  Node: PostScript Variables,  Next: Printing Package,  Prev: PostScript,  Up: Printing

45 Variables for PostScript Hardcopy
************************************

All the PostScript hardcopy commands use the variables `ps-lpr-command'
and `ps-lpr-switches' to specify how to print the output.
`ps-lpr-command' specifies the command name to run, `ps-lpr-switches'
specifies command line options to use, and `ps-printer-name' specifies
the printer.  If you don't set the first two variables yourself, they
take their initial values from `lpr-command' and `lpr-switches'.  If
`ps-printer-name' is `nil', `printer-name' is used.

   The variable `ps-print-header' controls whether these commands add
header lines to each page--set it to `nil' to turn headers off.

   If your printer doesn't support colors, you should turn off color
processing by setting `ps-print-color-p' to `nil'.  By default, if the
display supports colors, Emacs produces hardcopy output with color
information; on black-and-white printers, colors are emulated with
shades of gray.  This might produce illegible output, even if your
screen colors only use shades of gray.

   Alternatively, you can set `ps-print-color-p' to `black-white' to
print colors on black/white printers.

   By default, PostScript printing ignores the background colors of the
faces, unless the variable `ps-use-face-background' is non-`nil'.  This
is to avoid unwanted interference with the zebra stripes and background
image/text.

   The variable `ps-paper-type' specifies which size of paper to format
for; legitimate values include `a4', `a3', `a4small', `b4', `b5',
`executive', `ledger', `legal', `letter', `letter-small', `statement',
`tabloid'.  The default is `letter'.  You can define additional paper
sizes by changing the variable `ps-page-dimensions-database'.

   The variable `ps-landscape-mode' specifies the orientation of
printing on the page.  The default is `nil', which stands for
"portrait" mode.  Any non-`nil' value specifies "landscape" mode.

   The variable `ps-number-of-columns' specifies the number of columns;
it takes effect in both landscape and portrait mode.  The default is 1.

   The variable `ps-font-family' specifies which font family to use for
printing ordinary text.  Legitimate values include `Courier',
`Helvetica', `NewCenturySchlbk', `Palatino' and `Times'.  The variable
`ps-font-size' specifies the size of the font for ordinary text.  It
defaults to 8.5 points.

   Emacs supports more scripts and characters than a typical PostScript
printer.  Thus, some of the characters in your buffer might not be
printable using the fonts built into your printer.  You can augment the
fonts supplied with the printer with those from the GNU Intlfonts
package, or you can instruct Emacs to use Intlfonts exclusively.  The
variable `ps-multibyte-buffer' controls this: the default value, `nil',
is appropriate for printing ASCII and Latin-1 characters; a value of
`non-latin-printer' is for printers which have the fonts for ASCII,
Latin-1, Japanese, and Korean characters built into them.  A value of
`bdf-font' arranges for the BDF fonts from the Intlfonts package to be
used for _all_ characters.  Finally, a value of `bdf-font-except-latin'
instructs the printer to use built-in fonts for ASCII and Latin-1
characters, and Intlfonts BDF fonts for the rest.

   To be able to use the BDF fonts, Emacs needs to know where to find
them.  The variable `bdf-directory-list' holds the list of directories
where Emacs should look for the fonts; the default value includes a
single directory `/usr/local/share/emacs/fonts/bdf'.

   Many other customization variables for these commands are defined and
described in the Lisp files `ps-print.el' and `ps-mule.el'.


File: emacs,  Node: Printing Package,  Prev: PostScript Variables,  Up: Printing

46 Printing Package
*******************

The basic Emacs facilities for printing hardcopy can be extended using
the Printing package.  This provides an easy-to-use interface for
choosing what to print, previewing PostScript files before printing,
and setting various printing options such as print headers, landscape
or portrait modes, duplex modes, and so forth.  On GNU/Linux or Unix
systems, the Printing package relies on the `gs' and `gv' utilities,
which are distributed as part of the GhostScript program.  On
MS-Windows, the `gstools' port of Ghostscript can be used.

   To use the Printing package, add `(require 'printing)' to your init
file (*note Init File::), followed by `(pr-update-menus)'.  This
function replaces the usual printing commands in the menu bar with a
`Printing' submenu that contains various printing options.  You can
also type `M-x pr-interface RET'; this creates a `*Printing Interface*'
buffer, similar to a customization buffer, where you can set the
printing options.  After selecting what and how to print, you start the
print job using the `Print' button (click `mouse-2' on it, or move
point over it and type `RET').  For further information on the various
options, use the `Interface Help' button.


File: emacs,  Node: Sorting,  Next: Narrowing,  Prev: Printing,  Up: Top

47 Sorting Text
***************

Emacs provides several commands for sorting text in the buffer.  All
operate on the contents of the region.  They divide the text of the
region into many "sort records", identify a "sort key" for each record,
and then reorder the records into the order determined by the sort
keys.  The records are ordered so that their keys are in alphabetical
order, or, for numeric sorting, in numeric order.  In alphabetic
sorting, all upper-case letters `A' through `Z' come before lower-case
`a', in accord with the ASCII character sequence.

   The various sort commands differ in how they divide the text into
sort records and in which part of each record is used as the sort key.
Most of the commands make each line a separate sort record, but some
commands use paragraphs or pages as sort records.  Most of the sort
commands use each entire sort record as its own sort key, but some use
only a portion of the record as the sort key.

`M-x sort-lines'
     Divide the region into lines, and sort by comparing the entire
     text of a line.  A numeric argument means sort into descending
     order.

`M-x sort-paragraphs'
     Divide the region into paragraphs, and sort by comparing the entire
     text of a paragraph (except for leading blank lines).  A numeric
     argument means sort into descending order.

`M-x sort-pages'
     Divide the region into pages, and sort by comparing the entire
     text of a page (except for leading blank lines).  A numeric
     argument means sort into descending order.

`M-x sort-fields'
     Divide the region into lines, and sort by comparing the contents of
     one field in each line.  Fields are defined as separated by
     whitespace, so the first run of consecutive non-whitespace
     characters in a line constitutes field 1, the second such run
     constitutes field 2, etc.

     Specify which field to sort by with a numeric argument: 1 to sort
     by field 1, etc.  A negative argument means count fields from the
     right instead of from the left; thus, minus 1 means sort by the
     last field.  If several lines have identical contents in the field
     being sorted, they keep the same relative order that they had in
     the original buffer.

`M-x sort-numeric-fields'
     Like `M-x sort-fields' except the specified field is converted to
     an integer for each line, and the numbers are compared.  `10'
     comes before `2' when considered as text, but after it when
     considered as a number.  By default, numbers are interpreted
     according to `sort-numeric-base', but numbers beginning with `0x'
     or `0' are interpreted as hexadecimal and octal, respectively.

`M-x sort-columns'
     Like `M-x sort-fields' except that the text within each line used
     for comparison comes from a fixed range of columns.  See below for
     an explanation.

`M-x reverse-region'
     Reverse the order of the lines in the region.  This is useful for
     sorting into descending order by fields or columns, since those
     sort commands do not have a feature for doing that.

   For example, if the buffer contains this:

     On systems where clash detection (locking of files being edited) is
     implemented, Emacs also checks the first time you modify a buffer
     whether the file has changed on disk since it was last visited or
     saved.  If it has, you are asked to confirm that you want to change
     the buffer.

applying `M-x sort-lines' to the entire buffer produces this:

     On systems where clash detection (locking of files being edited) is
     implemented, Emacs also checks the first time you modify a buffer
     saved.  If it has, you are asked to confirm that you want to change
     the buffer.
     whether the file has changed on disk since it was last visited or

where the upper-case `O' sorts before all lower-case letters.  If you
use `C-u 2 M-x sort-fields' instead, you get this:

     implemented, Emacs also checks the first time you modify a buffer
     saved.  If it has, you are asked to confirm that you want to change
     the buffer.
     On systems where clash detection (locking of files being edited) is
     whether the file has changed on disk since it was last visited or

where the sort keys were `Emacs', `If', `buffer', `systems' and `the'.

   `M-x sort-columns' requires more explanation.  You specify the
columns by putting point at one of the columns and the mark at the other
column.  Because this means you cannot put point or the mark at the
beginning of the first line of the text you want to sort, this command
uses an unusual definition of "region": all of the line point is in is
considered part of the region, and so is all of the line the mark is in,
as well as all the lines in between.

   For example, to sort a table by information found in columns 10 to
15, you could put the mark on column 10 in the first line of the table,
and point on column 15 in the last line of the table, and then run
`sort-columns'.  Equivalently, you could run it with the mark on column
15 in the first line and point on column 10 in the last line.

   This can be thought of as sorting the rectangle specified by point
and the mark, except that the text on each line to the left or right of
the rectangle moves along with the text inside the rectangle.  *Note
Rectangles::.

   Many of the sort commands ignore case differences when comparing, if
`sort-fold-case' is non-`nil'.


File: emacs,  Node: Narrowing,  Next: Two-Column,  Prev: Sorting,  Up: Top

48 Narrowing
************

"Narrowing" means focusing in on some portion of the buffer, making the
rest temporarily inaccessible.  The portion which you can still get to
is called the "accessible portion".  Canceling the narrowing, which
makes the entire buffer once again accessible, is called "widening".
The bounds of narrowing in effect in a buffer are called the buffer's
"restriction".

   Narrowing can make it easier to concentrate on a single subroutine or
paragraph by eliminating clutter.  It can also be used to limit the
range of operation of a replace command or repeating keyboard macro.

`C-x n n'
     Narrow down to between point and mark (`narrow-to-region').

`C-x n w'
     Widen to make the entire buffer accessible again (`widen').

`C-x n p'
     Narrow down to the current page (`narrow-to-page').

`C-x n d'
     Narrow down to the current defun (`narrow-to-defun').

   When you have narrowed down to a part of the buffer, that part
appears to be all there is.  You can't see the rest, you can't move
into it (motion commands won't go outside the accessible part), you
can't change it in any way.  However, it is not gone, and if you save
the file all the inaccessible text will be saved.  The word `Narrow'
appears in the mode line whenever narrowing is in effect.

   The primary narrowing command is `C-x n n' (`narrow-to-region').  It
sets the current buffer's restrictions so that the text in the current
region remains accessible, but all text before the region or after the
region is inaccessible.  Point and mark do not change.

   Alternatively, use `C-x n p' (`narrow-to-page') to narrow down to
the current page.  *Note Pages::, for the definition of a page.  `C-x n
d' (`narrow-to-defun') narrows down to the defun containing point
(*note Defuns::).

   The way to cancel narrowing is to widen with `C-x n w' (`widen').
This makes all text in the buffer accessible again.

   You can get information on what part of the buffer you are narrowed
down to using the `C-x =' command.  *Note Position Info::.

   Because narrowing can easily confuse users who do not understand it,
`narrow-to-region' is normally a disabled command.  Attempting to use
this command asks for confirmation and gives you the option of enabling
it; if you enable the command, confirmation will no longer be required
for it.  *Note Disabling::.


File: emacs,  Node: Two-Column,  Next: Editing Binary Files,  Prev: Narrowing,  Up: Top

49 Two-Column Editing
*********************

Two-column mode lets you conveniently edit two side-by-side columns of
text.  It uses two side-by-side windows, each showing its own buffer.

   There are three ways to enter two-column mode:

`<F2> 2' or `C-x 6 2'
     Enter two-column mode with the current buffer on the left, and on
     the right, a buffer whose name is based on the current buffer's
     name (`2C-two-columns').  If the right-hand buffer doesn't already
     exist, it starts out empty; the current buffer's contents are not
     changed.

     This command is appropriate when the current buffer is empty or
     contains just one column and you want to add another column.

`<F2> s' or `C-x 6 s'
     Split the current buffer, which contains two-column text, into two
     buffers, and display them side by side (`2C-split').  The current
     buffer becomes the left-hand buffer, but the text in the right-hand
     column is moved into the right-hand buffer.  The current column
     specifies the split point.  Splitting starts with the current line
     and continues to the end of the buffer.

     This command is appropriate when you have a buffer that already
     contains two-column text, and you wish to separate the columns
     temporarily.

`<F2> b BUFFER <RET>'
`C-x 6 b BUFFER <RET>'
     Enter two-column mode using the current buffer as the left-hand
     buffer, and using buffer BUFFER as the right-hand buffer
     (`2C-associate-buffer').

   `<F2> s' or `C-x 6 s' looks for a column separator, which is a
string that appears on each line between the two columns.  You can
specify the width of the separator with a numeric argument to `<F2> s';
that many characters, before point, constitute the separator string.
By default, the width is 1, so the column separator is the character
before point.

   When a line has the separator at the proper place, `<F2> s' puts the
text after the separator into the right-hand buffer, and deletes the
separator.  Lines that don't have the column separator at the proper
place remain unsplit; they stay in the left-hand buffer, and the
right-hand buffer gets an empty line to correspond.  (This is the way
to write a line that "spans both columns while in two-column mode":
write it in the left-hand buffer, and put an empty line in the
right-hand buffer.)

   The command `C-x 6 <RET>' or `<F2> <RET>' (`2C-newline') inserts a
newline in each of the two buffers at corresponding positions.  This is
the easiest way to add a new line to the two-column text while editing
it in split buffers.

   When you have edited both buffers as you wish, merge them with `<F2>
1' or `C-x 6 1' (`2C-merge').  This copies the text from the right-hand
buffer as a second column in the other buffer.  To go back to
two-column editing, use `<F2> s'.

   Use `<F2> d' or `C-x 6 d' to dissociate the two buffers, leaving
each as it stands (`2C-dissociate').  If the other buffer, the one not
current when you type `<F2> d', is empty, `<F2> d' kills it.


File: emacs,  Node: Editing Binary Files,  Next: Saving Emacs Sessions,  Prev: Two-Column,  Up: Top

50 Editing Binary Files
***********************

There is a special major mode for editing binary files: Hexl mode.  To
use it, use `M-x hexl-find-file' instead of `C-x C-f' to visit the
file.  This command converts the file's contents to hexadecimal and
lets you edit the translation.  When you save the file, it is converted
automatically back to binary.

   You can also use `M-x hexl-mode' to translate an existing buffer
into hex.  This is useful if you visit a file normally and then discover
it is a binary file.

   Ordinary text characters overwrite in Hexl mode.  This is to reduce
the risk of accidentally spoiling the alignment of data in the file.
There are special commands for insertion.  Here is a list of the
commands of Hexl mode:

`C-M-d'
     Insert a byte with a code typed in decimal.

`C-M-o'
     Insert a byte with a code typed in octal.

`C-M-x'
     Insert a byte with a code typed in hex.

`C-x ['
     Move to the beginning of a 1k-byte "page."

`C-x ]'
     Move to the end of a 1k-byte "page."

`M-g'
     Move to an address specified in hex.

`M-j'
     Move to an address specified in decimal.

`C-c C-c'
     Leave Hexl mode, going back to the major mode this buffer had
     before you invoked `hexl-mode'.

Other Hexl commands let you insert strings (sequences) of binary bytes,
move by `short's or `int's, etc.; type `C-h a hexl-<RET>' for details.


File: emacs,  Node: Saving Emacs Sessions,  Next: Recursive Edit,  Prev: Editing Binary Files,  Up: Top

51 Saving Emacs Sessions
************************

Use the desktop library to save the state of Emacs from one session to
another.  Once you save the Emacs "desktop"--the buffers, their file
names, major modes, buffer positions, and so on--then subsequent Emacs
sessions reload the saved desktop.

   You can save the desktop manually with the command `M-x
desktop-save'.  You can also enable automatic saving of the desktop
when you exit Emacs, and automatic restoration of the last saved
desktop when Emacs starts: use the Customization buffer (*note Easy
Customization::) to set `desktop-save-mode' to `t' for future sessions,
or add this line in your init file (*note Init File::):

     (desktop-save-mode 1)

   If you turn on `desktop-save-mode' in your init file, then when
Emacs starts, it looks for a saved desktop in the current directory.
(More precisely, it looks in the directories specified by DESKTOP-PATH,
and uses the first desktop it finds.)  Thus, you can have separate
saved desktops in different directories, and the starting directory
determines which one Emacs reloads.  You can save the current desktop
and reload one saved in another directory by typing `M-x
desktop-change-dir'.  Typing `M-x desktop-revert' reverts to the
desktop previously reloaded.

   Specify the option `--no-desktop' on the command line when you don't
want it to reload any saved desktop.  This turns off
`desktop-save-mode' for the current session.  Starting Emacs with the
`--no-init-file' option also disables desktop reloading, since it
bypasses the init file, where `desktop-save-mode' is usually turned on.

   By default, all the buffers in the desktop are restored at one go.
However, this may be slow if there are a lot of buffers in the desktop.
You can specify the maximum number of buffers to restore immediately
with the variable `desktop-restore-eager'; the remaining buffers are
restored "lazily," when Emacs is idle.

   Type `M-x desktop-clear' to empty the Emacs desktop.  This kills all
buffers except for internal ones, and clears the global variables
listed in `desktop-globals-to-clear'.  If you want this to preserve
certain buffers, customize the variable
`desktop-clear-preserve-buffers-regexp', whose value is a regular
expression matching the names of buffers not to kill.

   If you want to save minibuffer history from one session to another,
use the `savehist' library.


File: emacs,  Node: Recursive Edit,  Next: Emulation,  Prev: Saving Emacs Sessions,  Up: Top

52 Recursive Editing Levels
***************************

A "recursive edit" is a situation in which you are using Emacs commands
to perform arbitrary editing while in the middle of another Emacs
command.  For example, when you type `C-r' inside of a `query-replace',
you enter a recursive edit in which you can change the current buffer.
On exiting from the recursive edit, you go back to the `query-replace'.

   "Exiting" the recursive edit means returning to the unfinished
command, which continues execution.  The command to exit is `C-M-c'
(`exit-recursive-edit').

   You can also "abort" the recursive edit.  This is like exiting, but
also quits the unfinished command immediately.  Use the command `C-]'
(`abort-recursive-edit') to do this.  *Note Quitting::.

   The mode line shows you when you are in a recursive edit by
displaying square brackets around the parentheses that always surround
the major and minor mode names.  Every window's mode line shows this in
the same way, since being in a recursive edit is true of Emacs as a
whole rather than any particular window or buffer.

   It is possible to be in recursive edits within recursive edits.  For
example, after typing `C-r' in a `query-replace', you may type a
command that enters the debugger.  This begins a recursive editing level
for the debugger, within the recursive editing level for `C-r'.  Mode
lines display a pair of square brackets for each recursive editing
level currently in progress.

   Exiting the inner recursive edit (such as with the debugger `c'
command) resumes the command running in the next level up.  When that
command finishes, you can then use `C-M-c' to exit another recursive
editing level, and so on.  Exiting applies to the innermost level only.
Aborting also gets out of only one level of recursive edit; it returns
immediately to the command level of the previous recursive edit.  If you
wish, you can then abort the next recursive editing level.

   Alternatively, the command `M-x top-level' aborts all levels of
recursive edits, returning immediately to the top-level command reader.
It also exits the minibuffer, if it is active.

   The text being edited inside the recursive edit need not be the same
text that you were editing at top level.  It depends on what the
recursive edit is for.  If the command that invokes the recursive edit
selects a different buffer first, that is the buffer you will edit
recursively.  In any case, you can switch buffers within the recursive
edit in the normal manner (as long as the buffer-switching keys have
not been rebound).  You could probably do all the rest of your editing
inside the recursive edit, visiting files and all.  But this could have
surprising effects (such as stack overflow) from time to time.  So
remember to exit or abort the recursive edit when you no longer need it.

   In general, we try to minimize the use of recursive editing levels in
GNU Emacs.  This is because they constrain you to "go back" in a
particular order--from the innermost level toward the top level.  When
possible, we present different activities in separate buffers so that
you can switch between them as you please.  Some commands switch to a
new major mode which provides a command to switch back.  These
approaches give you more flexibility to go back to unfinished tasks in
the order you choose.


File: emacs,  Node: Emulation,  Next: Hyperlinking,  Prev: Recursive Edit,  Up: Top

53 Emulation
************

GNU Emacs can be programmed to emulate (more or less) most other
editors.  Standard facilities can emulate these:

CRiSP/Brief (PC editor)
     You can turn on key bindings to emulate the CRiSP/Brief editor with
     `M-x crisp-mode'.  Note that this rebinds `M-x' to exit Emacs
     unless you set the variable `crisp-override-meta-x'.  You can also
     use the command `M-x scroll-all-mode' or set the variable
     `crisp-load-scroll-all' to emulate CRiSP's scroll-all feature
     (scrolling all windows together).

EDT (DEC VMS editor)
     Turn on EDT emulation `M-x edt-emulation-on'; use `M-x
     edt-emulation-off' to restore normal Emacs command bindings.

     Most of the EDT emulation commands are keypad keys, and most
     standard Emacs key bindings are still available.  The EDT
     emulation rebindings are done in the global keymap, so there is no
     problem switching buffers or major modes while in EDT emulation.

TPU (DEC VMS editor)
     `M-x tpu-edt-on' turns on emulation of the TPU editor emulating
     EDT.

vi (Berkeley editor)
     Viper is the newest emulator for vi.  It implements several levels
     of emulation; level 1 is closest to vi itself, while level 5
     departs somewhat from strict emulation to take advantage of the
     capabilities of Emacs.  To invoke Viper, type `M-x viper-mode'; it
     will guide you the rest of the way and ask for the emulation
     level.  *note Viper: (viper)Top.

vi (another emulator)
     `M-x vi-mode' enters a major mode that replaces the previously
     established major mode.  All of the vi commands that, in real vi,
     enter "input" mode are programmed instead to return to the
     previous major mode.  Thus, ordinary Emacs serves as vi's "input"
     mode.

     Because vi emulation works through major modes, it does not work
     to switch buffers during emulation.  Return to normal Emacs first.

     If you plan to use vi emulation much, you probably want to bind a
     key to the `vi-mode' command.

vi (alternate emulator)
     `M-x vip-mode' invokes another vi emulator, said to resemble real
     vi more thoroughly than `M-x vi-mode'.  "Input" mode in this
     emulator is changed from ordinary Emacs so you can use <ESC> to go
     back to emulated vi command mode.  To get from emulated vi command
     mode back to ordinary Emacs, type `C-z'.

     This emulation does not work through major modes, and it is
     possible to switch buffers in various ways within the emulator.
     It is not so necessary to assign a key to the command `vip-mode' as
     it is with `vi-mode' because terminating insert mode does not use
     it.

     *note VIP: (vip)Top, for full information.

WordStar (old wordprocessor)
     `M-x wordstar-mode' provides a major mode with WordStar-like key
     bindings.


File: emacs,  Node: Hyperlinking,  Next: Dissociated Press,  Prev: Emulation,  Up: Top

54 Hyperlinking and Navigation Features
***************************************

Various modes documented elsewhere have hypertext features so that you
can follow links, usually by clicking `Mouse-2' on the link or typing
<RET> while point is on the link.  Clicking `Mouse-1' quickly on the
link also follows it.  (Hold `Mouse-1' for longer if you want to set
point instead.)

   Info mode, Help mode and the Dired-like modes are examples of modes
that have links in the buffer.  The Tags facility links between uses
and definitions in source files, see *note Tags::.  Imenu provides
navigation amongst items indexed in the current buffer, see *note
Imenu::.  Info-lookup provides mode-specific lookup of definitions in
Info indexes, see *note Documentation::.  Speedbar maintains a frame in
which links to files, and locations in files are displayed, see *note
Speedbar::.

   Other non-mode-specific facilities described in this section enable
following links from the current buffer in a context-sensitive fashion.

* Menu:

* Browse-URL::                  Following URLs.
* Goto Address mode::           Activating URLs.
* FFAP::                        Finding files etc. at point.


File: emacs,  Node: Browse-URL,  Next: Goto Address mode,  Up: Hyperlinking

54.1 Following URLs
===================

`M-x browse-url <RET> URL <RET>'
     Load a URL into a Web browser.

   The Browse-URL package provides facilities for following URLs
specifying links on the World Wide Web.  Usually this works by invoking
a web browser, but you can, for instance, arrange to invoke
`compose-mail' from `mailto:' URLs.

   The general way to use this feature is to type `M-x browse-url',
which displays a specified URL.  If point is located near a plausible
URL, that URL is used as the default.  Other commands are available
which you might like to bind to keys, such as `browse-url-at-point' and
`browse-url-at-mouse'.

   You can customize Browse-URL's behavior via various options in the
`browse-url' Customize group, particularly
`browse-url-browser-function'.  You can invoke actions dependent on the
type of URL by defining `browse-url-browser-function' as an association
list.  The package's commentary available via `C-h p' under the
`hypermedia' keyword provides more information.  Packages with
facilities for following URLs should always go through Browse-URL, so
that the customization options for Browse-URL will affect all browsing
in Emacs.


File: emacs,  Node: Goto Address mode,  Next: FFAP,  Prev: Browse-URL,  Up: Hyperlinking

54.2 Activating URLs
====================

`M-x goto-address-mode'
     Activate URLs and e-mail addresses in the current buffer.

   You can make URLs in the current buffer active with `M-x
goto-address-mode'.  This minor mode finds all the URLs in the buffer,
highlights them, and turns them into "buttons": if you click on a URL
with `Mouse-1' or `Mouse-2' (*note Mouse References::), or move to the
URL and type `C-c <RET>', that displays the web page that the URL
specifies.  For a `mailto' URL, it sends mail instead, using your
selected mail-composition method (*note Mail Methods::).

   It can be useful to add `goto-address-mode' to mode hooks and the
hooks used to display an incoming message (e.g.,
`rmail-show-message-hook' for Rmail, and `mh-show-mode-hook' for MH-E).
This is not needed for Gnus, which has a similar feature of its own.


File: emacs,  Node: FFAP,  Prev: Goto Address mode,  Up: Hyperlinking

54.3 Finding Files and URLs at Point
====================================

FFAP mode replaces certain key bindings for finding files, including
`C-x C-f', with commands that provide more sensitive defaults.  These
commands behave like the ordinary ones when given a prefix argument.
Otherwise, they get the default file name or URL from the text around
point.  If what is found in the buffer has the form of a URL rather
than a file name, the commands use `browse-url' to view it.

   This feature is useful for following references in mail or news
buffers, `README' files, `MANIFEST' files, and so on.  The `ffap'
package's commentary available via `C-h p' under the `files' keyword
and the `ffap' Custom group provide details.

   You can turn on FFAP minor mode by calling `ffap-bindings' to make
the following key bindings and to install hooks for using `ffap' in
Rmail, Gnus and VM article buffers.

`C-x C-f FILENAME <RET>'
     Find FILENAME, guessing a default from text around point
     (`find-file-at-point').

`C-x C-r'
     `ffap-read-only', analogous to `find-file-read-only'.

`C-x C-v'
     `ffap-alternate-file', analogous to `find-alternate-file'.

`C-x d DIRECTORY <RET>'
     Start Dired on DIRECTORY, defaulting to the directory name at
     point (`dired-at-point').

`C-x C-d'
     `ffap-list-directory', analogous to `list-directory'.

`C-x 4 f'
     `ffap-other-window', analogous to `find-file-other-window'.

`C-x 4 r'
     `ffap-read-only-other-window', analogous to
     `find-file-read-only-other-window'.

`C-x 4 d'
     `ffap-dired-other-window', analogous to `dired-other-window'.

`C-x 5 f'
     `ffap-other-frame', analogous to `find-file-other-frame'.

`C-x 5 r'
     `ffap-read-only-other-frame', analogous to
     `find-file-read-only-other-frame'.

`C-x 5 d'
     `ffap-dired-other-frame', analogous to `dired-other-frame'.

`M-x ffap-next'
     Search buffer for next file name or URL, then find that file or
     URL.

`S-Mouse-3'
     `ffap-at-mouse' finds the file guessed from text around the
     position of a mouse click.

`C-S-Mouse-3'
     Display a menu of files and URLs mentioned in current buffer, then
     find the one you select (`ffap-menu').


File: emacs,  Node: Dissociated Press,  Next: Amusements,  Prev: Hyperlinking,  Up: Top

55 Dissociated Press
********************

`M-x dissociated-press' is a command for scrambling a file of text
either word by word or character by character.  Starting from a buffer
of straight English, it produces extremely amusing output.  The input
comes from the current Emacs buffer.  Dissociated Press writes its
output in a buffer named `*Dissociation*', and redisplays that buffer
after every couple of lines (approximately) so you can read the output
as it comes out.

   Dissociated Press asks every so often whether to continue generating
output.  Answer `n' to stop it.  You can also stop at any time by
typing `C-g'.  The dissociation output remains in the `*Dissociation*'
buffer for you to copy elsewhere if you wish.

   Dissociated Press operates by jumping at random from one point in
the buffer to another.  In order to produce plausible output rather
than gibberish, it insists on a certain amount of overlap between the
end of one run of consecutive words or characters and the start of the
next.  That is, if it has just output `president' and then decides to
jump to a different point in the buffer, it might spot the `ent' in
`pentagon' and continue from there, producing `presidentagon'.  Long
sample texts produce the best results.

   A positive argument to `M-x dissociated-press' tells it to operate
character by character, and specifies the number of overlap characters.
A negative argument tells it to operate word by word, and specifies the
number of overlap words.  In this mode, whole words are treated as the
elements to be permuted, rather than characters.  No argument is
equivalent to an argument of two.  For your againformation, the output
goes only into the buffer `*Dissociation*'.  The buffer you start with
is not changed.

   Dissociated Press produces results fairly like those of a Markov
chain based on a frequency table constructed from the sample text.  It
is, however, an independent, ignoriginal invention.  Dissociated Press
techniquitously copies several consecutive characters from the sample
text between random jumps, unlike a Markov chain which would jump
randomly after each word or character.  This makes for more plausible
sounding results, and runs faster.

   It is a mustatement that too much use of Dissociated Press can be a
developediment to your real work, sometimes to the point of outragedy.
And keep dissociwords out of your documentation, if you want it to be
well userenced and properbose.  Have fun.  Your buggestions are welcome.


File: emacs,  Node: Amusements,  Next: Customization,  Prev: Dissociated Press,  Up: Top

56 Other Amusements
*******************

If you are a little bit bored, you can try `M-x hanoi'.  If you are
considerably bored, give it a numeric argument.  If you are very, very
bored, try an argument of 9.  Sit back and watch.

   If you want a little more personal involvement, try `M-x gomoku',
which plays the game Go Moku with you.

   `M-x bubbles' is a game in which the object is to remove as many
bubbles as you can in the smallest number of moves.

   `M-x blackbox', `M-x mpuz' and `M-x 5x5' are puzzles.  `blackbox'
challenges you to determine the location of objects inside a box by
tomography.  `mpuz' displays a multiplication puzzle with letters
standing for digits in a code that you must guess--to guess a value,
type a letter and then the digit you think it stands for.  The aim of
`5x5' is to fill in all the squares.

   `M-x decipher' helps you to cryptanalyze a buffer which is encrypted
in a simple monoalphabetic substitution cipher.

   `M-x dunnet' runs an adventure-style exploration game, which is a
bigger sort of puzzle.

   `M-x lm' runs a relatively non-participatory game in which a robot
attempts to maneuver towards a tree at the center of the window based on
unique olfactory cues from each of the four directions.

   `M-x life' runs Conway's "Life" cellular automaton.

   `M-x morse-region' converts text in a region to Morse code and `M-x
unmorse-region' converts it back.  No cause for remorse.

   `M-x pong' plays a Pong-like game, bouncing the ball off opposing
bats.

   `M-x solitaire' plays a game of solitaire in which you jump pegs
across other pegs.

   The `animate' package makes text dance.  For an example, try `M-x
animate-birthday-present'.

   `M-x studlify-region' studlify-cases the region, producing text like
this:

     M-x stUdlIfY-RegioN stUdlIfY-CaSeS thE region.

   `M-x tetris' runs an implementation of the well-known Tetris game.
Likewise, `M-x snake' provides an implementation of Snake.

   When you are frustrated, try the famous Eliza program.  Just do `M-x
doctor'.  End each input by typing <RET> twice.

   When you are feeling strange, type `M-x yow'.

   The command `M-x zone' plays games with the display when Emacs is
idle.


File: emacs,  Node: Customization,  Next: Quitting,  Prev: Amusements,  Up: Top

57 Customization
****************

This chapter describes some simple methods to customize the behavior of
Emacs.

   Apart from the methods described here, see *note X Resources:: for
information about using X resources to customize Emacs, and see *note
Keyboard Macros:: for information about recording and replaying
keyboard macros.  Making more far-reaching and open-ended changes
involves writing Emacs Lisp code; see *note Emacs Lisp: (elisp)Top.

* Menu:

* Minor Modes::         Each minor mode is a feature you can turn on
                          independently of any others.
* Easy Customization::  Convenient way to browse and change settings.
* Variables::           Many Emacs commands examine Emacs variables
                          to decide what to do; by setting variables,
                          you can control their functioning.
* Key Bindings::        The keymaps say what command each key runs.
                          By changing them, you can "redefine keys".
* Syntax::              The syntax table controls how words and
                          expressions are parsed.
* Init File::           How to write common customizations in the
                          `.emacs' file.


File: emacs,  Node: Minor Modes,  Next: Easy Customization,  Up: Customization

57.1 Minor Modes
================

Minor modes are optional features which you can turn on or off.  For
example, Auto Fill mode is a minor mode in which <SPC> breaks lines
between words as you type.  Minor modes are independent of one another
and of the selected major mode.  Most minor modes say in the mode line
when they are enabled; for example, `Fill' in the mode line means that
Auto Fill mode is enabled.

   Each minor mode is associated with a command, called the "mode
command", which turns it on or off.  The name of this command consists
of the name of the minor mode, followed by `-mode'; for instance, the
mode command for Auto Fill mode is `auto-fill-mode'.  Calling the minor
mode command with no prefix argument "toggles" the mode, turning it on
if it was off, and off if it was on.  A positive argument always turns
the mode on, and a zero or negative argument always turns it off.  Mode
commands are usually invoked with `M-x', but you can bind keys to them
if you wish (*note Key Bindings::).

   Most minor modes also have a "mode variable", with the same name as
the mode command.  Its value is non-`nil' if the mode is enabled, and
`nil' if it is disabled.  In some minor modes--but not all--the value
of the variable alone determines whether the mode is active: the mode
command works simply by setting the variable, and changing the value of
the variable has the same effect as calling the mode command.  Because
not all minor modes work this way, we recommend that you avoid changing
the mode variables directly; use the mode commands instead.

   Some minor modes are "buffer-local": they apply only to the current
buffer, so you can enable the mode in certain buffers and not others.
Other minor modes are "global": while enabled, they affect everything
you do in the Emacs session, in all buffers.  Some global minor modes
are enabled by default.

   The following is a list of some buffer-local minor modes:

   * Abbrev mode automatically expands text based on pre-defined
     abbreviation definitions.  *Note Abbrevs::.

   * Auto Fill mode inserts newlines as you type to prevent lines from
     becoming too long.  *Note Filling::.

   * Auto Save mode saves the buffer contents periodically to reduce the
     amount of work you can lose in case of a crash.  *Note Auto Save::.

   * Enriched mode enables editing and saving of formatted text.  *Note
     Formatted Text::.

   * Flyspell mode automatically highlights misspelled words.  *Note
     Spelling::.

   * Font-Lock mode automatically highlights certain textual units
     found in programs.  It is enabled globally by default, but you can
     disable it in individual buffers.  *Note Faces::.

   * Linum mode displays each line's line number in the window's left
     margin.  Its mode command is `linum-mode'.

   * Outline minor mode provides similar facilities to the major mode
     called Outline mode.  *Note Outline Mode::.

   * Overwrite mode causes ordinary printing characters to replace
     existing text instead of shoving it to the right.  For example, if
     point is in front of the `B' in `FOOBAR', then in Overwrite mode
     typing a `G' changes it to `FOOGAR', instead of producing
     `FOOGBAR' as usual.  In Overwrite mode, the command `C-q' inserts
     the next character whatever it may be, even if it is a digit--this
     gives you a way to insert a character instead of replacing an
     existing character.  The mode command, `overwrite-mode', is bound
     to the <Insert> key.

   * Binary Overwrite mode is a variant of Overwrite mode for editing
     binary files; it treats newlines and tabs like other characters, so
     that they overwrite other characters and can be overwritten by
     them.  In Binary Overwrite mode, digits after `C-q' specify an
     octal character code, as usual.

   * Visual Line mode performs "word wrapping", causing long lines to be
     wrapped at word boundaries.  *Note Visual Line Mode::.

   Here are some useful global minor modes.  Since Line Number mode and
Transient Mark mode can be enabled or disabled just by setting the
value of the minor mode variable, you _can_ set them differently for
particular buffers, by explicitly making the corresponding variable
local in those buffers.  *Note Locals::.

   * Column Number mode enables display of the current column number in
     the mode line.  *Note Mode Line::.

   * Delete Selection mode causes text insertion to first delete the
     text in the region, if the region is active.  *Note Using Region::.

   * Icomplete mode displays an indication of available completions when
     you are in the minibuffer and completion is active.  *Note
     Completion Options::.

   * Line Number mode enables display of the current line number in the
     mode line.  It is enabled by default.  *Note Mode Line::.

   * Menu Bar mode gives each frame a menu bar.  It is enabled by
     default.  *Note Menu Bars::.

   * Scroll Bar mode gives each window a scroll bar.  It is enabled by
     default, but the scroll bar is only displayed on graphical
     terminals.  *Note Scroll Bars::.

   * Tool Bar mode gives each frame a tool bar.  It is enabled by
     default, but the tool bar is only displayed on graphical
     terminals.  *Note Tool Bars::.

   * Transient Mark mode highlights the region, and makes many Emacs
     commands operate on the region when the mark is active.  It is
     enabled by default.  *Note Mark::.


File: emacs,  Node: Easy Customization,  Next: Variables,  Prev: Minor Modes,  Up: Customization

57.2 Easy Customization Interface
=================================

Emacs has many "settings" which have values that you can change.  Many
are documented in this manual.  Most settings are "user options"--that
is to say, Lisp variables (*note Variables::)--and their names appear
in the Variable Index (*note Variable Index::).  The other settings are
faces and their attributes (*note Faces::).

   You can browse settings and change them using `M-x customize'.  This
creates a "customization buffer", which lets you navigate through a
logically organized list of settings, edit and set their values, and
save them permanently in your initialization file (*note Init File::).

* Menu:

* Customization Groups::     How settings are classified in a structure.
* Browsing Custom::          Browsing and searching for settings.
* Changing a Variable::      How to edit an option's value and set the option.
* Saving Customizations::    Specifying the file for saving customizations.
* Face Customization::       How to edit the attributes of a face.
* Specific Customization::   Making a customization buffer for specific
                                variables, faces, or groups.
* Custom Themes::            How to define collections of customized options
                                that can be loaded and unloaded together.


File: emacs,  Node: Customization Groups,  Next: Browsing Custom,  Up: Easy Customization

57.2.1 Customization Groups
---------------------------

For customization purposes, settings are organized into "groups" to
help you find them.  Groups are collected into bigger groups, all the
way up to a master group called `Emacs'.

   `M-x customize' creates a customization buffer that shows the
top-level `Emacs' group and the second-level groups immediately under
it.  It looks like this, in part:

     /- Emacs group: Customization of the One True Editor. -------------\
           [State]: visible group members are all at standard values.

        See also [Manual].

     [Editing] : Basic text editing facilities.

     [External] : Interfacing to external utilities.

     MORE SECOND-LEVEL GROUPS

     \- Emacs group end ------------------------------------------------/

This says that the buffer displays the contents of the `Emacs' group.
The other groups are listed because they are its contents.  But they
are listed differently, without indentation and dashes, because _their_
contents are not included.  Each group has a single-line documentation
string; the `Emacs' group also has a `[State]' line.

   Most of the text in the customization buffer is read-only, but it
typically includes some "editable fields" that you can edit.  There are
also "buttons" and "links", which do something when you "invoke" them.
To invoke a button or a link, either click on it with `Mouse-1', or
move point to it and type <RET>.

   For example, the phrase `[State]' that appears in a second-level
group is a button.  It operates on the same customization buffer.  Each
group name, such as `[Editing]', is a hypertext link to that group;
invoking it creates a new customization buffer, showing the group and
its contents.

   The `Emacs' group only contains other groups.  These groups, in
turn, can contain settings or still more groups.  By browsing the
hierarchy of groups, you will eventually find the feature you are
interested in customizing.  Then you can use the customization buffer
to set that feature's settings.  You can also go straight to a
particular group by name, using the command `M-x customize-group'.


File: emacs,  Node: Browsing Custom,  Next: Changing a Variable,  Prev: Customization Groups,  Up: Easy Customization

57.2.2 Browsing and Searching for Options and Faces
---------------------------------------------------

`M-x customize-browse' is another way to browse the available settings.
This command creates a special customization buffer which shows only
the names of groups and settings, and puts them in a structure.

   In this buffer, you can show the contents of a group by invoking the
`[+]' button.  When the group contents are visible, this button changes
to `[-]'; invoking that hides the group contents again.

   Each group or setting in this buffer has a link which says
`[Group]', `[Option]' or `[Face]'.  Invoking this link creates an
ordinary customization buffer showing just that group and its contents,
just that user option, or just that face.  This is the way to change
settings that you find with `M-x customize-browse'.

   If you can guess part of the name of the settings you are interested
in, `M-x customize-apropos' is another way to search for settings.
However, unlike `customize' and `customize-browse', `customize-apropos'
can only find groups and settings that are loaded in the current Emacs
session.  *Note Customizing Specific Items: Specific Customization.


File: emacs,  Node: Changing a Variable,  Next: Saving Customizations,  Prev: Browsing Custom,  Up: Easy Customization

57.2.3 Changing a Variable
--------------------------

Here is an example of what a variable (a user option) looks like in the
customization buffer:

     Kill Ring Max: [Hide Value] 60
        [State]: STANDARD.
     Maximum length of kill ring before oldest elements are thrown away.

   The text following `[Hide Value]', `60' in this case, indicates the
current value of the variable.  If you see `[Show Value]' instead of
`[Hide Value]', it means that the value is hidden; the customization
buffer initially hides values that take up several lines.  Invoke
`[Show Value]' to show the value.

   The line after the variable name indicates the "customization state"
of the variable: in the example above, it says you have not changed the
option yet.  The `[State]' button at the beginning of this line gives
you a menu of various operations for customizing the variable.

   The line after the `[State]' line displays the beginning of the
variable's documentation string.  If there are more lines of
documentation, this line ends with a `[More]' button; invoke that to
show the full documentation string.

   To enter a new value for `Kill Ring Max', move point to the value
and edit it textually.  For example, you can type `M-d', then insert
another number.  As you begin to alter the text, you will see the
`[State]' line change to say that you have edited the value:

     [State]: EDITED, shown value does not take effect until you set or ...
                                                                save it.

   Editing the value does not actually set the variable.  To do that,
you must "set" the variable.  To do this, invoke the `[State]' button
and choose `Set for Current Session'.

   The state of the variable changes visibly when you set it:

     [State]: SET for current session only.

   You don't have to worry about specifying a value that is not valid;
the `Set for Current Session' operation checks for validity and will
not install an unacceptable value.

   While editing a field that is a file name, directory name, command
name, or anything else for which completion is defined, you can type
`M-<TAB>' (`widget-complete') to do completion.  (`<ESC> <TAB>' and
`C-M-i' do the same thing.)

   Some variables have a small fixed set of possible legitimate values.
These variables don't let you edit the value textually.  Instead, a
`[Value Menu]' button appears before the value; invoke this button to
change the value.  For a boolean "on or off" value, the button says
`[Toggle]', and it changes to the other value.  `[Value Menu]' and
`[Toggle]' simply edit the buffer; the changes take real effect when
you use the `Set for Current Session' operation.

   Some variables have values with complex structure.  For example, the
value of `file-coding-system-alist' is an association list.  Here is
how it appears in the customization buffer:

     File Coding System Alist: [Hide Value]
     [INS] [DEL] File regexp: \.elc\'
                 Choice: [Value Menu] Encoding/decoding pair:
                 Decoding: emacs-mule
                 Encoding: emacs-mule
     [INS] [DEL] File regexp: \(\`\|/\)loaddefs.el\'
                 Choice: [Value Menu] Encoding/decoding pair:
                 Decoding: raw-text
                 Encoding: raw-text-unix
     [INS] [DEL] File regexp: \.tar\'
                 Choice: [Value Menu] Encoding/decoding pair:
                 Decoding: no-conversion
                 Encoding: no-conversion
     [INS] [DEL] File regexp:
                 Choice: [Value Menu] Encoding/decoding pair:
                 Decoding: undecided
                 Encoding: nil
     [INS]
        [State]: STANDARD.
     Alist to decide a coding system to use for a file I/O ...
                                     operation. [Hide Rest]
     The format is ((PATTERN . VAL) ...),
     where PATTERN is a regular expression matching a file name,
     [...more lines of documentation...]

Each association in the list appears on four lines, with several
editable fields and/or buttons.  You can edit the regexps and coding
systems using ordinary editing commands.  You can also invoke `[Value
Menu]' to switch to a different kind of value--for instance, to specify
a function instead of a pair of coding systems.

   To delete an association from the list, invoke the `[DEL]' button
for that item.  To add an association, invoke `[INS]' at the position
where you want to add it.  There is an `[INS]' button between each pair
of associations, another at the beginning and another at the end, so
you can add a new association at any position in the list.

   Two special commands, <TAB> and `S-<TAB>', are useful for moving
through the customization buffer.  <TAB> (`widget-forward') moves
forward to the next button or editable field; `S-<TAB>'
(`widget-backward') moves backward to the previous button or editable
field.

   Typing <RET> on an editable field also moves forward, just like
<TAB>.  You can thus type <RET> when you are finished editing a field,
to move on to the next button or field.  To insert a newline within an
editable field, use `C-o' or `C-q C-j'.

   Setting the variable changes its value in the current Emacs session;
"saving" the value changes it for future sessions as well.  To save the
variable, invoke `[State]' and select the `Save for Future Sessions'
operation.  This works by writing code so as to set the variable again,
each time you start Emacs (*note Saving Customizations::).

   You can also restore the variable to its standard value by invoking
`[State]' and selecting the `Erase Customization' operation.  There are
actually four reset operations:

`Undo Edits'
     If you have made some modifications and not yet set the variable,
     this restores the text in the customization buffer to match the
     actual value.

`Reset to Saved'
     This restores the value of the variable to the last saved value,
     and updates the text accordingly.

`Erase Customization'
     This sets the variable to its standard value, and updates the text
     accordingly.  This also eliminates any saved value for the
     variable, so that you will get the standard value in future Emacs
     sessions.

`Set to Backup Value'
     This sets the variable to a previous value that was set in the
     customization buffer in this session.  If you customize a variable
     and then reset it, which discards the customized value, you can
     get the discarded value back again with this operation.

   Sometimes it is useful to record a comment about a specific
customization.  Use the `Add Comment' item from the `[State]' menu to
create a field for entering the comment.  The comment you enter will be
saved, and displayed again if you again view the same variable in a
customization buffer, even in another session.

   The state of a group indicates whether anything in that group has
been edited, set or saved.

   Near the top of the customization buffer there are two lines of
buttons:

      [Set for Current Session] [Save for Future Sessions]
      [Undo Edits] [Reset to Saved] [Erase Customization]   [Finish]

Invoking `[Finish]' either buries or kills this customization buffer
according to the setting of the option `custom-buffer-done-kill'; the
default is to bury the buffer.  Each of the other buttons performs an
operation--set, save or reset--on each of the settings in the buffer
that could meaningfully be set, saved or reset.  They do not operate on
settings whose values are hidden, nor on subgroups which are hidden or
not visible in the buffer.


File: emacs,  Node: Saving Customizations,  Next: Face Customization,  Prev: Changing a Variable,  Up: Easy Customization

57.2.4 Saving Customizations
----------------------------

Saving customizations from the customization buffer works by writing
code to a file.  By reading this code, future sessions can set up the
customizations again.  Normally, the code is saved in your
initialization file (*note Init File::).

   You can choose to save your customizations in a file other than your
initialization file.  To make this work, you must add a couple of lines
of code to your initialization file, to set the variable `custom-file'
to the name of the desired file, and to load that file.  For example:

     (setq custom-file "~/.emacs-custom.el")
     (load custom-file)

   You can use `custom-file' to specify different customization files
for different Emacs versions, like this:

     (cond ((< emacs-major-version 22)
            ;; Emacs 21 customization.
            (setq custom-file "~/.custom-21.el"))
           ((and (= emacs-major-version 22)
                 (< emacs-minor-version 3))
            ;; Emacs 22 customization, before version 22.3.
            (setq custom-file "~/.custom-22.el"))
           (t
            ;; Emacs version 22.3 or later.
            (setq custom-file "~/.emacs-custom.el")))

     (load custom-file)

   If Emacs was invoked with the `-q' or `--no-init-file' options
(*note Initial Options::), it will not let you save your customizations
in your initialization file.  This is because saving customizations
from such a session would wipe out all the other customizations you
might have on your initialization file.


File: emacs,  Node: Face Customization,  Next: Specific Customization,  Prev: Saving Customizations,  Up: Easy Customization

57.2.5 Customizing Faces
------------------------

In addition to variables, some customization groups also include faces.
When you show the contents of a group, both the variables and the faces
in the group appear in the customization buffer.  Here is an example of
how a face looks:

     Custom Changed Face:(sample) [Hide Face]
        [State]: STANDARD.
     Face used when the customize item has been changed.
     Parent groups: [Custom Magic Faces]
     Attributes: [ ] Font Family: *
                 [ ] Width: *
                 [ ] Height: *
                 [ ] Weight: *
                 [ ] Slant: *
                 [ ] Underline: *
                 [ ] Overline: *
                 [ ] Strike-through: *
                 [ ] Box around text: *
                 [ ] Inverse-video: *
                 [X] Foreground: white       (sample)
                 [X] Background: blue        (sample)
                 [ ] Stipple: *
                 [ ] Inherit: *

   Each face attribute has its own line.  The `[X]' button before the
attribute name indicates whether the attribute is "enabled"; `[X]'
means that it's enabled, and `[ ]' means that it's disabled.  You can
enable or disable the attribute by clicking that button.  When the
attribute is enabled, you can change the attribute value in the usual
ways.

   You can specify a color name (use `M-x list-colors-display' for a
list of them) or a hexadecimal color specification of the form
`#RRGGBB'.  (`#000000' is black, `#ff0000' is red, `#00ff00' is green,
`#0000ff' is blue, and `#ffffff' is white.)  On a black-and-white
display, the colors you can use for the background are `black', `white',
`gray', `gray1', and `gray3'.  Emacs supports these shades of gray by
using background stipple patterns instead of a color.

   Setting, saving and resetting a face work like the same operations
for variables (*note Changing a Variable::).

   A face can specify different appearances for different types of
display.  For example, a face can make text red on a color display, but
use a bold font on a monochrome display.  To specify multiple
appearances for a face, select `For All Kinds of Displays' in the menu
you get from invoking `[State]'.

   Another more basic way to set the attributes of a specific face is
with `M-x modify-face'.  This command reads the name of a face, then
reads the attributes one by one.  For the color and stipple attributes,
the attribute's current value is the default--type just <RET> if you
don't want to change that attribute.  Type `none' if you want to clear
out the attribute.


File: emacs,  Node: Specific Customization,  Next: Custom Themes,  Prev: Face Customization,  Up: Easy Customization

57.2.6 Customizing Specific Items
---------------------------------

Instead of finding the setting you want to change by navigating the
structure of groups, here are other ways to specify the settings that
you want to customize.

`M-x customize-option <RET> OPTION <RET>'
     Set up a customization buffer with just one user option variable,
     OPTION.

`M-x customize-face <RET> FACE <RET>'
     Set up a customization buffer with just one face, FACE.

`M-x customize-group <RET> GROUP <RET>'
     Set up a customization buffer with just one group, GROUP.

`M-x customize-apropos <RET> REGEXP <RET>'
     Set up a customization buffer with all the settings and groups that
     match REGEXP.

`M-x customize-changed <RET> VERSION <RET>'
     Set up a customization buffer with all the settings and groups
     whose meaning has changed since Emacs version VERSION.

`M-x customize-saved'
     Set up a customization buffer containing all settings that you
     have saved with customization buffers.

`M-x customize-unsaved'
     Set up a customization buffer containing all settings that you have
     set but not saved.

   If you want to alter a particular user option with the customization
buffer, and you know its name, you can use the command `M-x
customize-option' and specify the user option (variable) name.  This
sets up the customization buffer with just one user option--the one
that you asked for.  Editing, setting and saving the value work as
described above, but only for the specified user option.  Minibuffer
completion is handy if you only know part of the name.  However, this
command can only see options that have been loaded in the current Emacs
session.

   Likewise, you can modify a specific face, chosen by name, using `M-x
customize-face'.  By default it operates on the face used on the
character after point.

   You can also set up the customization buffer with a specific group,
using `M-x customize-group'.  The immediate contents of the chosen
group, including settings (user options and faces), and other groups,
all appear as well (even if not already loaded).  However, the
subgroups' own contents are not included.

   For a more general way of controlling what to customize, you can use
`M-x customize-apropos'.  You specify a regular expression as argument;
then all _loaded_ settings and groups whose names match this regular
expression are set up in the customization buffer.  If you specify an
empty regular expression, this includes _all_ loaded groups and
settings--which takes a long time to set up.

   When you upgrade to a new Emacs version, you might want to consider
customizing new settings, and settings whose meanings or default values
have changed.  To do this, use `M-x customize-changed' and specify a
previous Emacs version number using the minibuffer.  It creates a
customization buffer which shows all the settings and groups whose
definitions have been changed since the specified version, loading them
if necessary.

   If you change settings and then decide the change was a mistake, you
can use two special commands to revisit your previous changes.  Use
`M-x customize-saved' to look at the settings that you have saved.  Use
`M-x customize-unsaved' to look at the settings that you have set but
not saved.


File: emacs,  Node: Custom Themes,  Prev: Specific Customization,  Up: Easy Customization

57.2.7 Customization Themes
---------------------------

"Custom themes" are collections of settings that can be enabled or
disabled as a unit.  You can use Custom themes to switch quickly and
easily between various collections of settings, and to transfer such
collections from one computer to another.

   To define a Custom theme, use `M-x customize-create-theme', which
brings up a buffer named `*New Custom Theme*'.  At the top of the
buffer is an editable field where you can specify the name of the
theme.  Click on the button labelled `Insert Variable' to add a
variable to the theme, and click on `Insert Face' to add a face.  You
can edit these values in the `*New Custom Theme*' buffer like in an
ordinary Customize buffer.  To remove an option from the theme, click
on its `State' button and select `Delete'.

   After adding the desired options, click on `Save Theme' to save the
Custom theme.  This writes the theme definition to a file
`FOO-theme.el' (where FOO is the theme name you supplied), in the
directory `~/.emacs.d/'.  You can specify the directory by setting
`custom-theme-directory'.

   You can view and edit the settings of a previously-defined theme by
clicking on `Visit Theme' and specifying the theme name.  You can also
import the variables and faces that you have set using Customize by
visiting the "special" theme named `user'.  This theme, which records
all the options that you set in the ordinary customization buffer, is
always enabled, and always takes precedence over all other enabled
Custom themes.  Additionally, the `user' theme is recorded with code in
your `.emacs' file, rather than a `user-theme.el' file.

   Once you have defined a Custom theme, you can use it by customizing
the variable `custom-enabled-themes'.  This is a list of Custom themes
that are "enabled", or put into effect.  If you set
`custom-enabled-themes' using the Customize interface, the theme
definitions are automatically loaded from the theme files, if they
aren't already.  If you save the value of `custom-enabled-themes' for
future Emacs sessions, those Custom themes will be enabled whenever
Emacs is started up.

   If two enabled themes specify different values for an option, the
theme occurring earlier in `custom-enabled-themes' takes effect.

   You can temporarily enable a Custom theme with `M-x enable-theme'.
This prompts for a theme name in the minibuffer, loads the theme from
the theme file if necessary, and enables the theme.  You can "disable"
any enabled theme with the command `M-x disable-theme'; this returns
the options specified in the theme to their original values.  To
re-enable the theme, type `M-x enable-theme' again.  If a theme file is
changed during your Emacs session, you can reload it by typing `M-x
load-theme'.  (This also enables the theme.)


File: emacs,  Node: Variables,  Next: Key Bindings,  Prev: Easy Customization,  Up: Customization

57.3 Variables
==============

A "variable" is a Lisp symbol which has a value.  The symbol's name is
also called the "variable name".  A variable name can contain any
characters that can appear in a file, but most variable names consist
of ordinary words separated by hyphens.

   The name of the variable serves as a compact description of its
role.  Most variables also have a "documentation string", which
describes what the variable's purpose is, what kind of value it should
have, and how the value will be used.  You can view this documentation
using the help command `C-h v' (`describe-variable').  *Note
Examining::.

   Emacs uses many Lisp variables for internal record keeping, but the
most interesting variables for a non-programmer user are those meant
for users to change--these are called "user options".  *Note Easy
Customization::, for information about using the Customize facility to
set user options.  In the following sections, we will describe other
aspects of Emacs variables, such as how to set them outside Customize.

   Emacs Lisp allows any variable (with a few exceptions) to have any
kind of value.  However, many variables are meaningful only if assigned
values of a certain type.  For example, only numbers are meaningful
values for `kill-ring-max', which specifies the maximum length of the
kill ring (*note Earlier Kills::); if you give `kill-ring-max' a string
value, commands such as `C-y' (`yank') will signal an error.  On the
other hand, some variables don't care about type; for instance, if a
variable has one effect for `nil' values and another effect for
"non-`nil'" values, then any value that is not the symbol `nil' induces
the second effect, regardless of its type (by convention, we usually
use the value `t'--a symbol which stands for "true"--to specify a
non-`nil' value).  If you set a variable using the customization
buffer, you need not worry about giving it an invalid type: the
customization buffer usually only allows you to enter meaningful
values.  When in doubt, use `C-h v' (`describe-variable') to check the
variable's documentation string to see kind of value it expects (*note
Examining::).

* Menu:

* Examining::           Examining or setting one variable's value.
* Hooks::               Hook variables let you specify programs for parts
                          of Emacs to run on particular occasions.
* Locals::              Per-buffer values of variables.
* File Variables::      How files can specify variable values.
* Directory Variables:: How variable values can be specified by directory.


File: emacs,  Node: Examining,  Next: Hooks,  Up: Variables

57.3.1 Examining and Setting Variables
--------------------------------------

`C-h v VAR <RET>'
     Display the value and documentation of variable VAR
     (`describe-variable').

`M-x set-variable <RET> VAR <RET> VALUE <RET>'
     Change the value of variable VAR to VALUE.

   To examine the value of a single variable, use `C-h v'
(`describe-variable'), which reads a variable name using the
minibuffer, with completion.  It displays both the value and the
documentation of the variable.  For example,

     C-h v fill-column <RET>

displays something like this:

     fill-column is a variable defined in `C source code'.
     fill-column's value is 70
     Local in buffer custom.texi; global value is 70
     Automatically becomes buffer-local when set in any fashion.

       Automatically becomes buffer-local when set in any fashion.
       This variable is safe as a file local variable if its value
       satisfies the predicate `integerp'.

     Documentation:
     *Column beyond which automatic line-wrapping should happen.
     Interactively, you can set the buffer local value using C-x f.

     You can customize this variable.

The line that says "You can customize the variable" indicates that this
variable is a user option.  `C-h v' is not restricted to user options;
it allows any variable name.

   The most convenient way to set a specific user option variable is
with `M-x set-variable'.  This reads the variable name with the
minibuffer (with completion), and then reads a Lisp expression for the
new value using the minibuffer a second time (you can insert the old
value into the minibuffer for editing via `M-n').  For example,

     M-x set-variable <RET> fill-column <RET> 75 <RET>

sets `fill-column' to 75.

   `M-x set-variable' is limited to user option variables, but you can
set any variable with a Lisp expression, using the function `setq'.
Here is a `setq' expression to set `fill-column':

     (setq fill-column 75)

   To execute an expression like this one, go to the `*scratch*'
buffer, type in the expression, and then type `C-j'.  *Note Lisp
Interaction::.

   Setting variables, like all means of customizing Emacs except where
otherwise stated, affects only the current Emacs session.  The only way
to alter the variable in future sessions is to put something in your
initialization file to set it those sessions (*note Init File::).


File: emacs,  Node: Hooks,  Next: Locals,  Prev: Examining,  Up: Variables

57.3.2 Hooks
------------

"Hooks" are an important mechanism for customizing Emacs.  A hook is a
Lisp variable which holds a list of functions, to be called on some
well-defined occasion.  (This is called "running the hook".)  The
individual functions in the list are called the "hook functions" of the
hook.  With rare exceptions, hooks in Emacs are empty when Emacs starts
up, so the only hook functions in any given hook are the ones you
explicitly put there as customization.

   Most major modes run one or more "mode hooks" as the last step of
initialization.  This makes it easy for you to customize the behavior
of the mode, by setting up a hook function to override the local
variable assignments already made by the mode.  But hooks are also used
in other contexts.  For example, the hook `kill-emacs-hook' runs just
before quitting the Emacs job (*note Exiting::).

   Most Emacs hooks are "normal hooks".  This means that running the
hook operates by calling all the hook functions, unconditionally, with
no arguments.  We have made an effort to keep most hooks normal so that
you can use them in a uniform way.  Every variable in Emacs whose name
ends in `-hook' is a normal hook.

   There are also a few "abnormal hooks".  These variables' names end
in `-hooks' or `-functions', instead of `-hook'.  What makes these
hooks abnormal is that there is something peculiar about the way its
functions are called--perhaps they are given arguments, or perhaps the
values they return are used in some way.  For example,
`find-file-not-found-functions' (*note Visiting::) is abnormal because
as soon as one hook function returns a non-`nil' value, the rest are
not called at all.  The documentation of each abnormal hook variable
explains in detail what is peculiar about it.

   You can set a hook variable with `setq' like any other Lisp
variable, but the recommended way to add a hook function to a hook
(either normal or abnormal) is by calling `add-hook'.  *Note Hooks:
(elisp)Hooks.

   For example, here's how to set up a hook to turn on Auto Fill mode
when entering Text mode and other modes based on Text mode:

     (add-hook 'text-mode-hook 'turn-on-auto-fill)

   The next example shows how to use a hook to customize the indentation
of C code.  (People often have strong personal preferences for one
format compared to another.)  Here the hook function is an anonymous
lambda expression.

     (setq my-c-style
       '((c-comment-only-line-offset . 4)
         (c-cleanup-list . (scope-operator
                            empty-defun-braces
                            defun-close-semi))
         (c-offsets-alist . ((arglist-close . c-lineup-arglist)
                             (substatement-open . 0)))))

     (add-hook 'c-mode-common-hook
       '(lambda ()
          (c-add-style "my-style" my-c-style t)))

   It is best to design your hook functions so that the order in which
they are executed does not matter.  Any dependence on the order is
"asking for trouble."  However, the order is predictable: the most
recently added hook functions are executed first.

   If you play with adding various different versions of a hook
function by calling `add-hook' over and over, remember that all the
versions you added will remain in the hook variable together.  You can
clear out individual functions by calling `remove-hook', or do `(setq
HOOK-VARIABLE nil)' to remove everything.


File: emacs,  Node: Locals,  Next: File Variables,  Prev: Hooks,  Up: Variables

57.3.3 Local Variables
----------------------

`M-x make-local-variable <RET> VAR <RET>'
     Make variable VAR have a local value in the current buffer.

`M-x kill-local-variable <RET> VAR <RET>'
     Make variable VAR use its global value in the current buffer.

`M-x make-variable-buffer-local <RET> VAR <RET>'
     Mark variable VAR so that setting it will make it local to the
     buffer that is current at that time.

   Almost any variable can be made "local" to a specific Emacs buffer.
This means that its value in that buffer is independent of its value in
other buffers.  A few variables are always local in every buffer.
Every other Emacs variable has a "global" value which is in effect in
all buffers that have not made the variable local.

   `M-x make-local-variable' reads the name of a variable and makes it
local to the current buffer.  Changing its value subsequently in this
buffer will not affect others, and changes in its global value will not
affect this buffer.

   `M-x make-variable-buffer-local' marks a variable so it will become
local automatically whenever it is set.  More precisely, once a
variable has been marked in this way, the usual ways of setting the
variable automatically do `make-local-variable' first.  We call such
variables "per-buffer" variables.  Many variables in Emacs are normally
per-buffer; the variable's document string tells you when this is so.
A per-buffer variable's global value is normally never effective in any
buffer, but it still has a meaning: it is the initial value of the
variable for each new buffer.

   Major modes (*note Major Modes::) always make variables local to the
buffer before setting the variables.  This is why changing major modes
in one buffer has no effect on other buffers.  Minor modes also work by
setting variables--normally, each minor mode has one controlling
variable which is non-`nil' when the mode is enabled (*note Minor
Modes::).  For many minor modes, the controlling variable is per
buffer, and thus always buffer-local.  Otherwise, you can make it local
in a specific buffer like any other variable.

   A few variables cannot be local to a buffer because they are always
local to each display instead (*note Multiple Displays::).  If you try
to make one of these variables buffer-local, you'll get an error
message.

   `M-x kill-local-variable' makes a specified variable cease to be
local to the current buffer.  The global value of the variable
henceforth is in effect in this buffer.  Setting the major mode kills
all the local variables of the buffer except for a few variables
specially marked as "permanent locals".

   To set the global value of a variable, regardless of whether the
variable has a local value in the current buffer, you can use the Lisp
construct `setq-default'.  This construct is used just like `setq', but
it sets variables' global values instead of their local values (if
any).  When the current buffer does have a local value, the new global
value may not be visible until you switch to another buffer.  Here is
an example:

     (setq-default fill-column 75)

`setq-default' is the only way to set the global value of a variable
that has been marked with `make-variable-buffer-local'.

   Lisp programs can use `default-value' to look at a variable's
default value.  This function takes a symbol as argument and returns its
default value.  The argument is evaluated; usually you must quote it
explicitly.  For example, here's how to obtain the default value of
`fill-column':

     (default-value 'fill-column)


File: emacs,  Node: File Variables,  Next: Directory Variables,  Prev: Locals,  Up: Variables

57.3.4 Local Variables in Files
-------------------------------

A file can specify local variable values for use when you edit the file
with Emacs.  Visiting the file checks for local variable
specifications; it automatically makes these variables local to the
buffer, and sets them to the values specified in the file.

* Menu:

* Specifying File Variables:: Specifying file local variables.
* Safe File Variables::       Making sure file local variables are safe.


File: emacs,  Node: Specifying File Variables,  Next: Safe File Variables,  Up: File Variables

57.3.4.1 Specifying File Variables
..................................

There are two ways to specify file local variable values: in the first
line, or with a local variables list.  Here's how to specify them in the
first line:

     -*- mode: MODENAME; VAR: VALUE; ... -*-

You can specify any number of variable/value pairs in this way, each
pair with a colon and semicolon as shown above.  The special
variable/value pair `mode: MODENAME;', if present, specifies a major or
minor mode; if you use this to specify a major mode, it should come
first in the line.  The VALUEs are used literally, and not evaluated.

   You can use the command `add-file-local-variable-prop-line' instead
of adding entries by hand.  It prompts for a variable and value, and
adds them to the first line in the appropriate way.  The command
`delete-file-local-variable-prop-line' deletes a variable from the
line.  The command `copy-dir-locals-to-file-locals-prop-line' copies
directory-local variables (*note Directory Variables::) to the first
line.

   Here is an example first line that specifies Lisp mode and sets two
variables with numeric values:

     ;; -*- mode: Lisp; fill-column: 75; comment-column: 50; -*-

Aside from `mode', other keywords that have special meanings as file
variables are `coding', `unibyte', and `eval'.  These are described
below.

   In shell scripts, the first line is used to identify the script
interpreter, so you cannot put any local variables there.  To
accommodate this, Emacs looks for local variable specifications in the
_second_ line if the first line specifies an interpreter.  The same is
true for man pages which start with the magic string `'\"' to specify a
list of troff preprocessors (not all do, however).

   Instead of using a `-*-' line, you can define file local variables
using a "local variables list" near the end of the file.  The start of
the local variables list should be no more than 3000 characters from
the end of the file, and must be on the last page if the file is
divided into pages.

   If a file has both a local variables list and a `-*-' line, Emacs
processes _everything_ in the `-*-' line first, and _everything_ in the
local variables list afterward.

   A local variables list starts with a line containing the string
`Local Variables:', and ends with a line containing the string `End:'.
In between come the variable names and values, one set per line, like
this:

     /* Local Variables: */
     /* mode:c           */
     /* comment-column:0 */
     /* End:             */

In this example, each line starts with the prefix `/*' and ends with
the suffix `*/'.  Emacs recognizes the prefix and suffix by finding
them surrounding the magic string `Local Variables:', on the first line
of the list; it then automatically discards them from the other lines
of the list.  The usual reason for using a prefix and/or suffix is to
embed the local variables list in a comment, so it won't confuse other
programs that the file is intended for.  The example above is for the C
programming language, where comment lines start with `/*' and end with
`*/'.

   You can construct the local variables list yourself, or use the
command `add-file-local-variable'.  This prompts for a variable and
value, and adds them to the list.  If necessary, it also adds the start
and end markers.  The command `delete-file-local-variable' deletes a
variable from the list.  The command `copy-dir-locals-to-file-locals'
copies directory-local variables (*note Directory Variables::) to the
list.

   As with the `-*-' line, the variables in a local variables list are
used literally, and are not evaluated first.  If you want to split a
long string across multiple lines of the file, you can use
backslash-newline, which is ignored in Lisp string constants; you
should put the prefix and suffix on each line, even lines that start or
end within the string, as they will be stripped off when processing the
list.  Here is an example:

     # Local Variables:
     # compile-command: "cc foo.c -Dfoo=bar -Dhack=whatever \
     #   -Dmumble=blaah"
     # End:

   Some "variable names" have special meanings in a local variables
list:

   * `mode' enables the specified major or minor mode.

   * `eval' evaluates the specified Lisp expression (the value returned
     by that expression is ignored).

   * `coding' specifies the coding system for character code conversion
     of this file.  *Note Coding Systems::.

   * `unibyte' says to visit the file in a unibyte buffer, if the value
     is `t'.  *Note Enabling Multibyte::.

These four "variables" are not really variables; setting them in any
other context has no special meaning.

   _If `mode' is used to set a major mode, it should be the first
"variable" in the list._  Otherwise, the entries that precede it will
usually have no effect, since most major modes kill all local variables
as part of their initialization.

   You can use the `mode' "variable" to enable minor modes as well as
the major modes; in fact, you can use it more than once, first to set
the major mode and then to enable minor modes which are specific to
particular buffers.

   Often, however, it is a mistake to enable minor modes this way.
Most minor modes, like Auto Fill mode, represent individual user
preferences.  If you want to use a minor mode, it is better to set up
major mode hooks with your init file to turn that minor mode on for
yourself alone (*note Init File::), instead of using a local variable
list to impose your taste on everyone.

   Use the command `normal-mode' to reset the local variables and major
mode of a buffer according to the file name and contents, including the
local variables list if any.  *Note Choosing Modes::.


File: emacs,  Node: Safe File Variables,  Prev: Specifying File Variables,  Up: File Variables

57.3.4.2 Safety of File Variables
.................................

File-local variables can be dangerous; when you visit someone else's
file, there's no telling what its local variables list could do to your
Emacs.  Improper values of the `eval' "variable", and other variables
such as `load-path', could execute Lisp code you didn't intend to run.

   Therefore, whenever Emacs encounters file local variable values that
are not known to be safe, it displays the file's entire local variables
list, and asks you for confirmation before setting them.  You can type
`y' or <SPC> to put the local variables list into effect, or `n' to
ignore it.  When Emacs is run in batch mode (*note Initial Options::),
it can't really ask you, so it assumes the answer `n'.

   Emacs normally recognizes certain variable/value pairs as safe.  For
instance, it is safe to give `comment-column' or `fill-column' any
integer value.  If a file specifies only known-safe variable/value
pairs, Emacs does not ask for confirmation before setting them.
Otherwise, you can tell Emacs to record all the variable/value pairs in
this file as safe, by typing `!' at the confirmation prompt.  When
Emacs encounters these variable/value pairs subsequently, in the same
file or others, it will assume they are safe.

   Some variables, such as `load-path', are considered particularly
"risky": there is seldom any reason to specify them as local variables,
and changing them can be dangerous.  If a file contains only risky
local variables, Emacs neither offers nor accepts `!' as input at the
confirmation prompt.  If some of the local variables in a file are
risky, and some are only potentially unsafe, you can enter `!' at the
prompt.  It applies all the variables, but only marks the non-risky
ones as safe for the future.  If you really want to record safe values
for risky variables, do it directly by customizing
`safe-local-variable-values' (*note Easy Customization::).

   The variable `enable-local-variables' allows you to change the way
Emacs processes local variables.  Its default value is `t', which
specifies the behavior described above.  If it is `nil', Emacs simply
ignores all file local variables.  `:safe' means use only the safe
values and ignore the rest.  Any other value says to query you about
each file that has local variables, without trying to determine whether
the values are known to be safe.

   The variable `enable-local-eval' controls whether Emacs processes
`eval' variables.  The three possibilities for the variable's value are
`t', `nil', and anything else, just as for `enable-local-variables'.
The default is `maybe', which is neither `t' nor `nil', so normally
Emacs does ask for confirmation about processing `eval' variables.

   As an exception, Emacs never asks for confirmation to evaluate any
`eval' form if that form occurs within the variable
`safe-local-eval-forms'.


File: emacs,  Node: Directory Variables,  Prev: File Variables,  Up: Variables

57.3.5 Per-Directory Local Variables
------------------------------------

A "project" is a collection of files on which you work together.
Usually, the project's files are kept in one or more directories.
Occasionally, you may wish to define Emacs settings that are common to
all the files that belong to the project.

   Emacs provides two ways to specify settings that are applicable to
files in a specific directory: you can put a special file in that
directory, or you can define a "project class" for that directory.

   If you put a file with a special name `.dir-locals.el'(1) in a
directory, Emacs will read it when it visits any file in that directory
or any of its subdirectories, and apply the settings it specifies to
the file's buffer.  Emacs searches for `.dir-locals.el' starting in the
directory of the visited file, and moving up the directory tree.  (To
avoid slowdown, this search is skipped for remote files.)

   The `.dir-locals.el' file should hold a specially-constructed list.
This list maps Emacs mode names (symbols) to alists; each alist
specifies values for variables to use when the respective mode is
turned on.  The special mode name `nil' means that its alist applies to
any mode.  Instead of a mode name, you can specify a string that is a
name of a subdirectory of the project's directory; then the
corresponding alist applies to all the files in that subdirectory.

   Here's an example of a `.dir-locals.el' file:

     ((nil . ((indent-tabs-mode . t)
              (tab-width . 4)
              (fill-column . 80)))
      (c-mode . ((c-file-style . "BSD")))
      (java-mode . ((c-file-style . "BSD")))
      ("src/imported"
       . ((nil . ((change-log-default-name .
                   "ChangeLog.local"))))))

This example shows some settings for a hypothetical project.  It sets
`indent-tabs-mode', `tab-width', and `fill-column' for any file in the
project's directory tree, and it sets the indentation style for any C
or Java source file.  Finally, it specifies a different `ChangeLog'
file name for any file in the `src/imported' subdirectory of the
directory where you put the `.dir-locals.el' file.

   You can edit the `.dir-locals.el' file by hand, or use the command
`add-dir-local-variable'.  This prompts for a mode (or subdirectory),
variable and value, and adds an entry to the file.  The command
`delete-dir-local-variable' deletes an entry.  The command
`copy-file-locals-to-dir-locals' copies file local variables (*note
File Variables::) to the `.dir-locals.el' file.

   Another method of specifying directory-local variables is to
explicitly define a project class using
`dir-locals-set-class-variables', and then tell Emacs which directories
correspond to that class, using `dir-locals-set-directory-class'.  You
can put calls to these functions in your `~/.emacs' init file; this can
be useful when you can't put `.dir-locals.el' in the directory for some
reason, or if you want to keep in a single place settings for several
directories that don't have a common parent.  For example, you could
apply settings to an unwritable directory this way:

     (dir-locals-set-class-variables 'unwritable-directory
        '((nil . ((some-useful-setting . value)))))

     (dir-locals-set-directory-class
        "/usr/include/" 'unwritable-directory)

   Unsafe directory-local variables are handled in the same way as
unsafe file-local variables (*note Safe File Variables::).

   ---------- Footnotes ----------

   (1) On MS-DOS, the name of this file should be `_dir-locals.el', due
to limitations of the DOS filesystems.  If the filesystem is limited to
8+3 file names, the name of the file will be truncated by the OS to
`_dir-loc.el'.


File: emacs,  Node: Key Bindings,  Next: Syntax,  Prev: Variables,  Up: Customization

57.4 Customizing Key Bindings
=============================

This section describes "key bindings", which map keys to commands, and
"keymaps", which record key bindings.  It also explains how to
customize key bindings, which is done by editing your init file (*note
Init Rebinding::).

* Menu:

* Keymaps::             Generalities.  The global keymap.
* Prefix Keymaps::      Keymaps for prefix keys.
* Local Keymaps::       Major and minor modes have their own keymaps.
* Minibuffer Maps::     The minibuffer uses its own local keymaps.
* Rebinding::           How to redefine one key's meaning conveniently.
* Init Rebinding::      Rebinding keys with your init file, `.emacs'.
* Modifier Keys::       Using modifier keys in key bindings.
* Function Keys::       Rebinding terminal function keys.
* Named ASCII Chars::   Distinguishing <TAB> from C-i, and so on.
* Mouse Buttons::       Rebinding mouse buttons in Emacs.
* Disabling::           Disabling a command means confirmation is required
                          before it can be executed.  This is done to protect
                          beginners from surprises.


File: emacs,  Node: Keymaps,  Next: Prefix Keymaps,  Up: Key Bindings

57.4.1 Keymaps
--------------

As described in *note Commands::, each Emacs command is a Lisp function
whose definition provides for interactive use.  Like every Lisp
function, a command has a function name, which usually consists of
lower-case letters and hyphens.

   A "key sequence" ("key", for short) is a sequence of "input events"
that have a meaning as a unit.  Input events include characters,
function keys and mouse buttons--all the inputs that you can send to
the computer.  A key sequence gets its meaning from its "binding",
which says what command it runs.

   The bindings between key sequences and command functions are
recorded in data structures called "keymaps".  Emacs has many of these,
each used on particular occasions.

   The "global" keymap is the most important keymap because it is
always in effect.  The global keymap defines keys for Fundamental mode
(*note Major Modes::); most of these definitions are common to most or
all major modes.  Each major or minor mode can have its own keymap
which overrides the global definitions of some keys.

   For example, a self-inserting character such as `g' is
self-inserting because the global keymap binds it to the command
`self-insert-command'.  The standard Emacs editing characters such as
`C-a' also get their standard meanings from the global keymap.
Commands to rebind keys, such as `M-x global-set-key', work by storing
the new binding in the proper place in the global map (*note
Rebinding::).

   Most modern keyboards have function keys as well as character keys.
Function keys send input events just as character keys do, and keymaps
can have bindings for them.  Key sequences can mix function keys and
characters.  For example, if your keyboard has a <Home> function key,
Emacs can recognize key sequences like `C-x <Home>'.  You can even mix
mouse events with keyboard events, such as `S-down-mouse-1'.

   On text terminals, typing a function key actually sends the computer
a sequence of characters; the precise details of the sequence depends
on the function key and on the terminal type.  (Often the sequence
starts with `<ESC> ['.)  If Emacs understands your terminal type
properly, it automatically handles such sequences as single input
events.


File: emacs,  Node: Prefix Keymaps,  Next: Local Keymaps,  Prev: Keymaps,  Up: Key Bindings

57.4.2 Prefix Keymaps
---------------------

Internally, Emacs records only single events in each keymap.
Interpreting a key sequence of multiple events involves a chain of
keymaps: the first keymap gives a definition for the first event, which
is another keymap, which is used to look up the second event in the
sequence, and so on.  Thus, a prefix key such as `C-x' or <ESC> has its
own keymap, which holds the definition for the event that immediately
follows that prefix.

   The definition of a prefix key is usually the keymap to use for
looking up the following event.  The definition can also be a Lisp
symbol whose function definition is the following keymap; the effect is
the same, but it provides a command name for the prefix key that can be
used as a description of what the prefix key is for.  Thus, the binding
of `C-x' is the symbol `Control-X-prefix', whose function definition is
the keymap for `C-x' commands.  The definitions of `C-c', `C-x', `C-h'
and <ESC> as prefix keys appear in the global map, so these prefix keys
are always available.

   Aside from ordinary prefix keys, there is a fictitious "prefix key"
which represents the menu bar; see *note Menu Bar: (elisp)Menu Bar, for
special information about menu bar key bindings.  Mouse button events
that invoke pop-up menus are also prefix keys; see *note Menu Keymaps:
(elisp)Menu Keymaps, for more details.

   Some prefix keymaps are stored in variables with names:

   * `ctl-x-map' is the variable name for the map used for characters
     that follow `C-x'.

   * `help-map' is for characters that follow `C-h'.

   * `esc-map' is for characters that follow <ESC>.  Thus, all Meta
     characters are actually defined by this map.

   * `ctl-x-4-map' is for characters that follow `C-x 4'.

   * `mode-specific-map' is for characters that follow `C-c'.


File: emacs,  Node: Local Keymaps,  Next: Minibuffer Maps,  Prev: Prefix Keymaps,  Up: Key Bindings

57.4.3 Local Keymaps
--------------------

So far, we have explained the ins and outs of the global map.  Major
modes customize Emacs by providing their own key bindings in "local
keymaps".  For example, C mode overrides <TAB> to make it indent the
current line for C code.  Minor modes can also have local keymaps;
whenever a minor mode is in effect, the definitions in its keymap
override both the major mode's local keymap and the global keymap.  In
addition, portions of text in the buffer can specify their own keymaps,
which override all other keymaps.

   A local keymap can redefine a key as a prefix key by defining it as
a prefix keymap.  If the key is also defined globally as a prefix, its
local and global definitions (both keymaps) effectively combine: both
definitions are used to look up the event that follows the prefix key.
For example, if a local keymap defines `C-c' as a prefix keymap, and
that keymap defines `C-z' as a command, this provides a local meaning
for `C-c C-z'.  This does not affect other sequences that start with
`C-c'; if those sequences don't have their own local bindings, their
global bindings remain in effect.

   Another way to think of this is that Emacs handles a multi-event key
sequence by looking in several keymaps, one by one, for a binding of the
whole key sequence.  First it checks the minor mode keymaps for minor
modes that are enabled, then it checks the major mode's keymap, and then
it checks the global keymap.  This is not precisely how key lookup
works, but it's good enough for understanding the results in ordinary
circumstances.


File: emacs,  Node: Minibuffer Maps,  Next: Rebinding,  Prev: Local Keymaps,  Up: Key Bindings

57.4.4 Minibuffer Keymaps
-------------------------

The minibuffer has its own set of local keymaps; they contain various
completion and exit commands.

   * `minibuffer-local-map' is used for ordinary input (no completion).

   * `minibuffer-local-ns-map' is similar, except that <SPC> exits just
     like <RET>.

   * `minibuffer-local-completion-map' is for permissive completion.

   * `minibuffer-local-must-match-map' is for strict completion and for
     cautious completion.

   * `minibuffer-local-filename-completion-map' and
     `minibuffer-local-must-match-filename-map' are like the two
     previous ones, but they are specifically for file name completion.
     They do not bind <SPC>.


File: emacs,  Node: Rebinding,  Next: Init Rebinding,  Prev: Minibuffer Maps,  Up: Key Bindings

57.4.5 Changing Key Bindings Interactively
------------------------------------------

The way to redefine an Emacs key is to change its entry in a keymap.
You can change the global keymap, in which case the change is effective
in all major modes (except those that have their own overriding local
bindings for the same key).  Or you can change a local keymap, which
affects all buffers using the same major mode.

   In this section, we describe how to rebind keys for the present
Emacs session.  *Note Init Rebinding::, for a description of how to
make key rebindings affect future Emacs sessions.

`M-x global-set-key <RET> KEY CMD <RET>'
     Define KEY globally to run CMD.

`M-x local-set-key <RET> KEY CMD <RET>'
     Define KEY locally (in the major mode now in effect) to run CMD.

`M-x global-unset-key <RET> KEY'
     Make KEY undefined in the global map.

`M-x local-unset-key <RET> KEY'
     Make KEY undefined locally (in the major mode now in effect).

   For example, the following binds `C-z' to the `shell' command (*note
Interactive Shell::), replacing the normal global definition of `C-z':

     M-x global-set-key <RET> C-z shell <RET>

The `global-set-key' command reads the command name after the key.
After you press the key, a message like this appears so that you can
confirm that you are binding the key you want:

     Set key C-z to command:

   You can redefine function keys and mouse events in the same way; just
type the function key or click the mouse when it's time to specify the
key to rebind.

   You can rebind a key that contains more than one event in the same
way.  Emacs keeps reading the key to rebind until it is a complete key
(that is, not a prefix key).  Thus, if you type `C-f' for KEY, that's
the end; it enters the minibuffer immediately to read CMD.  But if you
type `C-x', since that's a prefix, it reads another character; if that
is `4', another prefix character, it reads one more character, and so
on.  For example,

     M-x global-set-key <RET> C-x 4 $ spell-other-window <RET>

redefines `C-x 4 $' to run the (fictitious) command
`spell-other-window'.

   You can remove the global definition of a key with
`global-unset-key'.  This makes the key "undefined"; if you type it,
Emacs will just beep.  Similarly, `local-unset-key' makes a key
undefined in the current major mode keymap, which makes the global
definition (or lack of one) come back into effect in that major mode.

   If you have redefined (or undefined) a key and you subsequently wish
to retract the change, undefining the key will not do the job--you need
to redefine the key with its standard definition.  To find the name of
the standard definition of a key, go to a Fundamental mode buffer in a
fresh Emacs and use `C-h c'.  The documentation of keys in this manual
also lists their command names.

   If you want to prevent yourself from invoking a command by mistake,
it is better to disable the command than to undefine the key.  A
disabled command is less work to invoke when you really want to.  *Note
Disabling::.


File: emacs,  Node: Init Rebinding,  Next: Modifier Keys,  Prev: Rebinding,  Up: Key Bindings

57.4.6 Rebinding Keys in Your Init File
---------------------------------------

If you have a set of key bindings that you like to use all the time,
you can specify them in your initialization file by writing Lisp code.
*Note Init File::, for a description of the initialization file.

   There are several ways to write a key binding using Lisp.  The
simplest is to use the `kbd' macro, which converts a textual
representation of a key sequence--similar to how we have written key
sequences in this manual--into a form that can be passed as an argument
to `global-set-key'.  For example, here's how to bind `C-z' to the
`shell' command (*note Interactive Shell::):

     (global-set-key (kbd "C-z") 'shell)

The single-quote before the command name, `shell', marks it as a
constant symbol rather than a variable.  If you omit the quote, Emacs
would try to evaluate `shell' as a variable.  This probably causes an
error; it certainly isn't what you want.

   Here are some additional examples, including binding function keys
and mouse events:

     (global-set-key (kbd "C-c y") 'clipboard-yank)
     (global-set-key (kbd "C-M-q") 'query-replace)
     (global-set-key (kbd "<f5>") 'flyspell-mode)
     (global-set-key (kbd "C-<f5>") 'linum-mode)
     (global-set-key (kbd "C-<right>") 'forward-sentence)
     (global-set-key (kbd "<mouse-2>") 'mouse-save-then-kill)

   Instead of using the `kbd' macro, you can use a Lisp string or
vector to specify the key sequence.  Using a string is simpler, but
only works for ASCII characters and Meta-modified ASCII characters.
For example, here's how to bind `C-x M-l' to `make-symbolic-link'
(*note Misc File Ops::):

     (global-set-key "\C-x\M-l" 'make-symbolic-link)

   To put <TAB>, <RET>, <ESC>, or <DEL> in the string, use the Emacs
Lisp escape sequences `\t', `\r', `\e', and `\d' respectively.  Here is
an example which binds `C-x <TAB>' to `indent-rigidly' (*note
Indentation::):

     (global-set-key "\C-x\t" 'indent-rigidly)

   When the key sequence includes function keys or mouse button events,
or non-ASCII characters such as `C-=' or `H-a', you can use a vector to
specify the key sequence.  Each element in the vector stands for an
input event; the elements are separated by spaces and surrounded by a
pair of square brackets.  If a vector element is a character, write it
as a Lisp character constant: `?' followed by the character as it would
appear in a string.  Function keys are represented by symbols (*note
Function Keys::); simply write the symbol's name, with no other
delimiters or punctuation.  Here are some examples:

     (global-set-key [?\C-=] 'make-symbolic-link)
     (global-set-key [?\M-\C-=] 'make-symbolic-link)
     (global-set-key [?\H-a] 'make-symbolic-link)
     (global-set-key [f7] 'make-symbolic-link)
     (global-set-key [C-mouse-1] 'make-symbolic-link)

You can use a vector for the simple cases too:

     (global-set-key [?\C-z ?\M-l] 'make-symbolic-link)

   Language and coding systems may cause problems with key bindings for
non-ASCII characters.  *Note Init Non-ASCII::.

   As described in *note Local Keymaps::, major modes and minor modes
can define local keymaps.  These keymaps are constructed when the mode
is used for the first time in a session.  If you wish to change one of
these keymaps, you must use the "mode hook" (*note Hooks::).

   For example, Texinfo mode runs the hook `texinfo-mode-hook'.  Here's
how you can use the hook to add local bindings for `C-c n' and `C-c p'
in Texinfo mode:

     (add-hook 'texinfo-mode-hook
               '(lambda ()
                  (define-key texinfo-mode-map "\C-cp"
                              'backward-paragraph)
                  (define-key texinfo-mode-map "\C-cn"
                              'forward-paragraph)))


File: emacs,  Node: Modifier Keys,  Next: Function Keys,  Prev: Init Rebinding,  Up: Key Bindings

57.4.7 Modifier Keys
--------------------

The default key bindings in Emacs are set up so that modified
alphabetical characters are case-insensitive.  In other words, `C-A'
does the same thing as `C-a', and `M-A' does the same thing as `M-a'.
This concerns only alphabetical characters, and does not apply to
"shifted" versions of other keys; for instance, `C-@' is not the same
as `C-2'.

   A <Control>-modified alphabetical character is always considered
case-insensitive: Emacs always treats `C-A' as `C-a', `C-B' as `C-b',
and so forth.  The reason for this is historical.

   For all other modifiers, you can make the modified alphabetical
characters case-sensitive when you customize Emacs.  For instance, you
could make `M-a' and `M-A' run different commands.

   Although only the <Control> and <Meta> modifier keys are commonly
used, Emacs supports three other modifier keys.  These are called
<Super>, <Hyper> and <Alt>.  Few terminals provide ways to use these
modifiers; the key labeled <Alt> on most keyboards usually issues the
<Meta> modifier, not <Alt>.  The standard key bindings in Emacs do not
include any characters with these modifiers.  However, you can
customize Emacs to assign meanings to them.  The modifier bits are
labelled as `s-', `H-' and `A-' respectively.

   Even if your keyboard lacks these additional modifier keys, you can
enter it using `C-x @': `C-x @ h' adds the "hyper" flag to the next
character, `C-x @ s' adds the "super" flag, and `C-x @ a' adds the
"alt" flag.  For instance, `C-x @ h C-a' is a way to enter
`Hyper-Control-a'.  (Unfortunately, there is no way to add two
modifiers by using `C-x @' twice for the same character, because the
first one goes to work on the `C-x'.)


File: emacs,  Node: Function Keys,  Next: Named ASCII Chars,  Prev: Modifier Keys,  Up: Key Bindings

57.4.8 Rebinding Function Keys
------------------------------

Key sequences can contain function keys as well as ordinary characters.
Just as Lisp characters (actually integers) represent keyboard
characters, Lisp symbols represent function keys.  If the function key
has a word as its label, then that word is also the name of the
corresponding Lisp symbol.  Here are the conventional Lisp names for
common function keys:

`left', `up', `right', `down'
     Cursor arrow keys.

`begin', `end', `home', `next', `prior'
     Other cursor repositioning keys.

`select', `print', `execute', `backtab'
`insert', `undo', `redo', `clearline'
`insertline', `deleteline', `insertchar', `deletechar'
     Miscellaneous function keys.

`f1', `f2', ... `f35'
     Numbered function keys (across the top of the keyboard).

`kp-add', `kp-subtract', `kp-multiply', `kp-divide'
`kp-backtab', `kp-space', `kp-tab', `kp-enter'
`kp-separator', `kp-decimal', `kp-equal'
     Keypad keys (to the right of the regular keyboard), with names or
     punctuation.

`kp-0', `kp-1', ... `kp-9'
     Keypad keys with digits.

`kp-f1', `kp-f2', `kp-f3', `kp-f4'
     Keypad PF keys.

   These names are conventional, but some systems (especially when using
X) may use different names.  To make certain what symbol is used for a
given function key on your terminal, type `C-h c' followed by that key.

   *Note Init Rebinding::, for examples of binding function keys.

   Many keyboards have a "numeric keypad" on the right hand side.  The
numeric keys in the keypad double up as cursor motion keys, toggled by
a key labeled `Num Lock'.  By default, Emacs translates these keys to
the corresponding keys in the main keyboard.  For example, when `Num
Lock' is on, the key labeled `8' on the numeric keypad produces `kp-8',
which is translated to `8'; when `Num Lock' is off, the same key
produces `kp-up', which is translated to <UP>.  If you rebind a key
such as `8' or <UP>, it affects the equivalent keypad key too.
However, if you rebind a `kp-' key directly, that won't affect its
non-keypad equivalent.  Note that the modified keys are not translated:
for instance, if you hold down the <META> key while pressing the `8'
key on the numeric keypad, that generates `M-<kp-8>'.

   Emacs provides a convenient method for binding the numeric keypad
keys, using the variables `keypad-setup', `keypad-numlock-setup',
`keypad-shifted-setup', and `keypad-numlock-shifted-setup'.  These can
be found in the `keyboard' customization group (*note Easy
Customization::).  You can rebind the keys to perform other tasks, such
as issuing numeric prefix arguments.

