This is ../info/elisp, produced by makeinfo version 4.11 from
elisp.texi.

INFO-DIR-SECTION Emacs
START-INFO-DIR-ENTRY
* Elisp: (elisp).       The Emacs Lisp Reference Manual.
END-INFO-DIR-ENTRY

   This is edition 2.9 of the GNU Emacs Lisp Reference Manual,
corresponding to Emacs version 22.3.

   Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999,
2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008  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.2 or any later version published by the Free Software
     Foundation; with the Invariant Sections being "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 are free to copy and modify
     this GNU Manual. Buying copies from GNU Press supports the FSF in
     developing GNU and promoting software freedom."


File: elisp,  Node: Mode Line Variables,  Next: %-Constructs,  Prev: Mode Line Top,  Up: Mode Line Format

23.4.4 Variables Used in the Mode Line
--------------------------------------

This section describes variables incorporated by the standard value of
`mode-line-format' into the text of the mode line.  There is nothing
inherently special about these variables; any other variables could
have the same effects on the mode line if `mode-line-format''s value
were changed to use them.  However, various parts of Emacs set these
variables on the understanding that they will control parts of the mode
line; therefore, practically speaking, it is essential for the mode
line to use them.

 -- Variable: mode-line-mule-info
     This variable holds the value of the mode-line construct that
     displays information about the language environment, buffer coding
     system, and current input method.  *Note Non-ASCII Characters::.

 -- Variable: mode-line-modified
     This variable holds the value of the mode-line construct that
     displays whether the current buffer is modified.

     The default value of `mode-line-modified' is `("%1*%1+")'.  This
     means that the mode line displays `**' if the buffer is modified,
     `--' if the buffer is not modified, `%%' if the buffer is read
     only, and `%*' if the buffer is read only and modified.

     Changing this variable does not force an update of the mode line.

 -- Variable: mode-line-frame-identification
     This variable identifies the current frame.  The default value is
     `"  "' if you are using a window system which can show multiple
     frames, or `"-%F  "' on an ordinary terminal which shows only one
     frame at a time.

 -- Variable: mode-line-buffer-identification
     This variable identifies the buffer being displayed in the window.
     Its default value is `("%12b")', which displays the buffer name,
     padded with spaces to at least 12 columns.

 -- Variable: mode-line-position
     This variable indicates the position in the buffer.  Here is a
     simplified version of its default value.  The actual default value
     also specifies addition of the `help-echo' text property.

          ((-3 "%p")
           (size-indication-mode (8 " of %I"))
           (line-number-mode
            ((column-number-mode
              (10 " (%l,%c)")
              (6 " L%l")))
            ((column-number-mode
              (5 " C%c")))))

     This means that `mode-line-position' displays at least the buffer
     percentage and possibly the buffer size, the line number and the
     column number.

 -- Variable: vc-mode
     The variable `vc-mode', buffer-local in each buffer, records
     whether the buffer's visited file is maintained with version
     control, and, if so, which kind.  Its value is a string that
     appears in the mode line, or `nil' for no version control.

 -- Variable: mode-line-modes
     This variable displays the buffer's major and minor modes.  Here
     is a simplified version of its default value.  The real default
     value also specifies addition of text properties.

          ("%[(" mode-name
           mode-line-process minor-mode-alist
           "%n" ")%]--")

     So `mode-line-modes' normally also displays the recursive editing
     level, information on the process status and whether narrowing is
     in effect.

   The following three variables are used in `mode-line-modes':

 -- Variable: mode-name
     This buffer-local variable holds the "pretty" name of the current
     buffer's major mode.  Each major mode should set this variable so
     that the mode name will appear in the mode line.

 -- Variable: mode-line-process
     This buffer-local variable contains the mode-line information on
     process status in modes used for communicating with subprocesses.
     It is displayed immediately following the major mode name, with no
     intervening space.  For example, its value in the `*shell*' buffer
     is `(":%s")', which allows the shell to display its status along
     with the major mode as: `(Shell:run)'.  Normally this variable is
     `nil'.

 -- Variable: minor-mode-alist
     This variable holds an association list whose elements specify how
     the mode line should indicate that a minor mode is active.  Each
     element of the `minor-mode-alist' should be a two-element list:

          (MINOR-MODE-VARIABLE MODE-LINE-STRING)

     More generally, MODE-LINE-STRING can be any mode-line spec.  It
     appears in the mode line when the value of MINOR-MODE-VARIABLE is
     non-`nil', and not otherwise.  These strings should begin with
     spaces so that they don't run together.  Conventionally, the
     MINOR-MODE-VARIABLE for a specific mode is set to a non-`nil'
     value when that minor mode is activated.

     `minor-mode-alist' itself is not buffer-local.  Each variable
     mentioned in the alist should be buffer-local if its minor mode
     can be enabled separately in each buffer.

 -- Variable: global-mode-string
     This variable holds a mode-line spec that, by default, appears in
     the mode line just after the `which-func-mode' minor mode if set,
     else after `mode-line-modes'.  The command `display-time' sets
     `global-mode-string' to refer to the variable
     `display-time-string', which holds a string containing the time
     and load information.

     The `%M' construct substitutes the value of `global-mode-string',
     but that is obsolete, since the variable is included in the mode
     line from `mode-line-format'.

   The variable `default-mode-line-format' is where `mode-line-format'
usually gets its value:

 -- Variable: default-mode-line-format
     This variable holds the default `mode-line-format' for buffers
     that do not override it.  This is the same as `(default-value
     'mode-line-format)'.

     Here is a simplified version of the default value of
     `default-mode-line-format'.  The real default value also specifies
     addition of text properties.

          ("-"
           mode-line-mule-info
           mode-line-modified
           mode-line-frame-identification
           mode-line-buffer-identification
           "   "
           mode-line-position
           (vc-mode vc-mode)
           "   "
           mode-line-modes
           (which-func-mode ("" which-func-format "--"))
           (global-mode-string ("--" global-mode-string))
           "-%-")


File: elisp,  Node: %-Constructs,  Next: Properties in Mode,  Prev: Mode Line Variables,  Up: Mode Line Format

23.4.5 `%'-Constructs in the Mode Line
--------------------------------------

Strings used as mode-line constructs can use certain `%'-constructs to
substitute various kinds of data.  Here is a list of the defined
`%'-constructs, and what they mean.  In any construct except `%%', you
can add a decimal integer after the `%' to specify a minimum field
width.  If the width is less, the field is padded with spaces to the
right.

`%b'
     The current buffer name, obtained with the `buffer-name' function.
     *Note Buffer Names::.

`%c'
     The current column number of point.

`%e'
     When Emacs is nearly out of memory for Lisp objects, a brief
     message saying so.  Otherwise, this is empty.

`%f'
     The visited file name, obtained with the `buffer-file-name'
     function.  *Note Buffer File Name::.

`%F'
     The title (only on a window system) or the name of the selected
     frame.  *Note Basic Parameters::.

`%i'
     The size of the accessible part of the current buffer; basically
     `(- (point-max) (point-min))'.

`%I'
     Like `%i', but the size is printed in a more readable way by using
     `k' for 10^3, `M' for 10^6, `G' for 10^9, etc., to abbreviate.

`%l'
     The current line number of point, counting within the accessible
     portion of the buffer.

`%n'
     `Narrow' when narrowing is in effect; nothing otherwise (see
     `narrow-to-region' in *note Narrowing::).

`%p'
     The percentage of the buffer text above the *top* of window, or
     `Top', `Bottom' or `All'.  Note that the default mode-line
     specification truncates this to three characters.

`%P'
     The percentage of the buffer text that is above the *bottom* of
     the window (which includes the text visible in the window, as well
     as the text above the top), plus `Top' if the top of the buffer is
     visible on screen; or `Bottom' or `All'.

`%s'
     The status of the subprocess belonging to the current buffer,
     obtained with `process-status'.  *Note Process Information::.

`%t'
     Whether the visited file is a text file or a binary file.  This is
     a meaningful distinction only on certain operating systems (*note
     MS-DOS File Types::).

`%z'
     The mnemonics of keyboard, terminal, and buffer coding systems.

`%Z'
     Like `%z', but including the end-of-line format.

`%*'
     `%' if the buffer is read only (see `buffer-read-only');
     `*' if the buffer is modified (see `buffer-modified-p');
     `-' otherwise.  *Note Buffer Modification::.

`%+'
     `*' if the buffer is modified (see `buffer-modified-p');
     `%' if the buffer is read only (see `buffer-read-only');
     `-' otherwise.  This differs from `%*' only for a modified
     read-only buffer.  *Note Buffer Modification::.

`%&'
     `*' if the buffer is modified, and `-' otherwise.

`%['
     An indication of the depth of recursive editing levels (not
     counting minibuffer levels): one `[' for each editing level.
     *Note Recursive Editing::.

`%]'
     One `]' for each recursive editing level (not counting minibuffer
     levels).

`%-'
     Dashes sufficient to fill the remainder of the mode line.

`%%'
     The character `%'--this is how to include a literal `%' in a
     string in which `%'-constructs are allowed.

   The following two `%'-constructs are still supported, but they are
obsolete, since you can get the same results with the variables
`mode-name' and `global-mode-string'.

`%m'
     The value of `mode-name'.

`%M'
     The value of `global-mode-string'.


File: elisp,  Node: Properties in Mode,  Next: Header Lines,  Prev: %-Constructs,  Up: Mode Line Format

23.4.6 Properties in the Mode Line
----------------------------------

Certain text properties are meaningful in the mode line.  The `face'
property affects the appearance of text; the `help-echo' property
associates help strings with the text, and `local-map' can make the
text mouse-sensitive.

   There are four ways to specify text properties for text in the mode
line:

  1. Put a string with a text property directly into the mode-line data
     structure.

  2. Put a text property on a mode-line %-construct such as `%12b'; then
     the expansion of the %-construct will have that same text property.

  3. Use a `(:propertize ELT PROPS...)' construct to give ELT a text
     property specified by PROPS.

  4. Use a list containing `:eval FORM' in the mode-line data
     structure, and make FORM evaluate to a string that has a text
     property.

   You can use the `local-map' property to specify a keymap.  This
keymap only takes real effect for mouse clicks; binding character keys
and function keys to it has no effect, since it is impossible to move
point into the mode line.

   When the mode line refers to a variable which does not have a
non-`nil' `risky-local-variable' property, any text properties given or
specified within that variable's values are ignored.  This is because
such properties could otherwise specify functions to be called, and
those functions could come from file local variables.


File: elisp,  Node: Header Lines,  Next: Emulating Mode Line,  Prev: Properties in Mode,  Up: Mode Line Format

23.4.7 Window Header Lines
--------------------------

A window can have a "header line" at the top, just as it can have a
mode line at the bottom.  The header line feature works just like the
mode-line feature, except that it's controlled by different variables.

 -- Variable: header-line-format
     This variable, local in every buffer, specifies how to display the
     header line, for windows displaying the buffer.  The format of the
     value is the same as for `mode-line-format' (*note Mode Line
     Data::).

 -- Variable: default-header-line-format
     This variable holds the default `header-line-format' for buffers
     that do not override it.  This is the same as `(default-value
     'header-line-format)'.

     It is normally `nil', so that ordinary buffers have no header line.

   A window that is just one line tall never displays a header line.  A
window that is two lines tall cannot display both a mode line and a
header line at once; if it has a mode line, then it does not display a
header line.


File: elisp,  Node: Emulating Mode Line,  Prev: Header Lines,  Up: Mode Line Format

23.4.8 Emulating Mode-Line Formatting
-------------------------------------

You can use the function `format-mode-line' to compute the text that
would appear in a mode line or header line based on a certain mode-line
specification.

 -- Function: format-mode-line format &optional face window buffer
     This function formats a line of text according to FORMAT as if it
     were generating the mode line for WINDOW, but instead of
     displaying the text in the mode line or the header line, it returns
     the text as a string.  The argument WINDOW defaults to the
     selected window.  If BUFFER is non-`nil', all the information used
     is taken from BUFFER; by default, it comes from WINDOW's buffer.

     The value string normally has text properties that correspond to
     the faces, keymaps, etc., that the mode line would have.  And any
     character for which no `face' property is specified gets a default
     value which is usually FACE.  (If FACE is `t', that stands for
     either `mode-line' if WINDOW is selected, otherwise
     `mode-line-inactive'.  If FACE is `nil' or omitted, that stands
     for no face property.)

     However, if FACE is an integer, the value has no text properties.

     For example, `(format-mode-line header-line-format)' returns the
     text that would appear in the selected window's header line (`""'
     if it has no header line).  `(format-mode-line header-line-format
     'header-line)' returns the same text, with each character carrying
     the face that it will have in the header line itself.


File: elisp,  Node: Imenu,  Next: Font Lock Mode,  Prev: Mode Line Format,  Up: Modes

23.5 Imenu
==========

"Imenu" is a feature that lets users select a definition or section in
the buffer, from a menu which lists all of them, to go directly to that
location in the buffer.  Imenu works by constructing a buffer index
which lists the names and buffer positions of the definitions, or other
named portions of the buffer; then the user can choose one of them and
move point to it.  Major modes can add a menu bar item to use Imenu
using `imenu-add-to-menubar'.

 -- Function: imenu-add-to-menubar name
     This function defines a local menu bar item named NAME to run
     Imenu.

   The user-level commands for using Imenu are described in the Emacs
Manual (*note Imenu: (emacs)Imenu.).  This section explains how to
customize Imenu's method of finding definitions or buffer portions for
a particular major mode.

   The usual and simplest way is to set the variable
`imenu-generic-expression':

 -- Variable: imenu-generic-expression
     This variable, if non-`nil', is a list that specifies regular
     expressions for finding definitions for Imenu.  Simple elements of
     `imenu-generic-expression' look like this:

          (MENU-TITLE REGEXP INDEX)

     Here, if MENU-TITLE is non-`nil', it says that the matches for
     this element should go in a submenu of the buffer index;
     MENU-TITLE itself specifies the name for the submenu.  If
     MENU-TITLE is `nil', the matches for this element go directly in
     the top level of the buffer index.

     The second item in the list, REGEXP, is a regular expression
     (*note Regular Expressions::); anything in the buffer that it
     matches is considered a definition, something to mention in the
     buffer index.  The third item, INDEX, is a non-negative integer
     that indicates which subexpression in REGEXP matches the
     definition's name.

     An element can also look like this:

          (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)

     Each match for this element creates an index item, and when the
     index item is selected by the user, it calls FUNCTION with
     arguments consisting of the item name, the buffer position, and
     ARGUMENTS.

     For Emacs Lisp mode, `imenu-generic-expression' could look like
     this:

          ((nil "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\
          \\s-+\\([-A-Za-z0-9+]+\\)" 2)
           ("*Vars*" "^\\s-*(def\\(var\\|const\\)\
          \\s-+\\([-A-Za-z0-9+]+\\)" 2)
           ("*Types*"
            "^\\s-*\
          (def\\(type\\|struct\\|class\\|ine-condition\\)\
          \\s-+\\([-A-Za-z0-9+]+\\)" 2))

     Setting this variable makes it buffer-local in the current buffer.

 -- Variable: imenu-case-fold-search
     This variable controls whether matching against the regular
     expressions in the value of `imenu-generic-expression' is
     case-sensitive: `t', the default, means matching should ignore
     case.

     Setting this variable makes it buffer-local in the current buffer.

 -- Variable: imenu-syntax-alist
     This variable is an alist of syntax table modifiers to use while
     processing `imenu-generic-expression', to override the syntax table
     of the current buffer.  Each element should have this form:

          (CHARACTERS . SYNTAX-DESCRIPTION)

     The CAR, CHARACTERS, can be either a character or a string.  The
     element says to give that character or characters the syntax
     specified by SYNTAX-DESCRIPTION, which is passed to
     `modify-syntax-entry' (*note Syntax Table Functions::).

     This feature is typically used to give word syntax to characters
     which normally have symbol syntax, and thus to simplify
     `imenu-generic-expression' and speed up matching.  For example,
     Fortran mode uses it this way:

          (setq imenu-syntax-alist '(("_$" . "w")))

     The `imenu-generic-expression' regular expressions can then use
     `\\sw+' instead of `\\(\\sw\\|\\s_\\)+'.  Note that this technique
     may be inconvenient when the mode needs to limit the initial
     character of a name to a smaller set of characters than are
     allowed in the rest of a name.

     Setting this variable makes it buffer-local in the current buffer.

   Another way to customize Imenu for a major mode is to set the
variables `imenu-prev-index-position-function' and
`imenu-extract-index-name-function':

 -- Variable: imenu-prev-index-position-function
     If this variable is non-`nil', its value should be a function that
     finds the next "definition" to put in the buffer index, scanning
     backward in the buffer from point.  It should return `nil' if it
     doesn't find another "definition" before point.  Otherwise it
     should leave point at the place it finds a "definition" and return
     any non-`nil' value.

     Setting this variable makes it buffer-local in the current buffer.

 -- Variable: imenu-extract-index-name-function
     If this variable is non-`nil', its value should be a function to
     return the name for a definition, assuming point is in that
     definition as the `imenu-prev-index-position-function' function
     would leave it.

     Setting this variable makes it buffer-local in the current buffer.

   The last way to customize Imenu for a major mode is to set the
variable `imenu-create-index-function':

 -- Variable: imenu-create-index-function
     This variable specifies the function to use for creating a buffer
     index.  The function should take no arguments, and return an index
     alist for the current buffer.  It is called within
     `save-excursion', so where it leaves point makes no difference.

     The index alist can have three types of elements.  Simple elements
     look like this:

          (INDEX-NAME . INDEX-POSITION)

     Selecting a simple element has the effect of moving to position
     INDEX-POSITION in the buffer.  Special elements look like this:

          (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)

     Selecting a special element performs:

          (funcall FUNCTION
                   INDEX-NAME INDEX-POSITION ARGUMENTS...)

     A nested sub-alist element looks like this:

          (MENU-TITLE SUB-ALIST)

     It creates the submenu MENU-TITLE specified by SUB-ALIST.

     The default value of `imenu-create-index-function' is
     `imenu-default-create-index-function'.  This function calls the
     value of `imenu-prev-index-position-function' and the value of
     `imenu-extract-index-name-function' to produce the index alist.
     However, if either of these two variables is `nil', the default
     function uses `imenu-generic-expression' instead.

     Setting this variable makes it buffer-local in the current buffer.


File: elisp,  Node: Font Lock Mode,  Next: Desktop Save Mode,  Prev: Imenu,  Up: Modes

23.6 Font Lock Mode
===================

"Font Lock mode" is a feature that automatically attaches `face'
properties to certain parts of the buffer based on their syntactic
role.  How it parses the buffer depends on the major mode; most major
modes define syntactic criteria for which faces to use in which
contexts.  This section explains how to customize Font Lock for a
particular major mode.

   Font Lock mode finds text to highlight in two ways: through
syntactic parsing based on the syntax table, and through searching
(usually for regular expressions).  Syntactic fontification happens
first; it finds comments and string constants and highlights them.
Search-based fontification happens second.

* Menu:

* Font Lock Basics::            Overview of customizing Font Lock.
* Search-based Fontification::  Fontification based on regexps.
* Customizing Keywords::        Customizing search-based fontification.
* Other Font Lock Variables::   Additional customization facilities.
* Levels of Font Lock::         Each mode can define alternative levels
                                  so that the user can select more or less.
* Precalculated Fontification:: How Lisp programs that produce the buffer
                                  contents can also specify how to fontify it.
* Faces for Font Lock::         Special faces specifically for Font Lock.
* Syntactic Font Lock::         Fontification based on syntax tables.
* Setting Syntax Properties::   Defining character syntax based on context
                                  using the Font Lock mechanism.
* Multiline Font Lock::         How to coerce Font Lock into properly
                                  highlighting multiline constructs.


File: elisp,  Node: Font Lock Basics,  Next: Search-based Fontification,  Up: Font Lock Mode

23.6.1 Font Lock Basics
-----------------------

There are several variables that control how Font Lock mode highlights
text.  But major modes should not set any of these variables directly.
Instead, they should set `font-lock-defaults' as a buffer-local
variable.  The value assigned to this variable is used, if and when Font
Lock mode is enabled, to set all the other variables.

 -- Variable: font-lock-defaults
     This variable is set by major modes, as a buffer-local variable, to
     specify how to fontify text in that mode.  It automatically becomes
     buffer-local when you set it.  If its value is `nil', Font-Lock
     mode does no highlighting, and you can use the `Faces' menu (under
     `Edit' and then `Text Properties' in the menu bar) to assign faces
     explicitly to text in the buffer.

     If non-`nil', the value should look like this:

          (KEYWORDS [KEYWORDS-ONLY [CASE-FOLD
           [SYNTAX-ALIST [SYNTAX-BEGIN OTHER-VARS...]]]])

     The first element, KEYWORDS, indirectly specifies the value of
     `font-lock-keywords' which directs search-based fontification.  It
     can be a symbol, a variable or a function whose value is the list
     to use for `font-lock-keywords'.  It can also be a list of several
     such symbols, one for each possible level of fontification.  The
     first symbol specifies how to do level 1 fontification, the second
     symbol how to do level 2, and so on.  *Note Levels of Font Lock::.

     The second element, KEYWORDS-ONLY, specifies the value of the
     variable `font-lock-keywords-only'.  If this is omitted or `nil',
     syntactic fontification (of strings and comments) is also
     performed.  If this is non-`nil', such fontification is not
     performed.  *Note Syntactic Font Lock::.

     The third element, CASE-FOLD, specifies the value of
     `font-lock-keywords-case-fold-search'.  If it is non-`nil', Font
     Lock mode ignores case when searching as directed by
     `font-lock-keywords'.

     If the fourth element, SYNTAX-ALIST, is non-`nil', it should be a
     list of cons cells of the form `(CHAR-OR-STRING . STRING)'.  These
     are used to set up a syntax table for syntactic fontification
     (*note Syntax Table Functions::).  The resulting syntax table is
     stored in `font-lock-syntax-table'.

     The fifth element, SYNTAX-BEGIN, specifies the value of
     `font-lock-beginning-of-syntax-function'.  We recommend setting
     this variable to `nil' and using `syntax-begin-function' instead.

     All the remaining elements (if any) are collectively called
     OTHER-VARS.  Each of these elements should have the form
     `(VARIABLE . VALUE)'--which means, make VARIABLE buffer-local and
     then set it to VALUE.  You can use these OTHER-VARS to set other
     variables that affect fontification, aside from those you can
     control with the first five elements.  *Note Other Font Lock
     Variables::.

   If your mode fontifies text explicitly by adding `font-lock-face'
properties, it can specify `(nil t)' for `font-lock-defaults' to turn
off all automatic fontification.  However, this is not required; it is
possible to fontify some things using `font-lock-face' properties and
set up automatic fontification for other parts of the text.


File: elisp,  Node: Search-based Fontification,  Next: Customizing Keywords,  Prev: Font Lock Basics,  Up: Font Lock Mode

23.6.2 Search-based Fontification
---------------------------------

The most important variable for customizing Font Lock mode is
`font-lock-keywords'.  It specifies the search criteria for
search-based fontification.  You should specify the value of this
variable with KEYWORDS in `font-lock-defaults'.

 -- Variable: font-lock-keywords
     This variable's value is a list of the keywords to highlight.  Be
     careful when composing regular expressions for this list; a poorly
     written pattern can dramatically slow things down!

   Each element of `font-lock-keywords' specifies how to find certain
cases of text, and how to highlight those cases.  Font Lock mode
processes the elements of `font-lock-keywords' one by one, and for each
element, it finds and handles all matches.  Ordinarily, once part of
the text has been fontified already, this cannot be overridden by a
subsequent match in the same text; but you can specify different
behavior using the OVERRIDE element of a SUBEXP-HIGHLIGHTER.

   Each element of `font-lock-keywords' should have one of these forms:

`REGEXP'
     Highlight all matches for REGEXP using `font-lock-keyword-face'.
     For example,

          ;; Highlight occurrences of the word `foo'
          ;; using `font-lock-keyword-face'.
          "\\<foo\\>"

     The function `regexp-opt' (*note Regexp Functions::) is useful for
     calculating optimal regular expressions to match a number of
     different keywords.

`FUNCTION'
     Find text by calling FUNCTION, and highlight the matches it finds
     using `font-lock-keyword-face'.

     When FUNCTION is called, it receives one argument, the limit of
     the search; it should begin searching at point, and not search
     beyond the limit.  It should return non-`nil' if it succeeds, and
     set the match data to describe the match that was found.
     Returning `nil' indicates failure of the search.

     Fontification will call FUNCTION repeatedly with the same limit,
     and with point where the previous invocation left it, until
     FUNCTION fails.  On failure, FUNCTION need not reset point in any
     particular way.

`(MATCHER . SUBEXP)'
     In this kind of element, MATCHER is either a regular expression or
     a function, as described above.  The CDR, SUBEXP, specifies which
     subexpression of MATCHER should be highlighted (instead of the
     entire text that MATCHER matched).

          ;; Highlight the `bar' in each occurrence of `fubar',
          ;; using `font-lock-keyword-face'.
          ("fu\\(bar\\)" . 1)

     If you use `regexp-opt' to produce the regular expression MATCHER,
     you can use `regexp-opt-depth' (*note Regexp Functions::) to
     calculate the value for SUBEXP.

`(MATCHER . FACESPEC)'
     In this kind of element, FACESPEC is an expression whose value
     specifies the face to use for highlighting.  In the simplest case,
     FACESPEC is a Lisp variable (a symbol) whose value is a face name.

          ;; Highlight occurrences of `fubar',
          ;; using the face which is the value of `fubar-face'.
          ("fubar" . fubar-face)

     However, FACESPEC can also evaluate to a list of this form:

          (face FACE PROP1 VAL1 PROP2 VAL2...)

     to specify the face FACE and various additional text properties to
     put on the text that matches.  If you do this, be sure to add the
     other text property names that you set in this way to the value of
     `font-lock-extra-managed-props' so that the properties will also
     be cleared out when they are no longer appropriate.  Alternatively,
     you can set the variable `font-lock-unfontify-region-function' to
     a function that clears these properties.  *Note Other Font Lock
     Variables::.

`(MATCHER . SUBEXP-HIGHLIGHTER)'
     In this kind of element, SUBEXP-HIGHLIGHTER is a list which
     specifies how to highlight matches found by MATCHER.  It has the
     form:

          (SUBEXP FACESPEC [[OVERRIDE [LAXMATCH]])

     The CAR, SUBEXP, is an integer specifying which subexpression of
     the match to fontify (0 means the entire matching text).  The
     second subelement, FACESPEC, is an expression whose value
     specifies the face, as described above.

     The last two values in SUBEXP-HIGHLIGHTER, OVERRIDE and LAXMATCH,
     are optional flags.  If OVERRIDE is `t', this element can override
     existing fontification made by previous elements of
     `font-lock-keywords'.  If it is `keep', then each character is
     fontified if it has not been fontified already by some other
     element.  If it is `prepend', the face specified by FACESPEC is
     added to the beginning of the `font-lock-face' property.  If it is
     `append', the face is added to the end of the `font-lock-face'
     property.

     If LAXMATCH is non-`nil', it means there should be no error if
     there is no subexpression numbered SUBEXP in MATCHER.  Obviously,
     fontification of the subexpression numbered SUBEXP will not occur.
     However, fontification of other subexpressions (and other regexps)
     will continue.  If LAXMATCH is `nil', and the specified
     subexpression is missing, then an error is signaled which
     terminates search-based fontification.

     Here are some examples of elements of this kind, and what they do:

          ;; Highlight occurrences of either `foo' or `bar', using
          ;; `foo-bar-face', even if they have already been highlighted.
          ;; `foo-bar-face' should be a variable whose value is a face.
          ("foo\\|bar" 0 foo-bar-face t)

          ;; Highlight the first subexpression within each occurrence
          ;; that the function `fubar-match' finds,
          ;; using the face which is the value of `fubar-face'.
          (fubar-match 1 fubar-face)

`(MATCHER . ANCHORED-HIGHLIGHTER)'
     In this kind of element, ANCHORED-HIGHLIGHTER specifies how to
     highlight text that follows a match found by MATCHER.  So a match
     found by MATCHER acts as the anchor for further searches specified
     by ANCHORED-HIGHLIGHTER.  ANCHORED-HIGHLIGHTER is a list of the
     following form:

          (ANCHORED-MATCHER PRE-FORM POST-FORM
                                  SUBEXP-HIGHLIGHTERS...)

     Here, ANCHORED-MATCHER, like MATCHER, is either a regular
     expression or a function.  After a match of MATCHER is found,
     point is at the end of the match.  Now, Font Lock evaluates the
     form PRE-FORM.  Then it searches for matches of ANCHORED-MATCHER
     and uses SUBEXP-HIGHLIGHTERS to highlight these.  A
     SUBEXP-HIGHLIGHTER is as described above.  Finally, Font Lock
     evaluates POST-FORM.

     The forms PRE-FORM and POST-FORM can be used to initialize before,
     and cleanup after, ANCHORED-MATCHER is used.  Typically, PRE-FORM
     is used to move point to some position relative to the match of
     MATCHER, before starting with ANCHORED-MATCHER.  POST-FORM might
     be used to move back, before resuming with MATCHER.

     After Font Lock evaluates PRE-FORM, it does not search for
     ANCHORED-MATCHER beyond the end of the line.  However, if PRE-FORM
     returns a buffer position that is greater than the position of
     point after PRE-FORM is evaluated, then the position returned by
     PRE-FORM is used as the limit of the search instead.  It is
     generally a bad idea to return a position greater than the end of
     the line; in other words, the ANCHORED-MATCHER search should not
     span lines.

     For example,

          ;; Highlight occurrences of the word `item' following
          ;; an occurrence of the word `anchor' (on the same line)
          ;; in the value of `item-face'.
          ("\\<anchor\\>" "\\<item\\>" nil nil (0 item-face))

     Here, PRE-FORM and POST-FORM are `nil'.  Therefore searching for
     `item' starts at the end of the match of `anchor', and searching
     for subsequent instances of `anchor' resumes from where searching
     for `item' concluded.

`(MATCHER HIGHLIGHTERS...)'
     This sort of element specifies several HIGHLIGHTER lists for a
     single MATCHER.  A HIGHLIGHTER list can be of the type
     SUBEXP-HIGHLIGHTER or ANCHORED-HIGHLIGHTER as described above.

     For example,

          ;; Highlight occurrences of the word `anchor' in the value
          ;; of `anchor-face', and subsequent occurrences of the word
          ;; `item' (on the same line) in the value of `item-face'.
          ("\\<anchor\\>" (0 anchor-face)
                          ("\\<item\\>" nil nil (0 item-face)))

`(eval . FORM)'
     Here FORM is an expression to be evaluated the first time this
     value of `font-lock-keywords' is used in a buffer.  Its value
     should have one of the forms described in this table.

   *Warning:* Do not design an element of `font-lock-keywords' to match
text which spans lines; this does not work reliably.  For details, see
*Note Multiline Font Lock::.

   You can use CASE-FOLD in `font-lock-defaults' to specify the value
of `font-lock-keywords-case-fold-search' which says whether
search-based fontification should be case-insensitive.

 -- Variable: font-lock-keywords-case-fold-search
     Non-`nil' means that regular expression matching for the sake of
     `font-lock-keywords' should be case-insensitive.


File: elisp,  Node: Customizing Keywords,  Next: Other Font Lock Variables,  Prev: Search-based Fontification,  Up: Font Lock Mode

23.6.3 Customizing Search-Based Fontification
---------------------------------------------

You can use `font-lock-add-keywords' to add additional search-based
fontification rules to a major mode, and `font-lock-remove-keywords' to
removes rules.

 -- Function: font-lock-add-keywords mode keywords &optional how
     This function adds highlighting KEYWORDS, for the current buffer
     or for major mode MODE.  The argument KEYWORDS should be a list
     with the same format as the variable `font-lock-keywords'.

     If MODE is a symbol which is a major mode command name, such as
     `c-mode', the effect is that enabling Font Lock mode in MODE will
     add KEYWORDS to `font-lock-keywords'.  Calling with a non-`nil'
     value of MODE is correct only in your `~/.emacs' file.

     If MODE is `nil', this function adds KEYWORDS to
     `font-lock-keywords' in the current buffer.  This way of calling
     `font-lock-add-keywords' is usually used in mode hook functions.

     By default, KEYWORDS are added at the beginning of
     `font-lock-keywords'.  If the optional argument HOW is `set', they
     are used to replace the value of `font-lock-keywords'.  If HOW is
     any other non-`nil' value, they are added at the end of
     `font-lock-keywords'.

     Some modes provide specialized support you can use in additional
     highlighting patterns.  See the variables
     `c-font-lock-extra-types', `c++-font-lock-extra-types', and
     `java-font-lock-extra-types', for example.

     *Warning:* major mode functions must not call
     `font-lock-add-keywords' under any circumstances, either directly
     or indirectly, except through their mode hooks.  (Doing so would
     lead to incorrect behavior for some minor modes.)  They should set
     up their rules for search-based fontification by setting
     `font-lock-keywords'.

 -- Function: font-lock-remove-keywords mode keywords
     This function removes KEYWORDS from `font-lock-keywords' for the
     current buffer or for major mode MODE.  As in
     `font-lock-add-keywords', MODE should be a major mode command name
     or `nil'.  All the caveats and requirements for
     `font-lock-add-keywords' apply here too.

   For example, this code

     (font-lock-add-keywords 'c-mode
      '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
        ("\\<\\(and\\|or\\|not\\)\\>" . font-lock-keyword-face)))

adds two fontification patterns for C mode: one to fontify the word
`FIXME', even in comments, and another to fontify the words `and', `or'
and `not' as keywords.

That example affects only C mode proper.  To add the same patterns to C
mode _and_ all modes derived from it, do this instead:

     (add-hook 'c-mode-hook
      (lambda ()
       (font-lock-add-keywords nil
        '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
          ("\\<\\(and\\|or\\|not\\)\\>" .
           font-lock-keyword-face)))))


File: elisp,  Node: Other Font Lock Variables,  Next: Levels of Font Lock,  Prev: Customizing Keywords,  Up: Font Lock Mode

23.6.4 Other Font Lock Variables
--------------------------------

This section describes additional variables that a major mode can set
by means of OTHER-VARS in `font-lock-defaults' (*note Font Lock
Basics::).

 -- Variable: font-lock-mark-block-function
     If this variable is non-`nil', it should be a function that is
     called with no arguments, to choose an enclosing range of text for
     refontification for the command `M-o M-o'
     (`font-lock-fontify-block').

     The function should report its choice by placing the region around
     it.  A good choice is a range of text large enough to give proper
     results, but not too large so that refontification becomes slow.
     Typical values are `mark-defun' for programming modes or
     `mark-paragraph' for textual modes.

 -- Variable: font-lock-extra-managed-props
     This variable specifies additional properties (other than
     `font-lock-face') that are being managed by Font Lock mode.  It is
     used by `font-lock-default-unfontify-region', which normally only
     manages the `font-lock-face' property.  If you want Font Lock to
     manage other properties as well, you must specify them in a
     FACESPEC in `font-lock-keywords' as well as add them to this list.
     *Note Search-based Fontification::.

 -- Variable: font-lock-fontify-buffer-function
     Function to use for fontifying the buffer.  The default value is
     `font-lock-default-fontify-buffer'.

 -- Variable: font-lock-unfontify-buffer-function
     Function to use for unfontifying the buffer.  This is used when
     turning off Font Lock mode.  The default value is
     `font-lock-default-unfontify-buffer'.

 -- Variable: font-lock-fontify-region-function
     Function to use for fontifying a region.  It should take two
     arguments, the beginning and end of the region, and an optional
     third argument VERBOSE.  If VERBOSE is non-`nil', the function
     should print status messages.  The default value is
     `font-lock-default-fontify-region'.

 -- Variable: font-lock-unfontify-region-function
     Function to use for unfontifying a region.  It should take two
     arguments, the beginning and end of the region.  The default value
     is `font-lock-default-unfontify-region'.


File: elisp,  Node: Levels of Font Lock,  Next: Precalculated Fontification,  Prev: Other Font Lock Variables,  Up: Font Lock Mode

23.6.5 Levels of Font Lock
--------------------------

Many major modes offer three different levels of fontification.  You
can define multiple levels by using a list of symbols for KEYWORDS in
`font-lock-defaults'.  Each symbol specifies one level of
fontification; it is up to the user to choose one of these levels.  The
chosen level's symbol value is used to initialize `font-lock-keywords'.

   Here are the conventions for how to define the levels of
fontification:

   * Level 1: highlight function declarations, file directives (such as
     include or import directives), strings and comments.  The idea is
     speed, so only the most important and top-level components are
     fontified.

   * Level 2: in addition to level 1, highlight all language keywords,
     including type names that act like keywords, as well as named
     constant values.  The idea is that all keywords (either syntactic
     or semantic) should be fontified appropriately.

   * Level 3: in addition to level 2, highlight the symbols being
     defined in function and variable declarations, and all builtin
     function names, wherever they appear.


File: elisp,  Node: Precalculated Fontification,  Next: Faces for Font Lock,  Prev: Levels of Font Lock,  Up: Font Lock Mode

23.6.6 Precalculated Fontification
----------------------------------

In addition to using `font-lock-defaults' for search-based
fontification, you may use the special character property
`font-lock-face' (*note Special Properties::).  This property acts just
like the explicit `face' property, but its activation is toggled when
the user calls `M-x font-lock-mode'.  Using `font-lock-face' is
especially convenient for special modes which construct their text
programmatically, such as `list-buffers' and `occur'.

   If your mode does not use any of the other machinery of Font Lock
(i.e. it only uses the `font-lock-face' property), it should not set
the variable `font-lock-defaults'.


File: elisp,  Node: Faces for Font Lock,  Next: Syntactic Font Lock,  Prev: Precalculated Fontification,  Up: Font Lock Mode

23.6.7 Faces for Font Lock
--------------------------

You can make Font Lock mode use any face, but several faces are defined
specifically for Font Lock mode.  Each of these symbols is both a face
name, and a variable whose default value is the symbol itself.  Thus,
the default value of `font-lock-comment-face' is
`font-lock-comment-face'.  This means you can write
`font-lock-comment-face' in a context such as `font-lock-keywords'
where a face-name-valued expression is used.

`font-lock-comment-face'
     Used (typically) for comments.

`font-lock-comment-delimiter-face'
     Used (typically) for comments delimiters.

`font-lock-doc-face'
     Used (typically) for documentation strings in the code.

`font-lock-string-face'
     Used (typically) for string constants.

`font-lock-keyword-face'
     Used (typically) for keywords--names that have special syntactic
     significance, like `for' and `if' in C.

`font-lock-builtin-face'
     Used (typically) for built-in function names.

`font-lock-function-name-face'
     Used (typically) for the name of a function being defined or
     declared, in a function definition or declaration.

`font-lock-variable-name-face'
     Used (typically) for the name of a variable being defined or
     declared, in a variable definition or declaration.

`font-lock-type-face'
     Used (typically) for names of user-defined data types, where they
     are defined and where they are used.

`font-lock-constant-face'
     Used (typically) for constant names.

`font-lock-preprocessor-face'
     Used (typically) for preprocessor commands.

`font-lock-negation-char-face'
     Used (typically) for easily-overlooked negation characters.

`font-lock-warning-face'
     Used (typically) for constructs that are peculiar, or that greatly
     change the meaning of other text.  For example, this is used for
     `;;;###autoload' cookies in Emacs Lisp, and for `#error'
     directives in C.


File: elisp,  Node: Syntactic Font Lock,  Next: Setting Syntax Properties,  Prev: Faces for Font Lock,  Up: Font Lock Mode

23.6.8 Syntactic Font Lock
--------------------------

Syntactic fontification uses the syntax table to find comments and
string constants (*note Syntax Tables::).  It highlights them using
`font-lock-comment-face' and `font-lock-string-face' (*note Faces for
Font Lock::), or whatever `font-lock-syntactic-face-function' chooses.
There are several variables that affect syntactic fontification; you
should set them by means of `font-lock-defaults' (*note Font Lock
Basics::).

 -- Variable: font-lock-keywords-only
     Non-`nil' means Font Lock should not do syntactic fontification;
     it should only fontify based on `font-lock-keywords'.  The normal
     way for a mode to set this variable to `t' is with KEYWORDS-ONLY
     in `font-lock-defaults'.

 -- Variable: font-lock-syntax-table
     This variable holds the syntax table to use for fontification of
     comments and strings.  Specify it using SYNTAX-ALIST in
     `font-lock-defaults'.  If this is `nil', fontification uses the
     buffer's syntax table.

 -- Variable: font-lock-beginning-of-syntax-function
     If this variable is non-`nil', it should be a function to move
     point back to a position that is syntactically at "top level" and
     outside of strings or comments.  Font Lock uses this when necessary
     to get the right results for syntactic fontification.

     This function is called with no arguments.  It should leave point
     at the beginning of any enclosing syntactic block.  Typical values
     are `beginning-of-line' (used when the start of the line is known
     to be outside a syntactic block), or `beginning-of-defun' for
     programming modes, or `backward-paragraph' for textual modes.

     If the value is `nil', Font Lock uses `syntax-begin-function' to
     move back outside of any comment, string, or sexp.  This variable
     is semi-obsolete; we recommend setting `syntax-begin-function'
     instead.

     Specify this variable using SYNTAX-BEGIN in `font-lock-defaults'.

 -- Variable: font-lock-syntactic-face-function
     A function to determine which face to use for a given syntactic
     element (a string or a comment).  The function is called with one
     argument, the parse state at point returned by
     `parse-partial-sexp', and should return a face.  The default value
     returns `font-lock-comment-face' for comments and
     `font-lock-string-face' for strings.

     This can be used to highlighting different kinds of strings or
     comments differently.  It is also sometimes abused together with
     `font-lock-syntactic-keywords' to highlight constructs that span
     multiple lines, but this is too esoteric to document here.

     Specify this variable using OTHER-VARS in `font-lock-defaults'.


File: elisp,  Node: Setting Syntax Properties,  Next: Multiline Font Lock,  Prev: Syntactic Font Lock,  Up: Font Lock Mode

23.6.9 Setting Syntax Properties
--------------------------------

Font Lock mode can be used to update `syntax-table' properties
automatically (*note Syntax Properties::).  This is useful in languages
for which a single syntax table by itself is not sufficient.

 -- Variable: font-lock-syntactic-keywords
     This variable enables and controls updating `syntax-table'
     properties by Font Lock.  Its value should be a list of elements of
     this form:

          (MATCHER SUBEXP SYNTAX OVERRIDE LAXMATCH)

     The parts of this element have the same meanings as in the
     corresponding sort of element of `font-lock-keywords',

          (MATCHER SUBEXP FACESPEC OVERRIDE LAXMATCH)

     However, instead of specifying the value FACESPEC to use for the
     `face' property, it specifies the value SYNTAX to use for the
     `syntax-table' property.  Here, SYNTAX can be a string (as taken
     by `modify-syntax-entry'), a syntax table, a cons cell (as
     returned by `string-to-syntax'), or an expression whose value is
     one of those two types.  OVERRIDE cannot be `prepend' or `append'.

     For example, an element of the form:

          ("\\$\\(#\\)" 1 ".")

     highlights syntactically a hash character when following a dollar
     character, with a SYNTAX of `"."' (meaning punctuation syntax).
     Assuming that the buffer syntax table specifies hash characters to
     have comment start syntax, the element will only highlight hash
     characters that do not follow dollar characters as comments
     syntactically.

     An element of the form:

           ("\\('\\).\\('\\)"
            (1 "\"")
            (2 "\""))

     highlights syntactically both single quotes which surround a single
     character, with a SYNTAX of `"\""' (meaning string quote syntax).
     Assuming that the buffer syntax table does not specify single
     quotes to have quote syntax, the element will only highlight
     single quotes of the form `'C'' as strings syntactically.  Other
     forms, such as `foo'bar' or `'fubar'', will not be highlighted as
     strings.

     Major modes normally set this variable with OTHER-VARS in
     `font-lock-defaults'.


File: elisp,  Node: Multiline Font Lock,  Prev: Setting Syntax Properties,  Up: Font Lock Mode

23.6.10 Multiline Font Lock Constructs
--------------------------------------

Normally, elements of `font-lock-keywords' should not match across
multiple lines; that doesn't work reliably, because Font Lock usually
scans just part of the buffer, and it can miss a multi-line construct
that crosses the line boundary where the scan starts.  (The scan
normally starts at the beginning of a line.)

   Making elements that match multiline constructs work properly has
two aspects: correct _identification_ and correct _rehighlighting_.
The first means that Font Lock finds all multiline constructs.  The
second means that Font Lock will correctly rehighlight all the relevant
text when a multiline construct is changed--for example, if some of the
text that was previously part of a multiline construct ceases to be
part of it.  The two aspects are closely related, and often getting one
of them to work will appear to make the other also work.  However, for
reliable results you must attend explicitly to both aspects.

   There are three ways to ensure correct identification of multiline
constructs:

   * Add a function to `font-lock-extend-region-functions' that does
     the _identification_ and extends the scan so that the scanned text
     never starts or ends in the middle of a multiline construct.

   * Use the `font-lock-fontify-region-function' hook similarly to
     extend the scan so that the scanned text never starts or ends in
     the middle of a multiline construct.

   * Somehow identify the multiline construct right when it gets
     inserted into the buffer (or at any point after that but before
     font-lock tries to highlight it), and mark it with a
     `font-lock-multiline' which will instruct font-lock not to start
     or end the scan in the middle of the construct.

   There are three ways to do rehighlighting of multiline constructs:

   * Place a `font-lock-multiline' property on the construct.  This
     will rehighlight the whole construct if any part of it is changed.
     In some cases you can do this automatically by setting the
     `font-lock-multiline' variable, which see.

   * Make sure `jit-lock-contextually' is set and rely on it doing its
     job.  This will only rehighlight the part of the construct that
     follows the actual change, and will do it after a short delay.
     This only works if the highlighting of the various parts of your
     multiline construct never depends on text in subsequent lines.
     Since `jit-lock-contextually' is activated by default, this can be
     an attractive solution.

   * Place a `jit-lock-defer-multiline' property on the construct.
     This works only if `jit-lock-contextually' is used, and with the
     same delay before rehighlighting, but like `font-lock-multiline',
     it also handles the case where highlighting depends on subsequent
     lines.

* Menu:

* Font Lock Multiline::         Marking multiline chunks with a text property
* Region to Fontify::           Controlling which region gets refontified
                                  after a buffer change.


File: elisp,  Node: Font Lock Multiline,  Next: Region to Fontify,  Up: Multiline Font Lock

23.6.10.1 Font Lock Multiline
.............................

One way to ensure reliable rehighlighting of multiline Font Lock
constructs is to put on them the text property `font-lock-multiline'.
It should be present and non-`nil' for text that is part of a multiline
construct.

   When Font Lock is about to highlight a range of text, it first
extends the boundaries of the range as necessary so that they do not
fall within text marked with the `font-lock-multiline' property.  Then
it removes any `font-lock-multiline' properties from the range, and
highlights it.  The highlighting specification (mostly
`font-lock-keywords') must reinstall this property each time, whenever
it is appropriate.

   *Warning:* don't use the `font-lock-multiline' property on large
ranges of text, because that will make rehighlighting slow.

 -- Variable: font-lock-multiline
     If the `font-lock-multiline' variable is set to `t', Font Lock
     will try to add the `font-lock-multiline' property automatically
     on multiline constructs.  This is not a universal solution,
     however, since it slows down Font Lock somewhat.  It can miss some
     multiline constructs, or make the property larger or smaller than
     necessary.

     For elements whose MATCHER is a function, the function should
     ensure that submatch 0 covers the whole relevant multiline
     construct, even if only a small subpart will be highlighted.  It
     is often just as easy to add the `font-lock-multiline' property by
     hand.

   The `font-lock-multiline' property is meant to ensure proper
refontification; it does not automatically identify new multiline
constructs.  Identifying the requires that Font-Lock operate on large
enough chunks at a time.  This will happen by accident on many cases,
which may give the impression that multiline constructs magically work.
If you set the `font-lock-multiline' variable non-`nil', this
impression will be even stronger, since the highlighting of those
constructs which are found will be properly updated from then on.  But
that does not work reliably.

   To find multiline constructs reliably, you must either manually
place the `font-lock-multiline' property on the text before Font-Lock
looks at it, or use `font-lock-fontify-region-function'.


File: elisp,  Node: Region to Fontify,  Prev: Font Lock Multiline,  Up: Multiline Font Lock

23.6.10.2 Region to Fontify after a Buffer Change
.................................................

When a buffer is changed, the region that Font Lock refontifies is by
default the smallest sequence of whole lines that spans the change.
While this works well most of the time, sometimes it doesn't--for
example, when a change alters the syntactic meaning of text on an
earlier line.

   You can enlarge (or even reduce) the region to fontify by setting
one the following variables:

 -- Variable: font-lock-extend-after-change-region-function
     This buffer-local variable is either `nil' or a function for
     Font-Lock to call to determine the region to scan and fontify.

     The function is given three parameters, the standard BEG, END, and
     OLD-LEN from after-change-functions (*note Change Hooks::).  It
     should return either a cons of the beginning and end buffer
     positions (in that order) of the region to fontify, or `nil'
     (which means choose the region in the standard way).  This
     function needs to preserve point, the match-data, and the current
     restriction.  The region it returns may start or end in the middle
     of a line.

     Since this function is called after every buffer change, it should
     be reasonably fast.


File: elisp,  Node: Desktop Save Mode,  Prev: Font Lock Mode,  Up: Modes

23.7 Desktop Save Mode
======================

"Desktop Save Mode" is a feature to save the state of Emacs from one
session to another.  The user-level commands for using Desktop Save
Mode are described in the GNU Emacs Manual (*note Saving Emacs
Sessions: (emacs)Saving Emacs Sessions.).  Modes whose buffers visit a
file, don't have to do anything to use this feature.

   For buffers not visiting a file to have their state saved, the major
mode must bind the buffer local variable `desktop-save-buffer' to a
non-`nil' value.

 -- Variable: desktop-save-buffer
     If this buffer-local variable is non-`nil', the buffer will have
     its state saved in the desktop file at desktop save.  If the value
     is a function, it is called at desktop save with argument
     DESKTOP-DIRNAME, and its value is saved in the desktop file along
     with the state of the buffer for which it was called.  When file
     names are returned as part of the auxiliary information, they
     should be formatted using the call

          (desktop-file-name FILE-NAME DESKTOP-DIRNAME)


   For buffers not visiting a file to be restored, the major mode must
define a function to do the job, and that function must be listed in
the alist `desktop-buffer-mode-handlers'.

 -- Variable: desktop-buffer-mode-handlers
     Alist with elements

          (MAJOR-MODE . RESTORE-BUFFER-FUNCTION)

     The function RESTORE-BUFFER-FUNCTION will be called with argument
     list

          (BUFFER-FILE-NAME BUFFER-NAME DESKTOP-BUFFER-MISC)

     and it should return the restored buffer.  Here
     DESKTOP-BUFFER-MISC is the value returned by the function
     optionally bound to `desktop-save-buffer'.


File: elisp,  Node: Documentation,  Next: Files,  Prev: Modes,  Up: Top

24 Documentation
****************

GNU Emacs Lisp has convenient on-line help facilities, most of which
derive their information from the documentation strings associated with
functions and variables.  This chapter describes how to write good
documentation strings for your Lisp programs, as well as how to write
programs to access documentation.

   Note that the documentation strings for Emacs are not the same thing
as the Emacs manual.  Manuals have their own source files, written in
the Texinfo language; documentation strings are specified in the
definitions of the functions and variables they apply to.  A collection
of documentation strings is not sufficient as a manual because a good
manual is not organized in that fashion; it is organized in terms of
topics of discussion.

   For commands to display documentation strings, see *note Help:
(emacs)Help.  For the conventions for writing documentation strings,
see *note Documentation Tips::.

* Menu:

* Documentation Basics::      Good style for doc strings.
                                Where to put them.  How Emacs stores them.
* Accessing Documentation::   How Lisp programs can access doc strings.
* Keys in Documentation::     Substituting current key bindings.
* Describing Characters::     Making printable descriptions of
                                non-printing characters and key sequences.
* Help Functions::            Subroutines used by Emacs help facilities.


File: elisp,  Node: Documentation Basics,  Next: Accessing Documentation,  Up: Documentation

24.1 Documentation Basics
=========================

A documentation string is written using the Lisp syntax for strings,
with double-quote characters surrounding the text of the string.  This
is because it really is a Lisp string object.  The string serves as
documentation when it is written in the proper place in the definition
of a function or variable.  In a function definition, the documentation
string follows the argument list.  In a variable definition, the
documentation string follows the initial value of the variable.

   When you write a documentation string, make the first line a
complete sentence (or two complete sentences) since some commands, such
as `apropos', show only the first line of a multi-line documentation
string.  Also, you should not indent the second line of a documentation
string, if it has one, because that looks odd when you use `C-h f'
(`describe-function') or `C-h v' (`describe-variable') to view the
documentation string.  There are many other conventions for doc
strings; see *note Documentation Tips::.

   Documentation strings can contain several special substrings, which
stand for key bindings to be looked up in the current keymaps when the
documentation is displayed.  This allows documentation strings to refer
to the keys for related commands and be accurate even when a user
rearranges the key bindings.  (*Note Keys in Documentation::.)

   Emacs Lisp mode fills documentation strings to the width specified
by `emacs-lisp-docstring-fill-column'.

   In Emacs Lisp, a documentation string is accessible through the
function or variable that it describes:

   * The documentation for a function is usually stored in the function
     definition itself (*note Lambda Expressions::).  The function
     `documentation' knows how to extract it.  You can also put
     function documentation in the `function-documentation' property of
     the function name.  That is useful with definitions such as
     keyboard macros that can't hold a documentation string.

   * The documentation for a variable is stored in the variable's
     property list under the property name `variable-documentation'.
     The function `documentation-property' knows how to retrieve it.

   To save space, the documentation for preloaded functions and
variables (including primitive functions and autoloaded functions) is
stored in the file `emacs/etc/DOC-VERSION'--not inside Emacs.  The
documentation strings for functions and variables loaded during the
Emacs session from byte-compiled files are stored in those files (*note
Docs and Compilation::).

   The data structure inside Emacs has an integer offset into the file,
or a list containing a file name and an integer, in place of the
documentation string.  The functions `documentation' and
`documentation-property' use that information to fetch the
documentation string from the appropriate file; this is transparent to
the user.

   The `emacs/lib-src' directory contains two utilities that you can
use to print nice-looking hardcopy for the file
`emacs/etc/DOC-VERSION'.  These are `sorted-doc' and `digest-doc'.


File: elisp,  Node: Accessing Documentation,  Next: Keys in Documentation,  Prev: Documentation Basics,  Up: Documentation

24.2 Access to Documentation Strings
====================================

 -- Function: documentation-property symbol property &optional verbatim
     This function returns the documentation string that is recorded in
     SYMBOL's property list under property PROPERTY.  It retrieves the
     text from a file if the value calls for that.  If the property
     value isn't `nil', isn't a string, and doesn't refer to text in a
     file, then it is evaluated to obtain a string.

     The last thing this function does is pass the string through
     `substitute-command-keys' to substitute actual key bindings,
     unless VERBATIM is non-`nil'.

          (documentation-property 'command-line-processed
             'variable-documentation)
               => "Non-nil once command line has been processed"
          (symbol-plist 'command-line-processed)
               => (variable-documentation 188902)
          (documentation-property 'emacs 'group-documentation)
               => "Customization of the One True Editor."

 -- Function: documentation function &optional verbatim
     This function returns the documentation string of FUNCTION.
     `documentation' handles macros, named keyboard macros, and special
     forms, as well as ordinary functions.

     If FUNCTION is a symbol, this function first looks for the
     `function-documentation' property of that symbol; if that has a
     non-`nil' value, the documentation comes from that value (if the
     value is not a string, it is evaluated).  If FUNCTION is not a
     symbol, or if it has no `function-documentation' property, then
     `documentation' extracts the documentation string from the actual
     function definition, reading it from a file if called for.

     Finally, unless VERBATIM is non-`nil', it calls
     `substitute-command-keys' so as to return a value containing the
     actual (current) key bindings.

     The function `documentation' signals a `void-function' error if
     FUNCTION has no function definition.  However, it is OK if the
     function definition has no documentation string.  In that case,
     `documentation' returns `nil'.

 -- Function: face-documentation face
     This function returns the documentation string of FACE as a face.

   Here is an example of using the two functions, `documentation' and
`documentation-property', to display the documentation strings for
several symbols in a `*Help*' buffer.

     (defun describe-symbols (pattern)
       "Describe the Emacs Lisp symbols matching PATTERN.
     All symbols that have PATTERN in their name are described
     in the `*Help*' buffer."
       (interactive "sDescribe symbols matching: ")
       (let ((describe-func
              (function
               (lambda (s)
                 ;; Print description of symbol.
                 (if (fboundp s)             ; It is a function.
                     (princ
                      (format "%s\t%s\n%s\n\n" s
                        (if (commandp s)
                            (let ((keys (where-is-internal s)))
                              (if keys
                                  (concat
                                   "Keys: "
                                   (mapconcat 'key-description
                                              keys " "))
                                "Keys: none"))
                          "Function")
                        (or (documentation s)
                            "not documented"))))

                 (if (boundp s)              ; It is a variable.
                     (princ
                      (format "%s\t%s\n%s\n\n" s
                        (if (user-variable-p s)
                            "Option " "Variable")
                        (or (documentation-property
                              s 'variable-documentation)
                            "not documented")))))))
             sym-list)

         ;; Build a list of symbols that match pattern.
         (mapatoms (function
                    (lambda (sym)
                      (if (string-match pattern (symbol-name sym))
                          (setq sym-list (cons sym sym-list))))))

         ;; Display the data.
         (with-output-to-temp-buffer "*Help*"
           (mapcar describe-func (sort sym-list 'string<))
           (print-help-return-message))))

   The `describe-symbols' function works like `apropos', but provides
more information.

     (describe-symbols "goal")

     ---------- Buffer: *Help* ----------
     goal-column     Option
     *Semipermanent goal column for vertical motion, as set by ...

     set-goal-column Keys: C-x C-n
     Set the current horizontal position as a goal for C-n and C-p.
     Those commands will move to this position in the line moved to
     rather than trying to keep the same horizontal position.
     With a non-nil argument, clears out the goal column
     so that C-n and C-p resume vertical motion.
     The goal column is stored in the variable `goal-column'.

     temporary-goal-column   Variable
     Current goal column for vertical motion.
     It is the column where point was
     at the start of current run of vertical motion commands.
     When the `track-eol' feature is doing its job, the value is 9999.
     ---------- Buffer: *Help* ----------

   The asterisk `*' as the first character of a variable's doc string,
as shown above for the `goal-column' variable, means that it is a user
option; see the description of `defvar' in *note Defining Variables::.

 -- Function: Snarf-documentation filename
     This function is used only during Emacs initialization, just before
     the runnable Emacs is dumped.  It finds the file offsets of the
     documentation strings stored in the file FILENAME, and records
     them in the in-core function definitions and variable property
     lists in place of the actual strings.  *Note Building Emacs::.

     Emacs reads the file FILENAME from the `emacs/etc' directory.
     When the dumped Emacs is later executed, the same file will be
     looked for in the directory `doc-directory'.  Usually FILENAME is
     `"DOC-VERSION"'.

 -- Variable: doc-directory
     This variable holds the name of the directory which should contain
     the file `"DOC-VERSION"' that contains documentation strings for
     built-in and preloaded functions and variables.

     In most cases, this is the same as `data-directory'.  They may be
     different when you run Emacs from the directory where you built it,
     without actually installing it.  *Note Definition of
     data-directory::.

     In older Emacs versions, `exec-directory' was used for this.


File: elisp,  Node: Keys in Documentation,  Next: Describing Characters,  Prev: Accessing Documentation,  Up: Documentation

24.3 Substituting Key Bindings in Documentation
===============================================

When documentation strings refer to key sequences, they should use the
current, actual key bindings.  They can do so using certain special text
sequences described below.  Accessing documentation strings in the usual
way substitutes current key binding information for these special
sequences.  This works by calling `substitute-command-keys'.  You can
also call that function yourself.

   Here is a list of the special sequences and what they mean:

`\[COMMAND]'
     stands for a key sequence that will invoke COMMAND, or `M-x
     COMMAND' if COMMAND has no key bindings.

`\{MAPVAR}'
     stands for a summary of the keymap which is the value of the
     variable MAPVAR.  The summary is made using `describe-bindings'.

`\<MAPVAR>'
     stands for no text itself.  It is used only for a side effect: it
     specifies MAPVAR's value as the keymap for any following
     `\[COMMAND]' sequences in this documentation string.

`\='
     quotes the following character and is discarded; thus, `\=\[' puts
     `\[' into the output, and `\=\=' puts `\=' into the output.

   *Please note:* Each `\' must be doubled when written in a string in
Emacs Lisp.

 -- Function: substitute-command-keys string
     This function scans STRING for the above special sequences and
     replaces them by what they stand for, returning the result as a
     string.  This permits display of documentation that refers
     accurately to the user's own customized key bindings.

   Here are examples of the special sequences:

     (substitute-command-keys
        "To abort recursive edit, type: \\[abort-recursive-edit]")
     => "To abort recursive edit, type: C-]"

     (substitute-command-keys
        "The keys that are defined for the minibuffer here are:
       \\{minibuffer-local-must-match-map}")
     => "The keys that are defined for the minibuffer here are:

     ?               minibuffer-completion-help
     SPC             minibuffer-complete-word
     TAB             minibuffer-complete
     C-j             minibuffer-complete-and-exit
     RET             minibuffer-complete-and-exit
     C-g             abort-recursive-edit
     "

     (substitute-command-keys
        "To abort a recursive edit from the minibuffer, type\
     \\<minibuffer-local-must-match-map>\\[abort-recursive-edit].")
     => "To abort a recursive edit from the minibuffer, type C-g."

   There are other special conventions for the text in documentation
strings--for instance, you can refer to functions, variables, and
sections of this manual.  *Note Documentation Tips::, for details.


File: elisp,  Node: Describing Characters,  Next: Help Functions,  Prev: Keys in Documentation,  Up: Documentation

24.4 Describing Characters for Help Messages
============================================

These functions convert events, key sequences, or characters to textual
descriptions.  These descriptions are useful for including arbitrary
text characters or key sequences in messages, because they convert
non-printing and whitespace characters to sequences of printing
characters.  The description of a non-whitespace printing character is
the character itself.

 -- Function: key-description sequence &optional prefix
     This function returns a string containing the Emacs standard
     notation for the input events in SEQUENCE.  If PREFIX is
     non-`nil', it is a sequence of input events leading up to SEQUENCE
     and is included in the return value.  Both arguments may be
     strings, vectors or lists.  *Note Input Events::, for more
     information about valid events.

          (key-description [?\M-3 delete])
               => "M-3 <delete>"
          (key-description [delete] "\M-3")
               => "M-3 <delete>"

     See also the examples for `single-key-description', below.

 -- Function: single-key-description event &optional no-angles
     This function returns a string describing EVENT in the standard
     Emacs notation for keyboard input.  A normal printing character
     appears as itself, but a control character turns into a string
     starting with `C-', a meta character turns into a string starting
     with `M-', and space, tab, etc. appear as `SPC', `TAB', etc.  A
     function key symbol appears inside angle brackets `<...>'.  An
     event that is a list appears as the name of the symbol in the CAR
     of the list, inside angle brackets.

     If the optional argument NO-ANGLES is non-`nil', the angle
     brackets around function keys and event symbols are omitted; this
     is for compatibility with old versions of Emacs which didn't use
     the brackets.

          (single-key-description ?\C-x)
               => "C-x"
          (key-description "\C-x \M-y \n \t \r \f123")
               => "C-x SPC M-y SPC C-j SPC TAB SPC RET SPC C-l 1 2 3"
          (single-key-description 'delete)
               => "<delete>"
          (single-key-description 'C-mouse-1)
               => "<C-mouse-1>"
          (single-key-description 'C-mouse-1 t)
               => "C-mouse-1"

 -- Function: text-char-description character
     This function returns a string describing CHARACTER in the
     standard Emacs notation for characters that appear in text--like
     `single-key-description', except that control characters are
     represented with a leading caret (which is how control characters
     in Emacs buffers are usually displayed).  Another difference is
     that `text-char-description' recognizes the 2**7 bit as the Meta
     character, whereas `single-key-description' uses the 2**27 bit for
     Meta.

          (text-char-description ?\C-c)
               => "^C"
          (text-char-description ?\M-m)
               => "\xed"
          (text-char-description ?\C-\M-m)
               => "\x8d"
          (text-char-description (+ 128 ?m))
               => "M-m"
          (text-char-description (+ 128 ?\C-m))
               => "M-^M"

 -- Function: read-kbd-macro string &optional need-vector
     This function is used mainly for operating on keyboard macros, but
     it can also be used as a rough inverse for `key-description'.  You
     call it with a string containing key descriptions, separated by
     spaces; it returns a string or vector containing the corresponding
     events.  (This may or may not be a single valid key sequence,
     depending on what events you use; *note Key Sequences::.)  If
     NEED-VECTOR is non-`nil', the return value is always a vector.


File: elisp,  Node: Help Functions,  Prev: Describing Characters,  Up: Documentation

24.5 Help Functions
===================

Emacs provides a variety of on-line help functions, all accessible to
the user as subcommands of the prefix `C-h'.  For more information
about them, see *note Help: (emacs)Help.  Here we describe some
program-level interfaces to the same information.

 -- Command: apropos pattern &optional do-all
     This function finds all "meaningful" symbols whose names contain a
     match for the apropos pattern PATTERN.  An apropos pattern is
     either a word to match, a space-separated list of words of which at
     least two must match, or a regular expression (if any special
     regular expression characters occur).  A symbol is "meaningful" if
     it has a definition as a function, variable, or face, or has
     properties.

     The function returns a list of elements that look like this:

          (SYMBOL SCORE FN-DOC VAR-DOC
           PLIST-DOC WIDGET-DOC FACE-DOC GROUP-DOC)

     Here, SCORE is an integer measure of how important the symbol
     seems to be as a match, and the remaining elements are
     documentation strings for SYMBOL's various roles (or `nil').

     It also displays the symbols in a buffer named `*Apropos*', each
     with a one-line description taken from the beginning of its
     documentation string.

     If DO-ALL is non-`nil', or if the user option `apropos-do-all' is
     non-`nil', then `apropos' also shows key bindings for the
     functions that are found; it also shows _all_ interned symbols,
     not just meaningful ones (and it lists them in the return value as
     well).

 -- Variable: help-map
     The value of this variable is a local keymap for characters
     following the Help key, `C-h'.

 -- Prefix Command: help-command
     This symbol is not a function; its function definition cell holds
     the keymap known as `help-map'.  It is defined in `help.el' as
     follows:

          (define-key global-map (char-to-string help-char) 'help-command)
          (fset 'help-command help-map)

 -- Function: print-help-return-message &optional function
     This function builds a string that explains how to restore the
     previous state of the windows after a help command.  After
     building the message, it applies FUNCTION to it if FUNCTION is
     non-`nil'.  Otherwise it calls `message' to display it in the echo
     area.

     This function expects to be called inside a
     `with-output-to-temp-buffer' special form, and expects
     `standard-output' to have the value bound by that special form.
     For an example of its use, see the long example in *note Accessing
     Documentation::.

 -- Variable: help-char
     The value of this variable is the help character--the character
     that Emacs recognizes as meaning Help.  By default, its value is
     8, which stands for `C-h'.  When Emacs reads this character, if
     `help-form' is a non-`nil' Lisp expression, it evaluates that
     expression, and displays the result in a window if it is a string.

     Usually the value of `help-form' is `nil'.  Then the help
     character has no special meaning at the level of command input, and
     it becomes part of a key sequence in the normal way.  The standard
     key binding of `C-h' is a prefix key for several general-purpose
     help features.

     The help character is special after prefix keys, too.  If it has no
     binding as a subcommand of the prefix key, it runs
     `describe-prefix-bindings', which displays a list of all the
     subcommands of the prefix key.

 -- Variable: help-event-list
     The value of this variable is a list of event types that serve as
     alternative "help characters."  These events are handled just like
     the event specified by `help-char'.

 -- Variable: help-form
     If this variable is non-`nil', its value is a form to evaluate
     whenever the character `help-char' is read.  If evaluating the form
     produces a string, that string is displayed.

     A command that calls `read-event' or `read-char' probably should
     bind `help-form' to a non-`nil' expression while it does input.
     (The time when you should not do this is when `C-h' has some other
     meaning.)  Evaluating this expression should result in a string
     that explains what the input is for and how to enter it properly.

     Entry to the minibuffer binds this variable to the value of
     `minibuffer-help-form' (*note Definition of
     minibuffer-help-form::).

 -- Variable: prefix-help-command
     This variable holds a function to print help for a prefix key.  The
     function is called when the user types a prefix key followed by
     the help character, and the help character has no binding after
     that prefix.  The variable's default value is
     `describe-prefix-bindings'.

 -- Function: describe-prefix-bindings
     This function calls `describe-bindings' to display a list of all
     the subcommands of the prefix key of the most recent key sequence.
     The prefix described consists of all but the last event of that key
     sequence.  (The last event is, presumably, the help character.)

   The following two functions are meant for modes that want to provide
help without relinquishing control, such as the "electric" modes.
Their names begin with `Helper' to distinguish them from the ordinary
help functions.

 -- Command: Helper-describe-bindings
     This command pops up a window displaying a help buffer containing a
     listing of all of the key bindings from both the local and global
     keymaps.  It works by calling `describe-bindings'.

 -- Command: Helper-help
     This command provides help for the current mode.  It prompts the
     user in the minibuffer with the message `Help (Type ? for further
     options)', and then provides assistance in finding out what the key
     bindings are, and what the mode is intended for.  It returns `nil'.

     This can be customized by changing the map `Helper-help-map'.

 -- Variable: data-directory
     This variable holds the name of the directory in which Emacs finds
     certain documentation and text files that come with Emacs.  In
     older Emacs versions, `exec-directory' was used for this.

 -- Macro: make-help-screen fname help-line help-text help-map
     This macro defines a help command named FNAME that acts like a
     prefix key that shows a list of the subcommands it offers.

     When invoked, FNAME displays HELP-TEXT in a window, then reads and
     executes a key sequence according to HELP-MAP.  The string
     HELP-TEXT should describe the bindings available in HELP-MAP.

     The command FNAME is defined to handle a few events itself, by
     scrolling the display of HELP-TEXT.  When FNAME reads one of those
     special events, it does the scrolling and then reads another
     event.  When it reads an event that is not one of those few, and
     which has a binding in HELP-MAP, it executes that key's binding and
     then returns.

     The argument HELP-LINE should be a single-line summary of the
     alternatives in HELP-MAP.  In the current version of Emacs, this
     argument is used only if you set the option `three-step-help' to
     `t'.

     This macro is used in the command `help-for-help' which is the
     binding of `C-h C-h'.

 -- User Option: three-step-help
     If this variable is non-`nil', commands defined with
     `make-help-screen' display their HELP-LINE strings in the echo
     area at first, and display the longer HELP-TEXT strings only if
     the user types the help character again.


File: elisp,  Node: Files,  Next: Backups and Auto-Saving,  Prev: Documentation,  Up: Top

25 Files
********

In Emacs, you can find, create, view, save, and otherwise work with
files and file directories.  This chapter describes most of the
file-related functions of Emacs Lisp, but a few others are described in
*note Buffers::, and those related to backups and auto-saving are
described in *note Backups and Auto-Saving::.

   Many of the file functions take one or more arguments that are file
names.  A file name is actually a string.  Most of these functions
expand file name arguments by calling `expand-file-name', so that `~'
is handled correctly, as are relative file names (including `../').
These functions don't recognize environment variable substitutions such
as `$HOME'.  *Note File Name Expansion::.

   When file I/O functions signal Lisp errors, they usually use the
condition `file-error' (*note Handling Errors::).  The error message is
in most cases obtained from the operating system, according to locale
`system-message-locale', and decoded using coding system
`locale-coding-system' (*note Locales::).

* Menu:

* Visiting Files::           Reading files into Emacs buffers for editing.
* Saving Buffers::           Writing changed buffers back into files.
* Reading from Files::       Reading files into buffers without visiting.
* Writing to Files::         Writing new files from parts of buffers.
* File Locks::               Locking and unlocking files, to prevent
                               simultaneous editing by two people.
* Information about Files::  Testing existence, accessibility, size of files.
* Changing Files::           Renaming files, changing protection, etc.
* File Names::               Decomposing and expanding file names.
* Contents of Directories::  Getting a list of the files in a directory.
* Create/Delete Dirs::	     Creating and Deleting Directories.
* Magic File Names::	     Defining "magic" special handling
			       for certain file names.
* Format Conversion::        Conversion to and from various file formats.


File: elisp,  Node: Visiting Files,  Next: Saving Buffers,  Up: Files

25.1 Visiting Files
===================

Visiting a file means reading a file into a buffer.  Once this is done,
we say that the buffer is "visiting" that file, and call the file "the
visited file" of the buffer.

   A file and a buffer are two different things.  A file is information
recorded permanently in the computer (unless you delete it).  A buffer,
on the other hand, is information inside of Emacs that will vanish at
the end of the editing session (or when you kill the buffer).  Usually,
a buffer contains information that you have copied from a file; then we
say the buffer is visiting that file.  The copy in the buffer is what
you modify with editing commands.  Such changes to the buffer do not
change the file; therefore, to make the changes permanent, you must
"save" the buffer, which means copying the altered buffer contents back
into the file.

   In spite of the distinction between files and buffers, people often
refer to a file when they mean a buffer and vice-versa.  Indeed, we say,
"I am editing a file," rather than, "I am editing a buffer that I will
soon save as a file of the same name."  Humans do not usually need to
make the distinction explicit.  When dealing with a computer program,
however, it is good to keep the distinction in mind.

* Menu:

* Visiting Functions::         The usual interface functions for visiting.
* Subroutines of Visiting::    Lower-level subroutines that they use.


File: elisp,  Node: Visiting Functions,  Next: Subroutines of Visiting,  Up: Visiting Files

25.1.1 Functions for Visiting Files
-----------------------------------

This section describes the functions normally used to visit files.  For
historical reasons, these functions have names starting with `find-'
rather than `visit-'.  *Note Buffer File Name::, for functions and
variables that access the visited file name of a buffer or that find an
existing buffer by its visited file name.

   In a Lisp program, if you want to look at the contents of a file but
not alter it, the fastest way is to use `insert-file-contents' in a
temporary buffer.  Visiting the file is not necessary and takes longer.
*Note Reading from Files::.

 -- Command: find-file filename &optional wildcards
     This command selects a buffer visiting the file FILENAME, using an
     existing buffer if there is one, and otherwise creating a new
     buffer and reading the file into it.  It also returns that buffer.

     Aside from some technical details, the body of the `find-file'
     function is basically equivalent to:

          (switch-to-buffer (find-file-noselect filename nil nil wildcards))

     (See `switch-to-buffer' in *note Displaying Buffers::.)

     If WILDCARDS is non-`nil', which is always true in an interactive
     call, then `find-file' expands wildcard characters in FILENAME and
     visits all the matching files.

     When `find-file' is called interactively, it prompts for FILENAME
     in the minibuffer.

 -- Function: find-file-noselect filename &optional nowarn rawfile
          wildcards
     This function is the guts of all the file-visiting functions.  It
     returns a buffer visiting the file FILENAME.  You may make the
     buffer current or display it in a window if you wish, but this
     function does not do so.

     The function returns an existing buffer if there is one; otherwise
     it creates a new buffer and reads the file into it.  When
     `find-file-noselect' uses an existing buffer, it first verifies
     that the file has not changed since it was last visited or saved in
     that buffer.  If the file has changed, this function asks the user
     whether to reread the changed file.  If the user says `yes', any
     edits previously made in the buffer are lost.

     Reading the file involves decoding the file's contents (*note
     Coding Systems::), including end-of-line conversion, and format
     conversion (*note Format Conversion::).  If WILDCARDS is non-`nil',
     then `find-file-noselect' expands wildcard characters in FILENAME
     and visits all the matching files.

     This function displays warning or advisory messages in various
     peculiar cases, unless the optional argument NOWARN is non-`nil'.
     For example, if it needs to create a buffer, and there is no file
     named FILENAME, it displays the message `(New file)' in the echo
     area, and leaves the buffer empty.

     The `find-file-noselect' function normally calls `after-find-file'
     after reading the file (*note Subroutines of Visiting::).  That
     function sets the buffer major mode, parses local variables, warns
     the user if there exists an auto-save file more recent than the
     file just visited, and finishes by running the functions in
     `find-file-hook'.

     If the optional argument RAWFILE is non-`nil', then
     `after-find-file' is not called, and the
     `find-file-not-found-functions' are not run in case of failure.
     What's more, a non-`nil' RAWFILE value suppresses coding system
     conversion and format conversion.

     The `find-file-noselect' function usually returns the buffer that
     is visiting the file FILENAME.  But, if wildcards are actually
     used and expanded, it returns a list of buffers that are visiting
     the various files.

          (find-file-noselect "/etc/fstab")
               => #<buffer fstab>

 -- Command: find-file-other-window filename &optional wildcards
     This command selects a buffer visiting the file FILENAME, but does
     so in a window other than the selected window.  It may use another
     existing window or split a window; see *note Displaying Buffers::.

     When this command is called interactively, it prompts for FILENAME.

 -- Command: find-file-read-only filename &optional wildcards
     This command selects a buffer visiting the file FILENAME, like
     `find-file', but it marks the buffer as read-only.  *Note Read
     Only Buffers::, for related functions and variables.

     When this command is called interactively, it prompts for FILENAME.

 -- Command: view-file filename
     This command visits FILENAME using View mode, returning to the
     previous buffer when you exit View mode.  View mode is a minor
     mode that provides commands to skim rapidly through the file, but
     does not let you modify the text.  Entering View mode runs the
     normal hook `view-mode-hook'.  *Note Hooks::.

     When `view-file' is called interactively, it prompts for FILENAME.

 -- User Option: find-file-wildcards
     If this variable is non-`nil', then the various `find-file'
     commands check for wildcard characters and visit all the files that
     match them (when invoked interactively or when their WILDCARDS
     argument is non-`nil').  If this option is `nil', then the
     `find-file' commands ignore their WILDCARDS argument and never
     treat wildcard characters specially.

 -- Variable: find-file-hook
     The value of this variable is a list of functions to be called
     after a file is visited.  The file's local-variables specification
     (if any) will have been processed before the hooks are run.  The
     buffer visiting the file is current when the hook functions are
     run.

     This variable is a normal hook.  *Note Hooks::.

 -- Variable: find-file-not-found-functions
     The value of this variable is a list of functions to be called when
     `find-file' or `find-file-noselect' is passed a nonexistent file
     name.  `find-file-noselect' calls these functions as soon as it
     detects a nonexistent file.  It calls them in the order of the
     list, until one of them returns non-`nil'.  `buffer-file-name' is
     already set up.

     This is not a normal hook because the values of the functions are
     used, and in many cases only some of the functions are called.


File: elisp,  Node: Subroutines of Visiting,  Prev: Visiting Functions,  Up: Visiting Files

25.1.2 Subroutines of Visiting
------------------------------

The `find-file-noselect' function uses two important subroutines which
are sometimes useful in user Lisp code: `create-file-buffer' and
`after-find-file'.  This section explains how to use them.

 -- Function: create-file-buffer filename
     This function creates a suitably named buffer for visiting
     FILENAME, and returns it.  It uses FILENAME (sans directory) as
     the name if that name is free; otherwise, it appends a string such
     as `<2>' to get an unused name.  See also *note Creating Buffers::.

     *Please note:* `create-file-buffer' does _not_ associate the new
     buffer with a file and does not select the buffer.  It also does
     not use the default major mode.

          (create-file-buffer "foo")
               => #<buffer foo>
          (create-file-buffer "foo")
               => #<buffer foo<2>>
          (create-file-buffer "foo")
               => #<buffer foo<3>>

     This function is used by `find-file-noselect'.  It uses
     `generate-new-buffer' (*note Creating Buffers::).

 -- Function: after-find-file &optional error warn noauto
          after-find-file-from-revert-buffer nomodes
     This function sets the buffer major mode, and parses local
     variables (*note Auto Major Mode::).  It is called by
     `find-file-noselect' and by the default revert function (*note
     Reverting::).

     If reading the file got an error because the file does not exist,
     but its directory does exist, the caller should pass a non-`nil'
     value for ERROR.  In that case, `after-find-file' issues a warning:
     `(New file)'.  For more serious errors, the caller should usually
     not call `after-find-file'.

     If WARN is non-`nil', then this function issues a warning if an
     auto-save file exists and is more recent than the visited file.

     If NOAUTO is non-`nil', that says not to enable or disable
     Auto-Save mode.  The mode remains enabled if it was enabled before.

     If AFTER-FIND-FILE-FROM-REVERT-BUFFER is non-`nil', that means
     this call was from `revert-buffer'.  This has no direct effect,
     but some mode functions and hook functions check the value of this
     variable.

     If NOMODES is non-`nil', that means don't alter the buffer's major
     mode, don't process local variables specifications in the file,
     and don't run `find-file-hook'.  This feature is used by
     `revert-buffer' in some cases.

     The last thing `after-find-file' does is call all the functions in
     the list `find-file-hook'.


File: elisp,  Node: Saving Buffers,  Next: Reading from Files,  Prev: Visiting Files,  Up: Files

25.2 Saving Buffers
===================

When you edit a file in Emacs, you are actually working on a buffer
that is visiting that file--that is, the contents of the file are
copied into the buffer and the copy is what you edit.  Changes to the
buffer do not change the file until you "save" the buffer, which means
copying the contents of the buffer into the file.

 -- Command: save-buffer &optional backup-option
     This function saves the contents of the current buffer in its
     visited file if the buffer has been modified since it was last
     visited or saved.  Otherwise it does nothing.

     `save-buffer' is responsible for making backup files.  Normally,
     BACKUP-OPTION is `nil', and `save-buffer' makes a backup file only
     if this is the first save since visiting the file.  Other values
     for BACKUP-OPTION request the making of backup files in other
     circumstances:

        * With an argument of 4 or 64, reflecting 1 or 3 `C-u''s, the
          `save-buffer' function marks this version of the file to be
          backed up when the buffer is next saved.

        * With an argument of 16 or 64, reflecting 2 or 3 `C-u''s, the
          `save-buffer' function unconditionally backs up the previous
          version of the file before saving it.

        * With an argument of 0, unconditionally do _not_ make any
          backup file.

 -- Command: save-some-buffers &optional save-silently-p pred
     This command saves some modified file-visiting buffers.  Normally
     it asks the user about each buffer.  But if SAVE-SILENTLY-P is
     non-`nil', it saves all the file-visiting buffers without querying
     the user.

     The optional PRED argument controls which buffers to ask about (or
     to save silently if SAVE-SILENTLY-P is non-`nil').  If it is
     `nil', that means to ask only about file-visiting buffers.  If it
     is `t', that means also offer to save certain other non-file
     buffers--those that have a non-`nil' buffer-local value of
     `buffer-offer-save' (*note Killing Buffers::).  A user who says
     `yes' to saving a non-file buffer is asked to specify the file
     name to use.  The `save-buffers-kill-emacs' function passes the
     value `t' for PRED.

     If PRED is neither `t' nor `nil', then it should be a function of
     no arguments.  It will be called in each buffer to decide whether
     to offer to save that buffer.  If it returns a non-`nil' value in
     a certain buffer, that means do offer to save that buffer.

 -- Command: write-file filename &optional confirm
     This function writes the current buffer into file FILENAME, makes
     the buffer visit that file, and marks it not modified.  Then it
     renames the buffer based on FILENAME, appending a string like `<2>'
     if necessary to make a unique buffer name.  It does most of this
     work by calling `set-visited-file-name' (*note Buffer File Name::)
     and `save-buffer'.

     If CONFIRM is non-`nil', that means to ask for confirmation before
     overwriting an existing file.  Interactively, confirmation is
     required, unless the user supplies a prefix argument.

     If FILENAME is an existing directory, or a symbolic link to one,
     `write-file' uses the name of the visited file, in directory
     FILENAME.  If the buffer is not visiting a file, it uses the
     buffer name instead.

   Saving a buffer runs several hooks.  It also performs format
conversion (*note Format Conversion::), and may save text properties in
"annotations" (*note Saving Properties::).

 -- Variable: write-file-functions
     The value of this variable is a list of functions to be called
     before writing out a buffer to its visited file.  If one of them
     returns non-`nil', the file is considered already written and the
     rest of the functions are not called, nor is the usual code for
     writing the file executed.

     If a function in `write-file-functions' returns non-`nil', it is
     responsible for making a backup file (if that is appropriate).  To
     do so, execute the following code:

          (or buffer-backed-up (backup-buffer))

     You might wish to save the file modes value returned by
     `backup-buffer' and use that (if non-`nil') to set the mode bits
     of the file that you write.  This is what `save-buffer' normally
     does. *Note Making Backup Files: Making Backups.

     The hook functions in `write-file-functions' are also responsible
     for encoding the data (if desired): they must choose a suitable
     coding system and end-of-line conversion (*note Lisp and Coding
     Systems::), perform the encoding (*note Explicit Encoding::), and
     set `last-coding-system-used' to the coding system that was used
     (*note Encoding and I/O::).

     If you set this hook locally in a buffer, it is assumed to be
     associated with the file or the way the contents of the buffer were
     obtained.  Thus the variable is marked as a permanent local, so
     that changing the major mode does not alter a buffer-local value.
     On the other hand, calling `set-visited-file-name' will reset it.
     If this is not what you want, you might like to use
     `write-contents-functions' instead.

     Even though this is not a normal hook, you can use `add-hook' and
     `remove-hook' to manipulate the list.  *Note Hooks::.

 -- Variable: write-contents-functions
     This works just like `write-file-functions', but it is intended
     for hooks that pertain to the buffer's contents, not to the
     particular visited file or its location.  Such hooks are usually
     set up by major modes, as buffer-local bindings for this variable.
     This variable automatically becomes buffer-local whenever it is
     set; switching to a new major mode always resets this variable,
     but calling `set-visited-file-name' does not.

     If any of the functions in this hook returns non-`nil', the file
     is considered already written and the rest are not called and
     neither are the functions in `write-file-functions'.

 -- User Option: before-save-hook
     This normal hook runs before a buffer is saved in its visited file,
     regardless of whether that is done normally or by one of the hooks
     described above.  For instance, the `copyright.el' program uses
     this hook to make sure the file you are saving has the current
     year in its copyright notice.

 -- User Option: after-save-hook
     This normal hook runs after a buffer has been saved in its visited
     file.  One use of this hook is in Fast Lock mode; it uses this
     hook to save the highlighting information in a cache file.

 -- User Option: file-precious-flag
     If this variable is non-`nil', then `save-buffer' protects against
     I/O errors while saving by writing the new file to a temporary
     name instead of the name it is supposed to have, and then renaming
     it to the intended name after it is clear there are no errors.
     This procedure prevents problems such as a lack of disk space from
     resulting in an invalid file.

     As a side effect, backups are necessarily made by copying.  *Note
     Rename or Copy::.  Yet, at the same time, saving a precious file
     always breaks all hard links between the file you save and other
     file names.

     Some modes give this variable a non-`nil' buffer-local value in
     particular buffers.

 -- User Option: require-final-newline
     This variable determines whether files may be written out that do
     _not_ end with a newline.  If the value of the variable is `t',
     then `save-buffer' silently adds a newline at the end of the file
     whenever the buffer being saved does not already end in one.  If
     the value of the variable is non-`nil', but not `t', then
     `save-buffer' asks the user whether to add a newline each time the
     case arises.

     If the value of the variable is `nil', then `save-buffer' doesn't
     add newlines at all.  `nil' is the default value, but a few major
     modes set it to `t' in particular buffers.

   See also the function `set-visited-file-name' (*note Buffer File
Name::).


File: elisp,  Node: Reading from Files,  Next: Writing to Files,  Prev: Saving Buffers,  Up: Files

25.3 Reading from Files
=======================

You can copy a file from the disk and insert it into a buffer using the
`insert-file-contents' function.  Don't use the user-level command
`insert-file' in a Lisp program, as that sets the mark.

 -- Function: insert-file-contents filename &optional visit beg end
          replace
     This function inserts the contents of file FILENAME into the
     current buffer after point.  It returns a list of the absolute
     file name and the length of the data inserted.  An error is
     signaled if FILENAME is not the name of a file that can be read.

     The function `insert-file-contents' checks the file contents
     against the defined file formats, and converts the file contents if
     appropriate.  *Note Format Conversion::.  It also calls the
     functions in the list `after-insert-file-functions'; see *note
     Saving Properties::.  Normally, one of the functions in the
     `after-insert-file-functions' list determines the coding system
     (*note Coding Systems::) used for decoding the file's contents,
     including end-of-line conversion.

     If VISIT is non-`nil', this function additionally marks the buffer
     as unmodified and sets up various fields in the buffer so that it
     is visiting the file FILENAME: these include the buffer's visited
     file name and its last save file modtime.  This feature is used by
     `find-file-noselect' and you probably should not use it yourself.

     If BEG and END are non-`nil', they should be integers specifying
     the portion of the file to insert.  In this case, VISIT must be
     `nil'.  For example,

          (insert-file-contents filename nil 0 500)

     inserts the first 500 characters of a file.

     If the argument REPLACE is non-`nil', it means to replace the
     contents of the buffer (actually, just the accessible portion)
     with the contents of the file.  This is better than simply
     deleting the buffer contents and inserting the whole file, because
     (1) it preserves some marker positions and (2) it puts less data
     in the undo list.

     It is possible to read a special file (such as a FIFO or an I/O
     device) with `insert-file-contents', as long as REPLACE and VISIT
     are `nil'.

 -- Function: insert-file-contents-literally filename &optional visit
          beg end replace
     This function works like `insert-file-contents' except that it does
     not do format decoding (*note Format Conversion::), does not do
     character code conversion (*note Coding Systems::), does not run
     `find-file-hook', does not perform automatic uncompression, and so
     on.

   If you want to pass a file name to another process so that another
program can read the file, use the function `file-local-copy'; see
*note Magic File Names::.


File: elisp,  Node: Writing to Files,  Next: File Locks,  Prev: Reading from Files,  Up: Files

25.4 Writing to Files
=====================

You can write the contents of a buffer, or part of a buffer, directly
to a file on disk using the `append-to-file' and `write-region'
functions.  Don't use these functions to write to files that are being
visited; that could cause confusion in the mechanisms for visiting.

 -- Command: append-to-file start end filename
     This function appends the contents of the region delimited by
     START and END in the current buffer to the end of file FILENAME.
     If that file does not exist, it is created.  This function returns
     `nil'.

     An error is signaled if FILENAME specifies a nonwritable file, or
     a nonexistent file in a directory where files cannot be created.

     When called from Lisp, this function is completely equivalent to:

          (write-region start end filename t)

 -- Command: write-region start end filename &optional append visit
          lockname mustbenew
     This function writes the region delimited by START and END in the
     current buffer into the file specified by FILENAME.

     If START is `nil', then the command writes the entire buffer
     contents (_not_ just the accessible portion) to the file and
     ignores END.

     If START is a string, then `write-region' writes or appends that
     string, rather than text from the buffer.  END is ignored in this
     case.

     If APPEND is non-`nil', then the specified text is appended to the
     existing file contents (if any).  If APPEND is an integer,
     `write-region' seeks to that byte offset from the start of the
     file and writes the data from there.

     If MUSTBENEW is non-`nil', then `write-region' asks for
     confirmation if FILENAME names an existing file.  If MUSTBENEW is
     the symbol `excl', then `write-region' does not ask for
     confirmation, but instead it signals an error
     `file-already-exists' if the file already exists.

     The test for an existing file, when MUSTBENEW is `excl', uses a
     special system feature.  At least for files on a local disk, there
     is no chance that some other program could create a file of the
     same name before Emacs does, without Emacs's noticing.

     If VISIT is `t', then Emacs establishes an association between the
     buffer and the file: the buffer is then visiting that file.  It
     also sets the last file modification time for the current buffer to
     FILENAME's modtime, and marks the buffer as not modified.  This
     feature is used by `save-buffer', but you probably should not use
     it yourself.

     If VISIT is a string, it specifies the file name to visit.  This
     way, you can write the data to one file (FILENAME) while recording
     the buffer as visiting another file (VISIT).  The argument VISIT
     is used in the echo area message and also for file locking; VISIT
     is stored in `buffer-file-name'.  This feature is used to
     implement `file-precious-flag'; don't use it yourself unless you
     really know what you're doing.

     The optional argument LOCKNAME, if non-`nil', specifies the file
     name to use for purposes of locking and unlocking, overriding
     FILENAME and VISIT for that purpose.

     The function `write-region' converts the data which it writes to
     the appropriate file formats specified by `buffer-file-format'.
     *Note Format Conversion::.  It also calls the functions in the list
     `write-region-annotate-functions'; see *note Saving Properties::.

     Normally, `write-region' displays the message `Wrote FILENAME' in
     the echo area.  If VISIT is neither `t' nor `nil' nor a string,
     then this message is inhibited.  This feature is useful for
     programs that use files for internal purposes, files that the user
     does not need to know about.

 -- Macro: with-temp-file file body...
     The `with-temp-file' macro evaluates the BODY forms with a
     temporary buffer as the current buffer; then, at the end, it
     writes the buffer contents into file FILE.  It kills the temporary
     buffer when finished, restoring the buffer that was current before
     the `with-temp-file' form.  Then it returns the value of the last
     form in BODY.

     The current buffer is restored even in case of an abnormal exit via
     `throw' or error (*note Nonlocal Exits::).

     See also `with-temp-buffer' in *note The Current Buffer:
     Definition of with-temp-buffer.


File: elisp,  Node: File Locks,  Next: Information about Files,  Prev: Writing to Files,  Up: Files

25.5 File Locks
===============

When two users edit the same file at the same time, they are likely to
interfere with each other.  Emacs tries to prevent this situation from
arising by recording a "file lock" when a file is being modified.
(File locks are not implemented on Microsoft systems.)  Emacs can then
detect the first attempt to modify a buffer visiting a file that is
locked by another Emacs job, and ask the user what to do.  The file
lock is really a file, a symbolic link with a special name, stored in
the same directory as the file you are editing.

   When you access files using NFS, there may be a small probability
that you and another user will both lock the same file "simultaneously."
If this happens, it is possible for the two users to make changes
simultaneously, but Emacs will still warn the user who saves second.
Also, the detection of modification of a buffer visiting a file changed
on disk catches some cases of simultaneous editing; see *note
Modification Time::.

 -- Function: file-locked-p filename
     This function returns `nil' if the file FILENAME is not locked.
     It returns `t' if it is locked by this Emacs process, and it
     returns the name of the user who has locked it if it is locked by
     some other job.

          (file-locked-p "foo")
               => nil

 -- Function: lock-buffer &optional filename
     This function locks the file FILENAME, if the current buffer is
     modified.  The argument FILENAME defaults to the current buffer's
     visited file.  Nothing is done if the current buffer is not
     visiting a file, or is not modified, or if the system does not
     support locking.

 -- Function: unlock-buffer
     This function unlocks the file being visited in the current buffer,
     if the buffer is modified.  If the buffer is not modified, then
     the file should not be locked, so this function does nothing.  It
     also does nothing if the current buffer is not visiting a file, or
     if the system does not support locking.

   File locking is not supported on some systems.  On systems that do
not support it, the functions `lock-buffer', `unlock-buffer' and
`file-locked-p' do nothing and return `nil'.

 -- Function: ask-user-about-lock file other-user
     This function is called when the user tries to modify FILE, but it
     is locked by another user named OTHER-USER.  The default
     definition of this function asks the user to say what to do.  The
     value this function returns determines what Emacs does next:

        * A value of `t' says to grab the lock on the file.  Then this
          user may edit the file and OTHER-USER loses the lock.

        * A value of `nil' says to ignore the lock and let this user
          edit the file anyway.

        * This function may instead signal a `file-locked' error, in
          which case the change that the user was about to make does
          not take place.

          The error message for this error looks like this:

               error--> File is locked: FILE OTHER-USER

          where `file' is the name of the file and OTHER-USER is the
          name of the user who has locked the file.

     If you wish, you can replace the `ask-user-about-lock' function
     with your own version that makes the decision in another way.  The
     code for its usual definition is in `userlock.el'.


File: elisp,  Node: Information about Files,  Next: Changing Files,  Prev: File Locks,  Up: Files

25.6 Information about Files
============================

The functions described in this section all operate on strings that
designate file names.  With a few exceptions, all the functions have
names that begin with the word `file'.  These functions all return
information about actual files or directories, so their arguments must
all exist as actual files or directories unless otherwise noted.

* Menu:

* Testing Accessibility::   Is a given file readable?  Writable?
* Kinds of Files::          Is it a directory?  A symbolic link?
* Truenames::		    Eliminating symbolic links from a file name.
* File Attributes::         How large is it?  Any other names?  Etc.
* Locating Files::          How to find a file in standard places.


File: elisp,  Node: Testing Accessibility,  Next: Kinds of Files,  Up: Information about Files

25.6.1 Testing Accessibility
----------------------------

These functions test for permission to access a file in specific ways.
Unless explicitly stated otherwise, they recursively follow symbolic
links for their file name arguments, at all levels (at the level of the
file itself and at all levels of parent directories).

 -- Function: file-exists-p filename
     This function returns `t' if a file named FILENAME appears to
     exist.  This does not mean you can necessarily read the file, only
     that you can find out its attributes.  (On Unix and GNU/Linux,
     this is true if the file exists and you have execute permission on
     the containing directories, regardless of the protection of the
     file itself.)

     If the file does not exist, or if fascist access control policies
     prevent you from finding the attributes of the file, this function
     returns `nil'.

     Directories are files, so `file-exists-p' returns `t' when given a
     directory name.  However, symbolic links are treated specially;
     `file-exists-p' returns `t' for a symbolic link name only if the
     target file exists.

 -- Function: file-readable-p filename
     This function returns `t' if a file named FILENAME exists and you
     can read it.  It returns `nil' otherwise.

          (file-readable-p "files.texi")
               => t
          (file-exists-p "/usr/spool/mqueue")
               => t
          (file-readable-p "/usr/spool/mqueue")
               => nil

 -- Function: file-executable-p filename
     This function returns `t' if a file named FILENAME exists and you
     can execute it.  It returns `nil' otherwise.  On Unix and
     GNU/Linux, if the file is a directory, execute permission means
     you can check the existence and attributes of files inside the
     directory, and open those files if their modes permit.

 -- Function: file-writable-p filename
     This function returns `t' if the file FILENAME can be written or
     created by you, and `nil' otherwise.  A file is writable if the
     file exists and you can write it.  It is creatable if it does not
     exist, but the specified directory does exist and you can write in
     that directory.

     In the third example below, `foo' is not writable because the
     parent directory does not exist, even though the user could create
     such a directory.

          (file-writable-p "~/foo")
               => t
          (file-writable-p "/foo")
               => nil
          (file-writable-p "~/no-such-dir/foo")
               => nil

 -- Function: file-accessible-directory-p dirname
     This function returns `t' if you have permission to open existing
     files in the directory whose name as a file is DIRNAME; otherwise
     (or if there is no such directory), it returns `nil'.  The value
     of DIRNAME may be either a directory name (such as `/foo/') or the
     file name of a file which is a directory (such as `/foo', without
     the final slash).

     Example: after the following,

          (file-accessible-directory-p "/foo")
               => nil

     we can deduce that any attempt to read a file in `/foo/' will give
     an error.

 -- Function: access-file filename string
     This function opens file FILENAME for reading, then closes it and
     returns `nil'.  However, if the open fails, it signals an error
     using STRING as the error message text.

 -- Function: file-ownership-preserved-p filename
     This function returns `t' if deleting the file FILENAME and then
     creating it anew would keep the file's owner unchanged.  It also
     returns `t' for nonexistent files.

     If FILENAME is a symbolic link, then, unlike the other functions
     discussed here, `file-ownership-preserved-p' does _not_ replace
     FILENAME with its target.  However, it does recursively follow
     symbolic links at all levels of parent directories.

 -- Function: file-newer-than-file-p filename1 filename2
     This function returns `t' if the file FILENAME1 is newer than file
     FILENAME2.  If FILENAME1 does not exist, it returns `nil'.  If
     FILENAME1 does exist, but FILENAME2 does not, it returns `t'.

     In the following example, assume that the file `aug-19' was written
     on the 19th, `aug-20' was written on the 20th, and the file
     `no-file' doesn't exist at all.

          (file-newer-than-file-p "aug-19" "aug-20")
               => nil
          (file-newer-than-file-p "aug-20" "aug-19")
               => t
          (file-newer-than-file-p "aug-19" "no-file")
               => t
          (file-newer-than-file-p "no-file" "aug-19")
               => nil

     You can use `file-attributes' to get a file's last modification
     time as a list of two numbers.  *Note File Attributes::.


File: elisp,  Node: Kinds of Files,  Next: Truenames,  Prev: Testing Accessibility,  Up: Information about Files

25.6.2 Distinguishing Kinds of Files
------------------------------------

This section describes how to distinguish various kinds of files, such
as directories, symbolic links, and ordinary files.

 -- Function: file-symlink-p filename
     If the file FILENAME is a symbolic link, the `file-symlink-p'
     function returns the (non-recursive) link target as a string.
     (Determining the file name that the link points to from the target
     is nontrivial.)  First, this function recursively follows symbolic
     links at all levels of parent directories.

     If the file FILENAME is not a symbolic link (or there is no such
     file), `file-symlink-p' returns `nil'.

          (file-symlink-p "foo")
               => nil
          (file-symlink-p "sym-link")
               => "foo"
          (file-symlink-p "sym-link2")
               => "sym-link"
          (file-symlink-p "/bin")
               => "/pub/bin"


   The next two functions recursively follow symbolic links at all
levels for FILENAME.

 -- Function: file-directory-p filename
     This function returns `t' if FILENAME is the name of an existing
     directory, `nil' otherwise.

          (file-directory-p "~rms")
               => t
          (file-directory-p "~rms/lewis/files.texi")
               => nil
          (file-directory-p "~rms/lewis/no-such-file")
               => nil
          (file-directory-p "$HOME")
               => nil
          (file-directory-p
           (substitute-in-file-name "$HOME"))
               => t

 -- Function: file-regular-p filename
     This function returns `t' if the file FILENAME exists and is a
     regular file (not a directory, named pipe, terminal, or other I/O
     device).


File: elisp,  Node: Truenames,  Next: File Attributes,  Prev: Kinds of Files,  Up: Information about Files

25.6.3 Truenames
----------------

The "truename" of a file is the name that you get by following symbolic
links at all levels until none remain, then simplifying away `.' and
`..' appearing as name components.  This results in a sort of canonical
name for the file.  A file does not always have a unique truename; the
number of distinct truenames a file has is equal to the number of hard
links to the file.  However, truenames are useful because they
eliminate symbolic links as a cause of name variation.

 -- Function: file-truename filename
     The function `file-truename' returns the truename of the file
     FILENAME.  The argument must be an absolute file name.

     This function does not expand environment variables.  Only
     `substitute-in-file-name' does that.  *Note Definition of
     substitute-in-file-name::.

     If you may need to follow symbolic links preceding `..' appearing
     as a name component, you should make sure to call `file-truename'
     without prior direct or indirect calls to `expand-file-name', as
     otherwise the file name component immediately preceding `..' will
     be "simplified away" before `file-truename' is called.  To
     eliminate the need for a call to `expand-file-name',
     `file-truename' handles `~' in the same way that
     `expand-file-name' does.  *Note Functions that Expand Filenames:
     File Name Expansion.

 -- Function: file-chase-links filename &optional limit
     This function follows symbolic links, starting with FILENAME,
     until it finds a file name which is not the name of a symbolic
     link.  Then it returns that file name.  This function does _not_
     follow symbolic links at the level of parent directories.

     If you specify a number for LIMIT, then after chasing through that
     many links, the function just returns what it has even if that is
     still a symbolic link.

   To illustrate the difference between `file-chase-links' and
`file-truename', suppose that `/usr/foo' is a symbolic link to the
directory `/home/foo', and `/home/foo/hello' is an ordinary file (or at
least, not a symbolic link) or nonexistent.  Then we would have:

     (file-chase-links "/usr/foo/hello")
          ;; This does not follow the links in the parent directories.
          => "/usr/foo/hello"
     (file-truename "/usr/foo/hello")
          ;; Assuming that `/home' is not a symbolic link.
          => "/home/foo/hello"

   *Note Buffer File Name::, for related information.


File: elisp,  Node: File Attributes,  Next: Locating Files,  Prev: Truenames,  Up: Information about Files

25.6.4 Other Information about Files
------------------------------------

This section describes the functions for getting detailed information
about a file, other than its contents.  This information includes the
mode bits that control access permission, the owner and group numbers,
the number of names, the inode number, the size, and the times of access
and modification.

 -- Function: file-modes filename
     This function returns the mode bits of FILENAME, as an integer.
     The mode bits are also called the file permissions, and they
     specify access control in the usual Unix fashion.  If the
     low-order bit is 1, then the file is executable by all users, if
     the second-lowest-order bit is 1, then the file is writable by all
     users, etc.

     The highest value returnable is 4095 (7777 octal), meaning that
     everyone has read, write, and execute permission, that the SUID bit
     is set for both others and group, and that the sticky bit is set.

     If FILENAME does not exist, `file-modes' returns `nil'.

     This function recursively follows symbolic links at all levels.

          (file-modes "~/junk/diffs")
               => 492               ; Decimal integer.
          (format "%o" 492)
               => "754"             ; Convert to octal.

          (set-file-modes "~/junk/diffs" 438)
               => nil

          (format "%o" 438)
               => "666"             ; Convert to octal.

          % ls -l diffs
            -rw-rw-rw-  1 lewis 0 3063 Oct 30 16:00 diffs

   If the FILENAME argument to the next two functions is a symbolic
link, then these function do _not_ replace it with its target.
However, they both recursively follow symbolic links at all levels of
parent directories.

 -- Function: file-nlinks filename
     This functions returns the number of names (i.e., hard links) that
     file FILENAME has.  If the file does not exist, then this function
     returns `nil'.  Note that symbolic links have no effect on this
     function, because they are not considered to be names of the files
     they link to.

          % ls -l foo*
          -rw-rw-rw-  2 rms       4 Aug 19 01:27 foo
          -rw-rw-rw-  2 rms       4 Aug 19 01:27 foo1

          (file-nlinks "foo")
               => 2
          (file-nlinks "doesnt-exist")
               => nil

 -- Function: file-attributes filename &optional id-format
     This function returns a list of attributes of file FILENAME.  If
     the specified file cannot be opened, it returns `nil'.  The
     optional parameter ID-FORMAT specifies the preferred format of
     attributes UID and GID (see below)--the valid values are `'string'
     and `'integer'.  The latter is the default, but we plan to change
     that, so you should specify a non-`nil' value for ID-FORMAT if you
     use the returned UID or GID.

     The elements of the list, in order, are:

       0. `t' for a directory, a string for a symbolic link (the name
          linked to), or `nil' for a text file.

       1. The number of names the file has.  Alternate names, also
          known as hard links, can be created by using the
          `add-name-to-file' function (*note Changing Files::).

       2. The file's UID, normally as a string.  However, if it does
          not correspond to a named user, the value is an integer or a
          floating point number.

       3. The file's GID, likewise.

       4. The time of last access, as a list of two integers.  The
          first integer has the high-order 16 bits of time, the second
          has the low 16 bits.  (This is similar to the value of
          `current-time'; see *note Time of Day::.)

       5. The time of last modification as a list of two integers (as
          above).  

       6. The time of last status change as a list of two integers (as
          above).

       7. The size of the file in bytes.  If the size is too large to
          fit in a Lisp integer, this is a floating point number.

       8. The file's modes, as a string of ten letters or dashes, as in
          `ls -l'.

       9. `t' if the file's GID would change if file were deleted and
          recreated; `nil' otherwise.

      10. The file's inode number.  If possible, this is an integer.
          If the inode number is too large to be represented as an
          integer in Emacs Lisp, then the value has the form `(HIGH .
          LOW)', where LOW holds the low 16 bits.

      11. The file system number of the file system that the file is in.
          Depending on the magnitude of the value, this can be either
          an integer or a cons cell, in the same manner as the inode
          number.  This element and the file's inode number together
          give enough information to distinguish any two files on the
          system--no two files can have the same values for both of
          these numbers.

     For example, here are the file attributes for `files.texi':

          (file-attributes "files.texi" 'string)
               =>  (nil 1 "lh" "users"
                    (8489 20284)
                    (8489 20284)
                    (8489 20285)
                    14906 "-rw-rw-rw-"
                    nil 129500 -32252)

     and here is how the result is interpreted:

    `nil'
          is neither a directory nor a symbolic link.

    `1'
          has only one name (the name `files.texi' in the current
          default directory).

    `"lh"'
          is owned by the user with name "lh".

    `"users"'
          is in the group with name "users".

    `(8489 20284)'
          was last accessed on Aug 19 00:09.

    `(8489 20284)'
          was last modified on Aug 19 00:09.

    `(8489 20285)'
          last had its inode changed on Aug 19 00:09.

    `14906'
          is 14906 bytes long.  (It may not contain 14906 characters,
          though, if some of the bytes belong to multibyte sequences.)

    `"-rw-rw-rw-"'
          has a mode of read and write access for the owner, group, and
          world.

    `nil'
          would retain the same GID if it were recreated.

    `129500'
          has an inode number of 129500.

    `-32252'
          is on file system number -32252.


File: elisp,  Node: Locating Files,  Prev: File Attributes,  Up: Information about Files

25.6.5 How to Locate Files in Standard Places
---------------------------------------------

This section explains how to search for a file in a list of directories
(a "path").  One example is when you need to look for a program's
executable file, e.g., to find out whether a given program is installed
on the user's system.  Another example is the search for Lisp libraries
(*note Library Search::).  Such searches generally need to try various
possible file name extensions, in addition to various possible
directories.  Emacs provides a function for such a generalized search
for a file.

 -- Function: locate-file filename path &optional suffixes predicate
     This function searches for a file whose name is FILENAME in a list
     of directories given by PATH, trying the suffixes in SUFFIXES.  If
     it finds such a file, it returns the full "absolute file name" of
     the file (*note Relative File Names::); otherwise it returns `nil'.

     The optional argument SUFFIXES gives the list of file-name
     suffixes to append to FILENAME when searching.  `locate-file'
     tries each possible directory with each of these suffixes.  If
     SUFFIXES is `nil', or `("")', then there are no suffixes, and
     FILENAME is used only as-is.  Typical values of SUFFIXES are
     `exec-suffixes' (*note exec-suffixes: Subprocess Creation.),
     `load-suffixes', `load-file-rep-suffixes' and the return value of
     the function `get-load-suffixes' (*note Load Suffixes::).

     Typical values for PATH are `exec-path' (*note exec-path:
     Subprocess Creation.) when looking for executable programs or
     `load-path' (*note load-path: Library Search.) when looking for
     Lisp files.  If FILENAME is absolute, PATH has no effect, but the
     suffixes in SUFFIXES are still tried.

     The optional argument PREDICATE, if non-`nil', specifies the
     predicate function to use for testing whether a candidate file is
     suitable.  The predicate function is passed the candidate file
     name as its single argument.  If PREDICATE is `nil' or unspecified,
     `locate-file' uses `file-readable-p' as the default predicate.
     Useful non-default predicates include `file-executable-p',
     `file-directory-p', and other predicates described in *note Kinds
     of Files::.

     For compatibility, PREDICATE can also be one of the symbols
     `executable', `readable', `writable', `exists', or a list of one
     or more of these symbols.

 -- Function: executable-find program
     This function searches for the executable file of the named
     PROGRAM and returns the full absolute name of the executable,
     including its file-name extensions, if any.  It returns `nil' if
     the file is not found.  The functions searches in all the
     directories in `exec-path' and tries all the file-name extensions
     in `exec-suffixes'.


File: elisp,  Node: Changing Files,  Next: File Names,  Prev: Information about Files,  Up: Files

25.7 Changing File Names and Attributes
=======================================

The functions in this section rename, copy, delete, link, and set the
modes of files.

   In the functions that have an argument NEWNAME, if a file by the
name of NEWNAME already exists, the actions taken depend on the value
of the argument OK-IF-ALREADY-EXISTS:

   * Signal a `file-already-exists' error if OK-IF-ALREADY-EXISTS is
     `nil'.

   * Request confirmation if OK-IF-ALREADY-EXISTS is a number.

   * Replace the old file without confirmation if OK-IF-ALREADY-EXISTS
     is any other value.

   The next four commands all recursively follow symbolic links at all
levels of parent directories for their first argument, but, if that
argument is itself a symbolic link, then only `copy-file' replaces it
with its (recursive) target.

 -- Command: add-name-to-file oldname newname &optional
          ok-if-already-exists
     This function gives the file named OLDNAME the additional name
     NEWNAME.  This means that NEWNAME becomes a new "hard link" to
     OLDNAME.

     In the first part of the following example, we list two files,
     `foo' and `foo3'.

          % ls -li fo*
          81908 -rw-rw-rw-  1 rms       29 Aug 18 20:32 foo
          84302 -rw-rw-rw-  1 rms       24 Aug 18 20:31 foo3

     Now we create a hard link, by calling `add-name-to-file', then list
     the files again.  This shows two names for one file, `foo' and
     `foo2'.

          (add-name-to-file "foo" "foo2")
               => nil

          % ls -li fo*
          81908 -rw-rw-rw-  2 rms       29 Aug 18 20:32 foo
          81908 -rw-rw-rw-  2 rms       29 Aug 18 20:32 foo2
          84302 -rw-rw-rw-  1 rms       24 Aug 18 20:31 foo3

     Finally, we evaluate the following:

          (add-name-to-file "foo" "foo3" t)

     and list the files again.  Now there are three names for one file:
     `foo', `foo2', and `foo3'.  The old contents of `foo3' are lost.

          (add-name-to-file "foo1" "foo3")
               => nil

          % ls -li fo*
          81908 -rw-rw-rw-  3 rms       29 Aug 18 20:32 foo
          81908 -rw-rw-rw-  3 rms       29 Aug 18 20:32 foo2
          81908 -rw-rw-rw-  3 rms       29 Aug 18 20:32 foo3

     This function is meaningless on operating systems where multiple
     names for one file are not allowed.  Some systems implement
     multiple names by copying the file instead.

     See also `file-nlinks' in *note File Attributes::.

 -- Command: rename-file filename newname &optional ok-if-already-exists
     This command renames the file FILENAME as NEWNAME.

     If FILENAME has additional names aside from FILENAME, it continues
     to have those names.  In fact, adding the name NEWNAME with
     `add-name-to-file' and then deleting FILENAME has the same effect
     as renaming, aside from momentary intermediate states.

 -- Command: copy-file oldname newname &optional ok-if-exists time
          preserve-uid-gid
     This command copies the file OLDNAME to NEWNAME.  An error is
     signaled if OLDNAME does not exist.  If NEWNAME names a directory,
     it copies OLDNAME into that directory, preserving its final name
     component.

     If TIME is non-`nil', then this function gives the new file the
     same last-modified time that the old one has.  (This works on only
     some operating systems.)  If setting the time gets an error,
     `copy-file' signals a `file-date-error' error.  In an interactive
     call, a prefix argument specifies a non-`nil' value for TIME.

     This function copies the file modes, too.

     If argument PRESERVE-UID-GID is `nil', we let the operating system
     decide the user and group ownership of the new file (this is
     usually set to the user running Emacs).  If PRESERVE-UID-GID is
     non-`nil', we attempt to copy the user and group ownership of the
     file.  This works only on some operating systems, and only if you
     have the correct permissions to do so.

 -- Command: make-symbolic-link filename newname &optional ok-if-exists
     This command makes a symbolic link to FILENAME, named NEWNAME.
     This is like the shell command `ln -s FILENAME NEWNAME'.

     This function is not available on systems that don't support
     symbolic links.

 -- Command: delete-file filename
     This command deletes the file FILENAME, like the shell command `rm
     FILENAME'.  If the file has multiple names, it continues to exist
     under the other names.

     A suitable kind of `file-error' error is signaled if the file does
     not exist, or is not deletable.  (On Unix and GNU/Linux, a file is
     deletable if its directory is writable.)

     If FILENAME is a symbolic link, `delete-file' does not replace it
     with its target, but it does follow symbolic links at all levels
     of parent directories.

     See also `delete-directory' in *note Create/Delete Dirs::.

 -- Function: define-logical-name varname string
     This function defines the logical name VARNAME to have the value
     STRING.  It is available only on VMS.

 -- Function: set-file-modes filename mode
     This function sets mode bits of FILENAME to MODE (which must be an
     integer).  Only the low 12 bits of MODE are used.  This function
     recursively follows symbolic links at all levels for FILENAME.

 -- Function: set-default-file-modes mode
     This function sets the default file protection for new files
     created by Emacs and its subprocesses.  Every file created with
     Emacs initially has this protection, or a subset of it
     (`write-region' will not give a file execute permission even if
     the default file protection allows execute permission).  On Unix
     and GNU/Linux, the default protection is the bitwise complement of
     the "umask" value.

     The argument MODE must be an integer.  On most systems, only the
     low 9 bits of MODE are meaningful.  You can use the Lisp construct
     for octal character codes to enter MODE; for example,

          (set-default-file-modes ?\644)

     Saving a modified version of an existing file does not count as
     creating the file; it preserves the existing file's mode, whatever
     that is.  So the default file protection has no effect.

 -- Function: default-file-modes
     This function returns the current default protection value.

 -- Function: set-file-times filename &optional time
     This function sets the access and modification times of FILENAME
     to TIME.  The return value is `t' if the times are successfully
     set, otherwise it is `nil'.  TIME defaults to the current time and
     must be in the format returned by `current-time' (*note Time of
     Day::).

   On MS-DOS, there is no such thing as an "executable" file mode bit.
So Emacs considers a file executable if its name ends in one of the
standard executable extensions, such as `.com', `.bat', `.exe', and
some others.  Files that begin with the Unix-standard `#!' signature,
such as shell and Perl scripts, are also considered as executable
files.  This is reflected in the values returned by `file-modes' and
`file-attributes'.  Directories are also reported with executable bit
set, for compatibility with Unix.


File: elisp,  Node: File Names,  Next: Contents of Directories,  Prev: Changing Files,  Up: Files

25.8 File Names
===============

Files are generally referred to by their names, in Emacs as elsewhere.
File names in Emacs are represented as strings.  The functions that
operate on a file all expect a file name argument.

   In addition to operating on files themselves, Emacs Lisp programs
often need to operate on file names; i.e., to take them apart and to use
part of a name to construct related file names.  This section describes
how to manipulate file names.

   The functions in this section do not actually access files, so they
can operate on file names that do not refer to an existing file or
directory.

   On MS-DOS and MS-Windows, these functions (like the function that
actually operate on files) accept MS-DOS or MS-Windows file-name syntax,
where backslashes separate the components, as well as Unix syntax; but
they always return Unix syntax.  On VMS, these functions (and the ones
that operate on files) understand both VMS file-name syntax and Unix
syntax.  This enables Lisp programs to specify file names in Unix syntax
and work properly on all systems without change.

* Menu:

* File Name Components::  The directory part of a file name, and the rest.
* Relative File Names::   Some file names are relative to a current directory.
* Directory Names::       A directory's name as a directory
                            is different from its name as a file.
* File Name Expansion::   Converting relative file names to absolute ones.
* Unique File Names::     Generating names for temporary files.
* File Name Completion::  Finding the completions for a given file name.
* Standard File Names::   If your package uses a fixed file name,
                            how to handle various operating systems simply.


File: elisp,  Node: File Name Components,  Next: Relative File Names,  Up: File Names

25.8.1 File Name Components
---------------------------

The operating system groups files into directories.  To specify a file,
you must specify the directory and the file's name within that
directory.  Therefore, Emacs considers a file name as having two main
parts: the "directory name" part, and the "nondirectory" part (or "file
name within the directory").  Either part may be empty.  Concatenating
these two parts reproduces the original file name.

   On most systems, the directory part is everything up to and including
the last slash (backslash is also allowed in input on MS-DOS or
MS-Windows); the nondirectory part is the rest.  The rules in VMS syntax
are complicated.

   For some purposes, the nondirectory part is further subdivided into
the name proper and the "version number".  On most systems, only backup
files have version numbers in their names.  On VMS, every file has a
version number, but most of the time the file name actually used in
Emacs omits the version number, so that version numbers in Emacs are
found mostly in directory lists.

 -- Function: file-name-directory filename
     This function returns the directory part of FILENAME, as a
     directory name (*note Directory Names::), or `nil' if FILENAME
     does not include a directory part.

     On GNU and Unix systems, a string returned by this function always
     ends in a slash.  On MS-DOS it can also end in a colon.  On VMS, it
     returns a string ending in one of the three characters `:', `]',
     or `>'.

          (file-name-directory "lewis/foo")  ; Unix example
               => "lewis/"
          (file-name-directory "foo")        ; Unix example
               => nil
          (file-name-directory "[X]FOO.TMP") ; VMS example
               => "[X]"

 -- Function: file-name-nondirectory filename
     This function returns the nondirectory part of FILENAME.

          (file-name-nondirectory "lewis/foo")
               => "foo"
          (file-name-nondirectory "foo")
               => "foo"
          (file-name-nondirectory "lewis/")
               => ""
          ;; The following example is accurate only on VMS.
          (file-name-nondirectory "[X]FOO.TMP")
               => "FOO.TMP"

 -- Function: file-name-sans-versions filename &optional
          keep-backup-version
     This function returns FILENAME with any file version numbers,
     backup version numbers, or trailing tildes discarded.

     If KEEP-BACKUP-VERSION is non-`nil', then true file version
     numbers understood as such by the file system are discarded from
     the return value, but backup version numbers are kept.

          (file-name-sans-versions "~rms/foo.~1~")
               => "~rms/foo"
          (file-name-sans-versions "~rms/foo~")
               => "~rms/foo"
          (file-name-sans-versions "~rms/foo")
               => "~rms/foo"
          ;; The following example applies to VMS only.
          (file-name-sans-versions "foo;23")
               => "foo"

 -- Function: file-name-extension filename &optional period
     This function returns FILENAME's final "extension," if any, after
     applying `file-name-sans-versions' to remove any version/backup
     part.  The extension, in a file name, is the part that starts with
     the last `.' in the last name component (minus any version/backup
     part).

     This function returns `nil' for extensionless file names such as
     `foo'.  It returns `""' for null extensions, as in `foo.'.  If the
     last component of a file name begins with a `.', that `.'  doesn't
     count as the beginning of an extension.  Thus, `.emacs''s
     "extension" is `nil', not `.emacs'.

     If PERIOD is non-`nil', then the returned value includes the
     period that delimits the extension, and if FILENAME has no
     extension, the value is `""'.

 -- Function: file-name-sans-extension filename
     This function returns FILENAME minus its extension, if any.  The
     version/backup part, if present, is only removed if the file has an
     extension.  For example,

          (file-name-sans-extension "foo.lose.c")
               => "foo.lose"
          (file-name-sans-extension "big.hack/foo")
               => "big.hack/foo"
          (file-name-sans-extension "/my/home/.emacs")
               => "/my/home/.emacs"
          (file-name-sans-extension "/my/home/.emacs.el")
               => "/my/home/.emacs"
          (file-name-sans-extension "~/foo.el.~3~")
               => "~/foo"
          (file-name-sans-extension "~/foo.~3~")
               => "~/foo.~3~"

     Note that the `.~3~' in the two last examples is the backup part,
     not an extension.


File: elisp,  Node: Relative File Names,  Next: Directory Names,  Prev: File Name Components,  Up: File Names

25.8.2 Absolute and Relative File Names
---------------------------------------

All the directories in the file system form a tree starting at the root
directory.  A file name can specify all the directory names starting
from the root of the tree; then it is called an "absolute" file name.
Or it can specify the position of the file in the tree relative to a
default directory; then it is called a "relative" file name.  On Unix
and GNU/Linux, an absolute file name starts with a slash or a tilde
(`~'), and a relative one does not.  On MS-DOS and MS-Windows, an
absolute file name starts with a slash or a backslash, or with a drive
specification `X:/', where X is the "drive letter".  The rules on VMS
are complicated.

 -- Function: file-name-absolute-p filename
     This function returns `t' if file FILENAME is an absolute file
     name, `nil' otherwise.  On VMS, this function understands both
     Unix syntax and VMS syntax.

          (file-name-absolute-p "~rms/foo")
               => t
          (file-name-absolute-p "rms/foo")
               => nil
          (file-name-absolute-p "/user/rms/foo")
               => t

   Given a possibly relative file name, you can convert it to an
absolute name using `expand-file-name' (*note File Name Expansion::).
This function converts absolute file names to relative names:

 -- Function: file-relative-name filename &optional directory
     This function tries to return a relative name that is equivalent to
     FILENAME, assuming the result will be interpreted relative to
     DIRECTORY (an absolute directory name or directory file name).  If
     DIRECTORY is omitted or `nil', it defaults to the current buffer's
     default directory.

     On some operating systems, an absolute file name begins with a
     device name.  On such systems, FILENAME has no relative equivalent
     based on DIRECTORY if they start with two different device names.
     In this case, `file-relative-name' returns FILENAME in absolute
     form.

          (file-relative-name "/foo/bar" "/foo/")
               => "bar"
          (file-relative-name "/foo/bar" "/hack/")
               => "../foo/bar"


File: elisp,  Node: Directory Names,  Next: File Name Expansion,  Prev: Relative File Names,  Up: File Names

25.8.3 Directory Names
----------------------

A "directory name" is the name of a directory.  A directory is actually
a kind of file, so it has a file name, which is related to the
directory name but not identical to it.  (This is not quite the same as
the usual Unix terminology.)  These two different names for the same
entity are related by a syntactic transformation.  On GNU and Unix
systems, this is simple: a directory name ends in a slash, whereas the
directory's name as a file lacks that slash.  On MS-DOS and VMS, the
relationship is more complicated.

   The difference between a directory name and its name as a file is
subtle but crucial.  When an Emacs variable or function argument is
described as being a directory name, a file name of a directory is not
acceptable.  When `file-name-directory' returns a string, that is
always a directory name.

   The following two functions convert between directory names and file
names.  They do nothing special with environment variable substitutions
such as `$HOME', and the constructs `~', `.' and `..'.

 -- Function: file-name-as-directory filename
     This function returns a string representing FILENAME in a form
     that the operating system will interpret as the name of a
     directory.  On most systems, this means appending a slash to the
     string (if it does not already end in one).  On VMS, the function
     converts a string of the form `[X]Y.DIR.1' to the form `[X.Y]'.

          (file-name-as-directory "~rms/lewis")
               => "~rms/lewis/"

 -- Function: directory-file-name dirname
     This function returns a string representing DIRNAME in a form that
     the operating system will interpret as the name of a file.  On most
     systems, this means removing the final slash (or backslash) from
     the string.  On VMS, the function converts a string of the form
     `[X.Y]' to `[X]Y.DIR.1'.

          (directory-file-name "~lewis/")
               => "~lewis"

   Given a directory name, you can combine it with a relative file name
using `concat':

     (concat DIRNAME RELFILE)

Be sure to verify that the file name is relative before doing that.  If
you use an absolute file name, the results could be syntactically
invalid or refer to the wrong file.

   If you want to use a directory file name in making such a
combination, you must first convert it to a directory name using
`file-name-as-directory':

     (concat (file-name-as-directory DIRFILE) RELFILE)

Don't try concatenating a slash by hand, as in

     ;;; Wrong!
     (concat DIRFILE "/" RELFILE)

because this is not portable.  Always use `file-name-as-directory'.

   Directory name abbreviations are useful for directories that are
normally accessed through symbolic links.  Sometimes the users recognize
primarily the link's name as "the name" of the directory, and find it
annoying to see the directory's "real" name.  If you define the link
name as an abbreviation for the "real" name, Emacs shows users the
abbreviation instead.

 -- Variable: directory-abbrev-alist
     The variable `directory-abbrev-alist' contains an alist of
     abbreviations to use for file directories.  Each element has the
     form `(FROM . TO)', and says to replace FROM with TO when it
     appears in a directory name.  The FROM string is actually a
     regular expression; it should always start with `^'.  The TO
     string should be an ordinary absolute directory name.  Do not use
     `~' to stand for a home directory in that string.  The function
     `abbreviate-file-name' performs these substitutions.

     You can set this variable in `site-init.el' to describe the
     abbreviations appropriate for your site.

     Here's an example, from a system on which file system `/home/fsf'
     and so on are normally accessed through symbolic links named `/fsf'
     and so on.

          (("^/home/fsf" . "/fsf")
           ("^/home/gp" . "/gp")
           ("^/home/gd" . "/gd"))

   To convert a directory name to its abbreviation, use this function:

 -- Function: abbreviate-file-name filename
     This function applies abbreviations from `directory-abbrev-alist'
     to its argument, and substitutes `~' for the user's home
     directory.  You can use it for directory names and for file names,
     because it recognizes abbreviations even as part of the name.


File: elisp,  Node: File Name Expansion,  Next: Unique File Names,  Prev: Directory Names,  Up: File Names

25.8.4 Functions that Expand Filenames
--------------------------------------

"Expansion" of a file name means converting a relative file name to an
absolute one.  Since this is done relative to a default directory, you
must specify the default directory name as well as the file name to be
expanded.  Expansion also simplifies file names by eliminating
redundancies such as `./' and `NAME/../'.

 -- Function: expand-file-name filename &optional directory
     This function converts FILENAME to an absolute file name.  If
     DIRECTORY is supplied, it is the default directory to start with
     if FILENAME is relative.  (The value of DIRECTORY should itself be
     an absolute directory name or directory file name; it may start
     with `~'.)  Otherwise, the current buffer's value of
     `default-directory' is used.  For example:

          (expand-file-name "foo")
               => "/xcssun/users/rms/lewis/foo"
          (expand-file-name "../foo")
               => "/xcssun/users/rms/foo"
          (expand-file-name "foo" "/usr/spool/")
               => "/usr/spool/foo"
          (expand-file-name "$HOME/foo")
               => "/xcssun/users/rms/lewis/$HOME/foo"

     If the part of the combined file name before the first slash is
     `~', it expands to the value of the `HOME' environment variable
     (usually your home directory).  If the part before the first slash
     is `~USER' and if USER is a valid login name, it expands to USER's
     home directory.

     Filenames containing `.' or `..' are simplified to their canonical
     form:

          (expand-file-name "bar/../foo")
               => "/xcssun/users/rms/lewis/foo"

     In some cases, a leading `..' component can remain in the output:

          (expand-file-name "../home" "/")
               => "/../home"

     This is for the sake of filesystems that have the concept of a
     "superroot" above the root directory `/'.  On other filesystems,
     `/../' is interpreted exactly the same as `/'.

     Note that `expand-file-name' does _not_ expand environment
     variables; only `substitute-in-file-name' does that.

     Note also that `expand-file-name' does not follow symbolic links
     at any level.  This results in a difference between the way
     `file-truename' and `expand-file-name' treat `..'.  Assuming that
     `/tmp/bar' is a symbolic link to the directory `/tmp/foo/bar' we
     get:

          (file-truename "/tmp/bar/../myfile")
               => "/tmp/foo/myfile"
          (expand-file-name "/tmp/bar/../myfile")
               => "/tmp/myfile"

     If you may need to follow symbolic links preceding `..', you
     should make sure to call `file-truename' without prior direct or
     indirect calls to `expand-file-name'.  *Note Truenames::.

 -- Variable: default-directory
     The value of this buffer-local variable is the default directory
     for the current buffer.  It should be an absolute directory name;
     it may start with `~'.  This variable is buffer-local in every
     buffer.

     `expand-file-name' uses the default directory when its second
     argument is `nil'.

     Aside from VMS, the value is always a string ending with a slash.

          default-directory
               => "/user/lewis/manual/"

 -- Function: substitute-in-file-name filename
     This function replaces environment variable references in FILENAME
     with the environment variable values.  Following standard Unix
     shell syntax, `$' is the prefix to substitute an environment
     variable value.  If the input contains `$$', that is converted to
     `$'; this gives the user a way to "quote" a `$'.

     The environment variable name is the series of alphanumeric
     characters (including underscores) that follow the `$'.  If the
     character following the `$' is a `{', then the variable name is
     everything up to the matching `}'.

     Calling `substitute-in-file-name' on output produced by
     `substitute-in-file-name' tends to give incorrect results.  For
     instance, use of `$$' to quote a single `$' won't work properly,
     and `$' in an environment variable's value could lead to repeated
     substitution.  Therefore, programs that call this function and put
     the output where it will be passed to this function need to double
     all `$' characters to prevent subsequent incorrect results.

     Here we assume that the environment variable `HOME', which holds
     the user's home directory name, has value `/xcssun/users/rms'.

          (substitute-in-file-name "$HOME/foo")
               => "/xcssun/users/rms/foo"

     After substitution, if a `~' or a `/' appears immediately after
     another `/', the function discards everything before it (up
     through the immediately preceding `/').

          (substitute-in-file-name "bar/~/foo")
               => "~/foo"
          (substitute-in-file-name "/usr/local/$HOME/foo")
               => "/xcssun/users/rms/foo"
               ;; `/usr/local/' has been discarded.

     On VMS, `$' substitution is not done, so this function does nothing
     on VMS except discard superfluous initial components as shown
     above.


File: elisp,  Node: Unique File Names,  Next: File Name Completion,  Prev: File Name Expansion,  Up: File Names

25.8.5 Generating Unique File Names
-----------------------------------

Some programs need to write temporary files.  Here is the usual way to
construct a name for such a file:

     (make-temp-file NAME-OF-APPLICATION)

The job of `make-temp-file' is to prevent two different users or two
different jobs from trying to use the exact same file name.

 -- Function: make-temp-file prefix &optional dir-flag suffix
     This function creates a temporary file and returns its name.  Emacs
     creates the temporary file's name by adding to PREFIX some random
     characters that are different in each Emacs job.  The result is
     guaranteed to be a newly created empty file.  On MS-DOS, this
     function can truncate the STRING prefix to fit into the 8+3
     file-name limits.  If PREFIX is a relative file name, it is
     expanded against `temporary-file-directory'.

          (make-temp-file "foo")
               => "/tmp/foo232J6v"

     When `make-temp-file' returns, the file has been created and is
     empty.  At that point, you should write the intended contents into
     the file.

     If DIR-FLAG is non-`nil', `make-temp-file' creates an empty
     directory instead of an empty file.  It returns the file name, not
     the directory name, of that directory.  *Note Directory Names::.

     If SUFFIX is non-`nil', `make-temp-file' adds it at the end of the
     file name.

     To prevent conflicts among different libraries running in the same
     Emacs, each Lisp program that uses `make-temp-file' should have its
     own PREFIX.  The number added to the end of PREFIX distinguishes
     between the same application running in different Emacs jobs.
     Additional added characters permit a large number of distinct
     names even in one Emacs job.

   The default directory for temporary files is controlled by the
variable `temporary-file-directory'.  This variable gives the user a
uniform way to specify the directory for all temporary files.  Some
programs use `small-temporary-file-directory' instead, if that is
non-`nil'.  To use it, you should expand the prefix against the proper
directory before calling `make-temp-file'.

   In older Emacs versions where `make-temp-file' does not exist, you
should use `make-temp-name' instead:

     (make-temp-name
      (expand-file-name NAME-OF-APPLICATION
                        temporary-file-directory))

 -- Function: make-temp-name string
     This function generates a string that can be used as a unique file
     name.  The name starts with STRING, and has several random
     characters appended to it, which are different in each Emacs job.
     It is like `make-temp-file' except that it just constructs a name,
     and does not create a file.  Another difference is that STRING
     should be an absolute file name.  On MS-DOS, this function can
     truncate the STRING prefix to fit into the 8+3 file-name limits.

 -- Variable: temporary-file-directory
     This variable specifies the directory name for creating temporary
     files.  Its value should be a directory name (*note Directory
     Names::), but it is good for Lisp programs to cope if the value is
     a directory's file name instead.  Using the value as the second
     argument to `expand-file-name' is a good way to achieve that.

     The default value is determined in a reasonable way for your
     operating system; it is based on the `TMPDIR', `TMP' and `TEMP'
     environment variables, with a fall-back to a system-dependent name
     if none of these variables is defined.

     Even if you do not use `make-temp-file' to create the temporary
     file, you should still use this variable to decide which directory
     to put the file in.  However, if you expect the file to be small,
     you should use `small-temporary-file-directory' first if that is
     non-`nil'.

 -- Variable: small-temporary-file-directory
     This variable specifies the directory name for creating certain
     temporary files, which are likely to be small.

     If you want to write a temporary file which is likely to be small,
     you should compute the directory like this:

          (make-temp-file
            (expand-file-name PREFIX
                              (or small-temporary-file-directory
                                  temporary-file-directory)))


File: elisp,  Node: File Name Completion,  Next: Standard File Names,  Prev: Unique File Names,  Up: File Names

25.8.6 File Name Completion
---------------------------

This section describes low-level subroutines for completing a file
name.  For higher level functions, see *note Reading File Names::.

 -- Function: file-name-all-completions partial-filename directory
     This function returns a list of all possible completions for a file
     whose name starts with PARTIAL-FILENAME in directory DIRECTORY.
     The order of the completions is the order of the files in the
     directory, which is unpredictable and conveys no useful
     information.

     The argument PARTIAL-FILENAME must be a file name containing no
     directory part and no slash (or backslash on some systems).  The
     current buffer's default directory is prepended to DIRECTORY, if
     DIRECTORY is not absolute.

     In the following example, suppose that `~rms/lewis' is the current
     default directory, and has five files whose names begin with `f':
     `foo', `file~', `file.c', `file.c.~1~', and `file.c.~2~'.

          (file-name-all-completions "f" "")
               => ("foo" "file~" "file.c.~2~"
                          "file.c.~1~" "file.c")

          (file-name-all-completions "fo" "")
               => ("foo")

 -- Function: file-name-completion filename directory &optional
          predicate
     This function completes the file name FILENAME in directory
     DIRECTORY.  It returns the longest prefix common to all file names
     in directory DIRECTORY that start with FILENAME.  If PREDICATE is
     non-`nil' then it ignores possible completions that don't satisfy
     PREDICATE, after calling that function with one argument, the
     expanded absolute file name.

     If only one match exists and FILENAME matches it exactly, the
     function returns `t'.  The function returns `nil' if directory
     DIRECTORY contains no name starting with FILENAME.

     In the following example, suppose that the current default
     directory has five files whose names begin with `f': `foo',
     `file~', `file.c', `file.c.~1~', and `file.c.~2~'.

          (file-name-completion "fi" "")
               => "file"

          (file-name-completion "file.c.~1" "")
               => "file.c.~1~"

          (file-name-completion "file.c.~1~" "")
               => t

          (file-name-completion "file.c.~3" "")
               => nil

 -- User Option: completion-ignored-extensions
     `file-name-completion' usually ignores file names that end in any
     string in this list.  It does not ignore them when all the possible
     completions end in one of these suffixes.  This variable has no
     effect on `file-name-all-completions'.

     A typical value might look like this:

          completion-ignored-extensions
               => (".o" ".elc" "~" ".dvi")

     If an element of `completion-ignored-extensions' ends in a slash
     `/', it signals a directory.  The elements which do _not_ end in a
     slash will never match a directory; thus, the above value will not
     filter out a directory named `foo.elc'.


File: elisp,  Node: Standard File Names,  Prev: File Name Completion,  Up: File Names

25.8.7 Standard File Names
--------------------------

Most of the file names used in Lisp programs are entered by the user.
But occasionally a Lisp program needs to specify a standard file name
for a particular use--typically, to hold customization information
about each user.  For example, abbrev definitions are stored (by
default) in the file `~/.abbrev_defs'; the `completion' package stores
completions in the file `~/.completions'.  These are two of the many
standard file names used by parts of Emacs for certain purposes.

   Various operating systems have their own conventions for valid file
names and for which file names to use for user profile data.  A Lisp
program which reads a file using a standard file name ought to use, on
each type of system, a file name suitable for that system.  The function
`convert-standard-filename' makes this easy to do.

 -- Function: convert-standard-filename filename
     This function alters the file name FILENAME to fit the conventions
     of the operating system in use, and returns the result as a new
     string.

   The recommended way to specify a standard file name in a Lisp program
is to choose a name which fits the conventions of GNU and Unix systems,
usually with a nondirectory part that starts with a period, and pass it
to `convert-standard-filename' instead of using it directly.  Here is
an example from the `completion' package:

     (defvar save-completions-file-name
             (convert-standard-filename "~/.completions")
       "*The file name to save completions to.")

   On GNU and Unix systems, and on some other systems as well,
`convert-standard-filename' returns its argument unchanged.  On some
other systems, it alters the name to fit the system's conventions.

   For example, on MS-DOS the alterations made by this function include
converting a leading `.'  to `_', converting a `_' in the middle of the
name to `.' if there is no other `.', inserting a `.' after eight
characters if there is none, and truncating to three characters after
the `.'.  (It makes other changes as well.)  Thus, `.abbrev_defs'
becomes `_abbrev.def', and `.completions' becomes `_complet.ion'.


File: elisp,  Node: Contents of Directories,  Next: Create/Delete Dirs,  Prev: File Names,  Up: Files

25.9 Contents of Directories
============================

A directory is a kind of file that contains other files entered under
various names.  Directories are a feature of the file system.

   Emacs can list the names of the files in a directory as a Lisp list,
or display the names in a buffer using the `ls' shell command.  In the
latter case, it can optionally display information about each file,
depending on the options passed to the `ls' command.

 -- Function: directory-files directory &optional full-name
          match-regexp nosort
     This function returns a list of the names of the files in the
     directory DIRECTORY.  By default, the list is in alphabetical
     order.

     If FULL-NAME is non-`nil', the function returns the files'
     absolute file names.  Otherwise, it returns the names relative to
     the specified directory.

     If MATCH-REGEXP is non-`nil', this function returns only those
     file names that contain a match for that regular expression--the
     other file names are excluded from the list.  On case-insensitive
     filesystems, the regular expression matching is case-insensitive.

     If NOSORT is non-`nil', `directory-files' does not sort the list,
     so you get the file names in no particular order.  Use this if you
     want the utmost possible speed and don't care what order the files
     are processed in.  If the order of processing is visible to the
     user, then the user will probably be happier if you do sort the
     names.

          (directory-files "~lewis")
               => ("#foo#" "#foo.el#" "." ".."
                   "dired-mods.el" "files.texi"
                   "files.texi.~1~")

     An error is signaled if DIRECTORY is not the name of a directory
     that can be read.

 -- Function: directory-files-and-attributes directory &optional
          full-name match-regexp nosort id-format
     This is similar to `directory-files' in deciding which files to
     report on and how to report their names.  However, instead of
     returning a list of file names, it returns for each file a list
     `(FILENAME . ATTRIBUTES)', where ATTRIBUTES is what
     `file-attributes' would return for that file.  The optional
     argument ID-FORMAT has the same meaning as the corresponding
     argument to `file-attributes' (*note Definition of
     file-attributes::).

 -- Function: file-name-all-versions file dirname
     This function returns a list of all versions of the file named
     FILE in directory DIRNAME.  It is only available on VMS.

 -- Function: file-expand-wildcards pattern &optional full
     This function expands the wildcard pattern PATTERN, returning a
     list of file names that match it.

     If PATTERN is written as an absolute file name, the values are
     absolute also.

     If PATTERN is written as a relative file name, it is interpreted
     relative to the current default directory.  The file names
     returned are normally also relative to the current default
     directory.  However, if FULL is non-`nil', they are absolute.

 -- Function: insert-directory file switches &optional wildcard
          full-directory-p
     This function inserts (in the current buffer) a directory listing
     for directory FILE, formatted with `ls' according to SWITCHES.  It
     leaves point after the inserted text.  SWITCHES may be a string of
     options, or a list of strings representing individual options.

     The argument FILE may be either a directory name or a file
     specification including wildcard characters.  If WILDCARD is
     non-`nil', that means treat FILE as a file specification with
     wildcards.

     If FULL-DIRECTORY-P is non-`nil', that means the directory listing
     is expected to show the full contents of a directory.  You should
     specify `t' when FILE is a directory and switches do not contain
     `-d'.  (The `-d' option to `ls' says to describe a directory
     itself as a file, rather than showing its contents.)

     On most systems, this function works by running a directory listing
     program whose name is in the variable `insert-directory-program'.
     If WILDCARD is non-`nil', it also runs the shell specified by
     `shell-file-name', to expand the wildcards.

     MS-DOS and MS-Windows systems usually lack the standard Unix
     program `ls', so this function emulates the standard Unix program
     `ls' with Lisp code.

     As a technical detail, when SWITCHES contains the long `--dired'
     option, `insert-directory' treats it specially, for the sake of
     dired.  However, the normally equivalent short `-D' option is just
     passed on to `insert-directory-program', as any other option.

 -- Variable: insert-directory-program
     This variable's value is the program to run to generate a
     directory listing for the function `insert-directory'.  It is
     ignored on systems which generate the listing with Lisp code.


File: elisp,  Node: Create/Delete Dirs,  Next: Magic File Names,  Prev: Contents of Directories,  Up: Files

25.10 Creating and Deleting Directories
=======================================

Most Emacs Lisp file-manipulation functions get errors when used on
files that are directories.  For example, you cannot delete a directory
with `delete-file'.  These special functions exist to create and delete
directories.

 -- Function: make-directory dirname &optional parents
     This function creates a directory named DIRNAME.  If PARENTS is
     non-`nil', as is always the case in an interactive call, that
     means to create the parent directories first, if they don't
     already exist.

 -- Function: delete-directory dirname
     This function deletes the directory named DIRNAME.  The function
     `delete-file' does not work for files that are directories; you
     must use `delete-directory' for them.  If the directory contains
     any files, `delete-directory' signals an error.

     This function only follows symbolic links at the level of parent
     directories.


File: elisp,  Node: Magic File Names,  Next: Format Conversion,  Prev: Create/Delete Dirs,  Up: Files

25.11 Making Certain File Names "Magic"
=======================================

You can implement special handling for certain file names.  This is
called making those names "magic".  The principal use for this feature
is in implementing remote file names (*note Remote Files: (emacs)Remote
Files.).

   To define a kind of magic file name, you must supply a regular
expression to define the class of names (all those that match the
regular expression), plus a handler that implements all the primitive
Emacs file operations for file names that do match.

   The variable `file-name-handler-alist' holds a list of handlers,
together with regular expressions that determine when to apply each
handler.  Each element has this form:

     (REGEXP . HANDLER)

All the Emacs primitives for file access and file name transformation
check the given file name against `file-name-handler-alist'.  If the
file name matches REGEXP, the primitives handle that file by calling
HANDLER.

   The first argument given to HANDLER is the name of the primitive, as
a symbol; the remaining arguments are the arguments that were passed to
that primitive.  (The first of these arguments is most often the file
name itself.)  For example, if you do this:

     (file-exists-p FILENAME)

and FILENAME has handler HANDLER, then HANDLER is called like this:

     (funcall HANDLER 'file-exists-p FILENAME)

   When a function takes two or more arguments that must be file names,
it checks each of those names for a handler.  For example, if you do
this:

     (expand-file-name FILENAME DIRNAME)

then it checks for a handler for FILENAME and then for a handler for
DIRNAME.  In either case, the HANDLER is called like this:

     (funcall HANDLER 'expand-file-name FILENAME DIRNAME)

The HANDLER then needs to figure out whether to handle FILENAME or
DIRNAME.

   If the specified file name matches more than one handler, the one
whose match starts last in the file name gets precedence.  This rule is
chosen so that handlers for jobs such as uncompression are handled
first, before handlers for jobs such as remote file access.

   Here are the operations that a magic file name handler gets to
handle:

`access-file', `add-name-to-file', `byte-compiler-base-file-name',
`copy-file', `delete-directory', `delete-file',
`diff-latest-backup-file', `directory-file-name', `directory-files',
`directory-files-and-attributes', `dired-call-process',
`dired-compress-file', `dired-uncache',
`expand-file-name', `file-accessible-directory-p', `file-attributes',
`file-directory-p', `file-executable-p', `file-exists-p',
`file-local-copy', `file-remote-p', `file-modes',
`file-name-all-completions', `file-name-as-directory',
`file-name-completion', `file-name-directory', `file-name-nondirectory',
`file-name-sans-versions', `file-newer-than-file-p',
`file-ownership-preserved-p', `file-readable-p', `file-regular-p',
`file-symlink-p', `file-truename', `file-writable-p',
`find-backup-file-name', `find-file-noselect',
`get-file-buffer', `insert-directory', `insert-file-contents',
`load', `make-auto-save-file-name', `make-directory',
`make-directory-internal', `make-symbolic-link',
`rename-file', `set-file-modes', `set-file-times',
`set-visited-file-modtime', `shell-command', `substitute-in-file-name',
`unhandled-file-name-directory', `vc-registered',
`verify-visited-file-modtime',
`write-region'.

   Handlers for `insert-file-contents' typically need to clear the
buffer's modified flag, with `(set-buffer-modified-p nil)', if the
VISIT argument is non-`nil'.  This also has the effect of unlocking the
buffer if it is locked.

   The handler function must handle all of the above operations, and
possibly others to be added in the future.  It need not implement all
these operations itself--when it has nothing special to do for a
certain operation, it can reinvoke the primitive, to handle the
operation "in the usual way."  It should always reinvoke the primitive
for an operation it does not recognize.  Here's one way to do this:

     (defun my-file-handler (operation &rest args)
       ;; First check for the specific operations
       ;; that we have special handling for.
       (cond ((eq operation 'insert-file-contents) ...)
             ((eq operation 'write-region) ...)
             ...
             ;; Handle any operation we don't know about.
             (t (let ((inhibit-file-name-handlers
                       (cons 'my-file-handler
                             (and (eq inhibit-file-name-operation operation)
                                  inhibit-file-name-handlers)))
                      (inhibit-file-name-operation operation))
                  (apply operation args)))))

   When a handler function decides to call the ordinary Emacs primitive
for the operation at hand, it needs to prevent the primitive from
calling the same handler once again, thus leading to an infinite
recursion.  The example above shows how to do this, with the variables
`inhibit-file-name-handlers' and `inhibit-file-name-operation'.  Be
careful to use them exactly as shown above; the details are crucial for
proper behavior in the case of multiple handlers, and for operations
that have two file names that may each have handlers.

   Handlers that don't really do anything special for actual access to
the file--such as the ones that implement completion of host names for
remote file names--should have a non-`nil' `safe-magic' property.  For
instance, Emacs normally "protects" directory names it finds in `PATH'
from becoming magic, if they look like magic file names, by prefixing
them with `/:'.  But if the handler that would be used for them has a
non-`nil' `safe-magic' property, the `/:' is not added.

   A file name handler can have an `operations' property to declare
which operations it handles in a nontrivial way.  If this property has
a non-`nil' value, it should be a list of operations; then only those
operations will call the handler.  This avoids inefficiency, but its
main purpose is for autoloaded handler functions, so that they won't be
loaded except when they have real work to do.

   Simply deferring all operations to the usual primitives does not
work.  For instance, if the file name handler applies to
`file-exists-p', then it must handle `load' itself, because the usual
`load' code won't work properly in that case.  However, if the handler
uses the `operations' property to say it doesn't handle
`file-exists-p', then it need not handle `load' nontrivially.

 -- Variable: inhibit-file-name-handlers
     This variable holds a list of handlers whose use is presently
     inhibited for a certain operation.

 -- Variable: inhibit-file-name-operation
     The operation for which certain handlers are presently inhibited.

 -- Function: find-file-name-handler file operation
     This function returns the handler function for file name FILE, or
     `nil' if there is none.  The argument OPERATION should be the
     operation to be performed on the file--the value you will pass to
     the handler as its first argument when you call it.  If OPERATION
     equals `inhibit-file-name-operation', or if it is not found in the
     `operations' property of the handler, this function returns `nil'.

 -- Function: file-local-copy filename
     This function copies file FILENAME to an ordinary non-magic file
     on the local machine, if it isn't on the local machine already.
     Magic file names should handle the `file-local-copy' operation if
     they refer to files on other machines.  A magic file name that is
     used for other purposes than remote file access should not handle
     `file-local-copy'; then this function will treat the file as local.

     If FILENAME is local, whether magic or not, this function does
     nothing and returns `nil'.  Otherwise it returns the file name of
     the local copy file.

 -- Function: file-remote-p filename
     This function tests whether FILENAME is a remote file.  If
     FILENAME is local (not remote), the return value is `nil'.  If
     FILENAME is indeed remote, the return value is a string that
     identifies the remote system.

     This identifier string can include a host name and a user name, as
     well as characters designating the method used to access the remote
     system.  For example, the remote identifier string for the filename
     `/ssh:user@host:/some/file' is `/ssh:user@host:'.

     If `file-remote-p' returns the same identifier for two different
     filenames, that means they are stored on the same file system and
     can be accessed locally with respect to each other.  This means,
     for example, that it is possible to start a remote process
     accessing both files at the same time.  Implementors of file
     handlers need to ensure this principle is valid.

 -- Function: unhandled-file-name-directory filename
     This function returns the name of a directory that is not magic.
     It uses the directory part of FILENAME if that is not magic.  For a
     magic file name, it invokes the file name handler, which therefore
     decides what value to return.

     This is useful for running a subprocess; every subprocess must
     have a non-magic directory to serve as its current directory, and
     this function is a good way to come up with one.


File: elisp,  Node: Format Conversion,  Prev: Magic File Names,  Up: Files

25.12 File Format Conversion
============================

The variable `format-alist' defines a list of "file formats", which
describe textual representations used in files for the data (text,
text-properties, and possibly other information) in an Emacs buffer.
Emacs performs format conversion if appropriate when reading and writing
files.

 -- Variable: format-alist
     This list contains one format definition for each defined file
     format.

   Each format definition is a list of this form:

     (NAME DOC-STRING REGEXP FROM-FN TO-FN MODIFY MODE-FN)

   Here is what the elements in a format definition mean:

NAME
     The name of this format.

DOC-STRING
     A documentation string for the format.

REGEXP
     A regular expression which is used to recognize files represented
     in this format.

FROM-FN
     A shell command or function to decode data in this format (to
     convert file data into the usual Emacs data representation).

     A shell command is represented as a string; Emacs runs the command
     as a filter to perform the conversion.

     If FROM-FN is a function, it is called with two arguments, BEGIN
     and END, which specify the part of the buffer it should convert.
     It should convert the text by editing it in place.  Since this can
     change the length of the text, FROM-FN should return the modified
     end position.

     One responsibility of FROM-FN is to make sure that the beginning
     of the file no longer matches REGEXP.  Otherwise it is likely to
     get called again.

TO-FN
     A shell command or function to encode data in this format--that
     is, to convert the usual Emacs data representation into this
     format.

     If TO-FN is a string, it is a shell command; Emacs runs the
     command as a filter to perform the conversion.

     If TO-FN is a function, it is called with three arguments: BEGIN
     and END, which specify the part of the buffer it should convert,
     and BUFFER, which specifies which buffer.  There are two ways it
     can do the conversion:

        * By editing the buffer in place.  In this case, TO-FN should
          return the end-position of the range of text, as modified.

        * By returning a list of annotations.  This is a list of
          elements of the form `(POSITION . STRING)', where POSITION is
          an integer specifying the relative position in the text to be
          written, and STRING is the annotation to add there.  The list
          must be sorted in order of position when TO-FN returns it.

          When `write-region' actually writes the text from the buffer
          to the file, it intermixes the specified annotations at the
          corresponding positions.  All this takes place without
          modifying the buffer.

MODIFY
     A flag, `t' if the encoding function modifies the buffer, and
     `nil' if it works by returning a list of annotations.

MODE-FN
     A minor-mode function to call after visiting a file converted from
     this format.  The function is called with one argument, the
     integer 1; that tells a minor-mode function to enable the mode.

   The function `insert-file-contents' automatically recognizes file
formats when it reads the specified file.  It checks the text of the
beginning of the file against the regular expressions of the format
definitions, and if it finds a match, it calls the decoding function for
that format.  Then it checks all the known formats over again.  It
keeps checking them until none of them is applicable.

   Visiting a file, with `find-file-noselect' or the commands that use
it, performs conversion likewise (because it calls
`insert-file-contents'); it also calls the mode function for each
format that it decodes.  It stores a list of the format names in the
buffer-local variable `buffer-file-format'.

 -- Variable: buffer-file-format
     This variable states the format of the visited file.  More
     precisely, this is a list of the file format names that were
     decoded in the course of visiting the current buffer's file.  It
     is always buffer-local in all buffers.

   When `write-region' writes data into a file, it first calls the
encoding functions for the formats listed in `buffer-file-format', in
the order of appearance in the list.

 -- Command: format-write-file file format &optional confirm
     This command writes the current buffer contents into the file FILE
     in format FORMAT, and makes that format the default for future
     saves of the buffer.  The argument FORMAT is a list of format
     names.  Except for the FORMAT argument, this command is similar to
     `write-file'.  In particular, CONFIRM has the same meaning and
     interactive treatment as the corresponding argument to
     `write-file'.  *Note Definition of write-file::.

 -- Command: format-find-file file format
     This command finds the file FILE, converting it according to
     format FORMAT.  It also makes FORMAT the default if the buffer is
     saved later.

     The argument FORMAT is a list of format names.  If FORMAT is
     `nil', no conversion takes place.  Interactively, typing just
     <RET> for FORMAT specifies `nil'.

 -- Command: format-insert-file file format &optional beg end
     This command inserts the contents of file FILE, converting it
     according to format FORMAT.  If BEG and END are non-`nil', they
     specify which part of the file to read, as in
     `insert-file-contents' (*note Reading from Files::).

     The return value is like what `insert-file-contents' returns: a
     list of the absolute file name and the length of the data inserted
     (after conversion).

     The argument FORMAT is a list of format names.  If FORMAT is
     `nil', no conversion takes place.  Interactively, typing just
     <RET> for FORMAT specifies `nil'.

 -- Variable: buffer-auto-save-file-format
     This variable specifies the format to use for auto-saving.  Its
     value is a list of format names, just like the value of
     `buffer-file-format'; however, it is used instead of
     `buffer-file-format' for writing auto-save files.  If the value is
     `t', the default, auto-saving uses the same format as a regular
     save in the same buffer.  This variable is always buffer-local in
     all buffers.


File: elisp,  Node: Backups and Auto-Saving,  Next: Buffers,  Prev: Files,  Up: Top

26 Backups and Auto-Saving
**************************

Backup files and auto-save files are two methods by which Emacs tries
to protect the user from the consequences of crashes or of the user's
own errors.  Auto-saving preserves the text from earlier in the current
editing session; backup files preserve file contents prior to the
current session.

* Menu:

* Backup Files::   How backup files are made; how their names are chosen.
* Auto-Saving::    How auto-save files are made; how their names are chosen.
* Reverting::      `revert-buffer', and how to customize what it does.


File: elisp,  Node: Backup Files,  Next: Auto-Saving,  Up: Backups and Auto-Saving

26.1 Backup Files
=================

A "backup file" is a copy of the old contents of a file you are
editing.  Emacs makes a backup file the first time you save a buffer
into its visited file.  Thus, normally, the backup file contains the
contents of the file as it was before the current editing session.  The
contents of the backup file normally remain unchanged once it exists.

   Backups are usually made by renaming the visited file to a new name.
Optionally, you can specify that backup files should be made by copying
the visited file.  This choice makes a difference for files with
multiple names; it also can affect whether the edited file remains owned
by the original owner or becomes owned by the user editing it.

   By default, Emacs makes a single backup file for each file edited.
You can alternatively request numbered backups; then each new backup
file gets a new name.  You can delete old numbered backups when you
don't want them any more, or Emacs can delete them automatically.

* Menu:

* Making Backups::     How Emacs makes backup files, and when.
* Rename or Copy::     Two alternatives: renaming the old file or copying it.
* Numbered Backups::   Keeping multiple backups for each source file.
* Backup Names::       How backup file names are computed; customization.


File: elisp,  Node: Making Backups,  Next: Rename or Copy,  Up: Backup Files

26.1.1 Making Backup Files
--------------------------

 -- Function: backup-buffer
     This function makes a backup of the file visited by the current
     buffer, if appropriate.  It is called by `save-buffer' before
     saving the buffer the first time.

     If a backup was made by renaming, the return value is a cons cell
     of the form (MODES . BACKUPNAME), where MODES are the mode bits of
     the original file, as returned by `file-modes' (*note Other
     Information about Files: File Attributes.), and BACKUPNAME is the
     name of the backup.  In all other cases, that is, if a backup was
     made by copying or if no backup was made, this function returns
     `nil'.

 -- Variable: buffer-backed-up
     This buffer-local variable says whether this buffer's file has
     been backed up on account of this buffer.  If it is non-`nil', the
     backup file has been written.  Otherwise, the file should be backed
     up when it is next saved (if backups are enabled).  This is a
     permanent local; `kill-all-local-variables' does not alter it.

 -- User Option: make-backup-files
     This variable determines whether or not to make backup files.  If
     it is non-`nil', then Emacs creates a backup of each file when it
     is saved for the first time--provided that `backup-inhibited' is
     `nil' (see below).

     The following example shows how to change the `make-backup-files'
     variable only in the Rmail buffers and not elsewhere.  Setting it
     `nil' stops Emacs from making backups of these files, which may
     save disk space.  (You would put this code in your init file.)

          (add-hook 'rmail-mode-hook
                    (function (lambda ()
                                (make-local-variable
                                 'make-backup-files)
                                (setq make-backup-files nil))))

 -- Variable: backup-enable-predicate
     This variable's value is a function to be called on certain
     occasions to decide whether a file should have backup files.  The
     function receives one argument, an absolute file name to consider.
     If the function returns `nil', backups are disabled for that file.
     Otherwise, the other variables in this section say whether and how
     to make backups.

     The default value is `normal-backup-enable-predicate', which checks
     for files in `temporary-file-directory' and
     `small-temporary-file-directory'.

 -- Variable: backup-inhibited
     If this variable is non-`nil', backups are inhibited.  It records
     the result of testing `backup-enable-predicate' on the visited file
     name.  It can also coherently be used by other mechanisms that
     inhibit backups based on which file is visited.  For example, VC
     sets this variable non-`nil' to prevent making backups for files
     managed with a version control system.

     This is a permanent local, so that changing the major mode does
     not lose its value.  Major modes should not set this
     variable--they should set `make-backup-files' instead.

 -- Variable: backup-directory-alist
     This variable's value is an alist of filename patterns and backup
     directory names.  Each element looks like
          (REGEXP . DIRECTORY)

     Backups of files with names matching REGEXP will be made in
     DIRECTORY.  DIRECTORY may be relative or absolute.  If it is
     absolute, so that all matching files are backed up into the same
     directory, the file names in this directory will be the full name
     of the file backed up with all directory separators changed to `!'
     to prevent clashes.  This will not work correctly if your
     filesystem truncates the resulting name.

     For the common case of all backups going into one directory, the
     alist should contain a single element pairing `"."' with the
     appropriate directory name.

     If this variable is `nil', or it fails to match a filename, the
     backup is made in the original file's directory.

     On MS-DOS filesystems without long names this variable is always
     ignored.

 -- Variable: make-backup-file-name-function
     This variable's value is a function to use for making backups
     instead of the default `make-backup-file-name'.  A value of `nil'
     gives the default `make-backup-file-name' behavior.  *Note Naming
     Backup Files: Backup Names.

     This could be buffer-local to do something special for specific
     files.  If you define it, you may need to change
     `backup-file-name-p' and `file-name-sans-versions' too.


File: elisp,  Node: Rename or Copy,  Next: Numbered Backups,  Prev: Making Backups,  Up: Backup Files

26.1.2 Backup by Renaming or by Copying?
----------------------------------------

There are two ways that Emacs can make a backup file:

   * Emacs can rename the original file so that it becomes a backup
     file, and then write the buffer being saved into a new file.
     After this procedure, any other names (i.e., hard links) of the
     original file now refer to the backup file.  The new file is owned
     by the user doing the editing, and its group is the default for
     new files written by the user in that directory.

   * Emacs can copy the original file into a backup file, and then
     overwrite the original file with new contents.  After this
     procedure, any other names (i.e., hard links) of the original file
     continue to refer to the current (updated) version of the file.
     The file's owner and group will be unchanged.

   The first method, renaming, is the default.

   The variable `backup-by-copying', if non-`nil', says to use the
second method, which is to copy the original file and overwrite it with
the new buffer contents.  The variable `file-precious-flag', if
non-`nil', also has this effect (as a sideline of its main
significance).  *Note Saving Buffers::.

 -- User Option: backup-by-copying
     If this variable is non-`nil', Emacs always makes backup files by
     copying.

   The following three variables, when non-`nil', cause the second
method to be used in certain special cases.  They have no effect on the
treatment of files that don't fall into the special cases.

 -- User Option: backup-by-copying-when-linked
     If this variable is non-`nil', Emacs makes backups by copying for
     files with multiple names (hard links).

     This variable is significant only if `backup-by-copying' is `nil',
     since copying is always used when that variable is non-`nil'.

 -- User Option: backup-by-copying-when-mismatch
     If this variable is non-`nil', Emacs makes backups by copying in
     cases where renaming would change either the owner or the group of
     the file.

     The value has no effect when renaming would not alter the owner or
     group of the file; that is, for files which are owned by the user
     and whose group matches the default for a new file created there
     by the user.

     This variable is significant only if `backup-by-copying' is `nil',
     since copying is always used when that variable is non-`nil'.

 -- User Option: backup-by-copying-when-privileged-mismatch
     This variable, if non-`nil', specifies the same behavior as
     `backup-by-copying-when-mismatch', but only for certain user-id
     values: namely, those less than or equal to a certain number.  You
     set this variable to that number.

     Thus, if you set `backup-by-copying-when-privileged-mismatch' to
     0, backup by copying is done for the superuser only, when
     necessary to prevent a change in the owner of the file.

     The default is 200.


File: elisp,  Node: Numbered Backups,  Next: Backup Names,  Prev: Rename or Copy,  Up: Backup Files

26.1.3 Making and Deleting Numbered Backup Files
------------------------------------------------

If a file's name is `foo', the names of its numbered backup versions
are `foo.~V~', for various integers V, like this: `foo.~1~', `foo.~2~',
`foo.~3~', ..., `foo.~259~', and so on.

 -- User Option: version-control
     This variable controls whether to make a single non-numbered backup
     file or multiple numbered backups.

    `nil'
          Make numbered backups if the visited file already has
          numbered backups; otherwise, do not.  This is the default.

    `never'
          Do not make numbered backups.

    ANYTHING ELSE
          Make numbered backups.

   The use of numbered backups ultimately leads to a large number of
backup versions, which must then be deleted.  Emacs can do this
automatically or it can ask the user whether to delete them.

 -- User Option: kept-new-versions
     The value of this variable is the number of newest versions to keep
     when a new numbered backup is made.  The newly made backup is
     included in the count.  The default value is 2.

 -- User Option: kept-old-versions
     The value of this variable is the number of oldest versions to keep
     when a new numbered backup is made.  The default value is 2.

   If there are backups numbered 1, 2, 3, 5, and 7, and both of these
variables have the value 2, then the backups numbered 1 and 2 are kept
as old versions and those numbered 5 and 7 are kept as new versions;
backup version 3 is excess.  The function `find-backup-file-name'
(*note Backup Names::) is responsible for determining which backup
versions to delete, but does not delete them itself.

 -- User Option: delete-old-versions
     If this variable is `t', then saving a file deletes excess backup
     versions silently.  If it is `nil', that means to ask for
     confirmation before deleting excess backups.  Otherwise, they are
     not deleted at all.

 -- User Option: dired-kept-versions
     This variable specifies how many of the newest backup versions to
     keep in the Dired command `.' (`dired-clean-directory').  That's
     the same thing `kept-new-versions' specifies when you make a new
     backup file.  The default is 2.


File: elisp,  Node: Backup Names,  Prev: Numbered Backups,  Up: Backup Files

26.1.4 Naming Backup Files
--------------------------

The functions in this section are documented mainly because you can
customize the naming conventions for backup files by redefining them.
If you change one, you probably need to change the rest.

 -- Function: backup-file-name-p filename
     This function returns a non-`nil' value if FILENAME is a possible
     name for a backup file.  It just checks the name, not whether a
     file with the name FILENAME exists.

          (backup-file-name-p "foo")
               => nil
          (backup-file-name-p "foo~")
               => 3

     The standard definition of this function is as follows:

          (defun backup-file-name-p (file)
            "Return non-nil if FILE is a backup file \
          name (numeric or not)..."
            (string-match "~\\'" file))

     Thus, the function returns a non-`nil' value if the file name ends
     with a `~'.  (We use a backslash to split the documentation
     string's first line into two lines in the text, but produce just
     one line in the string itself.)

     This simple expression is placed in a separate function to make it
     easy to redefine for customization.

 -- Function: make-backup-file-name filename
     This function returns a string that is the name to use for a
     non-numbered backup file for file FILENAME.  On Unix, this is just
     FILENAME with a tilde appended.

     The standard definition of this function, on most operating
     systems, is as follows:

          (defun make-backup-file-name (file)
            "Create the non-numeric backup file name for FILE..."
            (concat file "~"))

     You can change the backup-file naming convention by redefining this
     function.  The following example redefines `make-backup-file-name'
     to prepend a `.' in addition to appending a tilde:

          (defun make-backup-file-name (filename)
            (expand-file-name
              (concat "." (file-name-nondirectory filename) "~")
              (file-name-directory filename)))

          (make-backup-file-name "backups.texi")
               => ".backups.texi~"

     Some parts of Emacs, including some Dired commands, assume that
     backup file names end with `~'.  If you do not follow that
     convention, it will not cause serious problems, but these commands
     may give less-than-desirable results.

 -- Function: find-backup-file-name filename
     This function computes the file name for a new backup file for
     FILENAME.  It may also propose certain existing backup files for
     deletion.  `find-backup-file-name' returns a list whose CAR is the
     name for the new backup file and whose CDR is a list of backup
     files whose deletion is proposed.  The value can also be `nil',
     which means not to make a backup.

     Two variables, `kept-old-versions' and `kept-new-versions',
     determine which backup versions should be kept.  This function
     keeps those versions by excluding them from the CDR of the value.
     *Note Numbered Backups::.

     In this example, the value says that `~rms/foo.~5~' is the name to
     use for the new backup file, and `~rms/foo.~3~' is an "excess"
     version that the caller should consider deleting now.

          (find-backup-file-name "~rms/foo")
               => ("~rms/foo.~5~" "~rms/foo.~3~")

 -- Function: file-newest-backup filename
     This function returns the name of the most recent backup file for
     FILENAME, or `nil' if that file has no backup files.

     Some file comparison commands use this function so that they can
     automatically compare a file with its most recent backup.


File: elisp,  Node: Auto-Saving,  Next: Reverting,  Prev: Backup Files,  Up: Backups and Auto-Saving

26.2 Auto-Saving
================

Emacs periodically saves all files that you are visiting; this is
called "auto-saving".  Auto-saving prevents you from losing more than a
limited amount of work if the system crashes.  By default, auto-saves
happen every 300 keystrokes, or after around 30 seconds of idle time.
*Note Auto Save: (emacs)Auto Save, for information on auto-save for
users.  Here we describe the functions used to implement auto-saving
and the variables that control them.

 -- Variable: buffer-auto-save-file-name
     This buffer-local variable is the name of the file used for
     auto-saving the current buffer.  It is `nil' if the buffer should
     not be auto-saved.

          buffer-auto-save-file-name
               => "/xcssun/users/rms/lewis/#backups.texi#"

 -- Command: auto-save-mode arg
     When used interactively without an argument, this command is a
     toggle switch: it turns on auto-saving of the current buffer if it
     is off, and vice versa.  With an argument ARG, the command turns
     auto-saving on if the value of ARG is `t', a nonempty list, or a
     positive integer.  Otherwise, it turns auto-saving off.

 -- Function: auto-save-file-name-p filename
     This function returns a non-`nil' value if FILENAME is a string
     that could be the name of an auto-save file.  It assumes the usual
     naming convention for auto-save files: a name that begins and ends
     with hash marks (`#') is a possible auto-save file name.  The
     argument FILENAME should not contain a directory part.

          (make-auto-save-file-name)
               => "/xcssun/users/rms/lewis/#backups.texi#"
          (auto-save-file-name-p "#backups.texi#")
               => 0
          (auto-save-file-name-p "backups.texi")
               => nil

     The standard definition of this function is as follows:

          (defun auto-save-file-name-p (filename)
            "Return non-nil if FILENAME can be yielded by..."
            (string-match "^#.*#$" filename))

     This function exists so that you can customize it if you wish to
     change the naming convention for auto-save files.  If you redefine
     it, be sure to redefine the function `make-auto-save-file-name'
     correspondingly.

 -- Function: make-auto-save-file-name
     This function returns the file name to use for auto-saving the
     current buffer.  This is just the file name with hash marks (`#')
     prepended and appended to it.  This function does not look at the
     variable `auto-save-visited-file-name' (described below); callers
     of this function should check that variable first.

          (make-auto-save-file-name)
               => "/xcssun/users/rms/lewis/#backups.texi#"

     Here is a simplified version of the standard definition of this
     function:

          (defun make-auto-save-file-name ()
            "Return file name to use for auto-saves \
          of current buffer.."
            (if buffer-file-name
                (concat
                 (file-name-directory buffer-file-name)
                 "#"
                 (file-name-nondirectory buffer-file-name)
                 "#")
              (expand-file-name
               (concat "#%" (buffer-name) "#"))))

     This exists as a separate function so that you can redefine it to
     customize the naming convention for auto-save files.  Be sure to
     change `auto-save-file-name-p' in a corresponding way.

 -- User Option: auto-save-visited-file-name
     If this variable is non-`nil', Emacs auto-saves buffers in the
     files they are visiting.  That is, the auto-save is done in the
     same file that you are editing.  Normally, this variable is `nil',
     so auto-save files have distinct names that are created by
     `make-auto-save-file-name'.

     When you change the value of this variable, the new value does not
     take effect in an existing buffer until the next time auto-save
     mode is reenabled in it.  If auto-save mode is already enabled,
     auto-saves continue to go in the same file name until
     `auto-save-mode' is called again.

 -- Function: recent-auto-save-p
     This function returns `t' if the current buffer has been
     auto-saved since the last time it was read in or saved.

 -- Function: set-buffer-auto-saved
     This function marks the current buffer as auto-saved.  The buffer
     will not be auto-saved again until the buffer text is changed
     again.  The function returns `nil'.

 -- User Option: auto-save-interval
     The value of this variable specifies how often to do auto-saving,
     in terms of number of input events.  Each time this many
     additional input events are read, Emacs does auto-saving for all
     buffers in which that is enabled.  Setting this to zero disables
     autosaving based on the number of characters typed.

 -- User Option: auto-save-timeout
     The value of this variable is the number of seconds of idle time
     that should cause auto-saving.  Each time the user pauses for this
     long, Emacs does auto-saving for all buffers in which that is
     enabled.  (If the current buffer is large, the specified timeout
     is multiplied by a factor that increases as the size increases;
     for a million-byte buffer, the factor is almost 4.)

     If the value is zero or `nil', then auto-saving is not done as a
     result of idleness, only after a certain number of input events as
     specified by `auto-save-interval'.

 -- Variable: auto-save-hook
     This normal hook is run whenever an auto-save is about to happen.

 -- User Option: auto-save-default
     If this variable is non-`nil', buffers that are visiting files
     have auto-saving enabled by default.  Otherwise, they do not.

 -- Command: do-auto-save &optional no-message current-only
     This function auto-saves all buffers that need to be auto-saved.
     It saves all buffers for which auto-saving is enabled and that
     have been changed since the previous auto-save.

     If any buffers are auto-saved, `do-auto-save' normally displays a
     message saying `Auto-saving...' in the echo area while auto-saving
     is going on.  However, if NO-MESSAGE is non-`nil', the message is
     inhibited.

     If CURRENT-ONLY is non-`nil', only the current buffer is
     auto-saved.

 -- Function: delete-auto-save-file-if-necessary &optional force
     This function deletes the current buffer's auto-save file if
     `delete-auto-save-files' is non-`nil'.  It is called every time a
     buffer is saved.

     Unless FORCE is non-`nil', this function only deletes the file if
     it was written by the current Emacs session since the last true
     save.

 -- User Option: delete-auto-save-files
     This variable is used by the function
     `delete-auto-save-file-if-necessary'.  If it is non-`nil', Emacs
     deletes auto-save files when a true save is done (in the visited
     file).  This saves disk space and unclutters your directory.

 -- Function: rename-auto-save-file
     This function adjusts the current buffer's auto-save file name if
     the visited file name has changed.  It also renames an existing
     auto-save file, if it was made in the current Emacs session.  If
     the visited file name has not changed, this function does nothing.

 -- Variable: buffer-saved-size
     The value of this buffer-local variable is the length of the
     current buffer, when it was last read in, saved, or auto-saved.
     This is used to detect a substantial decrease in size, and turn
     off auto-saving in response.

     If it is -1, that means auto-saving is temporarily shut off in
     this buffer due to a substantial decrease in size.  Explicitly
     saving the buffer stores a positive value in this variable, thus
     reenabling auto-saving.  Turning auto-save mode off or on also
     updates this variable, so that the substantial decrease in size is
     forgotten.

 -- Variable: auto-save-list-file-name
     This variable (if non-`nil') specifies a file for recording the
     names of all the auto-save files.  Each time Emacs does
     auto-saving, it writes two lines into this file for each buffer
     that has auto-saving enabled.  The first line gives the name of
     the visited file (it's empty if the buffer has none), and the
     second gives the name of the auto-save file.

     When Emacs exits normally, it deletes this file; if Emacs crashes,
     you can look in the file to find all the auto-save files that
     might contain work that was otherwise lost.  The `recover-session'
     command uses this file to find them.

     The default name for this file specifies your home directory and
     starts with `.saves-'.  It also contains the Emacs process ID and
     the host name.

 -- Variable: auto-save-list-file-prefix
     After Emacs reads your init file, it initializes
     `auto-save-list-file-name' (if you have not already set it
     non-`nil') based on this prefix, adding the host name and process
     ID.  If you set this to `nil' in your init file, then Emacs does
     not initialize `auto-save-list-file-name'.


File: elisp,  Node: Reverting,  Prev: Auto-Saving,  Up: Backups and Auto-Saving

26.3 Reverting
==============

If you have made extensive changes to a file and then change your mind
about them, you can get rid of them by reading in the previous version
of the file with the `revert-buffer' command.  *Note Reverting a
Buffer: (emacs)Reverting.

 -- Command: revert-buffer &optional ignore-auto noconfirm
          preserve-modes
     This command replaces the buffer text with the text of the visited
     file on disk.  This action undoes all changes since the file was
     visited or saved.

     By default, if the latest auto-save file is more recent than the
     visited file, and the argument IGNORE-AUTO is `nil',
     `revert-buffer' asks the user whether to use that auto-save
     instead.  When you invoke this command interactively, IGNORE-AUTO
     is `t' if there is no numeric prefix argument; thus, the
     interactive default is not to check the auto-save file.

     Normally, `revert-buffer' asks for confirmation before it changes
     the buffer; but if the argument NOCONFIRM is non-`nil',
     `revert-buffer' does not ask for confirmation.

     Normally, this command reinitializes the buffer's major and minor
     modes using `normal-mode'.  But if PRESERVE-MODES is non-`nil',
     the modes remain unchanged.

     Reverting tries to preserve marker positions in the buffer by
     using the replacement feature of `insert-file-contents'.  If the
     buffer contents and the file contents are identical before the
     revert operation, reverting preserves all the markers.  If they
     are not identical, reverting does change the buffer; in that case,
     it preserves the markers in the unchanged text (if any) at the
     beginning and end of the buffer.  Preserving any additional
     markers would be problematical.

   You can customize how `revert-buffer' does its work by setting the
variables described in the rest of this section.

 -- User Option: revert-without-query
     This variable holds a list of files that should be reverted without
     query.  The value is a list of regular expressions.  If the
     visited file name matches one of these regular expressions, and
     the file has changed on disk but the buffer is not modified, then
     `revert-buffer' reverts the file without asking the user for
     confirmation.

   Some major modes customize `revert-buffer' by making buffer-local
bindings for these variables:

 -- Variable: revert-buffer-function
     The value of this variable is the function to use to revert this
     buffer.  If non-`nil', it should be a function with two optional
     arguments to do the work of reverting.  The two optional arguments,
     IGNORE-AUTO and NOCONFIRM, are the arguments that `revert-buffer'
     received.  If the value is `nil', reverting works the usual way.

     Modes such as Dired mode, in which the text being edited does not
     consist of a file's contents but can be regenerated in some other
     fashion, can give this variable a buffer-local value that is a
     function to regenerate the contents.

 -- Variable: revert-buffer-insert-file-contents-function
     The value of this variable, if non-`nil', specifies the function
     to use to insert the updated contents when reverting this buffer.
     The function receives two arguments: first the file name to use;
     second, `t' if the user has asked to read the auto-save file.

     The reason for a mode to set this variable instead of
     `revert-buffer-function' is to avoid duplicating or replacing the
     rest of what `revert-buffer' does: asking for confirmation,
     clearing the undo list, deciding the proper major mode, and
     running the hooks listed below.

 -- Variable: before-revert-hook
     This normal hook is run by `revert-buffer' before inserting the
     modified contents--but only if `revert-buffer-function' is `nil'.

 -- Variable: after-revert-hook
     This normal hook is run by `revert-buffer' after inserting the
     modified contents--but only if `revert-buffer-function' is `nil'.


File: elisp,  Node: Buffers,  Next: Windows,  Prev: Backups and Auto-Saving,  Up: Top

27 Buffers
**********

A "buffer" is a Lisp object containing text to be edited.  Buffers are
used to hold the contents of files that are being visited; there may
also be buffers that are not visiting files.  While several buffers may
exist at one time, only one buffer is designated the "current buffer"
at any time.  Most editing commands act on the contents of the current
buffer.  Each buffer, including the current buffer, may or may not be
displayed in any windows.

* Menu:

* Buffer Basics::       What is a buffer?
* Current Buffer::      Designating a buffer as current
                          so that primitives will access its contents.
* Buffer Names::        Accessing and changing buffer names.
* Buffer File Name::    The buffer file name indicates which file is visited.
* Buffer Modification:: A buffer is "modified" if it needs to be saved.
* Modification Time::   Determining whether the visited file was changed
                         ``behind Emacs's back''.
* Read Only Buffers::   Modifying text is not allowed in a read-only buffer.
* The Buffer List::     How to look at all the existing buffers.
* Creating Buffers::    Functions that create buffers.
* Killing Buffers::     Buffers exist until explicitly killed.
* Indirect Buffers::    An indirect buffer shares text with some other buffer.
* Buffer Gap::          The gap in the buffer.


File: elisp,  Node: Buffer Basics,  Next: Current Buffer,  Up: Buffers

27.1 Buffer Basics
==================

A "buffer" is a Lisp object containing text to be edited.  Buffers are
used to hold the contents of files that are being visited; there may
also be buffers that are not visiting files.  Although several buffers
normally exist, only one buffer is designated the "current buffer" at
any time.  Most editing commands act on the contents of the current
buffer.  Each buffer, including the current buffer, may or may not be
displayed in any windows.

Buffers in Emacs editing are objects that have distinct names and hold
text that can be edited.  Buffers appear to Lisp programs as a special
data type.  You can think of the contents of a buffer as a string that
you can extend; insertions and deletions may occur in any part of the
buffer.  *Note Text::.

   A Lisp buffer object contains numerous pieces of information.  Some
of this information is directly accessible to the programmer through
variables, while other information is accessible only through
special-purpose functions.  For example, the visited file name is
directly accessible through a variable, while the value of point is
accessible only through a primitive function.

   Buffer-specific information that is directly accessible is stored in
"buffer-local" variable bindings, which are variable values that are
effective only in a particular buffer.  This feature allows each buffer
to override the values of certain variables.  Most major modes override
variables such as `fill-column' or `comment-column' in this way.  For
more information about buffer-local variables and functions related to
them, see *note Buffer-Local Variables::.

   For functions and variables related to visiting files in buffers, see
*note Visiting Files:: and *note Saving Buffers::.  For functions and
variables related to the display of buffers in windows, see *note
Buffers and Windows::.

 -- Function: bufferp object
     This function returns `t' if OBJECT is a buffer, `nil' otherwise.


File: elisp,  Node: Current Buffer,  Next: Buffer Names,  Prev: Buffer Basics,  Up: Buffers

27.2 The Current Buffer
=======================

There are, in general, many buffers in an Emacs session.  At any time,
one of them is designated as the "current buffer".  This is the buffer
in which most editing takes place, because most of the primitives for
examining or changing text in a buffer operate implicitly on the
current buffer (*note Text::).  Normally the buffer that is displayed on
the screen in the selected window is the current buffer, but this is not
always so: a Lisp program can temporarily designate any buffer as
current in order to operate on its contents, without changing what is
displayed on the screen.

   The way to designate a current buffer in a Lisp program is by calling
`set-buffer'.  The specified buffer remains current until a new one is
designated.

   When an editing command returns to the editor command loop, the
command loop designates the buffer displayed in the selected window as
current, to prevent confusion: the buffer that the cursor is in when
Emacs reads a command is the buffer that the command will apply to.
(*Note Command Loop::.)  Therefore, `set-buffer' is not the way to
switch visibly to a different buffer so that the user can edit it.  For
that, you must use the functions described in *note Displaying
Buffers::.

   *Warning:* Lisp functions that change to a different current buffer
should not depend on the command loop to set it back afterwards.
Editing commands written in Emacs Lisp can be called from other programs
as well as from the command loop; it is convenient for the caller if
the subroutine does not change which buffer is current (unless, of
course, that is the subroutine's purpose).  Therefore, you should
normally use `set-buffer' within a `save-current-buffer' or
`save-excursion' (*note Excursions::) form that will restore the
current buffer when your function is done.  Here is an example, the
code for the command `append-to-buffer' (with the documentation string
abridged):

     (defun append-to-buffer (buffer start end)
       "Append to specified buffer the text of the region.
     ..."
       (interactive "BAppend to buffer: \nr")
       (let ((oldbuf (current-buffer)))
         (save-current-buffer
           (set-buffer (get-buffer-create buffer))
           (insert-buffer-substring oldbuf start end))))

This function binds a local variable to record the current buffer, and
then `save-current-buffer' arranges to make it current again.  Next,
`set-buffer' makes the specified buffer current.  Finally,
`insert-buffer-substring' copies the string from the original current
buffer to the specified (and now current) buffer.

   If the buffer appended to happens to be displayed in some window,
the next redisplay will show how its text has changed.  Otherwise, you
will not see the change immediately on the screen.  The buffer becomes
current temporarily during the execution of the command, but this does
not cause it to be displayed.

   If you make local bindings (with `let' or function arguments) for a
variable that may also have buffer-local bindings, make sure that the
same buffer is current at the beginning and at the end of the local
binding's scope.  Otherwise you might bind it in one buffer and unbind
it in another!  There are two ways to do this.  In simple cases, you may
see that nothing ever changes the current buffer within the scope of the
binding.  Otherwise, use `save-current-buffer' or `save-excursion' to
make sure that the buffer current at the beginning is current again
whenever the variable is unbound.

   Do not rely on using `set-buffer' to change the current buffer back,
because that won't do the job if a quit happens while the wrong buffer
is current.  Here is what _not_ to do:

     (let (buffer-read-only
           (obuf (current-buffer)))
       (set-buffer ...)
       ...
       (set-buffer obuf))

Using `save-current-buffer', as shown here, handles quitting, errors,
and `throw', as well as ordinary evaluation.

     (let (buffer-read-only)
       (save-current-buffer
         (set-buffer ...)
         ...))

 -- Function: current-buffer
     This function returns the current buffer.

          (current-buffer)
               => #<buffer buffers.texi>

 -- Function: set-buffer buffer-or-name
     This function makes BUFFER-OR-NAME the current buffer.  This does
     not display the buffer in any window, so the user cannot
     necessarily see the buffer.  But Lisp programs will now operate on
     it.

     This function returns the buffer identified by BUFFER-OR-NAME.  An
     error is signaled if BUFFER-OR-NAME does not identify an existing
     buffer.

 -- Special Form: save-current-buffer body...
     The `save-current-buffer' special form saves the identity of the
     current buffer, evaluates the BODY forms, and finally restores
     that buffer as current.  The return value is the value of the last
     form in BODY.  The current buffer is restored even in case of an
     abnormal exit via `throw' or error (*note Nonlocal Exits::).

     If the buffer that used to be current has been killed by the time
     of exit from `save-current-buffer', then it is not made current
     again, of course.  Instead, whichever buffer was current just
     before exit remains current.

 -- Macro: with-current-buffer buffer-or-name body...
     The `with-current-buffer' macro saves the identity of the current
     buffer, makes BUFFER-OR-NAME current, evaluates the BODY forms,
     and finally restores the buffer.  The return value is the value of
     the last form in BODY.  The current buffer is restored even in
     case of an abnormal exit via `throw' or error (*note Nonlocal
     Exits::).

     An error is signaled if BUFFER-OR-NAME does not identify an
     existing buffer.

 -- Macro: with-temp-buffer body...
     The `with-temp-buffer' macro evaluates the BODY forms with a
     temporary buffer as the current buffer.  It saves the identity of
     the current buffer, creates a temporary buffer and makes it
     current, evaluates the BODY forms, and finally restores the
     previous current buffer while killing the temporary buffer.  By
     default, undo information (*note Undo::) is not recorded in the
     buffer created by this macro (but BODY can enable that, if needed).

     The return value is the value of the last form in BODY.  You can
     return the contents of the temporary buffer by using
     `(buffer-string)' as the last form.

     The current buffer is restored even in case of an abnormal exit via
     `throw' or error (*note Nonlocal Exits::).

     See also `with-temp-file' in *note Writing to Files: Definition of
     with-temp-file.


File: elisp,  Node: Buffer Names,  Next: Buffer File Name,  Prev: Current Buffer,  Up: Buffers

27.3 Buffer Names
=================

Each buffer has a unique name, which is a string.  Many of the
functions that work on buffers accept either a buffer or a buffer name
as an argument.  Any argument called BUFFER-OR-NAME is of this sort,
and an error is signaled if it is neither a string nor a buffer.  Any
argument called BUFFER must be an actual buffer object, not a name.

   Buffers that are ephemeral and generally uninteresting to the user
have names starting with a space, so that the `list-buffers' and
`buffer-menu' commands don't mention them (but if such a buffer visits
a file, it *is* mentioned).  A name starting with space also initially
disables recording undo information; see *note Undo::.

 -- Function: buffer-name &optional buffer
     This function returns the name of BUFFER as a string.  If BUFFER
     is not supplied, it defaults to the current buffer.

     If `buffer-name' returns `nil', it means that BUFFER has been
     killed.  *Note Killing Buffers::.

          (buffer-name)
               => "buffers.texi"

          (setq foo (get-buffer "temp"))
               => #<buffer temp>
          (kill-buffer foo)
               => nil
          (buffer-name foo)
               => nil
          foo
               => #<killed buffer>

 -- Command: rename-buffer newname &optional unique
     This function renames the current buffer to NEWNAME.  An error is
     signaled if NEWNAME is not a string.

     Ordinarily, `rename-buffer' signals an error if NEWNAME is already
     in use.  However, if UNIQUE is non-`nil', it modifies NEWNAME to
     make a name that is not in use.  Interactively, you can make
     UNIQUE non-`nil' with a numeric prefix argument.  (This is how the
     command `rename-uniquely' is implemented.)

     This function returns the name actually given to the buffer.

 -- Function: get-buffer buffer-or-name
     This function returns the buffer specified by BUFFER-OR-NAME.  If
     BUFFER-OR-NAME is a string and there is no buffer with that name,
     the value is `nil'.  If BUFFER-OR-NAME is a buffer, it is returned
     as given; that is not very useful, so the argument is usually a
     name.  For example:

          (setq b (get-buffer "lewis"))
               => #<buffer lewis>
          (get-buffer b)
               => #<buffer lewis>
          (get-buffer "Frazzle-nots")
               => nil

     See also the function `get-buffer-create' in *note Creating
     Buffers::.

 -- Function: generate-new-buffer-name starting-name &optional ignore
     This function returns a name that would be unique for a new
     buffer--but does not create the buffer.  It starts with
     STARTING-NAME, and produces a name not currently in use for any
     buffer by appending a number inside of `<...>'.  It starts at 2
     and keeps incrementing the number until it is not the name of an
     existing buffer.

     If the optional second argument IGNORE is non-`nil', it should be
     a string, a potential buffer name.  It means to consider that
     potential buffer acceptable, if it is tried, even it is the name
     of an existing buffer (which would normally be rejected).  Thus, if
     buffers named `foo', `foo<2>', `foo<3>' and `foo<4>' exist,

          (generate-new-buffer-name "foo")
               => "foo<5>"
          (generate-new-buffer-name "foo" "foo<3>")
               => "foo<3>"
          (generate-new-buffer-name "foo" "foo<6>")
               => "foo<5>"

     See the related function `generate-new-buffer' in *note Creating
     Buffers::.


File: elisp,  Node: Buffer File Name,  Next: Buffer Modification,  Prev: Buffer Names,  Up: Buffers

27.4 Buffer File Name
=====================

The "buffer file name" is the name of the file that is visited in that
buffer.  When a buffer is not visiting a file, its buffer file name is
`nil'.  Most of the time, the buffer name is the same as the
nondirectory part of the buffer file name, but the buffer file name and
the buffer name are distinct and can be set independently.  *Note
Visiting Files::.

 -- Function: buffer-file-name &optional buffer
     This function returns the absolute file name of the file that
     BUFFER is visiting.  If BUFFER is not visiting any file,
     `buffer-file-name' returns `nil'.  If BUFFER is not supplied, it
     defaults to the current buffer.

          (buffer-file-name (other-buffer))
               => "/usr/user/lewis/manual/files.texi"

 -- Variable: buffer-file-name
     This buffer-local variable contains the name of the file being
     visited in the current buffer, or `nil' if it is not visiting a
     file.  It is a permanent local variable, unaffected by
     `kill-all-local-variables'.

          buffer-file-name
               => "/usr/user/lewis/manual/buffers.texi"

     It is risky to change this variable's value without doing various
     other things.  Normally it is better to use
     `set-visited-file-name' (see below); some of the things done
     there, such as changing the buffer name, are not strictly
     necessary, but others are essential to avoid confusing Emacs.

 -- Variable: buffer-file-truename
     This buffer-local variable holds the abbreviated truename of the
     file visited in the current buffer, or `nil' if no file is visited.
     It is a permanent local, unaffected by `kill-all-local-variables'.
     *Note Truenames::, and *note Definition of abbreviate-file-name::.

 -- Variable: buffer-file-number
     This buffer-local variable holds the file number and directory
     device number of the file visited in the current buffer, or `nil'
     if no file or a nonexistent file is visited.  It is a permanent
     local, unaffected by `kill-all-local-variables'.

     The value is normally a list of the form `(FILENUM DEVNUM)'.  This
     pair of numbers uniquely identifies the file among all files
     accessible on the system.  See the function `file-attributes', in
     *note File Attributes::, for more information about them.

     If `buffer-file-name' is the name of a symbolic link, then both
     numbers refer to the recursive target.

 -- Function: get-file-buffer filename
     This function returns the buffer visiting file FILENAME.  If there
     is no such buffer, it returns `nil'.  The argument FILENAME, which
     must be a string, is expanded (*note File Name Expansion::), then
     compared against the visited file names of all live buffers.  Note
     that the buffer's `buffer-file-name' must match the expansion of
     FILENAME exactly.  This function will not recognize other names
     for the same file.

          (get-file-buffer "buffers.texi")
              => #<buffer buffers.texi>

     In unusual circumstances, there can be more than one buffer
     visiting the same file name.  In such cases, this function returns
     the first such buffer in the buffer list.

 -- Function: find-buffer-visiting filename &optional predicate
     This is like `get-file-buffer', except that it can return any
     buffer visiting the file _possibly under a different name_.  That
     is, the buffer's `buffer-file-name' does not need to match the
     expansion of FILENAME exactly, it only needs to refer to the same
     file.  If PREDICATE is non-`nil', it should be a function of one
     argument, a buffer visiting FILENAME.  The buffer is only
     considered a suitable return value if PREDICATE returns non-`nil'.
     If it can not find a suitable buffer to return,
     `find-buffer-visiting' returns `nil'.

 -- Command: set-visited-file-name filename &optional no-query
          along-with-file
     If FILENAME is a non-empty string, this function changes the name
     of the file visited in the current buffer to FILENAME.  (If the
     buffer had no visited file, this gives it one.)  The _next time_
     the buffer is saved it will go in the newly-specified file.

     This command marks the buffer as modified, since it does not (as
     far as Emacs knows) match the contents of FILENAME, even if it
     matched the former visited file.  It also renames the buffer to
     correspond to the new file name, unless the new name is already in
     use.

     If FILENAME is `nil' or the empty string, that stands for "no
     visited file."  In this case, `set-visited-file-name' marks the
     buffer as having no visited file, without changing the buffer's
     modified flag.

     Normally, this function asks the user for confirmation if there
     already is a buffer visiting FILENAME.  If NO-QUERY is non-`nil',
     that prevents asking this question.  If there already is a buffer
     visiting FILENAME, and the user confirms or QUERY is non-`nil',
     this function makes the new buffer name unique by appending a
     number inside of `<...>' to FILENAME.

     If ALONG-WITH-FILE is non-`nil', that means to assume that the
     former visited file has been renamed to FILENAME.  In this case,
     the command does not change the buffer's modified flag, nor the
     buffer's recorded last file modification time as reported by
     `visited-file-modtime' (*note Modification Time::).  If
     ALONG-WITH-FILE is `nil', this function clears the recorded last
     file modification time, after which `visited-file-modtime' returns
     zero.

     When the function `set-visited-file-name' is called interactively,
     it prompts for FILENAME in the minibuffer.

 -- Variable: list-buffers-directory
     This buffer-local variable specifies a string to display in a
     buffer listing where the visited file name would go, for buffers
     that don't have a visited file name.  Dired buffers use this
     variable.


File: elisp,  Node: Buffer Modification,  Next: Modification Time,  Prev: Buffer File Name,  Up: Buffers

27.5 Buffer Modification
========================

Emacs keeps a flag called the "modified flag" for each buffer, to
record whether you have changed the text of the buffer.  This flag is
set to `t' whenever you alter the contents of the buffer, and cleared
to `nil' when you save it.  Thus, the flag shows whether there are
unsaved changes.  The flag value is normally shown in the mode line
(*note Mode Line Variables::), and controls saving (*note Saving
Buffers::) and auto-saving (*note Auto-Saving::).

   Some Lisp programs set the flag explicitly.  For example, the
function `set-visited-file-name' sets the flag to `t', because the text
does not match the newly-visited file, even if it is unchanged from the
file formerly visited.

   The functions that modify the contents of buffers are described in
*note Text::.

 -- Function: buffer-modified-p &optional buffer
     This function returns `t' if the buffer BUFFER has been modified
     since it was last read in from a file or saved, or `nil'
     otherwise.  If BUFFER is not supplied, the current buffer is
     tested.

 -- Function: set-buffer-modified-p flag
     This function marks the current buffer as modified if FLAG is
     non-`nil', or as unmodified if the flag is `nil'.

     Another effect of calling this function is to cause unconditional
     redisplay of the mode line for the current buffer.  In fact, the
     function `force-mode-line-update' works by doing this:

          (set-buffer-modified-p (buffer-modified-p))

 -- Function: restore-buffer-modified-p flag
     Like `set-buffer-modified-p', but does not force redisplay of mode
     lines.

 -- Command: not-modified &optional arg
     This command marks the current buffer as unmodified, and not
     needing to be saved.  If ARG is non-`nil', it marks the buffer as
     modified, so that it will be saved at the next suitable occasion.
     Interactively, ARG is the prefix argument.

     Don't use this function in programs, since it prints a message in
     the echo area; use `set-buffer-modified-p' (above) instead.

 -- Function: buffer-modified-tick &optional buffer
     This function returns BUFFER's modification-count.  This is a
     counter that increments every time the buffer is modified.  If
     BUFFER is `nil' (or omitted), the current buffer is used.  The
     counter can wrap around occasionally.

 -- Function: buffer-chars-modified-tick &optional buffer
     This function returns BUFFER's character-change modification-count.
     Changes to text properties leave this counter unchanged; however,
     each time text is inserted or removed from the buffer, the counter
     is reset to the value that would be returned by
     `buffer-modified-tick'.  By comparing the values returned by two
     `buffer-chars-modified-tick' calls, you can tell whether a
     character change occurred in that buffer in between the calls.  If
     BUFFER is `nil' (or omitted), the current buffer is used.


File: elisp,  Node: Modification Time,  Next: Read Only Buffers,  Prev: Buffer Modification,  Up: Buffers

27.6 Buffer Modification Time
=============================

Suppose that you visit a file and make changes in its buffer, and
meanwhile the file itself is changed on disk.  At this point, saving the
buffer would overwrite the changes in the file.  Occasionally this may
be what you want, but usually it would lose valuable information.  Emacs
therefore checks the file's modification time using the functions
described below before saving the file.  (*Note File Attributes::, for
how to examine a file's modification time.)

 -- Function: verify-visited-file-modtime buffer
     This function compares what BUFFER has recorded for the
     modification time of its visited file against the actual
     modification time of the file as recorded by the operating system.
     The two should be the same unless some other process has written
     the file since Emacs visited or saved it.

     The function returns `t' if the last actual modification time and
     Emacs's recorded modification time are the same, `nil' otherwise.
     It also returns `t' if the buffer has no recorded last
     modification time, that is if `visited-file-modtime' would return
     zero.

     It always returns `t' for buffers that are not visiting a file,
     even if `visited-file-modtime' returns a non-zero value.  For
     instance, it always returns `t' for dired buffers.  It returns `t'
     for buffers that are visiting a file that does not exist and never
     existed, but `nil' for file-visiting buffers whose file has been
     deleted.

 -- Function: clear-visited-file-modtime
     This function clears out the record of the last modification time
     of the file being visited by the current buffer.  As a result, the
     next attempt to save this buffer will not complain of a
     discrepancy in file modification times.

     This function is called in `set-visited-file-name' and other
     exceptional places where the usual test to avoid overwriting a
     changed file should not be done.

 -- Function: visited-file-modtime
     This function returns the current buffer's recorded last file
     modification time, as a list of the form `(HIGH LOW)'.  (This is
     the same format that `file-attributes' uses to return time values;
     see *note File Attributes::.)

     If the buffer has no recorded last modification time, this function
     returns zero.  This case occurs, for instance, if the buffer is not
     visiting a file or if the time has been explicitly cleared by
     `clear-visited-file-modtime'.  Note, however, that
     `visited-file-modtime' returns a list for some non-file buffers
     too.  For instance, in a Dired buffer listing a directory, it
     returns the last modification time of that directory, as recorded
     by Dired.

     For a new buffer visiting a not yet existing file, HIGH is -1 and
     LOW is 65535, that is, 2**16 - 1.

 -- Function: set-visited-file-modtime &optional time
     This function updates the buffer's record of the last modification
     time of the visited file, to the value specified by TIME if TIME
     is not `nil', and otherwise to the last modification time of the
     visited file.

     If TIME is neither `nil' nor zero, it should have the form `(HIGH
     . LOW)' or `(HIGH LOW)', in either case containing two integers,
     each of which holds 16 bits of the time.

     This function is useful if the buffer was not read from the file
     normally, or if the file itself has been changed for some known
     benign reason.

 -- Function: ask-user-about-supersession-threat filename
     This function is used to ask a user how to proceed after an
     attempt to modify an buffer visiting file FILENAME when the file
     is newer than the buffer text.  Emacs detects this because the
     modification time of the file on disk is newer than the last
     save-time of the buffer.  This means some other program has
     probably altered the file.

     Depending on the user's answer, the function may return normally,
     in which case the modification of the buffer proceeds, or it may
     signal a `file-supersession' error with data `(FILENAME)', in which
     case the proposed buffer modification is not allowed.

     This function is called automatically by Emacs on the proper
     occasions.  It exists so you can customize Emacs by redefining it.
     See the file `userlock.el' for the standard definition.

     See also the file locking mechanism in *note File Locks::.


File: elisp,  Node: Read Only Buffers,  Next: The Buffer List,  Prev: Modification Time,  Up: Buffers

27.7 Read-Only Buffers
======================

If a buffer is "read-only", then you cannot change its contents,
although you may change your view of the contents by scrolling and
narrowing.

   Read-only buffers are used in two kinds of situations:

   * A buffer visiting a write-protected file is normally read-only.

     Here, the purpose is to inform the user that editing the buffer
     with the aim of saving it in the file may be futile or
     undesirable.  The user who wants to change the buffer text despite
     this can do so after clearing the read-only flag with `C-x C-q'.

   * Modes such as Dired and Rmail make buffers read-only when altering
     the contents with the usual editing commands would probably be a
     mistake.

     The special commands of these modes bind `buffer-read-only' to
     `nil' (with `let') or bind `inhibit-read-only' to `t' around the
     places where they themselves change the text.

 -- Variable: buffer-read-only
     This buffer-local variable specifies whether the buffer is
     read-only.  The buffer is read-only if this variable is non-`nil'.

 -- Variable: inhibit-read-only
     If this variable is non-`nil', then read-only buffers and,
     depending on the actual value, some or all read-only characters
     may be modified.  Read-only characters in a buffer are those that
     have non-`nil' `read-only' properties (either text properties or
     overlay properties).  *Note Special Properties::, for more
     information about text properties.  *Note Overlays::, for more
     information about overlays and their properties.

     If `inhibit-read-only' is `t', all `read-only' character
     properties have no effect.  If `inhibit-read-only' is a list, then
     `read-only' character properties have no effect if they are members
     of the list (comparison is done with `eq').

 -- Command: toggle-read-only &optional arg
     This command toggles whether the current buffer is read-only.  It
     is intended for interactive use; do not use it in programs.  At
     any given point in a program, you should know whether you want the
     read-only flag on or off; so you can set `buffer-read-only'
     explicitly to the proper value, `t' or `nil'.

     If ARG is non-`nil', it should be a raw prefix argument.
     `toggle-read-only' sets `buffer-read-only' to `t' if the numeric
     value of that prefix argument is positive and to `nil' otherwise.
     *Note Prefix Command Arguments::.

 -- Function: barf-if-buffer-read-only
     This function signals a `buffer-read-only' error if the current
     buffer is read-only.  *Note Using Interactive::, for another way to
     signal an error if the current buffer is read-only.


File: elisp,  Node: The Buffer List,  Next: Creating Buffers,  Prev: Read Only Buffers,  Up: Buffers

27.8 The Buffer List
====================

The "buffer list" is a list of all live buffers.  The order of the
buffers in the list is based primarily on how recently each buffer has
been displayed in a window.  Several functions, notably `other-buffer',
use this ordering.  A buffer list displayed for the user also follows
this order.

   Creating a buffer adds it to the end of the buffer list, and killing
a buffer removes it.  Buffers move to the front of the list when they
are selected for display in a window (*note Displaying Buffers::), and
to the end when they are buried (see `bury-buffer', below).  There are
no functions available to the Lisp programmer which directly manipulate
the buffer list.

   In addition to the fundamental Emacs buffer list, each frame has its
own version of the buffer list, in which the buffers that have been
selected in that frame come first, starting with the buffers most
recently selected _in that frame_.  (This order is recorded in FRAME's
`buffer-list' frame parameter; see *note Buffer Parameters::.)  The
buffers that were never selected in FRAME come afterward, ordered
according to the fundamental Emacs buffer list.

 -- Function: buffer-list &optional frame
     This function returns the buffer list, including all buffers, even
     those whose names begin with a space.  The elements are actual
     buffers, not their names.

     If FRAME is a frame, this returns FRAME's buffer list.  If FRAME
     is `nil', the fundamental Emacs buffer list is used: all the
     buffers appear in order of most recent selection, regardless of
     which frames they were selected in.

          (buffer-list)
               => (#<buffer buffers.texi>
                   #<buffer  *Minibuf-1*> #<buffer buffer.c>
                   #<buffer *Help*> #<buffer TAGS>)

          ;; Note that the name of the minibuffer
          ;;   begins with a space!
          (mapcar (function buffer-name) (buffer-list))
              => ("buffers.texi" " *Minibuf-1*"
                  "buffer.c" "*Help*" "TAGS")

   The list that `buffer-list' returns is constructed specifically by
`buffer-list'; it is not an internal Emacs data structure, and
modifying it has no effect on the order of buffers.  If you want to
change the order of buffers in the frame-independent buffer list, here
is an easy way:

     (defun reorder-buffer-list (new-list)
       (while new-list
         (bury-buffer (car new-list))
         (setq new-list (cdr new-list))))

   With this method, you can specify any order for the list, but there
is no danger of losing a buffer or adding something that is not a valid
live buffer.

   To change the order or value of a frame's buffer list, set the
frame's `buffer-list' frame parameter with `modify-frame-parameters'
(*note Parameter Access::).

 -- Function: other-buffer &optional buffer visible-ok frame
     This function returns the first buffer in the buffer list other
     than BUFFER.  Usually this is the buffer selected most recently (in
     frame FRAME or else the currently selected frame, *note Input
     Focus::), aside from BUFFER.  Buffers whose names start with a
     space are not considered at all.

     If BUFFER is not supplied (or if it is not a buffer), then
     `other-buffer' returns the first buffer in the selected frame's
     buffer list that is not now visible in any window in a visible
     frame.

     If FRAME has a non-`nil' `buffer-predicate' parameter, then
     `other-buffer' uses that predicate to decide which buffers to
     consider.  It calls the predicate once for each buffer, and if the
     value is `nil', that buffer is ignored.  *Note Buffer Parameters::.

     If VISIBLE-OK is `nil', `other-buffer' avoids returning a buffer
     visible in any window on any visible frame, except as a last
     resort.   If VISIBLE-OK is non-`nil', then it does not matter
     whether a buffer is displayed somewhere or not.

     If no suitable buffer exists, the buffer `*scratch*' is returned
     (and created, if necessary).

 -- Command: bury-buffer &optional buffer-or-name
     This function puts BUFFER-OR-NAME at the end of the buffer list,
     without changing the order of any of the other buffers on the list.
     This buffer therefore becomes the least desirable candidate for
     `other-buffer' to return.  The argument can be either a buffer
     itself or the name of one.

     `bury-buffer' operates on each frame's `buffer-list' parameter as
     well as the frame-independent Emacs buffer list; therefore, the
     buffer that you bury will come last in the value of `(buffer-list
     FRAME)' and in the value of `(buffer-list nil)'.

     If BUFFER-OR-NAME is `nil' or omitted, this means to bury the
     current buffer.  In addition, if the buffer is displayed in the
     selected window, this switches to some other buffer (obtained using
     `other-buffer') in the selected window.  But if the buffer is
     displayed in some other window, it remains displayed there.

     To replace a buffer in all the windows that display it, use
     `replace-buffer-in-windows'.  *Note Buffers and Windows::.


File: elisp,  Node: Creating Buffers,  Next: Killing Buffers,  Prev: The Buffer List,  Up: Buffers

27.9 Creating Buffers
=====================

This section describes the two primitives for creating buffers.
`get-buffer-create' creates a buffer if it finds no existing buffer
with the specified name; `generate-new-buffer' always creates a new
buffer and gives it a unique name.

   Other functions you can use to create buffers include
`with-output-to-temp-buffer' (*note Temporary Displays::) and
`create-file-buffer' (*note Visiting Files::).  Starting a subprocess
can also create a buffer (*note Processes::).

 -- Function: get-buffer-create name
     This function returns a buffer named NAME.  It returns a live
     buffer with that name, if one exists; otherwise, it creates a new
     buffer.  The buffer does not become the current buffer--this
     function does not change which buffer is current.

     If NAME is a buffer instead of a string, it is returned, even if
     it is dead.  An error is signaled if NAME is neither a string nor
     a buffer.

          (get-buffer-create "foo")
               => #<buffer foo>

     The major mode for a newly created buffer is set to Fundamental
     mode.  (The variable `default-major-mode' is handled at a higher
     level; see *note Auto Major Mode::.)  If the name begins with a
     space, the buffer initially disables undo information recording
     (*note Undo::).

 -- Function: generate-new-buffer name
     This function returns a newly created, empty buffer, but does not
     make it current.  If there is no buffer named NAME, then that is
     the name of the new buffer.  If that name is in use, this function
     adds suffixes of the form `<N>' to NAME, where N is an integer.
     It tries successive integers starting with 2 until it finds an
     available name.

     An error is signaled if NAME is not a string.

          (generate-new-buffer "bar")
               => #<buffer bar>
          (generate-new-buffer "bar")
               => #<buffer bar<2>>
          (generate-new-buffer "bar")
               => #<buffer bar<3>>

     The major mode for the new buffer is set to Fundamental mode.  The
     variable `default-major-mode' is handled at a higher level.  *Note
     Auto Major Mode::.

     See the related function `generate-new-buffer-name' in *note
     Buffer Names::.


File: elisp,  Node: Killing Buffers,  Next: Indirect Buffers,  Prev: Creating Buffers,  Up: Buffers

27.10 Killing Buffers
=====================

"Killing a buffer" makes its name unknown to Emacs and makes the memory
space it occupied available for other use.

   The buffer object for the buffer that has been killed remains in
existence as long as anything refers to it, but it is specially marked
so that you cannot make it current or display it.  Killed buffers retain
their identity, however; if you kill two distinct buffers, they remain
distinct according to `eq' although both are dead.

   If you kill a buffer that is current or displayed in a window, Emacs
automatically selects or displays some other buffer instead.  This means
that killing a buffer can in general change the current buffer.
Therefore, when you kill a buffer, you should also take the precautions
associated with changing the current buffer (unless you happen to know
that the buffer being killed isn't current).  *Note Current Buffer::.

   If you kill a buffer that is the base buffer of one or more indirect
buffers, the indirect buffers are automatically killed as well.

   The `buffer-name' of a killed buffer is `nil'.  You can use this
feature to test whether a buffer has been killed:

     (defun buffer-killed-p (buffer)
       "Return t if BUFFER is killed."
       (not (buffer-name buffer)))

 -- Command: kill-buffer buffer-or-name
     This function kills the buffer BUFFER-OR-NAME, freeing all its
     memory for other uses or to be returned to the operating system.
     If BUFFER-OR-NAME is `nil', it kills the current buffer.

     Any processes that have this buffer as the `process-buffer' are
     sent the `SIGHUP' signal, which normally causes them to terminate.
     (The basic meaning of `SIGHUP' is that a dialup line has been
     disconnected.)  *Note Signals to Processes::.

     If the buffer is visiting a file and contains unsaved changes,
     `kill-buffer' asks the user to confirm before the buffer is killed.
     It does this even if not called interactively.  To prevent the
     request for confirmation, clear the modified flag before calling
     `kill-buffer'.  *Note Buffer Modification::.

     Killing a buffer that is already dead has no effect.

     This function returns `t' if it actually killed the buffer.  It
     returns `nil' if the user refuses to confirm or if BUFFER-OR-NAME
     was already dead.

          (kill-buffer "foo.unchanged")
               => t
          (kill-buffer "foo.changed")

          ---------- Buffer: Minibuffer ----------
          Buffer foo.changed modified; kill anyway? (yes or no) yes
          ---------- Buffer: Minibuffer ----------

               => t

 -- Variable: kill-buffer-query-functions
     After confirming unsaved changes, `kill-buffer' calls the functions
     in the list `kill-buffer-query-functions', in order of appearance,
     with no arguments.  The buffer being killed is the current buffer
     when they are called.  The idea of this feature is that these
     functions will ask for confirmation from the user.  If any of them
     returns `nil', `kill-buffer' spares the buffer's life.

 -- Variable: kill-buffer-hook
     This is a normal hook run by `kill-buffer' after asking all the
     questions it is going to ask, just before actually killing the
     buffer.  The buffer to be killed is current when the hook
     functions run.  *Note Hooks::.  This variable is a permanent
     local, so its local binding is not cleared by changing major modes.

 -- Variable: buffer-offer-save
     This variable, if non-`nil' in a particular buffer, tells
     `save-buffers-kill-emacs' and `save-some-buffers' (if the second
     optional argument to that function is `t') to offer to save that
     buffer, just as they offer to save file-visiting buffers.  *Note
     Definition of save-some-buffers::.  The variable
     `buffer-offer-save' automatically becomes buffer-local when set
     for any reason.  *Note Buffer-Local Variables::.

 -- Variable: buffer-save-without-query
     This variable, if non-`nil' in a particular buffer, tells
     `save-buffers-kill-emacs' and `save-some-buffers' to save this
     buffer (if it's modified) without asking the user.  The variable
     automatically becomes buffer-local when set for any reason.

 -- Function: buffer-live-p object
     This function returns `t' if OBJECT is a buffer which has not been
     killed, `nil' otherwise.


File: elisp,  Node: Indirect Buffers,  Next: Buffer Gap,  Prev: Killing Buffers,  Up: Buffers

27.11 Indirect Buffers
======================

An "indirect buffer" shares the text of some other buffer, which is
called the "base buffer" of the indirect buffer.  In some ways it is
the analogue, for buffers, of a symbolic link among files.  The base
buffer may not itself be an indirect buffer.

   The text of the indirect buffer is always identical to the text of
its base buffer; changes made by editing either one are visible
immediately in the other.  This includes the text properties as well as
the characters themselves.

   In all other respects, the indirect buffer and its base buffer are
completely separate.  They have different names, independent values of
point, independent narrowing, independent markers and overlays (though
inserting or deleting text in either buffer relocates the markers and
overlays for both), independent major modes, and independent
buffer-local variable bindings.

   An indirect buffer cannot visit a file, but its base buffer can.  If
you try to save the indirect buffer, that actually saves the base
buffer.

   Killing an indirect buffer has no effect on its base buffer.  Killing
the base buffer effectively kills the indirect buffer in that it cannot
ever again be the current buffer.

 -- Command: make-indirect-buffer base-buffer name &optional clone
     This creates and returns an indirect buffer named NAME whose base
     buffer is BASE-BUFFER.  The argument BASE-BUFFER may be a live
     buffer or the name (a string) of an existing buffer.  If NAME is
     the name of an existing buffer, an error is signaled.

     If CLONE is non-`nil', then the indirect buffer originally shares
     the "state" of BASE-BUFFER such as major mode, minor modes, buffer
     local variables and so on.  If CLONE is omitted or `nil' the
     indirect buffer's state is set to the default state for new
     buffers.

     If BASE-BUFFER is an indirect buffer, its base buffer is used as
     the base for the new buffer.  If, in addition, CLONE is non-`nil',
     the initial state is copied from the actual base buffer, not from
     BASE-BUFFER.

 -- Function: clone-indirect-buffer newname display-flag &optional
          norecord
     This function creates and returns a new indirect buffer that shares
     the current buffer's base buffer and copies the rest of the current
     buffer's attributes.  (If the current buffer is not indirect, it is
     used as the base buffer.)

     If DISPLAY-FLAG is non-`nil', that means to display the new buffer
     by calling `pop-to-buffer'.  If NORECORD is non-`nil', that means
     not to put the new buffer to the front of the buffer list.

 -- Function: buffer-base-buffer &optional buffer
     This function returns the base buffer of BUFFER, which defaults to
     the current buffer.  If BUFFER is not indirect, the value is
     `nil'.  Otherwise, the value is another buffer, which is never an
     indirect buffer.


File: elisp,  Node: Buffer Gap,  Prev: Indirect Buffers,  Up: Buffers

27.12 The Buffer Gap
====================

Emacs buffers are implemented using an invisible "gap" to make
insertion and deletion faster.  Insertion works by filling in part of
the gap, and deletion adds to the gap.  Of course, this means that the
gap must first be moved to the locus of the insertion or deletion.
Emacs moves the gap only when you try to insert or delete.  This is why
your first editing command in one part of a large buffer, after
previously editing in another far-away part, sometimes involves a
noticeable delay.

   This mechanism works invisibly, and Lisp code should never be
affected by the gap's current location, but these functions are
available for getting information about the gap status.

 -- Function: gap-position
     This function returns the current gap position in the current
     buffer.

 -- Function: gap-size
     This function returns the current gap size of the current buffer.


File: elisp,  Node: Windows,  Next: Frames,  Prev: Buffers,  Up: Top

28 Windows
**********

This chapter describes most of the functions and variables related to
Emacs windows.  See *note Display::, for information on how text is
displayed in windows.

* Menu:

* Basic Windows::           Basic information on using windows.
* Splitting Windows::       Splitting one window into two windows.
* Deleting Windows::        Deleting a window gives its space to other windows.
* Selecting Windows::       The selected window is the one that you edit in.
* Cyclic Window Ordering::  Moving around the existing windows.
* Buffers and Windows::     Each window displays the contents of a buffer.
* Displaying Buffers::      Higher-level functions for displaying a buffer
                              and choosing a window for it.
* Choosing Window::	    How to choose a window for displaying a buffer.
* Window Point::            Each window has its own location of point.
* Window Start::            The display-start position controls which text
                              is on-screen in the window.
* Textual Scrolling::       Moving text up and down through the window.
* Vertical Scrolling::      Moving the contents up and down on the window.
* Horizontal Scrolling::    Moving the contents sideways on the window.
* Size of Window::          Accessing the size of a window.
* Resizing Windows::        Changing the size of a window.
* Coordinates and Windows:: Converting coordinates to windows.
* Window Tree::             The layout and sizes of all windows in a frame.
* Window Configurations::   Saving and restoring the state of the screen.
* Window Hooks::            Hooks for scrolling, window size changes,
                              redisplay going past a certain point,
                              or window configuration changes.


File: elisp,  Node: Basic Windows,  Next: Splitting Windows,  Up: Windows

28.1 Basic Concepts of Emacs Windows
====================================

A "window" in Emacs is the physical area of the screen in which a
buffer is displayed.  The term is also used to refer to a Lisp object
that represents that screen area in Emacs Lisp.  It should be clear
from the context which is meant.

   Emacs groups windows into frames.  A frame represents an area of
screen available for Emacs to use.  Each frame always contains at least
one window, but you can subdivide it vertically or horizontally into
multiple nonoverlapping Emacs windows.

   In each frame, at any time, one and only one window is designated as
"selected within the frame".  The frame's cursor appears in that
window, but the other windows have "non-selected" cursors, normally
less visible.  (*note Cursor Parameters::, for customization of this.)
At any time, one frame is the selected frame; and the window selected
within that frame is "the selected window".  The selected window's
buffer is usually the current buffer (except when `set-buffer' has been
used).  *Note Current Buffer::.

   For practical purposes, a window exists only while it is displayed in
a frame.  Once removed from the frame, the window is effectively deleted
and should not be used, _even though there may still be references to
it_ from other Lisp objects.  Restoring a saved window configuration is
the only way for a window no longer on the screen to come back to life.
(*Note Deleting Windows::.)

   Each window has the following attributes:

   * containing frame

   * window height

   * window width

   * window edges with respect to the screen or frame

   * the buffer it displays

   * position within the buffer at the upper left of the window

   * amount of horizontal scrolling, in columns

   * point

   * the mark

   * how recently the window was selected

   * fringe settings

   * display margins

   * scroll-bar settings

   Users create multiple windows so they can look at several buffers at
once.  Lisp libraries use multiple windows for a variety of reasons, but
most often to display related information.  In Rmail, for example, you
can move through a summary buffer in one window while the other window
shows messages one at a time as they are reached.

   The meaning of "window" in Emacs is similar to what it means in the
context of general-purpose window systems such as X, but not identical.
The X Window System places X windows on the screen; Emacs uses one or
more X windows as frames, and subdivides them into Emacs windows.  When
you use Emacs on a character-only terminal, Emacs treats the whole
terminal screen as one frame.

   Most window systems support arbitrarily located overlapping windows.
In contrast, Emacs windows are "tiled"; they never overlap, and
together they fill the whole screen or frame.  Because of the way in
which Emacs creates new windows and resizes them, not all conceivable
tilings of windows on an Emacs frame are actually possible.  *Note
Splitting Windows::, and *note Size of Window::.

   *Note Display::, for information on how the contents of the window's
buffer are displayed in the window.

 -- Function: windowp object
     This function returns `t' if OBJECT is a window.


File: elisp,  Node: Splitting Windows,  Next: Deleting Windows,  Prev: Basic Windows,  Up: Windows

28.2 Splitting Windows
======================

The functions described here are the primitives used to split a window
into two windows.  Two higher level functions sometimes split a window,
but not always: `pop-to-buffer' and `display-buffer' (*note Displaying
Buffers::).

   The functions described here do not accept a buffer as an argument.
The two "halves" of the split window initially display the same buffer
previously visible in the window that was split.

 -- Command: split-window &optional window size horizontal
     This function splits a new window out of WINDOW's screen area.  It
     returns the new window.

     If HORIZONTAL is non-`nil', then WINDOW splits into two side by
     side windows.  The original window WINDOW keeps the leftmost SIZE
     columns, and gives the rest of the columns to the new window.
     Otherwise, it splits into windows one above the other, and WINDOW
     keeps the upper SIZE lines and gives the rest of the lines to the
     new window.  The original window is therefore the left-hand or
     upper of the two, and the new window is the right-hand or lower.

     If WINDOW is omitted or `nil', that stands for the selected
     window.  When you split the selected window, it remains selected.

     If SIZE is omitted or `nil', then WINDOW is divided evenly into
     two parts.  (If there is an odd line, it is allocated to the new
     window.)  When `split-window' is called interactively, all its
     arguments are `nil'.

     If splitting would result in making a window that is smaller than
     `window-min-height' or `window-min-width', the function signals an
     error and does not split the window at all.

     The following example starts with one window on a screen that is 50
     lines high by 80 columns wide; then it splits the window.

          (setq w (selected-window))
               => #<window 8 on windows.texi>
          (window-edges)          ; Edges in order:
               => (0 0 80 50)     ;   left-top-right-bottom

          ;; Returns window created
          (setq w2 (split-window w 15))
               => #<window 28 on windows.texi>
          (window-edges w2)
               => (0 15 80 50)    ; Bottom window;
                                  ;   top is line 15
          (window-edges w)
               => (0 0 80 15)     ; Top window

     The screen looks like this:

                   __________
                  |          |  line 0
                  |    w     |
                  |__________|
                  |          |  line 15
                  |    w2    |
                  |__________|
                                line 50
           column 0   column 80

     Next, split the top window horizontally:

          (setq w3 (split-window w 35 t))
               => #<window 32 on windows.texi>
          (window-edges w3)
               => (35 0 80 15)  ; Left edge at column 35
          (window-edges w)
               => (0 0 35 15)   ; Right edge at column 35
          (window-edges w2)
               => (0 15 80 50)  ; Bottom window unchanged

     Now the screen looks like this:

               column 35
                   __________
                  |   |      |  line 0
                  | w |  w3  |
                  |___|______|
                  |          |  line 15
                  |    w2    |
                  |__________|
                                line 50
           column 0   column 80

     Normally, Emacs indicates the border between two side-by-side
     windows with a scroll bar (*note Scroll Bars: Layout Parameters.)
     or `|' characters.  The display table can specify alternative
     border characters; see *note Display Tables::.

 -- Command: split-window-vertically &optional size
     This function splits the selected window into two windows, one
     above the other, leaving the upper of the two windows selected,
     with SIZE lines.  (If SIZE is negative, then the lower of the two
     windows gets - SIZE lines and the upper window gets the rest, but
     the upper window is still the one selected.)  However, if
     `split-window-keep-point' (see below) is `nil', then either window
     can be selected.

     In other respects, this function is similar to `split-window'.  In
     particular, the upper window is the original one and the return
     value is the new, lower window.

 -- User Option: split-window-keep-point
     If this variable is non-`nil' (the default), then
     `split-window-vertically' behaves as described above.

     If it is `nil', then `split-window-vertically' adjusts point in
     each of the two windows to avoid scrolling.  (This is useful on
     slow terminals.)  It selects whichever window contains the screen
     line that point was previously on.

     This variable only affects the behavior of
     `split-window-vertically'.  It has no effect on the other
     functions described here.

 -- Command: split-window-horizontally &optional size
     This function splits the selected window into two windows
     side-by-side, leaving the selected window on the left with SIZE
     columns.  If SIZE is negative, the rightmost window gets - SIZE
     columns, but the leftmost window still remains selected.

     This function is basically an interface to `split-window'.  You
     could define a simplified version of the function like this:

          (defun split-window-horizontally (&optional arg)
            "Split selected window into two windows, side by side..."
            (interactive "P")
            (let ((size (and arg (prefix-numeric-value arg))))
              (and size (< size 0)
          	 (setq size (+ (window-width) size)))
              (split-window nil size t)))

 -- Function: one-window-p &optional no-mini all-frames
     This function returns non-`nil' if there is only one window.  The
     argument NO-MINI, if non-`nil', means don't count the minibuffer
     even if it is active; otherwise, the minibuffer window is counted
     when it is active.

     The argument ALL-FRAMES specifies which frames to consider.  Here
     are the possible values and their meanings:

    `nil'
          Count the windows in the selected frame, plus the minibuffer
          used by that frame even if it lies in some other frame.

    `t'
          Count all windows in all existing frames.

    `visible'
          Count all windows in all visible frames.

    0
          Count all windows in all visible or iconified frames.

    anything else
          Count precisely the windows in the selected frame, and no
          others.


File: elisp,  Node: Deleting Windows,  Next: Selecting Windows,  Prev: Splitting Windows,  Up: Windows

28.3 Deleting Windows
=====================

A window remains visible on its frame unless you "delete" it by calling
certain functions that delete windows.  A deleted window cannot appear
on the screen, but continues to exist as a Lisp object until there are
no references to it.  There is no way to cancel the deletion of a
window aside from restoring a saved window configuration (*note Window
Configurations::).  Restoring a window configuration also deletes any
windows that aren't part of that configuration.

   When you delete a window, the space it took up is given to one
adjacent sibling.

 -- Function: window-live-p window
     This function returns `nil' if WINDOW is deleted, and `t'
     otherwise.

     *Warning:* Erroneous information or fatal errors may result from
     using a deleted window as if it were live.

 -- Command: delete-window &optional window
     This function removes WINDOW from display, and returns `nil'.  If
     WINDOW is omitted, then the selected window is deleted.  An error
     is signaled if there is only one window when `delete-window' is
     called.

 -- Command: delete-other-windows &optional window
     This function makes WINDOW the only window on its frame, by
     deleting the other windows in that frame.  If WINDOW is omitted or
     `nil', then the selected window is used by default.

     The return value is `nil'.

 -- Command: delete-windows-on buffer-or-name &optional frame
     This function deletes all windows showing BUFFER-OR-NAME.  If
     there are no windows showing BUFFER-OR-NAME, it does nothing.
     BUFFER-OR-NAME must be a buffer or the name of an existing buffer.

     `delete-windows-on' operates frame by frame.  If a frame has
     several windows showing different buffers, then those showing
     BUFFER-OR-NAME are removed, and the others expand to fill the
     space.  If all windows in some frame are showing BUFFER-OR-NAME
     (including the case where there is only one window), then the frame
     winds up with a single window showing another buffer chosen with
     `other-buffer'.  *Note The Buffer List::.

     The argument FRAME controls which frames to operate on.  This
     function does not use it in quite the same way as the other
     functions which scan all windows; specifically, the values `t' and
     `nil' have the opposite of their meanings in other functions.
     Here are the full details:

        * If it is `nil', operate on all frames.

        * If it is `t', operate on the selected frame.

        * If it is `visible', operate on all visible frames.

        * If it is 0, operate on all visible or iconified frames.

        * If it is a frame, operate on that frame.

     This function always returns `nil'.


File: elisp,  Node: Selecting Windows,  Next: Cyclic Window Ordering,  Prev: Deleting Windows,  Up: Windows

28.4 Selecting Windows
======================

When a window is selected, the buffer in the window becomes the current
buffer, and the cursor will appear in it.

 -- Function: selected-window
     This function returns the selected window.  This is the window in
     which the cursor appears and to which many commands apply.

 -- Function: select-window window &optional norecord
     This function makes WINDOW the selected window.  The cursor then
     appears in WINDOW (on redisplay).  Unless WINDOW was already
     selected, `select-window' makes WINDOW's buffer the current buffer.

     Normally WINDOW's selected buffer is moved to the front of the
     buffer list, but if NORECORD is non-`nil', the buffer list order
     is unchanged.

     The return value is WINDOW.

          (setq w (next-window))
          (select-window w)
               => #<window 65 on windows.texi>

 -- Macro: save-selected-window forms...
     This macro records the selected frame, as well as the selected
     window of each frame, executes FORMS in sequence, then restores the
     earlier selected frame and windows.  It also saves and restores the
     current buffer.  It returns the value of the last form in FORMS.

     This macro does not save or restore anything about the sizes,
     arrangement or contents of windows; therefore, if the FORMS change
     them, the change persists.  If the previously selected window of
     some frame is no longer live at the time of exit from FORMS, that
     frame's selected window is left alone.  If the previously selected
     window is no longer live, then whatever window is selected at the
     end of FORMS remains selected.

 -- Macro: with-selected-window window forms...
     This macro selects WINDOW (without changing the buffer list),
     executes FORMS in sequence, then restores the previously selected
     window and current buffer.  It is just like
     `save-selected-window', except that it explicitly selects WINDOW,
     also without altering the buffer list sequence.

   The following functions choose one of the windows on the screen,
offering various criteria for the choice.

 -- Function: get-lru-window &optional frame dedicated
     This function returns the window least recently "used" (that is,
     selected).  If any full-width windows are present, it only
     considers these.  The selected window is always the most recently
     used window.

     The selected window can be the least recently used window if it is
     the only window.  A newly created window becomes the least
     recently used window until it is selected.  A minibuffer window is
     never a candidate.  Dedicated windows are never candidates unless
     the DEDICATED argument is non-`nil', so if all existing windows
     are dedicated, the value is `nil'.

     The argument FRAME controls which windows are considered.

        * If it is `nil', consider windows on the selected frame.

        * If it is `t', consider windows on all frames.

        * If it is `visible', consider windows on all visible frames.

        * If it is 0, consider windows on all visible or iconified
          frames.

        * If it is a frame, consider windows on that frame.

 -- Function: get-largest-window &optional frame dedicated
     This function returns the window with the largest area (height
     times width).  If there are no side-by-side windows, then this is
     the window with the most lines.  A minibuffer window is never a
     candidate.  Dedicated windows are never candidates unless the
     DEDICATED argument is non-`nil', so if all existing windows are
     dedicated, the value is `nil'.

     If there are two candidate windows of the same size, this function
     prefers the one that comes first in the cyclic ordering of windows
     (see following section), starting from the selected window.

     The argument FRAME controls which set of windows to consider.  See
     `get-lru-window', above.

 -- Function: get-window-with-predicate predicate &optional minibuf
          all-frames default
     This function returns a window satisfying PREDICATE.  It cycles
     through all visible windows using `walk-windows' (*note Cyclic
     Window Ordering::), calling PREDICATE on each one of them with
     that window as its argument.  The function returns the first
     window for which PREDICATE returns a non-`nil' value; if that
     never happens, it returns DEFAULT.

     The optional arguments MINIBUF and ALL-FRAMES specify the set of
     windows to include in the scan.  See the description of
     `next-window' in *note Cyclic Window Ordering::, for details.


File: elisp,  Node: Cyclic Window Ordering,  Next: Buffers and Windows,  Prev: Selecting Windows,  Up: Windows

28.5 Cyclic Ordering of Windows
===============================

When you use the command `C-x o' (`other-window') to select the next
window, it moves through all the windows on the screen in a specific
cyclic order.  For any given configuration of windows, this order never
varies.  It is called the "cyclic ordering of windows".

   This ordering generally goes from top to bottom, and from left to
right.  But it may go down first or go right first, depending on the
order in which the windows were split.

   If the first split was vertical (into windows one above each other),
and then the subwindows were split horizontally, then the ordering is
left to right in the top of the frame, and then left to right in the
next lower part of the frame, and so on.  If the first split was
horizontal, the ordering is top to bottom in the left part, and so on.
In general, within each set of siblings at any level in the window tree,
the order is left to right, or top to bottom.

 -- Function: next-window &optional window minibuf all-frames
     This function returns the window following WINDOW in the cyclic
     ordering of windows.  This is the window that `C-x o' would select
     if typed when WINDOW is selected.  If WINDOW is the only window
     visible, then this function returns WINDOW.  If omitted, WINDOW
     defaults to the selected window.

     The value of the argument MINIBUF determines whether the
     minibuffer is included in the window order.  Normally, when
     MINIBUF is `nil', the minibuffer is included if it is currently
     active; this is the behavior of `C-x o'.  (The minibuffer window
     is active while the minibuffer is in use.  *Note Minibuffers::.)

     If MINIBUF is `t', then the cyclic ordering includes the
     minibuffer window even if it is not active.

     If MINIBUF is neither `t' nor `nil', then the minibuffer window is
     not included even if it is active.

     The argument ALL-FRAMES specifies which frames to consider.  Here
     are the possible values and their meanings:

    `nil'
          Consider all the windows in WINDOW's frame, plus the
          minibuffer used by that frame even if it lies in some other
          frame.  If the minibuffer counts (as determined by MINIBUF),
          then all windows on all frames that share that minibuffer
          count too.

    `t'
          Consider all windows in all existing frames.

    `visible'
          Consider all windows in all visible frames.  (To get useful
          results, you must ensure WINDOW is in a visible frame.)

    0
          Consider all windows in all visible or iconified frames.

    a frame
          Consider all windows on that frame.

    anything else
          Consider precisely the windows in WINDOW's frame, and no
          others.

     This example assumes there are two windows, both displaying the
     buffer `windows.texi':

          (selected-window)
               => #<window 56 on windows.texi>
          (next-window (selected-window))
               => #<window 52 on windows.texi>
          (next-window (next-window (selected-window)))
               => #<window 56 on windows.texi>

 -- Function: previous-window &optional window minibuf all-frames
     This function returns the window preceding WINDOW in the cyclic
     ordering of windows.  The other arguments specify which windows to
     include in the cycle, as in `next-window'.

 -- Command: other-window count &optional all-frames
     This function selects the COUNTth following window in the cyclic
     order.  If count is negative, then it moves back -COUNT windows in
     the cycle, rather than forward.  It returns `nil'.

     The argument ALL-FRAMES has the same meaning as in `next-window',
     but the MINIBUF argument of `next-window' is always effectively
     `nil'.

     In an interactive call, COUNT is the numeric prefix argument.

 -- Function: walk-windows proc &optional minibuf all-frames
     This function cycles through all windows.  It calls the function
     `proc' once for each window, with the window as its sole argument.

     The optional arguments MINIBUF and ALL-FRAMES specify the set of
     windows to include in the scan.  See `next-window', above, for
     details.

 -- Function: window-list &optional frame minibuf window
     This function returns a list of the windows on FRAME, starting
     with WINDOW.  If FRAME is `nil' or omitted, `window-list' uses the
     selected frame instead; if WINDOW is `nil' or omitted, it uses the
     selected window.

     The value of MINIBUF determines if the minibuffer window is
     included in the result list.  If MINIBUF is `t', the result always
     includes the minibuffer window.  If MINIBUF is `nil' or omitted,
     that includes the minibuffer window if it is active.  If MINIBUF
     is neither `nil' nor `t', the result never includes the minibuffer
     window.


File: elisp,  Node: Buffers and Windows,  Next: Displaying Buffers,  Prev: Cyclic Window Ordering,  Up: Windows

28.6 Buffers and Windows
========================

This section describes low-level functions to examine windows or to
display buffers in windows in a precisely controlled fashion.  *Note
Displaying Buffers::, for related functions that find a window to use
and specify a buffer for it.  The functions described there are easier
to use than these, but they employ heuristics in choosing or creating a
window; use these functions when you need complete control.

 -- Function: set-window-buffer window buffer-or-name &optional
          keep-margins
     This function makes WINDOW display BUFFER-OR-NAME as its contents.
     It returns `nil'.  BUFFER-OR-NAME must be a buffer, or the name of
     an existing buffer.  This is the fundamental primitive for
     changing which buffer is displayed in a window, and all ways of
     doing that call this function.

          (set-window-buffer (selected-window) "foo")
               => nil

     Normally, displaying BUFFER in WINDOW resets the window's display
     margins, fringe widths, scroll bar settings, and position based on
     the local variables of BUFFER.  However, if KEEP-MARGINS is
     non-`nil', the display margins and fringe widths of WINDOW remain
     unchanged.  *Note Fringes::.

 -- Variable: buffer-display-count
     This buffer-local variable records the number of times a buffer is
     displayed in a window.  It is incremented each time
     `set-window-buffer' is called for the buffer.

 -- Function: window-buffer &optional window
     This function returns the buffer that WINDOW is displaying.  If
     WINDOW is omitted, this function returns the buffer for the
     selected window.

          (window-buffer)
               => #<buffer windows.texi>

 -- Function: get-buffer-window buffer-or-name &optional all-frames
     This function returns a window currently displaying
     BUFFER-OR-NAME, or `nil' if there is none.  If there are several
     such windows, then the function returns the first one in the
     cyclic ordering of windows, starting from the selected window.
     *Note Cyclic Window Ordering::.

     The argument ALL-FRAMES controls which windows to consider.

        * If it is `nil', consider windows on the selected frame.

        * If it is `t', consider windows on all frames.

        * If it is `visible', consider windows on all visible frames.

        * If it is 0, consider windows on all visible or iconified
          frames.

        * If it is a frame, consider windows on that frame.

 -- Function: get-buffer-window-list buffer-or-name &optional minibuf
          all-frames
     This function returns a list of all the windows currently
     displaying BUFFER-OR-NAME.

     The two optional arguments work like the optional arguments of
     `next-window' (*note Cyclic Window Ordering::); they are _not_
     like the single optional argument of `get-buffer-window'.  Perhaps
     we should change `get-buffer-window' in the future to make it
     compatible with the other functions.

 -- Variable: buffer-display-time
     This variable records the time at which a buffer was last made
     visible in a window.  It is always local in each buffer; each time
     `set-window-buffer' is called, it sets this variable to
     `(current-time)' in the specified buffer (*note Time of Day::).
     When a buffer is first created, `buffer-display-time' starts out
     with the value `nil'.

