files.texi 132 KB
Newer Older
Glenn Morris's avatar
Glenn Morris committed
1 2
@c -*-texinfo-*-
@c This is part of the GNU Emacs Lisp Reference Manual.
3
@c Copyright (C) 1990-1995, 1998-1999, 2001-2014 Free Software
4
@c Foundation, Inc.
Glenn Morris's avatar
Glenn Morris committed
5
@c See the file elisp.texi for copying conditions.
6
@node Files
Glenn Morris's avatar
Glenn Morris committed
7 8
@chapter Files

9
  This chapter describes the Emacs Lisp functions and variables to
Chong Yidong's avatar
Chong Yidong committed
10
find, create, view, save, and otherwise work with files and
11
directories.  A few other file-related functions are described in
Glenn Morris's avatar
Glenn Morris committed
12 13 14 15
@ref{Buffers}, and those related to backups and auto-saving are
described in @ref{Backups and Auto-Saving}.

  Many of the file functions take one or more arguments that are file
Chong Yidong's avatar
Chong Yidong committed
16 17
names.  A file name is a string.  Most of these functions expand file
name arguments using the function @code{expand-file-name}, so that
Glenn Morris's avatar
Glenn Morris committed
18
@file{~} is handled correctly, as are relative file names (including
Chong Yidong's avatar
Chong Yidong committed
19
@file{../}).  @xref{File Name Expansion}.
20 21 22

  In addition, certain @dfn{magic} file names are handled specially.
For example, when a remote file name is specified, Emacs accesses the
Chong Yidong's avatar
Chong Yidong committed
23 24
file over the network via an appropriate protocol.  @xref{Remote
Files,, Remote Files, emacs, The GNU Emacs Manual}.  This handling is
25 26 27
done at a very low level, so you may assume that all the functions
described in this chapter accept magic file names as file name
arguments, except where noted.  @xref{Magic File Names}, for details.
Glenn Morris's avatar
Glenn Morris committed
28 29 30 31

  When file I/O functions signal Lisp errors, they usually use the
condition @code{file-error} (@pxref{Handling Errors}).  The error
message is in most cases obtained from the operating system, according
Leo Liu's avatar
Leo Liu committed
32
to locale @code{system-messages-locale}, and decoded using coding system
Glenn Morris's avatar
Glenn Morris committed
33 34 35 36 37 38 39 40 41 42
@code{locale-coding-system} (@pxref{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.
43
* Changing Files::           Renaming files, changing permissions, etc.
Glenn Morris's avatar
Glenn Morris committed
44 45
* File Names::               Decomposing and expanding file names.
* Contents of Directories::  Getting a list of the files in a directory.
Glenn Morris's avatar
Glenn Morris committed
46
* Create/Delete Dirs::       Creating and Deleting Directories.
47
* Magic File Names::         Special handling for certain file names.
Glenn Morris's avatar
Glenn Morris committed
48 49 50 51 52 53 54 55 56 57 58 59 60
* Format Conversion::        Conversion to and from various file formats.
@end menu

@node Visiting Files
@section Visiting Files
@cindex finding files
@cindex visiting files

  Visiting a file means reading a file into a buffer.  Once this is
done, we say that the buffer is @dfn{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
Chong Yidong's avatar
Chong Yidong committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
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).  When a buffer is visiting a file, it contains information
copied from the file.  The copy in the buffer is what you modify with
editing commands.  Changes to the buffer do not change the file; to
make the changes permanent, you must @dfn{save} the buffer, which
means copying the altered buffer contents back into the file.

  Despite 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.
Glenn Morris's avatar
Glenn Morris committed
76 77 78 79 80 81 82 83

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

@node Visiting Functions
@subsection Functions for Visiting Files
84 85
@cindex visiting files, functions for
@cindex how to visit files
Glenn Morris's avatar
Glenn Morris committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

  This section describes the functions normally used to visit files.
For historical reasons, these functions have names starting with
@samp{find-} rather than @samp{visit-}.  @xref{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 @code{insert-file-contents} in a
temporary buffer.  Visiting the file is not necessary and takes longer.
@xref{Reading from Files}.

@deffn Command find-file filename &optional wildcards
This command selects a buffer visiting the file @var{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 @code{find-file}
function is basically equivalent to:

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

@noindent
111
(See @code{switch-to-buffer} in @ref{Switching Buffers}.)
Glenn Morris's avatar
Glenn Morris committed
112 113 114 115 116 117 118 119 120

If @var{wildcards} is non-@code{nil}, which is always true in an
interactive call, then @code{find-file} expands wildcard characters in
@var{filename} and visits all the matching files.

When @code{find-file} is called interactively, it prompts for
@var{filename} in the minibuffer.
@end deffn

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
@deffn Command find-file-literally filename
This command visits @var{filename}, like @code{find-file} does, but it
does not perform any format conversions (@pxref{Format Conversion}),
character code conversions (@pxref{Coding Systems}), or end-of-line
conversions (@pxref{Coding System Basics, End of line conversion}).
The buffer visiting the file is made unibyte, and its major mode is
Fundamental mode, regardless of the file name.  File local variable
specifications  in the file (@pxref{File Local Variables}) are
ignored, and automatic decompression and adding a newline at the end
of the file due to @code{require-final-newline} (@pxref{Saving
Buffers, require-final-newline}) are also disabled.

Note that if Emacs already has a buffer visiting the same file
non-literally, it will not visit the same file literally, but instead
just switch to the existing buffer.  If you want to be sure of
accessing a file's contents literally, you should create a temporary
buffer and then read the file contents into it using
@code{insert-file-contents-literally} (@pxref{Reading from Files}).
@end deffn

Glenn Morris's avatar
Glenn Morris committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
@defun 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 @var{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
@code{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 @samp{yes}, any
edits previously made in the buffer are lost.

Reading the file involves decoding the file's contents (@pxref{Coding
Systems}), including end-of-line conversion, and format conversion
(@pxref{Format Conversion}).  If @var{wildcards} is non-@code{nil},
then @code{find-file-noselect} expands wildcard characters in
@var{filename} and visits all the matching files.

This function displays warning or advisory messages in various peculiar
cases, unless the optional argument @var{nowarn} is non-@code{nil}.  For
example, if it needs to create a buffer, and there is no file named
@var{filename}, it displays the message @samp{(New file)} in the echo
area, and leaves the buffer empty.

The @code{find-file-noselect} function normally calls
@code{after-find-file} after reading the file (@pxref{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
@code{find-file-hook}.

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

The @code{find-file-noselect} function usually returns the buffer that
is visiting the file @var{filename}.  But, if wildcards are actually
used and expanded, it returns a list of buffers that are visiting the
various files.

@example
@group
(find-file-noselect "/etc/fstab")
     @result{} #<buffer fstab>
@end group
@end example
@end defun

@deffn Command find-file-other-window filename &optional wildcards
This command selects a buffer visiting the file @var{filename}, but
195 196 197
does so in a window other than the selected window.  It may use
another existing window or split a window; see @ref{Switching
Buffers}.
Glenn Morris's avatar
Glenn Morris committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

When this command is called interactively, it prompts for
@var{filename}.
@end deffn

@deffn Command find-file-read-only filename &optional wildcards
This command selects a buffer visiting the file @var{filename}, like
@code{find-file}, but it marks the buffer as read-only.  @xref{Read Only
Buffers}, for related functions and variables.

When this command is called interactively, it prompts for
@var{filename}.
@end deffn

@defopt find-file-wildcards
If this variable is non-@code{nil}, then the various @code{find-file}
commands check for wildcard characters and visit all the files that
match them (when invoked interactively or when their @var{wildcards}
argument is non-@code{nil}).  If this option is @code{nil}, then
the @code{find-file} commands ignore their @var{wildcards} argument
and never treat wildcard characters specially.
@end defopt

221
@defopt find-file-hook
Glenn Morris's avatar
Glenn Morris committed
222 223 224 225 226 227
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.  @xref{Hooks}.
228
@end defopt
Glenn Morris's avatar
Glenn Morris committed
229 230 231 232 233 234 235 236 237 238 239 240 241

@defvar find-file-not-found-functions
The value of this variable is a list of functions to be called when
@code{find-file} or @code{find-file-noselect} is passed a nonexistent
file name.  @code{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-@code{nil}.  @code{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.
@end defvar

242 243 244
@defvar find-file-literally
This buffer-local variable, if set to a non-@code{nil} value, makes
@code{save-buffer} behave as if the buffer were visiting its file
245
literally, i.e., without conversions of any kind.  The command
246
@code{find-file-literally} sets this variable's local value, but other
247
equivalent functions and commands can do that as well, e.g., to avoid
248
automatic addition of a newline at the end of the file.  This variable
249
is permanent local, so it is unaffected by changes of major modes.
250 251
@end defvar

Glenn Morris's avatar
Glenn Morris committed
252 253 254 255 256 257 258
@node Subroutines of Visiting
@subsection Subroutines of Visiting

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

Glenn Morris's avatar
Glenn Morris committed
259 260 261
@c FIXME This does not describe the default behavior, because
@c uniquify is enabled by default and advises this function.
@c This is confusing.  uniquify should be folded into the function proper.
Glenn Morris's avatar
Glenn Morris committed
262 263 264 265 266
@defun create-file-buffer filename
This function creates a suitably named buffer for visiting
@var{filename}, and returns it.  It uses @var{filename} (sans directory)
as the name if that name is free; otherwise, it appends a string such as
@samp{<2>} to get an unused name.  See also @ref{Creating Buffers}.
Glenn Morris's avatar
Glenn Morris committed
267 268
Note that the @file{uniquify} library affects the result of this
function.  @xref{Uniquify,,, emacs, The GNU Emacs Manual}.
Glenn Morris's avatar
Glenn Morris committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

@strong{Please note:} @code{create-file-buffer} does @emph{not}
associate the new buffer with a file and does not select the buffer.
It also does not use the default major mode.

@example
@group
(create-file-buffer "foo")
     @result{} #<buffer foo>
@end group
@group
(create-file-buffer "foo")
     @result{} #<buffer foo<2>>
@end group
@group
(create-file-buffer "foo")
     @result{} #<buffer foo<3>>
@end group
@end example

This function is used by @code{find-file-noselect}.
It uses @code{generate-new-buffer} (@pxref{Creating Buffers}).
@end defun

@defun 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
(@pxref{Auto Major Mode}).  It is called by @code{find-file-noselect}
and by the default revert function (@pxref{Reverting}).

@cindex new file message
@cindex file open error
If reading the file got an error because the file does not exist, but
its directory does exist, the caller should pass a non-@code{nil} value
for @var{error}.  In that case, @code{after-find-file} issues a warning:
@samp{(New file)}.  For more serious errors, the caller should usually not
call @code{after-find-file}.

If @var{warn} is non-@code{nil}, then this function issues a warning
if an auto-save file exists and is more recent than the visited file.

If @var{noauto} is non-@code{nil}, that says not to enable or disable
Auto-Save mode.  The mode remains enabled if it was enabled before.

If @var{after-find-file-from-revert-buffer} is non-@code{nil}, that
means this call was from @code{revert-buffer}.  This has no direct
effect, but some mode functions and hook functions check the value
of this variable.

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

The last thing @code{after-find-file} does is call all the functions
in the list @code{find-file-hook}.
@end defun

@node Saving Buffers
@section Saving Buffers
@cindex 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 @dfn{save} the buffer, which
means copying the contents of the buffer into the file.

@deffn 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.

@code{save-buffer} is responsible for making backup files.  Normally,
@var{backup-option} is @code{nil}, and @code{save-buffer} makes a backup
file only if this is the first save since visiting the file.  Other
values for @var{backup-option} request the making of backup files in
other circumstances:

@itemize @bullet
@item
With an argument of 4 or 64, reflecting 1 or 3 @kbd{C-u}'s, the
@code{save-buffer} function marks this version of the file to be
backed up when the buffer is next saved.

@item
With an argument of 16 or 64, reflecting 2 or 3 @kbd{C-u}'s, the
@code{save-buffer} function unconditionally backs up the previous
version of the file before saving it.

@item
With an argument of 0, unconditionally do @emph{not} make any backup file.
@end itemize
@end deffn

@deffn Command save-some-buffers &optional save-silently-p pred
@anchor{Definition of save-some-buffers}
This command saves some modified file-visiting buffers.  Normally it
asks the user about each buffer.  But if @var{save-silently-p} is
non-@code{nil}, it saves all the file-visiting buffers without querying
the user.

The optional @var{pred} argument controls which buffers to ask about
(or to save silently if @var{save-silently-p} is non-@code{nil}).
If it is @code{nil}, that means to ask only about file-visiting buffers.
If it is @code{t}, that means also offer to save certain other non-file
buffers---those that have a non-@code{nil} buffer-local value of
@code{buffer-offer-save} (@pxref{Killing Buffers}).  A user who says
@samp{yes} to saving a non-file buffer is asked to specify the file
name to use.  The @code{save-buffers-kill-emacs} function passes the
value @code{t} for @var{pred}.

If @var{pred} is neither @code{t} nor @code{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-@code{nil}
value in a certain buffer, that means do offer to save that buffer.
@end deffn

@deffn Command write-file filename &optional confirm
@anchor{Definition of write-file}
This function writes the current buffer into file @var{filename}, makes
the buffer visit that file, and marks it not modified.  Then it renames
the buffer based on @var{filename}, appending a string like @samp{<2>}
if necessary to make a unique buffer name.  It does most of this work by
calling @code{set-visited-file-name} (@pxref{Buffer File Name}) and
@code{save-buffer}.

If @var{confirm} is non-@code{nil}, that means to ask for confirmation
before overwriting an existing file.  Interactively, confirmation is
required, unless the user supplies a prefix argument.

If @var{filename} is an existing directory, or a symbolic link to one,
@code{write-file} uses the name of the visited file, in directory
@var{filename}.  If the buffer is not visiting a file, it uses the
buffer name instead.
@end deffn

  Saving a buffer runs several hooks.  It also performs format
conversion (@pxref{Format Conversion}).

@defvar 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-@code{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 @code{write-file-functions} returns non-@code{nil}, it
is responsible for making a backup file (if that is appropriate).
To do so, execute the following code:

@example
(or buffer-backed-up (backup-buffer))
@end example

You might wish to save the file modes value returned by
@code{backup-buffer} and use that (if non-@code{nil}) to set the mode
bits of the file that you write.  This is what @code{save-buffer}
normally does. @xref{Making Backups,, Making Backup Files}.

The hook functions in @code{write-file-functions} are also responsible
for encoding the data (if desired): they must choose a suitable coding
system and end-of-line conversion (@pxref{Lisp and Coding Systems}),
perform the encoding (@pxref{Explicit Encoding}), and set
@code{last-coding-system-used} to the coding system that was used
(@pxref{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 @code{set-visited-file-name} will reset it.
If this is not what you want, you might like to use
@code{write-contents-functions} instead.

Even though this is not a normal hook, you can use @code{add-hook} and
@code{remove-hook} to manipulate the list.  @xref{Hooks}.
@end defvar

@c Emacs 19 feature
@defvar write-contents-functions
This works just like @code{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
@code{set-visited-file-name} does not.

If any of the functions in this hook returns non-@code{nil}, the file
is considered already written and the rest are not called and neither
are the functions in @code{write-file-functions}.
@end defvar

@defopt 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 @file{copyright.el} program uses
this hook to make sure the file you are saving has the current year in
its copyright notice.
@end defopt

@c Emacs 19 feature
@defopt 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.
@end defopt

@defopt file-precious-flag
If this variable is non-@code{nil}, then @code{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.  @xref{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-@code{nil} buffer-local value
in particular buffers.
@end defopt

@defopt require-final-newline
This variable determines whether files may be written out that do
@emph{not} end with a newline.  If the value of the variable is
496 497 498 499 500 501 502
@code{t}, then @code{save-buffer} silently adds a newline at the end
of the buffer whenever it does not already end in one.  If the value
is @code{visit}, Emacs adds a missing newline just after it visits the
file.  If the value is @code{visit-save}, Emacs adds a missing newline
both on visiting and on saving.  For any other non-@code{nil} value,
@code{save-buffer} asks the user whether to add a newline each time
the case arises.
Glenn Morris's avatar
Glenn Morris committed
503 504 505 506 507 508 509 510 511 512 513 514 515

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

  See also the function @code{set-visited-file-name} (@pxref{Buffer File
Name}).

@node Reading from Files
@section Reading from Files
@cindex reading from files

Chong Yidong's avatar
Chong Yidong committed
516 517 518
  To copy the contents of a file into a buffer, use the function
@code{insert-file-contents}.  (Don't use the command
@code{insert-file} in a Lisp program, as that sets the mark.)
Glenn Morris's avatar
Glenn Morris committed
519 520 521 522 523 524 525

@defun insert-file-contents filename &optional visit beg end replace
This function inserts the contents of file @var{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
@var{filename} is not the name of a file that can be read.

526 527 528 529
This function checks the file contents against the defined file
formats, and converts the file contents if appropriate and also calls
the functions in the list @code{after-insert-file-functions}.
@xref{Format Conversion}.  Normally, one of the functions in the
Glenn Morris's avatar
Glenn Morris committed
530 531
@code{after-insert-file-functions} list determines the coding system
(@pxref{Coding Systems}) used for decoding the file's contents,
532
including end-of-line conversion.  However, if the file contains null
533 534
bytes, it is by default visited without any code conversions.
@xref{Lisp and Coding Systems, inhibit-null-byte-detection}.
Glenn Morris's avatar
Glenn Morris committed
535 536 537 538 539 540 541

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

542 543 544
If @var{beg} and @var{end} are non-@code{nil}, they should be numbers
that are byte offsets specifying the portion of the file to insert.
In this case, @var{visit} must be @code{nil}.  For example,
Glenn Morris's avatar
Glenn Morris committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564

@example
(insert-file-contents filename nil 0 500)
@end example

@noindent
inserts the first 500 characters of a file.

If the argument @var{replace} is non-@code{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 @code{insert-file-contents}, as long as @var{replace} and
@var{visit} are @code{nil}.
@end defun

@defun insert-file-contents-literally filename &optional visit beg end replace
565 566 567
This function works like @code{insert-file-contents} except that it
does not run @code{find-file-hook}, and does not do format decoding,
character code conversion, automatic uncompression, and so on.
Glenn Morris's avatar
Glenn Morris committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
@end defun

If you want to pass a file name to another process so that another
program can read the file, use the function @code{file-local-copy}; see
@ref{Magic File Names}.

@node Writing to Files
@section Writing to Files
@cindex writing to files

  You can write the contents of a buffer, or part of a buffer, directly
to a file on disk using the @code{append-to-file} and
@code{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.

@deffn Command append-to-file start end filename
This function appends the contents of the region delimited by
@var{start} and @var{end} in the current buffer to the end of file
@var{filename}.  If that file does not exist, it is created.  This
function returns @code{nil}.

An error is signaled if @var{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:

@example
(write-region start end filename t)
@end example
@end deffn

@deffn Command write-region start end filename &optional append visit lockname mustbenew
This function writes the region delimited by @var{start} and @var{end}
in the current buffer into the file specified by @var{filename}.

If @var{start} is @code{nil}, then the command writes the entire buffer
contents (@emph{not} just the accessible portion) to the file and
ignores @var{end}.

@c Emacs 19 feature
If @var{start} is a string, then @code{write-region} writes or appends
that string, rather than text from the buffer.  @var{end} is ignored in
this case.

If @var{append} is non-@code{nil}, then the specified text is appended
614 615
to the existing file contents (if any).  If @var{append} is a
number, @code{write-region} seeks to that byte offset from the start
Glenn Morris's avatar
Glenn Morris committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
of the file and writes the data from there.

If @var{mustbenew} is non-@code{nil}, then @code{write-region} asks
for confirmation if @var{filename} names an existing file.  If
@var{mustbenew} is the symbol @code{excl}, then @code{write-region}
does not ask for confirmation, but instead it signals an error
@code{file-already-exists} if the file already exists.

The test for an existing file, when @var{mustbenew} is @code{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 @var{visit} is @code{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
@var{filename}'s modtime, and marks the buffer as not modified.  This
feature is used by @code{save-buffer}, but you probably should not use
it yourself.

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

The optional argument @var{lockname}, if non-@code{nil}, specifies the
file name to use for purposes of locking and unlocking, overriding
@var{filename} and @var{visit} for that purpose.

The function @code{write-region} converts the data which it writes to
the appropriate file formats specified by @code{buffer-file-format}
and also calls the functions in the list
@code{write-region-annotate-functions}.
@xref{Format Conversion}.

Normally, @code{write-region} displays the message @samp{Wrote
@var{filename}} in the echo area.  If @var{visit} is neither @code{t}
nor @code{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.
@end deffn

@defmac with-temp-file file body@dots{}
@anchor{Definition of with-temp-file}
The @code{with-temp-file} macro evaluates the @var{body} forms with a
temporary buffer as the current buffer; then, at the end, it writes the
buffer contents into file @var{file}.  It kills the temporary buffer
when finished, restoring the buffer that was current before the
@code{with-temp-file} form.  Then it returns the value of the last form
in @var{body}.

The current buffer is restored even in case of an abnormal exit via
@code{throw} or error (@pxref{Nonlocal Exits}).

See also @code{with-temp-buffer} in @ref{Definition of
with-temp-buffer,, The Current Buffer}.
@end defmac

@node File Locks
@section File Locks
@cindex file locks
@cindex lock file

  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 @dfn{file lock} when a file is being
686
modified.
Glenn Morris's avatar
Glenn Morris committed
687 688 689
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,
690 691
stored in the same directory as the file you are editing.  (On file
systems that do not support symbolic links, a regular file is used.)
Glenn Morris's avatar
Glenn Morris committed
692 693

  When you access files using NFS, there may be a small probability that
694
you and another user will both lock the same file ``simultaneously''.
Glenn Morris's avatar
Glenn Morris committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
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
@ref{Modification Time}.

@defun file-locked-p filename
This function returns @code{nil} if the file @var{filename} is not
locked.  It returns @code{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.

@example
@group
(file-locked-p "foo")
     @result{} nil
@end group
@end example
@end defun

@defun lock-buffer &optional filename
This function locks the file @var{filename}, if the current buffer is
modified.  The argument @var{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.
@end defun

@defun 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.
@end defun

730 731 732
@defopt create-lockfiles
If this variable is @code{nil}, Emacs does not lock files.
@end defopt
Glenn Morris's avatar
Glenn Morris committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

@defun ask-user-about-lock file other-user
This function is called when the user tries to modify @var{file}, but it
is locked by another user named @var{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:

@itemize @bullet
@item
A value of @code{t} says to grab the lock on the file.  Then
this user may edit the file and @var{other-user} loses the lock.

@item
A value of @code{nil} says to ignore the lock and let this
user edit the file anyway.

@item
@kindex file-locked
This function may instead signal a @code{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:

@example
@error{} File is locked: @var{file} @var{other-user}
@end example

@noindent
where @code{file} is the name of the file and @var{other-user} is the
name of the user who has locked the file.
@end itemize

If you wish, you can replace the @code{ask-user-about-lock} function
766
with your own version that makes the decision in another way.
Glenn Morris's avatar
Glenn Morris committed
767 768 769 770 771 772
@end defun

@node Information about Files
@section Information about Files
@cindex file, information about

Chong Yidong's avatar
Chong Yidong committed
773 774 775 776 777
  This section describes the functions for retrieving various types of
information about files (or directories or symbolic links), such as
whether a file is readable or writable, and its size.  These functions
all take arguments which are file names.  Except where noted, these
arguments need to specify existing files, or an error is signaled.
Glenn Morris's avatar
Glenn Morris committed
778

779 780
@cindex file names, trailing whitespace
@cindex trailing blanks in file names
Chong Yidong's avatar
Chong Yidong committed
781 782 783
  Be careful with file names that end in spaces.  On some filesystems
(notably, MS-Windows), trailing whitespace characters in file names
are silently and automatically ignored.
784

Glenn Morris's avatar
Glenn Morris committed
785 786 787
@menu
* Testing Accessibility::   Is a given file readable?  Writable?
* Kinds of Files::          Is it a directory?  A symbolic link?
Glenn Morris's avatar
Glenn Morris committed
788
* Truenames::               Eliminating symbolic links from a file name.
Chong Yidong's avatar
Chong Yidong committed
789 790
* File Attributes::         File sizes, modification times, etc.
* Extended Attributes::     Extended file attributes for access control.
Glenn Morris's avatar
Glenn Morris committed
791 792 793 794 795 796 797 798
* Locating Files::          How to find a file in standard places.
@end menu

@node Testing Accessibility
@subsection Testing Accessibility
@cindex accessibility of a file
@cindex file accessibility

Chong Yidong's avatar
Chong Yidong committed
799 800 801 802 803 804 805 806 807 808
  These functions test for permission to access a file for reading,
writing, or execution.  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).

  On some operating systems, more complex sets of access permissions
can be specified, via mechanisms such as Access Control Lists (ACLs).
@xref{Extended Attributes}, for how to query and set those
permissions.
Glenn Morris's avatar
Glenn Morris committed
809 810 811 812 813 814

@defun file-exists-p filename
This function returns @code{t} if a file named @var{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
815
containing directories, regardless of the permissions of the file
Glenn Morris's avatar
Glenn Morris committed
816 817
itself.)

Chong Yidong's avatar
Chong Yidong committed
818 819
If the file does not exist, or if access control policies prevent you
from finding its attributes, this function returns @code{nil}.
Glenn Morris's avatar
Glenn Morris committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846

Directories are files, so @code{file-exists-p} returns @code{t} when
given a directory name.  However, symbolic links are treated
specially; @code{file-exists-p} returns @code{t} for a symbolic link
name only if the target file exists.
@end defun

@defun file-readable-p filename
This function returns @code{t} if a file named @var{filename} exists
and you can read it.  It returns @code{nil} otherwise.
@end defun

@defun file-executable-p filename
This function returns @code{t} if a file named @var{filename} exists and
you can execute it.  It returns @code{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.
@end defun

@defun file-writable-p filename
This function returns @code{t} if the file @var{filename} can be written
or created by you, and @code{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.

Chong Yidong's avatar
Chong Yidong committed
847 848 849
In the example below, @file{foo} is not writable because the parent
directory does not exist, even though the user could create such a
directory.
Glenn Morris's avatar
Glenn Morris committed
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866

@example
@group
(file-writable-p "~/no-such-dir/foo")
     @result{} nil
@end group
@end example
@end defun

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

Chong Yidong's avatar
Chong Yidong committed
867 868
For example, from the following we deduce that any attempt to read a
file in @file{/foo/} will give an error:
Glenn Morris's avatar
Glenn Morris committed
869 870 871 872 873 874 875 876 877 878 879 880 881

@example
(file-accessible-directory-p "/foo")
     @result{} nil
@end example
@end defun

@defun access-file filename string
This function opens file @var{filename} for reading, then closes it and
returns @code{nil}.  However, if the open fails, it signals an error
using @var{string} as the error message text.
@end defun

882
@defun file-ownership-preserved-p filename &optional group
Glenn Morris's avatar
Glenn Morris committed
883 884 885 886
This function returns @code{t} if deleting the file @var{filename} and
then creating it anew would keep the file's owner unchanged.  It also
returns @code{t} for nonexistent files.

887 888 889
If the optional argument @var{group} is non-@code{nil}, this function
also checks that the file's group would be unchanged.

Glenn Morris's avatar
Glenn Morris committed
890 891 892 893 894 895
If @var{filename} is a symbolic link, then, unlike the other functions
discussed here, @code{file-ownership-preserved-p} does @emph{not}
replace @var{filename} with its target.  However, it does recursively
follow symbolic links at all levels of parent directories.
@end defun

Chong Yidong's avatar
Chong Yidong committed
896 897 898 899 900 901 902 903 904
@defun file-modes filename
@cindex mode bits
@cindex file permissions
@cindex permissions, file
@cindex file modes
This function returns the @dfn{mode bits} of @var{filename}---an
integer summarizing its read, write, and execution permissions.
Symbolic links in @var{filename} are recursively followed at all
levels.  If the file does not exist, the return value is @code{nil}.
Glenn Morris's avatar
Glenn Morris committed
905

Chong Yidong's avatar
Chong Yidong committed
906 907 908 909 910 911 912 913 914 915
@xref{File permissions,,, coreutils, The @sc{gnu} @code{Coreutils}
Manual}, for a description of mode bits.  For example, if the
low-order bit is 1, the file is executable by all users; if the
second-lowest-order bit is 1, the file is writable by all users; etc.
The highest possible value is 4095 (7777 octal), meaning that everyone
has read, write, and execute permission, the @acronym{SUID} bit is set
for both others and group, and the sticky bit is set.

@xref{Changing Files}, for the @code{set-file-modes} function, which
can be used to set these permissions.
Glenn Morris's avatar
Glenn Morris committed
916 917 918

@example
@group
Chong Yidong's avatar
Chong Yidong committed
919 920
(file-modes "~/junk/diffs")
     @result{} 492               ; @r{Decimal integer.}
Glenn Morris's avatar
Glenn Morris committed
921 922
@end group
@group
Chong Yidong's avatar
Chong Yidong committed
923 924
(format "%o" 492)
     @result{} "754"             ; @r{Convert to octal.}
Glenn Morris's avatar
Glenn Morris committed
925
@end group
Chong Yidong's avatar
Chong Yidong committed
926

Glenn Morris's avatar
Glenn Morris committed
927
@group
Chong Yidong's avatar
Chong Yidong committed
928 929
(set-file-modes "~/junk/diffs" #o666)
     @result{} nil
Glenn Morris's avatar
Glenn Morris committed
930
@end group
Chong Yidong's avatar
Chong Yidong committed
931

Glenn Morris's avatar
Glenn Morris committed
932
@group
Chong Yidong's avatar
Chong Yidong committed
933 934
$ ls -l diffs
-rw-rw-rw- 1 lewis lewis 3063 Oct 30 16:00 diffs
Glenn Morris's avatar
Glenn Morris committed
935 936 937
@end group
@end example

Chong Yidong's avatar
Chong Yidong committed
938 939 940 941 942 943 944 945 946 947 948
@cindex MS-DOS and file modes
@cindex file modes and MS-DOS
@strong{MS-DOS note:} On MS-DOS, there is no such thing as an
``executable'' file mode bit.  So @code{file-modes} considers a file
executable if its name ends in one of the standard executable
extensions, such as @file{.com}, @file{.bat}, @file{.exe}, and some
others.  Files that begin with the Unix-standard @samp{#!} signature,
such as shell and Perl scripts, are also considered executable.
Directories are also reported as executable, for compatibility with
Unix.  These conventions are also followed by @code{file-attributes}
(@pxref{File Attributes}).
Glenn Morris's avatar
Glenn Morris committed
949 950 951 952
@end defun

@node Kinds of Files
@subsection Distinguishing Kinds of Files
953 954
@cindex file classification
@cindex classification of file types
Glenn Morris's avatar
Glenn Morris committed
955 956 957 958 959 960 961

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

@defun file-symlink-p filename
@cindex file symbolic links
If the file @var{filename} is a symbolic link, the
962 963 964 965 966 967 968 969
@code{file-symlink-p} function returns its (non-recursive) link target
as a string.  (The link target string is not necessarily the full
absolute file name of the target; determining the full file name that
the link points to is nontrivial, see below.)  If the leading
directories of @var{filename} include symbolic links, this function
recursively follows them.

If the file @var{filename} is not a symbolic link, or does not exist,
Glenn Morris's avatar
Glenn Morris committed
970 971
@code{file-symlink-p} returns @code{nil}.

972 973
Here are a few examples of using this function:

Glenn Morris's avatar
Glenn Morris committed
974 975
@example
@group
976
(file-symlink-p "not-a-symlink")
Glenn Morris's avatar
Glenn Morris committed
977 978 979 980
     @result{} nil
@end group
@group
(file-symlink-p "sym-link")
981
     @result{} "not-a-symlink"
Glenn Morris's avatar
Glenn Morris committed
982 983 984 985 986 987 988 989 990 991
@end group
@group
(file-symlink-p "sym-link2")
     @result{} "sym-link"
@end group
@group
(file-symlink-p "/bin")
     @result{} "/pub/bin"
@end group
@end example
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

Note that in the third example, the function returned @file{sym-link},
but did not proceed to resolve it, although that file is itself a
symbolic link.  This is what we meant by ``non-recursive'' above---the
process of following the symbolic links does not recurse if the link
target is itself a link.

The string that this function returns is what is recorded in the
symbolic link; it may or may not include any leading directories.
This function does @emph{not} expand the link target to produce a
fully-qualified file name, and in particular does not use the leading
directories, if any, of the @var{filename} argument if the link target
is not an absolute file name.  Here's an example:

@example
@group
(file-symlink-p "/foo/bar/baz")
     @result{} "some-file"
@end group
@end example

@noindent
Here, although @file{/foo/bar/baz} was given as a fully-qualified file
name, the result is not, and in fact does not have any leading
directories at all.  And since @file{some-file} might itself be a
symbolic link, you cannot simply prepend leading directories to it,
nor even naively use @code{expand-file-name} (@pxref{File Name
Expansion}) to produce its absolute file name.

For this reason, this function is seldom useful if you need to
determine more than just the fact that a file is or isn't a symbolic
link.  If you actually need the file name of the link target, use
@code{file-chase-links} or @code{file-truename}, described in
@ref{Truenames}.
Glenn Morris's avatar
Glenn Morris committed
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
@end defun

The next two functions recursively follow symbolic links at
all levels for @var{filename}.

@defun file-directory-p filename
This function returns @code{t} if @var{filename} is the name of an
existing directory, @code{nil} otherwise.

@example
@group
(file-directory-p "~rms")
     @result{} t
@end group
@group
(file-directory-p "~rms/lewis/files.texi")
     @result{} nil
@end group
@group
(file-directory-p "~rms/lewis/no-such-file")
     @result{} nil
@end group
@group
(file-directory-p "$HOME")
     @result{} nil
@end group
@group
(file-directory-p
 (substitute-in-file-name "$HOME"))
     @result{} t
@end group
@end example
@end defun

@defun file-regular-p filename
This function returns @code{t} if the file @var{filename} exists and is
a regular file (not a directory, named pipe, terminal, or
other I/O device).
@end defun

@node Truenames
@subsection Truenames
@cindex truename (of file)

  The @dfn{truename} of a file is the name that you get by following
symbolic links at all levels until none remain, then simplifying away
@samp{.}@: and @samp{..}@: 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.

@defun file-truename filename
1079 1080 1081
This function returns the truename of the file @var{filename}.  If the
argument is not an absolute file name, this function first expands it
against @code{default-directory}.
Glenn Morris's avatar
Glenn Morris committed
1082 1083 1084 1085 1086 1087

This function does not expand environment variables.  Only
@code{substitute-in-file-name} does that.  @xref{Definition of
substitute-in-file-name}.

If you may need to follow symbolic links preceding @samp{..}@:
Chong Yidong's avatar
Chong Yidong committed
1088 1089 1090 1091 1092 1093 1094 1095
appearing as a name component, call @code{file-truename} without prior
direct or indirect calls to @code{expand-file-name}.  Otherwise, the
file name component immediately preceding @samp{..} will be
``simplified away'' before @code{file-truename} is called.  To
eliminate the need for a call to @code{expand-file-name},
@code{file-truename} handles @samp{~} in the same way that
@code{expand-file-name} does.  @xref{File Name Expansion,, Functions
that Expand Filenames}.
Glenn Morris's avatar
Glenn Morris committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
@end defun

@defun file-chase-links filename &optional limit
This function follows symbolic links, starting with @var{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 @emph{not} follow
symbolic links at the level of parent directories.

If you specify a number for @var{limit}, then after chasing through
that many links, the function just returns what it has even if that is
still a symbolic link.
@end defun

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

@example
(file-chase-links "/usr/foo/hello")
     ;; @r{This does not follow the links in the parent directories.}
     @result{} "/usr/foo/hello"
(file-truename "/usr/foo/hello")
     ;; @r{Assuming that @file{/home} is not a symbolic link.}
     @result{} "/home/foo/hello"
@end example

Chong Yidong's avatar
Chong Yidong committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
@defun file-equal-p file1 file2
This function returns @code{t} if the files @var{file1} and
@var{file2} name the same file.  This is similar to comparing their
truenames, except that remote file names are also handled in an
appropriate manner.  If @var{file1} or @var{file2} does not exist, the
return value is unspecified.
@end defun

@defun file-in-directory-p file dir
This function returns @code{t} if @var{file} is a file in directory
@var{dir}, or in a subdirectory of @var{dir}.  It also returns
@code{t} if @var{file} and @var{dir} are the same directory.  It
compares the truenames of the two directories.  If @var{dir} does not
name an existing directory, the return value is @code{nil}.
@end defun
Glenn Morris's avatar
Glenn Morris committed
1139 1140

@node File Attributes
Chong Yidong's avatar
Chong Yidong committed
1141 1142
@subsection File Attributes
@cindex file attributes
Glenn Morris's avatar
Glenn Morris committed
1143

1144
  This section describes the functions for getting detailed
Chong Yidong's avatar
Chong Yidong committed
1145 1146 1147
information about a file, including the owner and group numbers, the
number of names, the inode number, the size, and the times of access
and modification.
Glenn Morris's avatar
Glenn Morris committed
1148

Chong Yidong's avatar
Chong Yidong committed
1149 1150 1151 1152 1153 1154 1155
@defun file-newer-than-file-p filename1 filename2
@cindex file age
@cindex file modification time
This function returns @code{t} if the file @var{filename1} is
newer than file @var{filename2}.  If @var{filename1} does not
exist, it returns @code{nil}.  If @var{filename1} does exist, but
@var{filename2} does not, it returns @code{t}.
1156

Chong Yidong's avatar
Chong Yidong committed
1157 1158 1159
In the following example, assume that the file @file{aug-19} was written
on the 19th, @file{aug-20} was written on the 20th, and the file
@file{no-file} doesn't exist at all.
Glenn Morris's avatar
Glenn Morris committed
1160 1161 1162

@example
@group
Chong Yidong's avatar
Chong Yidong committed
1163 1164
(file-newer-than-file-p "aug-19" "aug-20")
     @result{} nil
Glenn Morris's avatar
Glenn Morris committed
1165 1166
@end group
@group
Chong Yidong's avatar
Chong Yidong committed
1167 1168
(file-newer-than-file-p "aug-20" "aug-19")
     @result{} t
Glenn Morris's avatar
Glenn Morris committed
1169 1170
@end group
@group
Chong Yidong's avatar
Chong Yidong committed
1171 1172
(file-newer-than-file-p "aug-19" "no-file")
     @result{} t
Glenn Morris's avatar
Glenn Morris committed
1173 1174
@end group
@group
Chong Yidong's avatar
Chong Yidong committed
1175 1176
(file-newer-than-file-p "no-file" "aug-19")
     @result{} nil
Glenn Morris's avatar
Glenn Morris committed
1177 1178 1179 1180
@end group
@end example
@end defun

1181 1182 1183 1184
  If the @var{filename} argument to the next two functions is a
symbolic link, then these function do @emph{not} replace it with its
target.  However, they both recursively follow symbolic links at all
levels of parent directories.
Glenn Morris's avatar
Glenn Morris committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

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

The elements of the list, in order, are:

@enumerate 0
@item
@code{t} for a directory, a string for a symbolic link (the name
linked to), or @code{nil} for a text file.

@c Wordy so as to prevent an overfull hbox.  --rjc 15mar92
@item
The number of names the file has.  Alternate names, also known as hard
links, can be created by using the @code{add-name-to-file} function
(@pxref{Changing Files}).

@item
The file's @acronym{UID}, normally as a string.  However, if it does
1212
not correspond to a named user, the value is a number.
Glenn Morris's avatar
Glenn Morris committed
1213 1214 1215 1216 1217

@item
The file's @acronym{GID}, likewise.

@item
1218 1219
The time of last access, as a list of four integers @code{(@var{sec-high}
@var{sec-low} @var{microsec} @var{picosec})}.  (This is similar to the
1220 1221 1222
value of @code{current-time}; see @ref{Time of Day}.)  Note that on
some FAT-based filesystems, only the date of last access is recorded,
so this time will always hold the midnight of the day of last access.
Glenn Morris's avatar
Glenn Morris committed
1223

1224
@cindex modification time of file
Glenn Morris's avatar
Glenn Morris committed
1225
@item
1226
The time of last modification as a list of four integers (as above).
1227
This is the last time when the file's contents were modified.
Glenn Morris's avatar
Glenn Morris committed
1228 1229

@item
1230
The time of last status change as a list of four integers (as above).
1231 1232 1233
This is the time of the last change to the file's access mode bits,
its owner and group, and other information recorded in the filesystem
for the file, beyond the file's contents.
Glenn Morris's avatar
Glenn Morris committed
1234 1235

@item
1236 1237
The size of the file in bytes.  This is floating point if the size is
too large to fit in a Lisp integer.
Glenn Morris's avatar
Glenn Morris committed
1238 1239 1240 1241 1242 1243

@item
The file's modes, as a string of ten letters or dashes,
as in @samp{ls -l}.

@item
1244
An unspecified value, present for backward compatibility.
Glenn Morris's avatar
Glenn Morris committed
1245 1246

@item
1247 1248
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
1249
Lisp but dividing it by @math{2^{16}} yields a representable integer,
1250
then the value has the
1251
form @code{(@var{high} . @var{low})}, where @var{low} holds the low 16
1252
bits.  If the inode number is too wide for even that, the value is of the form
1253
@code{(@var{high} @var{middle} . @var{low})}, where @code{high} holds
1254
the high bits, @var{middle} the middle 24 bits, and @var{low} the low
1255
16 bits.
Glenn Morris's avatar
Glenn Morris committed
1256 1257

@item
1258 1259 1260 1261 1262 1263
The filesystem number of the device that the file is on.  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.
Glenn Morris's avatar
Glenn Morris committed
1264 1265 1266 1267 1268 1269 1270 1271
@end enumerate

For example, here are the file attributes for @file{files.texi}:

@example
@group
(file-attributes "files.texi" 'string)
     @result{}  (nil 1 "lh" "users"
1272 1273 1274
          (20614 64019 50040 152000)
          (20000 23 0 0)
          (20614 64555 902289 872000)
1275
          122295 "-rw-rw-rw-"
1276
          t (5888 2 . 43978)
1277
          (15479 . 46724))
Glenn Morris's avatar
Glenn Morris committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
@end group
@end example

@noindent
and here is how the result is interpreted:

@table @code
@item nil
is neither a directory nor a symbolic link.

@item 1
has only one name (the name @file{files.texi} in the current default
directory).

@item "lh"
is owned by the user with name "lh".

@item "users"
is in the group with name "users".

1298 1299
@item (20614 64019 50040 152000)
was last accessed on October 23, 2012, at 20:12:03.050040152 UTC.
Glenn Morris's avatar
Glenn Morris committed
1300

1301 1302
@item (20000 23 0 0)
was last modified on July 15, 2001, at 08:53:43 UTC.
Glenn Morris's avatar
Glenn Morris committed
1303

1304 1305
@item (20614 64555 902289 872000)
last had its status changed on October 23, 2012, at 20:20:59.902289872 UTC.
Glenn Morris's avatar
Glenn Morris committed
1306

1307 1308 1309 1310
@item 122295
is 122295 bytes long.  (It may not contain 122295 characters, though,
if some of the bytes belong to multibyte sequences, and also if the
end-of-line format is CR-LF.)
Glenn Morris's avatar
Glenn Morris committed
1311 1312 1313 1314

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

1315 1316
@item t
is merely a placeholder; it carries no information.
Glenn Morris's avatar
Glenn Morris committed
1317

1318 1319 1320 1321 1322
@item (5888 2 . 43978)
has an inode number of 6473924464520138.

@item (15479 . 46724)
is on the file-system device whose number is 1014478468.
Glenn Morris's avatar
Glenn Morris committed
1323 1324 1325
@end table
@end defun

Chong Yidong's avatar
Chong Yidong committed
1326 1327 1328 1329 1330 1331
@defun file-nlinks filename
This function returns the number of names (i.e., hard links) that
file @var{filename} has.  If the file does not exist, this function
returns @code{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.
1332

Chong Yidong's avatar
Chong Yidong committed
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
@example
@group
$ ls -l foo*
-rw-rw-rw- 2 rms rms 4 Aug 19 01:27 foo
-rw-rw-rw- 2 rms rms 4 Aug 19 01:27 foo1
@end group

@group
(file-nlinks "foo")
     @result{} 2
@end group
@group
(file-nlinks "doesnt-exist")
     @result{} nil
@end group
@end example
1349
@end defun
1350

Chong Yidong's avatar
Chong Yidong committed
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
@node Extended Attributes
@subsection Extended File Attributes
@cindex extended file attributes

On some operating systems, each file can be associated with arbitrary
@dfn{extended file attributes}.  At present, Emacs supports querying
and setting two specific sets of extended file attributes: Access
Control Lists (ACLs) and SELinux contexts.  These extended file
attributes are used, on some systems, to impose more sophisticated
file access controls than the basic ``Unix-style'' permissions
discussed in the previous sections.

1363 1364
@cindex access control list
@cindex ACL entries
Chong Yidong's avatar
Chong Yidong committed
1365 1366 1367 1368 1369 1370
@cindex SELinux context
  A detailed explanation of ACLs and SELinux is beyond the scope of
this manual.  For our purposes, each file can be associated with an
@dfn{ACL}, which specifies its properties under an ACL-based file
control system, and/or an @dfn{SELinux context}, which specifies its
properties under the SELinux system.
1371 1372

@defun file-acl filename
Chong Yidong's avatar
Chong Yidong committed
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
This function returns the ACL for the file @var{filename}.  The exact
Lisp representation of the ACL is unspecified (and may change in
future Emacs versions), but it is the same as what @code{set-file-acl}
takes for its @var{acl} argument (@pxref{Changing Files}).

The underlying ACL implementation is platform-specific; on GNU/Linux
and BSD, Emacs uses the POSIX ACL interface, while on MS-Windows Emacs
emulates the POSIX ACL interface with native file security APIs.

If Emacs was not compiled with ACL support, or the file does not exist
or is inaccessible, or Emacs was unable to determine the ACL entries
for any other reason, then the return value is @code{nil}.
@end defun

@defun file-selinux-context filename
This function returns the SELinux context of the file @var{filename},
as a list of the form @code{(@var{user} @var{role} @var{type}
@var{range})}.  The list elements are the context's user, role, type,
and range respectively, as Lisp strings; see the SELinux documentation
for details about what these actually mean.  The return value has the
same form as what @code{set-file-selinux-context} takes for its
@var{context} argument (@pxref{Changing Files}).

If Emacs was not compiled with SELinux support, or the file does not
exist or is inaccessible, or if the system does not support SELinux,
then the return value is @code{(nil nil nil nil)}.
@end defun

@defun file-extended-attributes filename
This function returns an alist of the Emacs-recognized extended
attributes of file @var{filename}.  Currently, it serves as a
convenient way to retrieve both the ACL and SELinux context; you can
then call the function @code{set-file-extended-attributes}, with the
returned alist as its second argument, to apply the same file access
attributes to another file (@pxref{Changing Files}).

One of the elements is @code{(acl . @var{acl})}, where @var{acl} has
the same form returned by @code{file-acl}.

Another element is @code{(selinux-context . @var{context})}, where
@var{context} is the SELinux context, in the same form returned by
@code{file-selinux-context}.
1415 1416
@end defun

Glenn Morris's avatar
Glenn Morris committed
1417
@node Locating Files
Chong Yidong's avatar
Chong Yidong committed
1418
@subsection Locating Files in Standard Places
Glenn Morris's avatar
Glenn Morris committed
1419 1420 1421 1422
@cindex locate file in path
@cindex find file in path

  This section explains how to search for a file in a list of
1423
directories (a @dfn{path}), or for an executable file in the standard
1424 1425 1426 1427
list of executable file directories.

  To search for a user-specific configuration file, @xref{Standard
File Names}, for the @code{locate-user-emacs-file} function.
Glenn Morris's avatar
Glenn Morris committed
1428 1429 1430 1431

@defun locate-file filename path &optional suffixes predicate
This function searches for a file whose name is @var{filename} in a
list of directories given by @var{path}, trying the suffixes in
1432 1433 1434
@var{suffixes}.  If it finds such a file, it returns the file's
absolute file name (@pxref{Relative File Names}); otherwise it returns
@code{nil}.
Glenn Morris's avatar
Glenn Morris committed
1435 1436 1437 1438 1439 1440 1441

The optional argument @var{suffixes} gives the list of file-name
suffixes to append to @var{filename} when searching.
@code{locate-file} tries each possible directory with each of these
suffixes.  If @var{suffixes} is @code{nil}, or @code{("")}, then there
are no suffixes, and @var{filename} is used only as-is.  Typical
values of @var{suffixes} are @code{exec-suffixes} (@pxref{Subprocess
1442 1443 1444
Creation}), @code{load-suffixes}, @code{load-file-rep-suffixes} and
the return value of the function @code{get-load-suffixes} (@pxref{Load
Suffixes}).
Glenn Morris's avatar
Glenn Morris committed
1445 1446

Typical values for @var{path} are @code{exec-path} (@pxref{Subprocess
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
Creation}) when looking for executable programs, or @code{load-path}
(@pxref{Library Search}) when looking for Lisp files.  If
@var{filename} is absolute, @var{path} has no effect, but the suffixes
in @var{suffixes} are still tried.

The optional argument @var{predicate}, if non-@code{nil}, specifies a
predicate function for testing whether a candidate file is suitable.
The predicate is passed the candidate file name as its single
argument.  If @var{predicate} is @code{nil} or omitted,
@code{locate-file} uses @code{file-readable-p} as the predicate.
1457
@xref{Kinds of Files}, for other useful predicates, e.g.,
1458
@code{file-executable-p} and @code{file-directory-p}.
Glenn Morris's avatar
Glenn Morris committed
1459 1460 1461 1462 1463 1464 1465 1466

For compatibility, @var{predicate} can also be one of the symbols
@code{executable}, @code{readable}, @code{writable}, @code{exists}, or
a list of one or more of these symbols.
@end defun

@defun executable-find program
This function searches for the executable file of the named
1467
@var{program} and returns the absolute file name of the executable,
Glenn Morris's avatar
Glenn Morris committed
1468 1469
including its file-name extensions, if any.  It returns @code{nil} if
the file is not found.  The functions searches in all the directories
1470 1471 1472 1473
in @code{exec-path}, and tries all the file-name extensions in
@code{exec-suffixes} (@pxref{Subprocess Creation}).
@end defun

Glenn Morris's avatar
Glenn Morris committed
1474 1475 1476 1477 1478 1479 1480 1481
@node Changing Files
@section Changing File Names and Attributes
@c @cindex renaming files  Duplicates rename-file
@cindex copying files
@cindex deleting files
@cindex linking files
@cindex setting modes of files

1482 1483
  The functions in this section rename, copy, delete, link, and set
the modes (permissions) of files.
Glenn Morris's avatar
Glenn Morris committed
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518

  In the functions that have an argument @var{newname}, if a file by the
name of @var{newname} already exists, the actions taken depend on the
value of the argument @var{ok-if-already-exists}:

@itemize @bullet
@item
Signal a @code{file-already-exists} error if
@var{ok-if-already-exists} is @code{nil}.

@item
Request confirmation if @var{ok-if-already-exists} is a number.

@item
Replace the old file without confirmation if @var{ok-if-already-exists}
is any other value.
@end itemize

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 @code{copy-file}
replaces it with its (recursive) target.

@deffn Command add-name-to-file oldname newname &optional ok-if-already-exists
@cindex file with multiple names
@cindex file hard link
This function gives the file named @var{oldname} the additional name
@var{newname}.  This means that @var{newname} becomes a new ``hard
link'' to @var{oldname}.

In the first part of the following example, we list two files,
@file{foo} and @file{foo3}.

@example
@group
1519 1520 1521
$ ls -li fo*
81908 -rw-rw-rw- 1 rms rms 29 Aug 18 20:32 foo
84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
Glenn Morris's avatar
Glenn Morris committed
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
@end group
@end example

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

@example
@group
(add-name-to-file "foo" "foo2")
     @result{} nil
@end group

@group
1536 1537 1538 1539
$ ls -li fo*
81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo2
84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
Glenn Morris's avatar
Glenn Morris committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
@end group
@end example

Finally, we evaluate the following:

@example
(add-name-to-file "foo" "foo3" t)
@end example

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

@example
@group
(add-name-to-file "foo1" "foo3")
     @result{} nil
@end group

@group
1561 1562 1563 1564
$ ls -li fo*
81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo2
81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo3
Glenn Morris's avatar
Glenn Morris committed
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
@end group
@end example

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 @code{file-nlinks} in @ref{File Attributes}.
@end deffn

@deffn Command rename-file filename newname &optional ok-if-already-exists
This command renames the file @var{filename} as @var{newname}.

If @var{filename} has additional names aside from @var{filename}, it
continues to have those names.  In fact, adding the name @var{newname}
with @code{add-name-to-file} and then deleting @var{filename} has the
same effect as renaming, aside from momentary intermediate states.
@end deffn

Xue Fuqiao's avatar
Xue Fuqiao committed
1584
@deffn Command copy-file oldname newname &optional ok-if-exists time preserve-uid-gid preserve-extended-attributes
Glenn Morris's avatar
Glenn Morris committed
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
This command copies the file @var{oldname} to @var{newname}.  An
error is signaled if @var{oldname} does not exist.  If @var{newname}
names a directory, it copies @var{oldname} into that directory,
preserving its final name component.

If @var{time} is non-@code{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,
@code{copy-file} signals a @code{file-date-error} error.  In an
interactive call, a prefix argument specifies a non-@code{nil} value
for @var{time}.

If argument @var{preserve-uid-gid} is @code{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 @var{preserve-uid-gid} is
non-@code{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.
Glenn Morris's avatar
Glenn Morris committed
1603

1604
If the optional argument @var{preserve-permissions} is non-@code{nil},
Chong Yidong's avatar
Chong Yidong committed
1605 1606 1607 1608 1609 1610 1611 1612 1613
this function copies the file modes (or ``permissions'') of
@var{oldname} to @var{newname}, as well as the Access Control List and
SELinux context (if any).  @xref{Information about Files}.

Otherwise, the file modes of @var{newname} are left unchanged if it is
an existing file, and set to those of @var{oldname}, masked by the
default file permissions (see @code{set-default-file-modes} below), if
@var{newname} is to be newly created.  The Access Control List or
SELinux context are not copied over in either case.
Glenn Morris's avatar
Glenn Morris committed
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
@end deffn

@deffn Command make-symbolic-link filename newname  &optional ok-if-exists
@pindex ln
@kindex file-already-exists
This command makes a symbolic link to @var{filename}, named
@var{newname}.  This is like the shell command @samp{ln -s
@var{filename} @var{newname}}.

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

1627 1628 1629
@cindex trash
@vindex delete-by-moving-to-trash
@deffn Command delete-file filename &optional trash
Glenn Morris's avatar
Glenn Morris committed
1630
@pindex rm
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
This command deletes the file @var{filename}.  If the file has
multiple names, it continues to exist under the other names.  If
@var{filename} is a symbolic link, @code{delete-file} deletes only the
symbolic link and not its target (though it does follow symbolic links
at all levels of parent directories).

A suitable kind of @code{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 the optional argument @var{trash} is non-@code{nil} and the
variable @code{delete-by-moving-to-trash} is non-@code{nil}, this
command moves the file into the system Trash instead of deleting it.
@xref{Misc File Ops,,Miscellaneous File Operations, emacs, The GNU
Emacs Manual}.  When called interactively, @var{trash} is @code{t} if
no prefix argument is given, and @code{nil} otherwise.
Glenn Morris's avatar
Glenn Morris committed
1647 1648