Fix recently-introduced copy-directory bug
[emacs.git] / doc / lispref / files.texi
blob6be998f0b2ea2440a3961d026c46872b68120c1d
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2017 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Files
7 @chapter Files
9   This chapter describes the Emacs Lisp functions and variables to
10 find, create, view, save, and otherwise work with files and
11 directories.  A few other file-related functions are described in
12 @ref{Buffers}, and those related to backups and auto-saving are
13 described in @ref{Backups and Auto-Saving}.
15   Many of the file functions take one or more arguments that are file
16 names.  A file name is a string.  Most of these functions expand file
17 name arguments using the function @code{expand-file-name}, so that
18 @file{~} is handled correctly, as are relative file names (including
19 @file{../}).  @xref{File Name Expansion}.
21   In addition, certain @dfn{magic} file names are handled specially.
22 For example, when a remote file name is specified, Emacs accesses the
23 file over the network via an appropriate protocol.  @xref{Remote
24 Files,, Remote Files, emacs, The GNU Emacs Manual}.  This handling is
25 done at a very low level, so you may assume that all the functions
26 described in this chapter accept magic file names as file name
27 arguments, except where noted.  @xref{Magic File Names}, for details.
29   When file I/O functions signal Lisp errors, they usually use the
30 condition @code{file-error} (@pxref{Handling Errors}).  The error
31 message is in most cases obtained from the operating system, according
32 to locale @code{system-messages-locale}, and decoded using coding system
33 @code{locale-coding-system} (@pxref{Locales}).
35 @menu
36 * Visiting Files::           Reading files into Emacs buffers for editing.
37 * Saving Buffers::           Writing changed buffers back into files.
38 * Reading from Files::       Reading files into buffers without visiting.
39 * Writing to Files::         Writing new files from parts of buffers.
40 * File Locks::               Locking and unlocking files, to prevent
41                                simultaneous editing by two people.
42 * Information about Files::  Testing existence, accessibility, size of files.
43 * Changing Files::           Renaming files, changing permissions, etc.
44 * Files and Storage::        Surviving power and media failures
45 * File Names::               Decomposing and expanding file names.
46 * Contents of Directories::  Getting a list of the files in a directory.
47 * Create/Delete Dirs::       Creating and Deleting Directories.
48 * Magic File Names::         Special handling for certain file names.
49 * Format Conversion::        Conversion to and from various file formats.
50 @end menu
52 @node Visiting Files
53 @section Visiting Files
54 @cindex finding files
55 @cindex visiting files
57   Visiting a file means reading a file into a buffer.  Once this is
58 done, we say that the buffer is @dfn{visiting} that file, and call the
59 file @dfn{the visited file} of the buffer.
61   A file and a buffer are two different things.  A file is information
62 recorded permanently in the computer (unless you delete it).  A
63 buffer, on the other hand, is information inside of Emacs that will
64 vanish at the end of the editing session (or when you kill the
65 buffer).  When a buffer is visiting a file, it contains information
66 copied from the file.  The copy in the buffer is what you modify with
67 editing commands.  Changes to the buffer do not change the file; to
68 make the changes permanent, you must @dfn{save} the buffer, which
69 means copying the altered buffer contents back into the file.
71   Despite the distinction between files and buffers, people often
72 refer to a file when they mean a buffer and vice-versa.  Indeed, we
73 say, ``I am editing a file'', rather than, ``I am editing a buffer
74 that I will soon save as a file of the same name''.  Humans do not
75 usually need to make the distinction explicit.  When dealing with a
76 computer program, however, it is good to keep the distinction in mind.
78 @menu
79 * Visiting Functions::         The usual interface functions for visiting.
80 * Subroutines of Visiting::    Lower-level subroutines that they use.
81 @end menu
83 @node Visiting Functions
84 @subsection Functions for Visiting Files
85 @cindex visiting files, functions for
86 @cindex how to visit files
88   This section describes the functions normally used to visit files.
89 For historical reasons, these functions have names starting with
90 @samp{find-} rather than @samp{visit-}.  @xref{Buffer File Name}, for
91 functions and variables that access the visited file name of a buffer or
92 that find an existing buffer by its visited file name.
94   In a Lisp program, if you want to look at the contents of a file but
95 not alter it, the fastest way is to use @code{insert-file-contents} in a
96 temporary buffer.  Visiting the file is not necessary and takes longer.
97 @xref{Reading from Files}.
99 @deffn Command find-file filename &optional wildcards
100 This command selects a buffer visiting the file @var{filename},
101 using an existing buffer if there is one, and otherwise creating a
102 new buffer and reading the file into it.  It also returns that buffer.
104 Aside from some technical details, the body of the @code{find-file}
105 function is basically equivalent to:
107 @smallexample
108 (switch-to-buffer (find-file-noselect filename nil nil wildcards))
109 @end smallexample
111 @noindent
112 (See @code{switch-to-buffer} in @ref{Switching Buffers}.)
114 If @var{wildcards} is non-@code{nil}, which is always true in an
115 interactive call, then @code{find-file} expands wildcard characters in
116 @var{filename} and visits all the matching files.
118 When @code{find-file} is called interactively, it prompts for
119 @var{filename} in the minibuffer.
120 @end deffn
122 @deffn Command find-file-literally filename
123 This command visits @var{filename}, like @code{find-file} does, but it
124 does not perform any format conversions (@pxref{Format Conversion}),
125 character code conversions (@pxref{Coding Systems}), or end-of-line
126 conversions (@pxref{Coding System Basics, End of line conversion}).
127 The buffer visiting the file is made unibyte, and its major mode is
128 Fundamental mode, regardless of the file name.  File local variable
129 specifications  in the file (@pxref{File Local Variables}) are
130 ignored, and automatic decompression and adding a newline at the end
131 of the file due to @code{require-final-newline} (@pxref{Saving
132 Buffers, require-final-newline}) are also disabled.
134 Note that if Emacs already has a buffer visiting the same file
135 non-literally, it will not visit the same file literally, but instead
136 just switch to the existing buffer.  If you want to be sure of
137 accessing a file's contents literally, you should create a temporary
138 buffer and then read the file contents into it using
139 @code{insert-file-contents-literally} (@pxref{Reading from Files}).
140 @end deffn
142 @defun find-file-noselect filename &optional nowarn rawfile wildcards
143 This function is the guts of all the file-visiting functions.  It
144 returns a buffer visiting the file @var{filename}.  You may make the
145 buffer current or display it in a window if you wish, but this
146 function does not do so.
148 The function returns an existing buffer if there is one; otherwise it
149 creates a new buffer and reads the file into it.  When
150 @code{find-file-noselect} uses an existing buffer, it first verifies
151 that the file has not changed since it was last visited or saved in
152 that buffer.  If the file has changed, this function asks the user
153 whether to reread the changed file.  If the user says @samp{yes}, any
154 edits previously made in the buffer are lost.
156 Reading the file involves decoding the file's contents (@pxref{Coding
157 Systems}), including end-of-line conversion, and format conversion
158 (@pxref{Format Conversion}).  If @var{wildcards} is non-@code{nil},
159 then @code{find-file-noselect} expands wildcard characters in
160 @var{filename} and visits all the matching files.
162 This function displays warning or advisory messages in various peculiar
163 cases, unless the optional argument @var{nowarn} is non-@code{nil}.  For
164 example, if it needs to create a buffer, and there is no file named
165 @var{filename}, it displays the message @samp{(New file)} in the echo
166 area, and leaves the buffer empty.
168 The @code{find-file-noselect} function normally calls
169 @code{after-find-file} after reading the file (@pxref{Subroutines of
170 Visiting}).  That function sets the buffer major mode, parses local
171 variables, warns the user if there exists an auto-save file more recent
172 than the file just visited, and finishes by running the functions in
173 @code{find-file-hook}.
175 If the optional argument @var{rawfile} is non-@code{nil}, then
176 @code{after-find-file} is not called, and the
177 @code{find-file-not-found-functions} are not run in case of failure.
178 What's more, a non-@code{nil} @var{rawfile} value suppresses coding
179 system conversion and format conversion.
181 The @code{find-file-noselect} function usually returns the buffer that
182 is visiting the file @var{filename}.  But, if wildcards are actually
183 used and expanded, it returns a list of buffers that are visiting the
184 various files.
186 @example
187 @group
188 (find-file-noselect "/etc/fstab")
189      @result{} #<buffer fstab>
190 @end group
191 @end example
192 @end defun
194 @deffn Command find-file-other-window filename &optional wildcards
195 This command selects a buffer visiting the file @var{filename}, but
196 does so in a window other than the selected window.  It may use
197 another existing window or split a window; see @ref{Switching
198 Buffers}.
200 When this command is called interactively, it prompts for
201 @var{filename}.
202 @end deffn
204 @deffn Command find-file-read-only filename &optional wildcards
205 This command selects a buffer visiting the file @var{filename}, like
206 @code{find-file}, but it marks the buffer as read-only.  @xref{Read Only
207 Buffers}, for related functions and variables.
209 When this command is called interactively, it prompts for
210 @var{filename}.
211 @end deffn
213 @defopt find-file-wildcards
214 If this variable is non-@code{nil}, then the various @code{find-file}
215 commands check for wildcard characters and visit all the files that
216 match them (when invoked interactively or when their @var{wildcards}
217 argument is non-@code{nil}).  If this option is @code{nil}, then
218 the @code{find-file} commands ignore their @var{wildcards} argument
219 and never treat wildcard characters specially.
220 @end defopt
222 @defopt find-file-hook
223 The value of this variable is a list of functions to be called after a
224 file is visited.  The file's local-variables specification (if any) will
225 have been processed before the hooks are run.  The buffer visiting the
226 file is current when the hook functions are run.
228 This variable is a normal hook.  @xref{Hooks}.
229 @end defopt
231 @defvar find-file-not-found-functions
232 The value of this variable is a list of functions to be called when
233 @code{find-file} or @code{find-file-noselect} is passed a nonexistent
234 file name.  @code{find-file-noselect} calls these functions as soon as
235 it detects a nonexistent file.  It calls them in the order of the list,
236 until one of them returns non-@code{nil}.  @code{buffer-file-name} is
237 already set up.
239 This is not a normal hook because the values of the functions are
240 used, and in many cases only some of the functions are called.
241 @end defvar
243 @defvar find-file-literally
244 This buffer-local variable, if set to a non-@code{nil} value, makes
245 @code{save-buffer} behave as if the buffer were visiting its file
246 literally, i.e., without conversions of any kind.  The command
247 @code{find-file-literally} sets this variable's local value, but other
248 equivalent functions and commands can do that as well, e.g., to avoid
249 automatic addition of a newline at the end of the file.  This variable
250 is permanent local, so it is unaffected by changes of major modes.
251 @end defvar
253 @node Subroutines of Visiting
254 @subsection Subroutines of Visiting
256   The @code{find-file-noselect} function uses two important subroutines
257 which are sometimes useful in user Lisp code: @code{create-file-buffer}
258 and @code{after-find-file}.  This section explains how to use them.
260 @c FIXME This does not describe the default behavior, because
261 @c uniquify is enabled by default and advises this function.
262 @c This is confusing.  uniquify should be folded into the function proper.
263 @defun create-file-buffer filename
264 This function creates a suitably named buffer for visiting
265 @var{filename}, and returns it.  It uses @var{filename} (sans directory)
266 as the name if that name is free; otherwise, it appends a string such as
267 @samp{<2>} to get an unused name.  See also @ref{Creating Buffers}.
268 Note that the @file{uniquify} library affects the result of this
269 function.  @xref{Uniquify,,, emacs, The GNU Emacs Manual}.
271 @strong{Please note:} @code{create-file-buffer} does @emph{not}
272 associate the new buffer with a file and does not select the buffer.
273 It also does not use the default major mode.
275 @example
276 @group
277 (create-file-buffer "foo")
278      @result{} #<buffer foo>
279 @end group
280 @group
281 (create-file-buffer "foo")
282      @result{} #<buffer foo<2>>
283 @end group
284 @group
285 (create-file-buffer "foo")
286      @result{} #<buffer foo<3>>
287 @end group
288 @end example
290 This function is used by @code{find-file-noselect}.
291 It uses @code{generate-new-buffer} (@pxref{Creating Buffers}).
292 @end defun
294 @defun after-find-file &optional error warn noauto after-find-file-from-revert-buffer nomodes
295 This function sets the buffer major mode, and parses local variables
296 (@pxref{Auto Major Mode}).  It is called by @code{find-file-noselect}
297 and by the default revert function (@pxref{Reverting}).
299 @cindex new file message
300 @cindex file open error
301 If reading the file got an error because the file does not exist, but
302 its directory does exist, the caller should pass a non-@code{nil} value
303 for @var{error}.  In that case, @code{after-find-file} issues a warning:
304 @samp{(New file)}.  For more serious errors, the caller should usually not
305 call @code{after-find-file}.
307 If @var{warn} is non-@code{nil}, then this function issues a warning
308 if an auto-save file exists and is more recent than the visited file.
310 If @var{noauto} is non-@code{nil}, that says not to enable or disable
311 Auto-Save mode.  The mode remains enabled if it was enabled before.
313 If @var{after-find-file-from-revert-buffer} is non-@code{nil}, that
314 means this call was from @code{revert-buffer}.  This has no direct
315 effect, but some mode functions and hook functions check the value
316 of this variable.
318 If @var{nomodes} is non-@code{nil}, that means don't alter the buffer's
319 major mode, don't process local variables specifications in the file,
320 and don't run @code{find-file-hook}.  This feature is used by
321 @code{revert-buffer} in some cases.
323 The last thing @code{after-find-file} does is call all the functions
324 in the list @code{find-file-hook}.
325 @end defun
327 @node Saving Buffers
328 @section Saving Buffers
329 @cindex saving buffers
331   When you edit a file in Emacs, you are actually working on a buffer
332 that is visiting that file---that is, the contents of the file are
333 copied into the buffer and the copy is what you edit.  Changes to the
334 buffer do not change the file until you @dfn{save} the buffer, which
335 means copying the contents of the buffer into the file.
337 @deffn Command save-buffer &optional backup-option
338 This function saves the contents of the current buffer in its visited
339 file if the buffer has been modified since it was last visited or saved.
340 Otherwise it does nothing.
342 @code{save-buffer} is responsible for making backup files.  Normally,
343 @var{backup-option} is @code{nil}, and @code{save-buffer} makes a backup
344 file only if this is the first save since visiting the file.  Other
345 values for @var{backup-option} request the making of backup files in
346 other circumstances:
348 @itemize @bullet
349 @item
350 With an argument of 4 or 64, reflecting 1 or 3 @kbd{C-u}'s, the
351 @code{save-buffer} function marks this version of the file to be
352 backed up when the buffer is next saved.
354 @item
355 With an argument of 16 or 64, reflecting 2 or 3 @kbd{C-u}'s, the
356 @code{save-buffer} function unconditionally backs up the previous
357 version of the file before saving it.
359 @item
360 With an argument of 0, unconditionally do @emph{not} make any backup file.
361 @end itemize
362 @end deffn
364 @deffn Command save-some-buffers &optional save-silently-p pred
365 @anchor{Definition of save-some-buffers}
366 This command saves some modified file-visiting buffers.  Normally it
367 asks the user about each buffer.  But if @var{save-silently-p} is
368 non-@code{nil}, it saves all the file-visiting buffers without querying
369 the user.
371 @vindex save-some-buffers-default-predicate
372 The optional @var{pred} argument provides a predicate that controls
373 which buffers to ask about (or to save silently if
374 @var{save-silently-p} is non-@code{nil}).  If @var{pred} is
375 @code{nil}, that means to use the value of
376 @code{save-some-buffers-default-predicate} instead of @var{pred}.  If
377 the result is @code{nil}, it means ask only about file-visiting
378 buffers.  If it is @code{t}, that means also offer to save certain
379 other non-file buffers---those that have a non-@code{nil} buffer-local
380 value of @code{buffer-offer-save} (@pxref{Killing Buffers}).  A user
381 who says @samp{yes} to saving a non-file buffer is asked to specify
382 the file name to use.  The @code{save-buffers-kill-emacs} function
383 passes the value @code{t} for @var{pred}.
385 If the predicate is neither @code{t} nor @code{nil}, then it should be
386 a function of no arguments.  It will be called in each buffer to decide
387 whether to offer to save that buffer.  If it returns a non-@code{nil}
388 value in a certain buffer, that means do offer to save that buffer.
389 @end deffn
391 @deffn Command write-file filename &optional confirm
392 @anchor{Definition of write-file}
393 This function writes the current buffer into file @var{filename}, makes
394 the buffer visit that file, and marks it not modified.  Then it renames
395 the buffer based on @var{filename}, appending a string like @samp{<2>}
396 if necessary to make a unique buffer name.  It does most of this work by
397 calling @code{set-visited-file-name} (@pxref{Buffer File Name}) and
398 @code{save-buffer}.
400 If @var{confirm} is non-@code{nil}, that means to ask for confirmation
401 before overwriting an existing file.  Interactively, confirmation is
402 required, unless the user supplies a prefix argument.
404 If @var{filename} is a directory name (@pxref{Directory Names}),
405 @code{write-file} uses the name of the visited file, in directory
406 @var{filename}.  If the buffer is not visiting a file, it uses the
407 buffer name instead.
408 @end deffn
410   Saving a buffer runs several hooks.  It also performs format
411 conversion (@pxref{Format Conversion}).  Note that these hooks,
412 described below, are only run by @code{save-buffer}, they are not run
413 by other primitives and functions that write buffer text to files, and
414 in particular auto-saving (@pxref{Auto-Saving}) doesn't run these
415 hooks.
417 @defvar write-file-functions
418 The value of this variable is a list of functions to be called before
419 writing out a buffer to its visited file.  If one of them returns
420 non-@code{nil}, the file is considered already written and the rest of
421 the functions are not called, nor is the usual code for writing the file
422 executed.
424 If a function in @code{write-file-functions} returns non-@code{nil}, it
425 is responsible for making a backup file (if that is appropriate).
426 To do so, execute the following code:
428 @example
429 (or buffer-backed-up (backup-buffer))
430 @end example
432 You might wish to save the file modes value returned by
433 @code{backup-buffer} and use that (if non-@code{nil}) to set the mode
434 bits of the file that you write.  This is what @code{save-buffer}
435 normally does.  @xref{Making Backups,, Making Backup Files}.
437 The hook functions in @code{write-file-functions} are also responsible
438 for encoding the data (if desired): they must choose a suitable coding
439 system and end-of-line conversion (@pxref{Lisp and Coding Systems}),
440 perform the encoding (@pxref{Explicit Encoding}), and set
441 @code{last-coding-system-used} to the coding system that was used
442 (@pxref{Encoding and I/O}).
444 If you set this hook locally in a buffer, it is assumed to be
445 associated with the file or the way the contents of the buffer were
446 obtained.  Thus the variable is marked as a permanent local, so that
447 changing the major mode does not alter a buffer-local value.  On the
448 other hand, calling @code{set-visited-file-name} will reset it.
449 If this is not what you want, you might like to use
450 @code{write-contents-functions} instead.
452 Even though this is not a normal hook, you can use @code{add-hook} and
453 @code{remove-hook} to manipulate the list.  @xref{Hooks}.
454 @end defvar
456 @c Emacs 19 feature
457 @defvar write-contents-functions
458 This works just like @code{write-file-functions}, but it is intended
459 for hooks that pertain to the buffer's contents, not to the particular
460 visited file or its location, and can be used to create arbitrary save
461 processes for buffers that aren't visiting files at all.  Such hooks
462 are usually set up by major modes, as buffer-local bindings for this
463 variable.  This variable automatically becomes buffer-local whenever
464 it is set; switching to a new major mode always resets this variable,
465 but calling @code{set-visited-file-name} does not.
467 If any of the functions in this hook returns non-@code{nil}, the file
468 is considered already written and the rest are not called and neither
469 are the functions in @code{write-file-functions}.
471 When using this hook to save buffers that are not visiting files (for
472 instance, special-mode buffers), keep in mind that, if the function
473 fails to save correctly and returns a @code{nil} value,
474 @code{save-buffer} will go on to prompt the user for a file to save
475 the buffer in.  If this is undesirable, consider having the function
476 fail by raising an error.
477 @end defvar
479 @defopt before-save-hook
480 This normal hook runs before a buffer is saved in its visited file,
481 regardless of whether that is done normally or by one of the hooks
482 described above.  For instance, the @file{copyright.el} program uses
483 this hook to make sure the file you are saving has the current year in
484 its copyright notice.
485 @end defopt
487 @c Emacs 19 feature
488 @defopt after-save-hook
489 This normal hook runs after a buffer has been saved in its visited file.
490 One use of this hook is in Fast Lock mode; it uses this hook to save the
491 highlighting information in a cache file.
492 @end defopt
494 @defopt file-precious-flag
495 If this variable is non-@code{nil}, then @code{save-buffer} protects
496 against I/O errors while saving by writing the new file to a temporary
497 name instead of the name it is supposed to have, and then renaming it to
498 the intended name after it is clear there are no errors.  This procedure
499 prevents problems such as a lack of disk space from resulting in an
500 invalid file.
502 As a side effect, backups are necessarily made by copying.  @xref{Rename
503 or Copy}.  Yet, at the same time, saving a precious file always breaks
504 all hard links between the file you save and other file names.
506 Some modes give this variable a non-@code{nil} buffer-local value
507 in particular buffers.
508 @end defopt
510 @defopt require-final-newline
511 This variable determines whether files may be written out that do
512 @emph{not} end with a newline.  If the value of the variable is
513 @code{t}, then @code{save-buffer} silently adds a newline at the end
514 of the buffer whenever it does not already end in one.  If the value
515 is @code{visit}, Emacs adds a missing newline just after it visits the
516 file.  If the value is @code{visit-save}, Emacs adds a missing newline
517 both on visiting and on saving.  For any other non-@code{nil} value,
518 @code{save-buffer} asks the user whether to add a newline each time
519 the case arises.
521 If the value of the variable is @code{nil}, then @code{save-buffer}
522 doesn't add newlines at all.  @code{nil} is the default value, but a few
523 major modes set it to @code{t} in particular buffers.
524 @end defopt
526   See also the function @code{set-visited-file-name} (@pxref{Buffer File
527 Name}).
529 @node Reading from Files
530 @section Reading from Files
531 @cindex reading from files
533   To copy the contents of a file into a buffer, use the function
534 @code{insert-file-contents}.  (Don't use the command
535 @code{insert-file} in a Lisp program, as that sets the mark.)
537 @defun insert-file-contents filename &optional visit beg end replace
538 This function inserts the contents of file @var{filename} into the
539 current buffer after point.  It returns a list of the absolute file name
540 and the length of the data inserted.  An error is signaled if
541 @var{filename} is not the name of a file that can be read.
543 This function checks the file contents against the defined file
544 formats, and converts the file contents if appropriate and also calls
545 the functions in the list @code{after-insert-file-functions}.
546 @xref{Format Conversion}.  Normally, one of the functions in the
547 @code{after-insert-file-functions} list determines the coding system
548 (@pxref{Coding Systems}) used for decoding the file's contents,
549 including end-of-line conversion.  However, if the file contains null
550 bytes, it is by default visited without any code conversions.
551 @xref{Lisp and Coding Systems, inhibit-null-byte-detection}.
553 If @var{visit} is non-@code{nil}, this function additionally marks the
554 buffer as unmodified and sets up various fields in the buffer so that it
555 is visiting the file @var{filename}: these include the buffer's visited
556 file name and its last save file modtime.  This feature is used by
557 @code{find-file-noselect} and you probably should not use it yourself.
559 If @var{beg} and @var{end} are non-@code{nil}, they should be numbers
560 that are byte offsets specifying the portion of the file to insert.
561 In this case, @var{visit} must be @code{nil}.  For example,
563 @example
564 (insert-file-contents filename nil 0 500)
565 @end example
567 @noindent
568 inserts the first 500 characters of a file.
570 If the argument @var{replace} is non-@code{nil}, it means to replace the
571 contents of the buffer (actually, just the accessible portion) with the
572 contents of the file.  This is better than simply deleting the buffer
573 contents and inserting the whole file, because (1) it preserves some
574 marker positions and (2) it puts less data in the undo list.
576 It is possible to read a special file (such as a FIFO or an I/O device)
577 with @code{insert-file-contents}, as long as @var{replace} and
578 @var{visit} are @code{nil}.
579 @end defun
581 @defun insert-file-contents-literally filename &optional visit beg end replace
582 This function works like @code{insert-file-contents} except that it
583 does not run @code{find-file-hook}, and does not do format decoding,
584 character code conversion, automatic uncompression, and so on.
585 @end defun
587 If you want to pass a file name to another process so that another
588 program can read the file, use the function @code{file-local-copy}; see
589 @ref{Magic File Names}.
591 @node Writing to Files
592 @section Writing to Files
593 @cindex writing to files
595   You can write the contents of a buffer, or part of a buffer, directly
596 to a file on disk using the @code{append-to-file} and
597 @code{write-region} functions.  Don't use these functions to write to
598 files that are being visited; that could cause confusion in the
599 mechanisms for visiting.
601 @deffn Command append-to-file start end filename
602 This function appends the contents of the region delimited by
603 @var{start} and @var{end} in the current buffer to the end of file
604 @var{filename}.  If that file does not exist, it is created.  This
605 function returns @code{nil}.
607 An error is signaled if @var{filename} specifies a nonwritable file,
608 or a nonexistent file in a directory where files cannot be created.
610 When called from Lisp, this function is completely equivalent to:
612 @example
613 (write-region start end filename t)
614 @end example
615 @end deffn
617 @deffn Command write-region start end filename &optional append visit lockname mustbenew
618 This function writes the region delimited by @var{start} and @var{end}
619 in the current buffer into the file specified by @var{filename}.
621 If @var{start} is @code{nil}, then the command writes the entire buffer
622 contents (@emph{not} just the accessible portion) to the file and
623 ignores @var{end}.
625 @c Emacs 19 feature
626 If @var{start} is a string, then @code{write-region} writes or appends
627 that string, rather than text from the buffer.  @var{end} is ignored in
628 this case.
630 If @var{append} is non-@code{nil}, then the specified text is appended
631 to the existing file contents (if any).  If @var{append} is a
632 number, @code{write-region} seeks to that byte offset from the start
633 of the file and writes the data from there.
635 If @var{mustbenew} is non-@code{nil}, then @code{write-region} asks
636 for confirmation if @var{filename} names an existing file.  If
637 @var{mustbenew} is the symbol @code{excl}, then @code{write-region}
638 does not ask for confirmation, but instead it signals an error
639 @code{file-already-exists} if the file already exists.  Although
640 @code{write-region} normally follows a symbolic link and creates the
641 pointed-to file if the symbolic link is dangling, it does not follow
642 symbolic links if @var{mustbenew} is @code{excl}.
644 The test for an existing file, when @var{mustbenew} is @code{excl}, uses
645 a special system feature.  At least for files on a local disk, there is
646 no chance that some other program could create a file of the same name
647 before Emacs does, without Emacs's noticing.
649 If @var{visit} is @code{t}, then Emacs establishes an association
650 between the buffer and the file: the buffer is then visiting that file.
651 It also sets the last file modification time for the current buffer to
652 @var{filename}'s modtime, and marks the buffer as not modified.  This
653 feature is used by @code{save-buffer}, but you probably should not use
654 it yourself.
656 @c Emacs 19 feature
657 If @var{visit} is a string, it specifies the file name to visit.  This
658 way, you can write the data to one file (@var{filename}) while recording
659 the buffer as visiting another file (@var{visit}).  The argument
660 @var{visit} is used in the echo area message and also for file locking;
661 @var{visit} is stored in @code{buffer-file-name}.  This feature is used
662 to implement @code{file-precious-flag}; don't use it yourself unless you
663 really know what you're doing.
665 The optional argument @var{lockname}, if non-@code{nil}, specifies the
666 file name to use for purposes of locking and unlocking, overriding
667 @var{filename} and @var{visit} for that purpose.
669 The function @code{write-region} converts the data which it writes to
670 the appropriate file formats specified by @code{buffer-file-format}
671 and also calls the functions in the list
672 @code{write-region-annotate-functions}.
673 @xref{Format Conversion}.
675 Normally, @code{write-region} displays the message @samp{Wrote
676 @var{filename}} in the echo area.  This message is inhibited if
677 @var{visit} is neither @code{t} nor @code{nil} nor a string, or if
678 Emacs is operating in batch mode (@pxref{Batch Mode}).  This
679 feature is useful for programs that use files for internal purposes,
680 files that the user does not need to know about.
681 @end deffn
683 @defvar write-region-inhibit-fsync
684 If this variable's value is @code{nil}, @code{write-region} uses the
685 @code{fsync} system call after writing a file.  Although this slows
686 Emacs down, it lessens the risk of data loss after power failure.  If
687 the value is @code{t}, Emacs does not use @code{fsync}.  The default
688 value is @code{nil} when Emacs is interactive, and @code{t} when Emacs
689 runs in batch mode.  @xref{Files and Storage}.
690 @end defvar
692 @defmac with-temp-file file body@dots{}
693 @anchor{Definition of with-temp-file}
694 The @code{with-temp-file} macro evaluates the @var{body} forms with a
695 temporary buffer as the current buffer; then, at the end, it writes the
696 buffer contents into file @var{file}.  It kills the temporary buffer
697 when finished, restoring the buffer that was current before the
698 @code{with-temp-file} form.  Then it returns the value of the last form
699 in @var{body}.
701 The current buffer is restored even in case of an abnormal exit via
702 @code{throw} or error (@pxref{Nonlocal Exits}).
704 See also @code{with-temp-buffer} in @ref{Definition of
705 with-temp-buffer,, The Current Buffer}.
706 @end defmac
708 @node File Locks
709 @section File Locks
710 @cindex file locks
711 @cindex lock file
713   When two users edit the same file at the same time, they are likely
714 to interfere with each other.  Emacs tries to prevent this situation
715 from arising by recording a @dfn{file lock} when a file is being
716 modified.
717 Emacs can then detect the first attempt to modify a buffer visiting a
718 file that is locked by another Emacs job, and ask the user what to do.
719 The file lock is really a file, a symbolic link with a special name,
720 stored in the same directory as the file you are editing.  (On file
721 systems that do not support symbolic links, a regular file is used.)
723   When you access files using NFS, there may be a small probability that
724 you and another user will both lock the same file simultaneously.
725 If this happens, it is possible for the two users to make changes
726 simultaneously, but Emacs will still warn the user who saves second.
727 Also, the detection of modification of a buffer visiting a file changed
728 on disk catches some cases of simultaneous editing; see
729 @ref{Modification Time}.
731 @defun file-locked-p filename
732 This function returns @code{nil} if the file @var{filename} is not
733 locked.  It returns @code{t} if it is locked by this Emacs process, and
734 it returns the name of the user who has locked it if it is locked by
735 some other job.
737 @example
738 @group
739 (file-locked-p "foo")
740      @result{} nil
741 @end group
742 @end example
743 @end defun
745 @defun lock-buffer &optional filename
746 This function locks the file @var{filename}, if the current buffer is
747 modified.  The argument @var{filename} defaults to the current buffer's
748 visited file.  Nothing is done if the current buffer is not visiting a
749 file, or is not modified, or if the option @code{create-lockfiles} is
750 @code{nil}.
751 @end defun
753 @defun unlock-buffer
754 This function unlocks the file being visited in the current buffer,
755 if the buffer is modified.  If the buffer is not modified, then
756 the file should not be locked, so this function does nothing.  It also
757 does nothing if the current buffer is not visiting a file, or is not locked.
758 @end defun
760 @defopt create-lockfiles
761 If this variable is @code{nil}, Emacs does not lock files.
762 @end defopt
764 @defun ask-user-about-lock file other-user
765 This function is called when the user tries to modify @var{file}, but it
766 is locked by another user named @var{other-user}.  The default
767 definition of this function asks the user to say what to do.  The value
768 this function returns determines what Emacs does next:
770 @itemize @bullet
771 @item
772 A value of @code{t} says to grab the lock on the file.  Then
773 this user may edit the file and @var{other-user} loses the lock.
775 @item
776 A value of @code{nil} says to ignore the lock and let this
777 user edit the file anyway.
779 @item
780 @kindex file-locked
781 This function may instead signal a @code{file-locked} error, in which
782 case the change that the user was about to make does not take place.
784 The error message for this error looks like this:
786 @example
787 @error{} File is locked: @var{file} @var{other-user}
788 @end example
790 @noindent
791 where @code{file} is the name of the file and @var{other-user} is the
792 name of the user who has locked the file.
793 @end itemize
795 If you wish, you can replace the @code{ask-user-about-lock} function
796 with your own version that makes the decision in another way.
797 @end defun
799 @node Information about Files
800 @section Information about Files
801 @cindex file, information about
803   This section describes the functions for retrieving various types of
804 information about files (or directories or symbolic links), such as
805 whether a file is readable or writable, and its size.  These functions
806 all take arguments which are file names.  Except where noted, these
807 arguments need to specify existing files, or an error is signaled.
809 @cindex file names, trailing whitespace
810 @cindex trailing blanks in file names
811   Be careful with file names that end in spaces.  On some filesystems
812 (notably, MS-Windows), trailing whitespace characters in file names
813 are silently and automatically ignored.
815 @menu
816 * Testing Accessibility::   Is a given file readable?  Writable?
817 * Kinds of Files::          Is it a directory?  A symbolic link?
818 * Truenames::               Eliminating symbolic links from a file name.
819 * File Attributes::         File sizes, modification times, etc.
820 * Extended Attributes::     Extended file attributes for access control.
821 * Locating Files::          How to find a file in standard places.
822 @end menu
824 @node Testing Accessibility
825 @subsection Testing Accessibility
826 @cindex accessibility of a file
827 @cindex file accessibility
829   These functions test for permission to access a file for reading,
830 writing, or execution.  Unless explicitly stated otherwise, they
831 follow symbolic links.  @xref{Kinds of Files}.
833   On some operating systems, more complex sets of access permissions
834 can be specified, via mechanisms such as Access Control Lists (ACLs).
835 @xref{Extended Attributes}, for how to query and set those
836 permissions.
838 @defun file-exists-p filename
839 This function returns @code{t} if a file named @var{filename} appears
840 to exist.  This does not mean you can necessarily read the file, only
841 that you can find out its attributes.  (On GNU and other POSIX-like
842 systems, this is true if the file exists and you have execute
843 permission on the containing directories, regardless of the
844 permissions of the file itself.)
846 If the file does not exist, or if access control policies prevent you
847 from finding its attributes, this function returns @code{nil}.
849 Directories are files, so @code{file-exists-p} can return @code{t} when
850 given a directory.  However, because @code{file-exists-p} follows
851 symbolic links, it returns @code{t} for a symbolic link
852 name only if the target file exists.
853 @end defun
855 @defun file-readable-p filename
856 This function returns @code{t} if a file named @var{filename} exists
857 and you can read it.  It returns @code{nil} otherwise.
858 @end defun
860 @defun file-executable-p filename
861 This function returns @code{t} if a file named @var{filename} exists
862 and you can execute it.  It returns @code{nil} otherwise.  On GNU and
863 other POSIX-like systems, if the file is a directory, execute
864 permission means you can check the existence and attributes of files
865 inside the directory, and open those files if their modes permit.
866 @end defun
868 @defun file-writable-p filename
869 This function returns @code{t} if the file @var{filename} can be written
870 or created by you, and @code{nil} otherwise.  A file is writable if the
871 file exists and you can write it.  It is creatable if it does not exist,
872 but the specified directory does exist and you can write in that
873 directory.
875 In the example below, @file{foo} is not writable because the parent
876 directory does not exist, even though the user could create such a
877 directory.
879 @example
880 @group
881 (file-writable-p "~/no-such-dir/foo")
882      @result{} nil
883 @end group
884 @end example
885 @end defun
887 @defun file-accessible-directory-p dirname
888 This function returns @code{t} if you have permission to open existing
889 files in the directory whose name as a file is @var{dirname};
890 otherwise (or if there is no such directory), it returns @code{nil}.
891 The value of @var{dirname} may be either a directory name (such as
892 @file{/foo/}) or the file name of a file which is a directory
893 (such as @file{/foo}, without the final slash).
895 For example, from the following we deduce that any attempt to read a
896 file in @file{/foo/} will give an error:
898 @example
899 (file-accessible-directory-p "/foo")
900      @result{} nil
901 @end example
902 @end defun
904 @defun access-file filename string
905 This function opens file @var{filename} for reading, then closes it and
906 returns @code{nil}.  However, if the open fails, it signals an error
907 using @var{string} as the error message text.
908 @end defun
910 @defun file-ownership-preserved-p filename &optional group
911 This function returns @code{t} if deleting the file @var{filename} and
912 then creating it anew would keep the file's owner unchanged.  It also
913 returns @code{t} for nonexistent files.
915 If the optional argument @var{group} is non-@code{nil}, this function
916 also checks that the file's group would be unchanged.
918 This function does not follow symbolic links.
919 @end defun
921 @defun file-modes filename
922 @cindex mode bits
923 @cindex file permissions
924 @cindex permissions, file
925 @cindex file modes
926 This function returns the @dfn{mode bits} of @var{filename}---an
927 integer summarizing its read, write, and execution permissions.
928 This function follows symbolic links.  If the file does not exist, the
929 return value is @code{nil}.
931 @xref{File permissions,,, coreutils, The @sc{gnu} @code{Coreutils}
932 Manual}, for a description of mode bits.  For example, if the
933 low-order bit is 1, the file is executable by all users; if the
934 second-lowest-order bit is 1, the file is writable by all users; etc.
935 The highest possible value is 4095 (7777 octal), meaning that everyone
936 has read, write, and execute permission, the @acronym{SUID} bit is set
937 for both others and group, and the sticky bit is set.
939 @xref{Changing Files}, for the @code{set-file-modes} function, which
940 can be used to set these permissions.
942 @example
943 @group
944 (file-modes "~/junk/diffs")
945      @result{} 492               ; @r{Decimal integer.}
946 @end group
947 @group
948 (format "%o" 492)
949      @result{} "754"             ; @r{Convert to octal.}
950 @end group
952 @group
953 (set-file-modes "~/junk/diffs" #o666)
954      @result{} nil
955 @end group
957 @group
958 $ ls -l diffs
959 -rw-rw-rw- 1 lewis lewis 3063 Oct 30 16:00 diffs
960 @end group
961 @end example
963 @cindex MS-DOS and file modes
964 @cindex file modes and MS-DOS
965 @strong{MS-DOS note:} On MS-DOS, there is no such thing as an
966 executable file mode bit.  So @code{file-modes} considers a file
967 executable if its name ends in one of the standard executable
968 extensions, such as @file{.com}, @file{.bat}, @file{.exe}, and some
969 others.  Files that begin with the POSIX-standard @samp{#!} signature,
970 such as shell and Perl scripts, are also considered executable.
971 Directories are also reported as executable, for compatibility with
972 POSIX@.  These conventions are also followed by @code{file-attributes}
973 (@pxref{File Attributes}).
974 @end defun
976 @node Kinds of Files
977 @subsection Distinguishing Kinds of Files
978 @cindex file classification
979 @cindex classification of file types
980 @cindex symbolic links
982   This section describes how to distinguish various kinds of files, such
983 as directories, symbolic links, and ordinary files.
985   Symbolic links are ordinarily followed wherever they appear.  For
986 example, to interpret the file name @file{a/b/c}, any of @file{a},
987 @file{a/b}, and @file{a/b/c} can be symbolic links that are followed,
988 possibly recursively if the link targets are themselves symbolic
989 links.  However, a few functions do not follow symbolic links at the
990 end of a file name (@file{a/b/c} in this example).  Such a function
991 is said to @dfn{not follow symbolic links}.
993 @defun file-symlink-p filename
994 @cindex symbolic links
995 If the file @var{filename} is a symbolic link, this function does not
996 follow it and instead returns its link target
997 as a string.  (The link target string is not necessarily the full
998 absolute file name of the target; determining the full file name that
999 the link points to is nontrivial, see below.)
1001 If the file @var{filename} is not a symbolic link, or does not exist,
1002 @code{file-symlink-p} returns @code{nil}.
1004 Here are a few examples of using this function:
1006 @example
1007 @group
1008 (file-symlink-p "not-a-symlink")
1009      @result{} nil
1010 @end group
1011 @group
1012 (file-symlink-p "sym-link")
1013      @result{} "not-a-symlink"
1014 @end group
1015 @group
1016 (file-symlink-p "sym-link2")
1017      @result{} "sym-link"
1018 @end group
1019 @group
1020 (file-symlink-p "/bin")
1021      @result{} "/pub/bin"
1022 @end group
1023 @end example
1025 Note that in the third example, the function returned @file{sym-link},
1026 but did not proceed to resolve it, although that file is itself a
1027 symbolic link.  That is because this function does not follow symbolic
1028 links---the process of following the symbolic links does not apply to
1029 the last component of the file name.
1031 The string that this function returns is what is recorded in the
1032 symbolic link; it may or may not include any leading directories.
1033 This function does @emph{not} expand the link target to produce a
1034 fully-qualified file name, and in particular does not use the leading
1035 directories, if any, of the @var{filename} argument if the link target
1036 is not an absolute file name.  Here's an example:
1038 @example
1039 @group
1040 (file-symlink-p "/foo/bar/baz")
1041      @result{} "some-file"
1042 @end group
1043 @end example
1045 @noindent
1046 Here, although @file{/foo/bar/baz} was given as a fully-qualified file
1047 name, the result is not, and in fact does not have any leading
1048 directories at all.  And since @file{some-file} might itself be a
1049 symbolic link, you cannot simply prepend leading directories to it,
1050 nor even naively use @code{expand-file-name} (@pxref{File Name
1051 Expansion}) to produce its absolute file name.
1053 For this reason, this function is seldom useful if you need to
1054 determine more than just the fact that a file is or isn't a symbolic
1055 link.  If you actually need the file name of the link target, use
1056 @code{file-chase-links} or @code{file-truename}, described in
1057 @ref{Truenames}.
1058 @end defun
1060 @defun file-directory-p filename
1061 This function returns @code{t} if @var{filename} is the name of an
1062 existing directory, @code{nil} otherwise.
1063 This function follows symbolic links.
1065 @example
1066 @group
1067 (file-directory-p "~rms")
1068      @result{} t
1069 @end group
1070 @group
1071 (file-directory-p "~rms/lewis/files.texi")
1072      @result{} nil
1073 @end group
1074 @group
1075 (file-directory-p "~rms/lewis/no-such-file")
1076      @result{} nil
1077 @end group
1078 @group
1079 (file-directory-p "$HOME")
1080      @result{} nil
1081 @end group
1082 @group
1083 (file-directory-p
1084  (substitute-in-file-name "$HOME"))
1085      @result{} t
1086 @end group
1087 @end example
1088 @end defun
1090 @defun file-regular-p filename
1091 This function returns @code{t} if the file @var{filename} exists and is
1092 a regular file (not a directory, named pipe, terminal, or
1093 other I/O device).
1094 This function follows symbolic links.
1095 @end defun
1097 @node Truenames
1098 @subsection Truenames
1099 @cindex truename (of file)
1101   The @dfn{truename} of a file is the name that you get by following
1102 symbolic links at all levels until none remain, then simplifying away
1103 @samp{.}@: and @samp{..}@: appearing as name components.  This results
1104 in a sort of canonical name for the file.  A file does not always have a
1105 unique truename; the number of distinct truenames a file has is equal to
1106 the number of hard links to the file.  However, truenames are useful
1107 because they eliminate symbolic links as a cause of name variation.
1109 @defun file-truename filename
1110 This function returns the truename of the file @var{filename}.  If the
1111 argument is not an absolute file name, this function first expands it
1112 against @code{default-directory}.
1114 This function does not expand environment variables.  Only
1115 @code{substitute-in-file-name} does that.  @xref{Definition of
1116 substitute-in-file-name}.
1118 If you may need to follow symbolic links preceding @samp{..}@:
1119 appearing as a name component, call @code{file-truename} without prior
1120 direct or indirect calls to @code{expand-file-name}.  Otherwise, the
1121 file name component immediately preceding @samp{..} will be
1122 simplified away before @code{file-truename} is called.  To
1123 eliminate the need for a call to @code{expand-file-name},
1124 @code{file-truename} handles @samp{~} in the same way that
1125 @code{expand-file-name} does.
1127 If the target of a symbolic links has remote file name syntax,
1128 @code{file-truename} returns it quoted.  @xref{File Name Expansion,,
1129 Functions that Expand Filenames}.
1130 @end defun
1132 @defun file-chase-links filename &optional limit
1133 This function follows symbolic links, starting with @var{filename},
1134 until it finds a file name which is not the name of a symbolic link.
1135 Then it returns that file name.  This function does @emph{not} follow
1136 symbolic links at the level of parent directories.
1138 If you specify a number for @var{limit}, then after chasing through
1139 that many links, the function just returns what it has even if that is
1140 still a symbolic link.
1141 @end defun
1143   To illustrate the difference between @code{file-chase-links} and
1144 @code{file-truename}, suppose that @file{/usr/foo} is a symbolic link to
1145 the directory @file{/home/foo}, and @file{/home/foo/hello} is an
1146 ordinary file (or at least, not a symbolic link) or nonexistent.  Then
1147 we would have:
1149 @example
1150 (file-chase-links "/usr/foo/hello")
1151      ;; @r{This does not follow the links in the parent directories.}
1152      @result{} "/usr/foo/hello"
1153 (file-truename "/usr/foo/hello")
1154      ;; @r{Assuming that @file{/home} is not a symbolic link.}
1155      @result{} "/home/foo/hello"
1156 @end example
1158 @defun file-equal-p file1 file2
1159 This function returns @code{t} if the files @var{file1} and
1160 @var{file2} name the same file.  This is similar to comparing their
1161 truenames, except that remote file names are also handled in an
1162 appropriate manner.  If @var{file1} or @var{file2} does not exist, the
1163 return value is unspecified.
1164 @end defun
1166 @defun file-name-case-insensitive-p filename
1167 Sometimes file names or their parts need to be compared as strings, in
1168 which case it's important to know whether the underlying filesystem is
1169 case-insensitive.  This function returns @code{t} if file
1170 @var{filename} is on a case-insensitive filesystem.  It always returns
1171 @code{t} on MS-DOS and MS-Windows.  On Cygwin and Mac OS X,
1172 filesystems may or may not be case-insensitive, and the function tries
1173 to determine case-sensitivity by a runtime test.  If the test is
1174 inconclusive, the function returns @code{t} on Cygwin and @code{nil}
1175 on Mac OS X.
1177 Currently this function always returns @code{nil} on platforms other
1178 than MS-DOS, MS-Windows, Cygwin, and Mac OS X.  It does not detect
1179 case-insensitivity of mounted filesystems, such as Samba shares or
1180 NFS-mounted Windows volumes.  On remote hosts, it assumes @code{t} for
1181 the @samp{smb} method.  For all other connection methods, runtime
1182 tests are performed.
1183 @end defun
1185 @defun file-in-directory-p file dir
1186 This function returns @code{t} if @var{file} is a file in directory
1187 @var{dir}, or in a subdirectory of @var{dir}.  It also returns
1188 @code{t} if @var{file} and @var{dir} are the same directory.  It
1189 compares the truenames of the two directories.  If @var{dir} does not
1190 name an existing directory, the return value is @code{nil}.
1191 @end defun
1193 @defun vc-responsible-backend file
1194 This function determines the responsible VC backend of the given
1195 @var{file}.  For example, if @file{emacs.c} is a file tracked by Git,
1196 @w{@code{(vc-responsible-backend "emacs.c")}} returns @samp{Git}.
1197 Note that if @var{file} is a symbolic link,
1198 @code{vc-responsible-backend} will not resolve it---the backend of the
1199 symbolic link file itself is reported.  To get the backend VC of the
1200 file to which @var{file} refers, wrap @var{file} with a symbolic link
1201 resolving function such as @code{file-chase-links}:
1203 @smallexample
1204 (vc-responsible-backend (file-chase-links "emacs.c"))
1205 @end smallexample
1206 @end defun
1208 @node File Attributes
1209 @subsection File Attributes
1210 @cindex file attributes
1212   This section describes the functions for getting detailed
1213 information about a file, including the owner and group numbers, the
1214 number of names, the inode number, the size, and the times of access
1215 and modification.
1217 @defun file-newer-than-file-p filename1 filename2
1218 @cindex file age
1219 @cindex file modification time
1220 This function returns @code{t} if the file @var{filename1} is
1221 newer than file @var{filename2}.  If @var{filename1} does not
1222 exist, it returns @code{nil}.  If @var{filename1} does exist, but
1223 @var{filename2} does not, it returns @code{t}.
1225 In the following example, assume that the file @file{aug-19} was written
1226 on the 19th, @file{aug-20} was written on the 20th, and the file
1227 @file{no-file} doesn't exist at all.
1229 @example
1230 @group
1231 (file-newer-than-file-p "aug-19" "aug-20")
1232      @result{} nil
1233 @end group
1234 @group
1235 (file-newer-than-file-p "aug-20" "aug-19")
1236      @result{} t
1237 @end group
1238 @group
1239 (file-newer-than-file-p "aug-19" "no-file")
1240      @result{} t
1241 @end group
1242 @group
1243 (file-newer-than-file-p "no-file" "aug-19")
1244      @result{} nil
1245 @end group
1246 @end example
1247 @end defun
1249 @defun file-attributes filename &optional id-format
1250 @anchor{Definition of file-attributes}
1251 This function returns a list of attributes of file @var{filename}.  If
1252 the specified file's attributes cannot be accessed, it returns @code{nil}.
1253 This function does not follow symbolic links.
1254 The optional parameter @var{id-format} specifies the preferred format
1255 of attributes @acronym{UID} and @acronym{GID} (see below)---the
1256 valid values are @code{'string} and @code{'integer}.  The latter is
1257 the default, but we plan to change that, so you should specify a
1258 non-@code{nil} value for @var{id-format} if you use the returned
1259 @acronym{UID} or @acronym{GID}.
1261 On GNU platforms when operating on a local file, this function is
1262 atomic: if the filesystem is simultaneously being changed by some
1263 other process, this function returns the file's attributes either
1264 before or after the change.  Otherwise this function is not atomic,
1265 and might return @code{nil} if it detects the race condition, or might
1266 return a hodgepodge of the previous and current file attributes.
1268 Accessor functions are provided to access the elements in this list.
1269 The accessors are mentioned along with the descriptions of the
1270 elements below.
1272 The elements of the list, in order, are:
1274 @enumerate 0
1275 @item
1276 @code{t} for a directory, a string for a symbolic link (the name
1277 linked to), or @code{nil} for a text file
1278 (@code{file-attribute-type}).
1280 @c Wordy so as to prevent an overfull hbox.  --rjc 15mar92
1281 @item
1282 The number of names the file has (@code{file-attribute-link-number}).
1283 Alternate names, also known as hard links, can be created by using the
1284 @code{add-name-to-file} function (@pxref{Changing Files}).
1286 @item
1287 The file's @acronym{UID}, normally as a string
1288 (@code{file-attribute-user-id}).  However, if it does not correspond
1289 to a named user, the value is a number.
1291 @item
1292 The file's @acronym{GID}, likewise (@code{file-attribute-group-id}).
1294 @item
1295 The time of last access, as a list of four integers
1296 @code{(@var{sec-high} @var{sec-low} @var{microsec} @var{picosec})}
1297 (@code{file-attribute-access-time}).  (This is similar to the value of
1298 @code{current-time}; see @ref{Time of Day}.)  Note that on some
1299 FAT-based filesystems, only the date of last access is recorded, so
1300 this time will always hold the midnight of the day of last access.
1302 @cindex modification time of file
1303 @item
1304 The time of last modification as a list of four integers (as above)
1305 (@code{file-attribute-modification-time}).  This is the last time when
1306 the file's contents were modified.
1308 @item
1309 The time of last status change as a list of four integers (as above)
1310 (@code{file-attribute-status-change-time}).  This is the time of the
1311 last change to the file's access mode bits, its owner and group, and
1312 other information recorded in the filesystem for the file, beyond the
1313 file's contents.
1315 @item
1316 The size of the file in bytes (@code{file-attribute-size}).  This is
1317 floating point if the size is too large to fit in a Lisp integer.
1319 @item
1320 The file's modes, as a string of ten letters or dashes, as in
1321 @samp{ls -l} (@code{file-attribute-modes}).
1323 @item
1324 An unspecified value, present for backward compatibility.
1326 @item
1327 The file's inode number (@code{file-attribute-inode-number}).  If
1328 possible, this is an integer.  If the inode number is too large to be
1329 represented as an integer in Emacs Lisp but dividing it by
1330 @math{2^{16}} yields a representable integer, then the value has the
1331 form @code{(@var{high} . @var{low})}, where @var{low} holds the low 16
1332 bits.  If the inode number is too wide for even that, the value is of
1333 the form @code{(@var{high} @var{middle} . @var{low})}, where
1334 @code{high} holds the high bits, @var{middle} the middle 24 bits, and
1335 @var{low} the low 16 bits.
1337 @item
1338 The filesystem number of the device that the file is on
1339 @code{file-attribute-device-number}).  Depending on the magnitude of
1340 the value, this can be either an integer or a cons cell, in the same
1341 manner as the inode number.  This element and the file's inode number
1342 together give enough information to distinguish any two files on the
1343 system---no two files can have the same values for both of these
1344 numbers.
1345 @end enumerate
1347 For example, here are the file attributes for @file{files.texi}:
1349 @example
1350 @group
1351 (file-attributes "files.texi" 'string)
1352      @result{}  (nil 1 "lh" "users"
1353           (20614 64019 50040 152000)
1354           (20000 23 0 0)
1355           (20614 64555 902289 872000)
1356           122295 "-rw-rw-rw-"
1357           t (5888 2 . 43978)
1358           (15479 . 46724))
1359 @end group
1360 @end example
1362 @noindent
1363 and here is how the result is interpreted:
1365 @table @code
1366 @item nil
1367 is neither a directory nor a symbolic link.
1369 @item 1
1370 has only one name (the name @file{files.texi} in the current default
1371 directory).
1373 @item "lh"
1374 is owned by the user with name @samp{lh}.
1376 @item "users"
1377 is in the group with name @samp{users}.
1379 @item (20614 64019 50040 152000)
1380 was last accessed on October 23, 2012, at 20:12:03.050040152 UTC.
1382 @item (20000 23 0 0)
1383 was last modified on July 15, 2001, at 08:53:43 UTC.
1385 @item (20614 64555 902289 872000)
1386 last had its status changed on October 23, 2012, at 20:20:59.902289872 UTC.
1388 @item 122295
1389 is 122295 bytes long.  (It may not contain 122295 characters, though,
1390 if some of the bytes belong to multibyte sequences, and also if the
1391 end-of-line format is CR-LF.)
1393 @item "-rw-rw-rw-"
1394 has a mode of read and write access for the owner, group, and world.
1396 @item t
1397 is merely a placeholder; it carries no information.
1399 @item (5888 2 . 43978)
1400 has an inode number of 6473924464520138.
1402 @item (15479 . 46724)
1403 is on the file-system device whose number is 1014478468.
1404 @end table
1405 @end defun
1407 @defun file-nlinks filename
1408 This function returns the number of names (i.e., hard links) that
1409 file @var{filename} has.  If the file does not exist, this function
1410 returns @code{nil}.  Note that symbolic links have no effect on this
1411 function, because they are not considered to be names of the files
1412 they link to.  This function does not follow symbolic links.
1414 @example
1415 @group
1416 $ ls -l foo*
1417 -rw-rw-rw- 2 rms rms 4 Aug 19 01:27 foo
1418 -rw-rw-rw- 2 rms rms 4 Aug 19 01:27 foo1
1419 @end group
1421 @group
1422 (file-nlinks "foo")
1423      @result{} 2
1424 @end group
1425 @group
1426 (file-nlinks "doesnt-exist")
1427      @result{} nil
1428 @end group
1429 @end example
1430 @end defun
1432 @node Extended Attributes
1433 @subsection Extended File Attributes
1434 @cindex extended file attributes
1436 On some operating systems, each file can be associated with arbitrary
1437 @dfn{extended file attributes}.  At present, Emacs supports querying
1438 and setting two specific sets of extended file attributes: Access
1439 Control Lists (ACLs) and SELinux contexts.  These extended file
1440 attributes are used, on some systems, to impose more sophisticated
1441 file access controls than the basic Unix-style permissions
1442 discussed in the previous sections.
1444 @cindex access control list
1445 @cindex ACL entries
1446 @cindex SELinux context
1447   A detailed explanation of ACLs and SELinux is beyond the scope of
1448 this manual.  For our purposes, each file can be associated with an
1449 @dfn{ACL}, which specifies its properties under an ACL-based file
1450 control system, and/or an @dfn{SELinux context}, which specifies its
1451 properties under the SELinux system.
1453 @defun file-acl filename
1454 This function returns the ACL for the file @var{filename}.  The exact
1455 Lisp representation of the ACL is unspecified (and may change in
1456 future Emacs versions), but it is the same as what @code{set-file-acl}
1457 takes for its @var{acl} argument (@pxref{Changing Files}).
1459 The underlying ACL implementation is platform-specific; on GNU/Linux
1460 and BSD, Emacs uses the POSIX ACL interface, while on MS-Windows Emacs
1461 emulates the POSIX ACL interface with native file security APIs.
1463 If Emacs was not compiled with ACL support, or the file does not exist
1464 or is inaccessible, or Emacs was unable to determine the ACL entries
1465 for any other reason, then the return value is @code{nil}.
1466 @end defun
1468 @defun file-selinux-context filename
1469 This function returns the SELinux context of the file @var{filename},
1470 as a list of the form @code{(@var{user} @var{role} @var{type}
1471 @var{range})}.  The list elements are the context's user, role, type,
1472 and range respectively, as Lisp strings; see the SELinux documentation
1473 for details about what these actually mean.  The return value has the
1474 same form as what @code{set-file-selinux-context} takes for its
1475 @var{context} argument (@pxref{Changing Files}).
1477 If Emacs was not compiled with SELinux support, or the file does not
1478 exist or is inaccessible, or if the system does not support SELinux,
1479 then the return value is @code{(nil nil nil nil)}.
1480 @end defun
1482 @defun file-extended-attributes filename
1483 This function returns an alist of the Emacs-recognized extended
1484 attributes of file @var{filename}.  Currently, it serves as a
1485 convenient way to retrieve both the ACL and SELinux context; you can
1486 then call the function @code{set-file-extended-attributes}, with the
1487 returned alist as its second argument, to apply the same file access
1488 attributes to another file (@pxref{Changing Files}).
1490 One of the elements is @code{(acl . @var{acl})}, where @var{acl} has
1491 the same form returned by @code{file-acl}.
1493 Another element is @code{(selinux-context . @var{context})}, where
1494 @var{context} is the SELinux context, in the same form returned by
1495 @code{file-selinux-context}.
1496 @end defun
1498 @node Locating Files
1499 @subsection Locating Files in Standard Places
1500 @cindex locate file in path
1501 @cindex find file in path
1503   This section explains how to search for a file in a list of
1504 directories (a @dfn{path}), or for an executable file in the standard
1505 list of executable file directories.
1507   To search for a user-specific configuration file, @xref{Standard
1508 File Names}, for the @code{locate-user-emacs-file} function.
1510 @defun locate-file filename path &optional suffixes predicate
1511 This function searches for a file whose name is @var{filename} in a
1512 list of directories given by @var{path}, trying the suffixes in
1513 @var{suffixes}.  If it finds such a file, it returns the file's
1514 absolute file name (@pxref{Relative File Names}); otherwise it returns
1515 @code{nil}.
1517 The optional argument @var{suffixes} gives the list of file-name
1518 suffixes to append to @var{filename} when searching.
1519 @code{locate-file} tries each possible directory with each of these
1520 suffixes.  If @var{suffixes} is @code{nil}, or @code{("")}, then there
1521 are no suffixes, and @var{filename} is used only as-is.  Typical
1522 values of @var{suffixes} are @code{exec-suffixes} (@pxref{Subprocess
1523 Creation}), @code{load-suffixes}, @code{load-file-rep-suffixes} and
1524 the return value of the function @code{get-load-suffixes} (@pxref{Load
1525 Suffixes}).
1527 Typical values for @var{path} are @code{exec-path} (@pxref{Subprocess
1528 Creation}) when looking for executable programs, or @code{load-path}
1529 (@pxref{Library Search}) when looking for Lisp files.  If
1530 @var{filename} is absolute, @var{path} has no effect, but the suffixes
1531 in @var{suffixes} are still tried.
1533 The optional argument @var{predicate}, if non-@code{nil}, specifies a
1534 predicate function for testing whether a candidate file is suitable.
1535 The predicate is passed the candidate file name as its single
1536 argument.  If @var{predicate} is @code{nil} or omitted,
1537 @code{locate-file} uses @code{file-readable-p} as the predicate.
1538 @xref{Kinds of Files}, for other useful predicates, e.g.,
1539 @code{file-executable-p} and @code{file-directory-p}.
1541 For compatibility, @var{predicate} can also be one of the symbols
1542 @code{executable}, @code{readable}, @code{writable}, @code{exists}, or
1543 a list of one or more of these symbols.
1544 @end defun
1546 @defun executable-find program
1547 This function searches for the executable file of the named
1548 @var{program} and returns the absolute file name of the executable,
1549 including its file-name extensions, if any.  It returns @code{nil} if
1550 the file is not found.  The functions searches in all the directories
1551 in @code{exec-path}, and tries all the file-name extensions in
1552 @code{exec-suffixes} (@pxref{Subprocess Creation}).
1553 @end defun
1555 @node Changing Files
1556 @section Changing File Names and Attributes
1557 @c @cindex renaming files  Duplicates rename-file
1558 @cindex copying files
1559 @cindex deleting files
1560 @cindex linking files
1561 @cindex setting modes of files
1563   The functions in this section rename, copy, delete, link, and set
1564 the modes (permissions) of files.  Typically, they signal a
1565 @code{file-error} error if they fail to perform their function,
1566 reporting the system-dependent error message that describes the reason
1567 for the failure.  If they fail because a file is missing, they signal
1568 a @code{file-missing} error instead.
1570   For performance, the operating system may cache or alias changes
1571 made by these functions instead of writing them immediately to
1572 secondary storage.  @xref{Files and Storage}.
1574   In the functions that have an argument @var{newname}, if this
1575 argument is a directory name it is treated as if the nondirectory part
1576 of the source name were appended.  Typically, a directory name is one
1577 that ends in @samp{/} (@pxref{Directory Names}).  For example, if the
1578 old name is @file{a/b/c}, the @var{newname} @file{d/e/f/} is treated
1579 as if it were @file{d/e/f/c}.  This special treatment does not apply
1580 if @var{newname} is not a directory name but names a file that is a
1581 directory; for example, the @var{newname} @file{d/e/f} is left as-is
1582 even if @file{d/e/f} happens to be a directory.
1584   In the functions that have an argument @var{newname}, if a file by the
1585 name of @var{newname} already exists, the actions taken depend on the
1586 value of the argument @var{ok-if-already-exists}:
1588 @itemize @bullet
1589 @item
1590 Signal a @code{file-already-exists} error if
1591 @var{ok-if-already-exists} is @code{nil}.
1593 @item
1594 Request confirmation if @var{ok-if-already-exists} is a number.
1596 @item
1597 Replace the old file without confirmation if @var{ok-if-already-exists}
1598 is any other value.
1599 @end itemize
1601 @deffn Command add-name-to-file oldname newname &optional ok-if-already-exists
1602 @cindex file with multiple names
1603 @cindex file hard link
1604 This function gives the file named @var{oldname} the additional name
1605 @var{newname}.  This means that @var{newname} becomes a new hard
1606 link to @var{oldname}.
1608 If @var{newname} is a symbolic link, its directory entry is replaced,
1609 not the directory entry it points to.  If @var{oldname} is a symbolic
1610 link, this function might or might not follow the link; it does not
1611 follow the link on GNU platforms.  If @var{oldname} is a directory,
1612 this function typically fails, although for the superuser on a few
1613 old-fashioned non-GNU platforms it can succeed and create a filesystem
1614 that is not tree-structured.
1616 In the first part of the following example, we list two files,
1617 @file{foo} and @file{foo3}.
1619 @example
1620 @group
1621 $ ls -li fo*
1622 81908 -rw-rw-rw- 1 rms rms 29 Aug 18 20:32 foo
1623 84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
1624 @end group
1625 @end example
1627 Now we create a hard link, by calling @code{add-name-to-file}, then list
1628 the files again.  This shows two names for one file, @file{foo} and
1629 @file{foo2}.
1631 @example
1632 @group
1633 (add-name-to-file "foo" "foo2")
1634      @result{} nil
1635 @end group
1637 @group
1638 $ ls -li fo*
1639 81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo
1640 81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo2
1641 84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
1642 @end group
1643 @end example
1645 Finally, we evaluate the following:
1647 @example
1648 (add-name-to-file "foo" "foo3" t)
1649 @end example
1651 @noindent
1652 and list the files again.  Now there are three names
1653 for one file: @file{foo}, @file{foo2}, and @file{foo3}.  The old
1654 contents of @file{foo3} are lost.
1656 @example
1657 @group
1658 (add-name-to-file "foo1" "foo3")
1659      @result{} nil
1660 @end group
1662 @group
1663 $ ls -li fo*
1664 81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo
1665 81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo2
1666 81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo3
1667 @end group
1668 @end example
1670 This function is meaningless on operating systems where multiple names
1671 for one file are not allowed.  Some systems implement multiple names
1672 by copying the file instead.
1674 See also @code{file-nlinks} in @ref{File Attributes}.
1675 @end deffn
1677 @deffn Command rename-file filename newname &optional ok-if-already-exists
1678 This command renames the file @var{filename} as @var{newname}.
1680 If @var{filename} has additional names aside from @var{filename}, it
1681 continues to have those names.  In fact, adding the name @var{newname}
1682 with @code{add-name-to-file} and then deleting @var{filename} has the
1683 same effect as renaming, aside from momentary intermediate states and
1684 treatment of errors, directories and symbolic links.
1686 This command does not follow symbolic links.  If @var{filename} is a
1687 symbolic link, this command renames the symbolic link, not the file it
1688 points to.  If @var{newname} is a symbolic link, its directory entry
1689 is replaced, not the directory entry it points to.
1691 This command does nothing if @var{filename} and @var{newname} are the
1692 same directory entry, i.e., if they refer to the same parent directory
1693 and give the same name within that directory.  Otherwise, if
1694 @var{filename} and @var{newname} name the same file, this command does
1695 nothing on POSIX-conforming systems, and removes @var{filename} on
1696 some non-POSIX systems.
1698 If @var{newname} exists, then it must be an empty directory if
1699 @var{oldname} is a directory and a non-directory otherwise.
1700 @end deffn
1702 @deffn Command copy-file oldname newname &optional ok-if-already-exists time preserve-uid-gid preserve-extended-attributes
1703 This command copies the file @var{oldname} to @var{newname}.  An
1704 error is signaled if @var{oldname} is not a regular file.  If @var{newname}
1705 names a directory, it copies @var{oldname} into that directory,
1706 preserving its final name component.
1707 @c FIXME: See Bug#27986 for how the previous sentence might change.
1709 This function follows symbolic links, except that it does not follow a
1710 dangling symbolic link to create @var{newname}.
1712 If @var{time} is non-@code{nil}, then this function gives the new file
1713 the same last-modified time that the old one has.  (This works on only
1714 some operating systems.)  If setting the time gets an error,
1715 @code{copy-file} signals a @code{file-date-error} error.  In an
1716 interactive call, a prefix argument specifies a non-@code{nil} value
1717 for @var{time}.
1719 If argument @var{preserve-uid-gid} is @code{nil}, we let the operating
1720 system decide the user and group ownership of the new file (this is
1721 usually set to the user running Emacs).  If @var{preserve-uid-gid} is
1722 non-@code{nil}, we attempt to copy the user and group ownership of the
1723 file.  This works only on some operating systems, and only if you have
1724 the correct permissions to do so.
1726 If the optional argument @var{preserve-permissions} is non-@code{nil},
1727 this function copies the file modes (or ``permissions'') of
1728 @var{oldname} to @var{newname}, as well as the Access Control List and
1729 SELinux context (if any).  @xref{Information about Files}.
1731 Otherwise, the file modes of @var{newname} are left unchanged if it is
1732 an existing file, and set to those of @var{oldname}, masked by the
1733 default file permissions (see @code{set-default-file-modes} below), if
1734 @var{newname} is to be newly created.  The Access Control List or
1735 SELinux context are not copied over in either case.
1736 @end deffn
1738 @deffn Command make-symbolic-link target newname &optional ok-if-already-exists
1739 @pindex ln
1740 @kindex file-already-exists
1741 This command makes a symbolic link to @var{target}, named
1742 @var{newname}.  This is like the shell command @samp{ln -s
1743 @var{target} @var{newname}}.  The @var{target} argument
1744 is treated only as a string; it need not name an existing file.
1745 If @var{ok-if-already-exists} is an integer, indicating interactive
1746 use, then leading @samp{~} is expanded and leading @samp{/:} is
1747 stripped in the @var{target} string.
1749 If @var{target} is a relative file name, the resulting symbolic link
1750 is interpreted relative to the directory containing the symbolic link.
1751 @xref{Relative File Names}.
1753 If both @var{target} and @var{newname} have remote file name syntax,
1754 and if both remote identifications are equal, the symbolic link points
1755 to the local file name part of @var{target}.
1757 This function is not available on systems that don't support symbolic
1758 links.
1759 @end deffn
1761 @cindex trash
1762 @vindex delete-by-moving-to-trash
1763 @deffn Command delete-file filename &optional trash
1764 @pindex rm
1765 This command deletes the file @var{filename}.  If the file has
1766 multiple names, it continues to exist under the other names.  If
1767 @var{filename} is a symbolic link, @code{delete-file} deletes only the
1768 symbolic link and not its target.
1770 A suitable kind of @code{file-error} error is signaled if the file
1771 does not exist, or is not deletable.  (On GNU and other POSIX-like
1772 systems, a file is deletable if its directory is writable.)
1774 If the optional argument @var{trash} is non-@code{nil} and the
1775 variable @code{delete-by-moving-to-trash} is non-@code{nil}, this
1776 command moves the file into the system Trash instead of deleting it.
1777 @xref{Misc File Ops,,Miscellaneous File Operations, emacs, The GNU
1778 Emacs Manual}.  When called interactively, @var{trash} is @code{t} if
1779 no prefix argument is given, and @code{nil} otherwise.
1781 See also @code{delete-directory} in @ref{Create/Delete Dirs}.
1782 @end deffn
1784 @cindex file permissions, setting
1785 @cindex permissions, file
1786 @cindex file modes, setting
1787 @deffn Command set-file-modes filename mode
1788 This function sets the @dfn{file mode} (or @dfn{permissions}) of
1789 @var{filename} to @var{mode}.  This function follows symbolic links.
1791 If called non-interactively, @var{mode} must be an integer.  Only the
1792 lowest 12 bits of the integer are used; on most systems, only the
1793 lowest 9 bits are meaningful.  You can use the Lisp construct for
1794 octal numbers to enter @var{mode}.  For example,
1796 @example
1797 (set-file-modes #o644)
1798 @end example
1800 @noindent
1801 specifies that the file should be readable and writable for its owner,
1802 readable for group members, and readable for all other users.
1803 @xref{File permissions,,, coreutils, The @sc{gnu} @code{Coreutils}
1804 Manual}, for a description of mode bit specifications.
1806 Interactively, @var{mode} is read from the minibuffer using
1807 @code{read-file-modes} (see below), which lets the user type in either
1808 an integer or a string representing the permissions symbolically.
1810 @xref{File Attributes}, for the function @code{file-modes}, which
1811 returns the permissions of a file.
1812 @end deffn
1814 @defun set-default-file-modes mode
1815 @cindex umask
1816 This function sets the default permissions for new files created by
1817 Emacs and its subprocesses.  Every file created with Emacs initially
1818 has these permissions, or a subset of them (@code{write-region} will
1819 not grant execute permissions even if the default file permissions
1820 allow execution).  On GNU and other POSIX-like systems, the default
1821 permissions are given by the bitwise complement of the @samp{umask}
1822 value.
1824 The argument @var{mode} should be an integer which specifies the
1825 permissions, similar to @code{set-file-modes} above.  Only the lowest
1826 9 bits are meaningful.
1828 The default file permissions have no effect when you save a modified
1829 version of an existing file; saving a file preserves its existing
1830 permissions.
1831 @end defun
1833 @defmac with-file-modes mode body@dots{}
1834 This macro evaluates the @var{body} forms with the default
1835 permissions for new files temporarily set to @var{modes} (whose value
1836 is as for @code{set-file-modes} above).  When finished, it restores
1837 the original default file permissions, and returns the value of the
1838 last form in @var{body}.
1840 This is useful for creating private files, for example.
1841 @end defmac
1843 @defun default-file-modes
1844 This function returns the default file permissions, as an integer.
1845 @end defun
1847 @defun read-file-modes &optional prompt base-file
1848 This function reads a set of file mode bits from the minibuffer.  The
1849 first optional argument @var{prompt} specifies a non-default prompt.
1850 Second second optional argument @var{base-file} is the name of a file
1851 on whose permissions to base the mode bits that this function returns,
1852 if what the user types specifies mode bits relative to permissions of
1853 an existing file.
1855 If user input represents an octal number, this function returns that
1856 number.  If it is a complete symbolic specification of mode bits, as
1857 in @code{"u=rwx"}, the function converts it to the equivalent numeric
1858 value using @code{file-modes-symbolic-to-number} and returns the
1859 result.  If the specification is relative, as in @code{"o+g"}, then
1860 the permissions on which the specification is based are taken from the
1861 mode bits of @var{base-file}.  If @var{base-file} is omitted or
1862 @code{nil}, the function uses @code{0} as the base mode bits.  The
1863 complete and relative specifications can be combined, as in
1864 @code{"u+r,g+rx,o+r,g-w"}.  @xref{File permissions,,, coreutils, The
1865 @sc{gnu} @code{Coreutils} Manual}, for a description of file mode
1866 specifications.
1867 @end defun
1869 @defun file-modes-symbolic-to-number modes &optional base-modes
1870 This function converts a symbolic file mode specification in
1871 @var{modes} into the equivalent integer.  If the symbolic
1872 specification is based on an existing file, that file's mode bits are
1873 taken from the optional argument @var{base-modes}; if that argument is
1874 omitted or @code{nil}, it defaults to 0, i.e., no access rights at
1875 all.
1876 @end defun
1878 @defun set-file-times filename &optional time
1879 This function sets the access and modification times of @var{filename}
1880 to @var{time}.  The return value is @code{t} if the times are successfully
1881 set, otherwise it is @code{nil}.  @var{time} defaults to the current
1882 time and must be in the format returned by @code{current-time}
1883 (@pxref{Time of Day}).
1884 @end defun
1886 @defun set-file-extended-attributes filename attribute-alist
1887 This function sets the Emacs-recognized extended file attributes for
1888 @code{filename}.  The second argument @var{attribute-alist} should be
1889 an alist of the same form returned by @code{file-extended-attributes}.
1890 The return value is @code{t} if the attributes are successfully set,
1891 otherwise it is @code{nil}.
1892 @xref{Extended Attributes}.
1893 @end defun
1895 @defun set-file-selinux-context filename context
1896 This function sets the SELinux security context for @var{filename} to
1897 @var{context}.  The @var{context} argument should be a list
1898 @code{(@var{user} @var{role} @var{type} @var{range})}, where each
1899 element is a string.  @xref{Extended Attributes}.
1901 The function returns @code{t} if it succeeds in setting the SELinux
1902 context of @var{filename}.  It returns @code{nil} if the context was
1903 not set (e.g., if SELinux is disabled, or if Emacs was compiled
1904 without SELinux support).
1905 @end defun
1907 @defun set-file-acl filename acl
1908 This function sets the Access Control List for @var{filename} to
1909 @var{acl}.  The @var{acl} argument should have the same form returned
1910 by the function @code{file-acl}.  @xref{Extended Attributes}.
1912 The function returns @code{t} if it successfully sets the ACL of
1913 @var{filename}, @code{nil} otherwise.
1914 @end defun
1916 @node Files and Storage
1917 @section Files and Secondary Storage
1918 @cindex secondary storage
1920 After Emacs changes a file, there are two reasons the changes might
1921 not survive later failures of power or media, both having to do with
1922 efficiency.  First, the operating system might alias written data with
1923 data already stored elsewhere on secondary storage until one file or
1924 the other is later modified; this will lose both files if the only
1925 copy on secondary storage is lost due to media failure.  Second, the
1926 operating system might not write data to secondary storage
1927 immediately, which will lose the data if power is lost.
1929 @findex write-region
1930 Although both sorts of failures can largely be avoided by a suitably
1931 configured file system, such systems are typically more expensive or
1932 less efficient.  In more-typical systems, to survive media failure you
1933 can copy the file to a different device, and to survive a power
1934 failure you can use the @code{write-region} function with the
1935 @code{write-region-inhibit-fsync} variable set to @code{nil}.
1936 @xref{Writing to Files}.
1938 @node File Names
1939 @section File Names
1940 @cindex file names
1942   Files are generally referred to by their names, in Emacs as elsewhere.
1943 File names in Emacs are represented as strings.  The functions that
1944 operate on a file all expect a file name argument.
1946   In addition to operating on files themselves, Emacs Lisp programs
1947 often need to operate on file names; i.e., to take them apart and to use
1948 part of a name to construct related file names.  This section describes
1949 how to manipulate file names.
1951   The functions in this section do not actually access files, so they
1952 can operate on file names that do not refer to an existing file or
1953 directory.
1955 @findex cygwin-convert-file-name-from-windows
1956 @findex cygwin-convert-file-name-to-windows
1957 @cindex MS-Windows file-name syntax
1958 @cindex converting file names from/to MS-Windows syntax
1959   On MS-DOS and MS-Windows, these functions (like the function that
1960 actually operate on files) accept MS-DOS or MS-Windows file-name syntax,
1961 where backslashes separate the components, as well as POSIX syntax; but
1962 they always return POSIX syntax.  This enables Lisp programs to specify
1963 file names in POSIX syntax and work properly on all systems without
1964 change.@footnote{In MS-Windows versions of Emacs compiled for the Cygwin
1965 environment, you can use the functions
1966 @code{cygwin-convert-file-name-to-windows} and
1967 @code{cygwin-convert-file-name-from-windows} to convert between the
1968 two file-name syntaxes.}
1970 @menu
1971 * File Name Components::  The directory part of a file name, and the rest.
1972 * Relative File Names::   Some file names are relative to a current directory.
1973 * Directory Names::       A directory's name as a directory
1974                             is different from its name as a file.
1975 * File Name Expansion::   Converting relative file names to absolute ones.
1976 * Unique File Names::     Generating names for temporary files.
1977 * File Name Completion::  Finding the completions for a given file name.
1978 * Standard File Names::   If your package uses a fixed file name,
1979                             how to handle various operating systems simply.
1980 @end menu
1982 @node File Name Components
1983 @subsection File Name Components
1984 @cindex directory part (of file name)
1985 @cindex nondirectory part (of file name)
1986 @cindex version number (in file name)
1988   The operating system groups files into directories.  To specify a
1989 file, you must specify the directory and the file's name within that
1990 directory.  Therefore, Emacs considers a file name as having two main
1991 parts: the @dfn{directory name} part, and the @dfn{nondirectory} part
1992 (or @dfn{file name within the directory}).  Either part may be empty.
1993 Concatenating these two parts reproduces the original file name.
1995   On most systems, the directory part is everything up to and including
1996 the last slash (backslash is also allowed in input on MS-DOS or
1997 MS-Windows); the nondirectory part is the rest.
1999   For some purposes, the nondirectory part is further subdivided into
2000 the name proper and the @dfn{version number}.  On most systems, only
2001 backup files have version numbers in their names.
2003 @defun file-name-directory filename
2004 This function returns the directory part of @var{filename}, as a
2005 directory name (@pxref{Directory Names}), or @code{nil} if
2006 @var{filename} does not include a directory part.
2008 On GNU and other POSIX-like systems, a string returned by this function always
2009 ends in a slash.  On MS-DOS it can also end in a colon.
2011 @example
2012 @group
2013 (file-name-directory "lewis/foo")  ; @r{GNU example}
2014      @result{} "lewis/"
2015 @end group
2016 @group
2017 (file-name-directory "foo")        ; @r{GNU example}
2018      @result{} nil
2019 @end group
2020 @end example
2021 @end defun
2023 @defun file-name-nondirectory filename
2024 This function returns the nondirectory part of @var{filename}.
2026 @example
2027 @group
2028 (file-name-nondirectory "lewis/foo")
2029      @result{} "foo"
2030 @end group
2031 @group
2032 (file-name-nondirectory "foo")
2033      @result{} "foo"
2034 @end group
2035 @group
2036 (file-name-nondirectory "lewis/")
2037      @result{} ""
2038 @end group
2039 @end example
2040 @end defun
2042 @defun file-name-sans-versions filename &optional keep-backup-version
2043 This function returns @var{filename} with any file version numbers,
2044 backup version numbers, or trailing tildes discarded.
2046 If @var{keep-backup-version} is non-@code{nil}, then true file version
2047 numbers understood as such by the file system are discarded from the
2048 return value, but backup version numbers are kept.
2050 @example
2051 @group
2052 (file-name-sans-versions "~rms/foo.~1~")
2053      @result{} "~rms/foo"
2054 @end group
2055 @group
2056 (file-name-sans-versions "~rms/foo~")
2057      @result{} "~rms/foo"
2058 @end group
2059 @group
2060 (file-name-sans-versions "~rms/foo")
2061      @result{} "~rms/foo"
2062 @end group
2063 @end example
2064 @end defun
2066 @defun file-name-extension filename &optional period
2067 This function returns @var{filename}'s final extension, if any,
2068 after applying @code{file-name-sans-versions} to remove any
2069 version/backup part.  The extension, in a file name, is the part that
2070 follows the last @samp{.} in the last name component (minus any
2071 version/backup part).
2073 This function returns @code{nil} for extensionless file names such as
2074 @file{foo}.  It returns @code{""} for null extensions, as in
2075 @file{foo.}.  If the last component of a file name begins with a
2076 @samp{.}, that @samp{.}  doesn't count as the beginning of an
2077 extension.  Thus, @file{.emacs}'s extension is @code{nil}, not
2078 @samp{.emacs}.
2080 If @var{period} is non-@code{nil}, then the returned value includes
2081 the period that delimits the extension, and if @var{filename} has no
2082 extension, the value is @code{""}.
2083 @end defun
2085 @defun file-name-sans-extension filename
2086 This function returns @var{filename} minus its extension, if any.  The
2087 version/backup part, if present, is only removed if the file has an
2088 extension.  For example,
2090 @example
2091 (file-name-sans-extension "foo.lose.c")
2092      @result{} "foo.lose"
2093 (file-name-sans-extension "big.hack/foo")
2094      @result{} "big.hack/foo"
2095 (file-name-sans-extension "/my/home/.emacs")
2096      @result{} "/my/home/.emacs"
2097 (file-name-sans-extension "/my/home/.emacs.el")
2098      @result{} "/my/home/.emacs"
2099 (file-name-sans-extension "~/foo.el.~3~")
2100      @result{} "~/foo"
2101 (file-name-sans-extension "~/foo.~3~")
2102      @result{} "~/foo.~3~"
2103 @end example
2105 Note that the @samp{.~3~} in the two last examples is the backup part,
2106 not an extension.
2107 @end defun
2109 @defun file-name-base &optional filename
2110 This function is the composition of @code{file-name-sans-extension}
2111 and @code{file-name-nondirectory}.  For example,
2113 @example
2114 (file-name-base "/my/home/foo.c")
2115     @result{} "foo"
2116 @end example
2118 The @var{filename} argument defaults to @code{buffer-file-name}.
2119 @end defun
2121 @node Relative File Names
2122 @subsection Absolute and Relative File Names
2123 @cindex absolute file name
2124 @cindex relative file name
2126   All the directories in the file system form a tree starting at the
2127 root directory.  A file name can specify all the directory names
2128 starting from the root of the tree; then it is called an
2129 @dfn{absolute} file name.  Or it can specify the position of the file
2130 in the tree relative to a default directory; then it is called a
2131 @dfn{relative} file name.  On GNU and other POSIX-like systems,
2132 after any leading @samp{~} has been expanded, an absolute file name
2133 starts with a @samp{/}
2134 (@pxref{abbreviate-file-name}), and a relative one does not.  On
2135 MS-DOS and MS-Windows, an absolute file name starts with a slash or a
2136 backslash, or with a drive specification @samp{@var{x}:/}, where
2137 @var{x} is the @dfn{drive letter}.
2139 @defun file-name-absolute-p filename
2140 This function returns @code{t} if file @var{filename} is an absolute
2141 file name or begins with @samp{~}, @code{nil} otherwise.
2143 @example
2144 @group
2145 (file-name-absolute-p "~rms/foo")
2146      @result{} t
2147 @end group
2148 @group
2149 (file-name-absolute-p "rms/foo")
2150      @result{} nil
2151 @end group
2152 @group
2153 (file-name-absolute-p "/user/rms/foo")
2154      @result{} t
2155 @end group
2156 @end example
2157 @end defun
2159   Given a possibly relative file name, you can expand any
2160 leading @samp{~} and convert the result to an
2161 absolute name using @code{expand-file-name} (@pxref{File Name
2162 Expansion}).  This function converts absolute file names to relative
2163 names:
2165 @defun file-relative-name filename &optional directory
2166 This function tries to return a relative name that is equivalent to
2167 @var{filename}, assuming the result will be interpreted relative to
2168 @var{directory} (an absolute directory name or directory file name).
2169 If @var{directory} is omitted or @code{nil}, it defaults to the
2170 current buffer's default directory.
2172 On some operating systems, an absolute file name begins with a device
2173 name.  On such systems, @var{filename} has no relative equivalent based
2174 on @var{directory} if they start with two different device names.  In
2175 this case, @code{file-relative-name} returns @var{filename} in absolute
2176 form.
2178 @example
2179 (file-relative-name "/foo/bar" "/foo/")
2180      @result{} "bar"
2181 (file-relative-name "/foo/bar" "/hack/")
2182      @result{} "../foo/bar"
2183 @end example
2184 @end defun
2186 @node Directory Names
2187 @subsection Directory Names
2188 @cindex directory name
2189 @cindex directory file name
2190 @cindex file name of directory
2192   A @dfn{directory name} is a string that must name a directory if it
2193 names any file at all.  A directory is actually a kind of file, and it
2194 has a file name (called the @dfn{directory file name}, which is
2195 related to the directory name but is typically not identical.  (This
2196 is not quite the same as the usual POSIX terminology.)  These two
2197 names for the same entity are related by a syntactic transformation.
2198 On GNU and other POSIX-like systems, this is simple: to obtain a
2199 directory name, append a @samp{/} to a directory file name that does
2200 not already end in @samp{/}.  On MS-DOS the relationship is more
2201 complicated.
2203   The difference between a directory name and a directory file name is
2204 subtle but crucial.  When an Emacs variable or function argument is
2205 described as being a directory name, a directory file name is not
2206 acceptable.  When @code{file-name-directory} returns a string, that is
2207 always a directory name.
2209   The following two functions convert between directory names and
2210 directory file names.  They do nothing special with environment
2211 variable substitutions such as @samp{$HOME}, and the constructs
2212 @samp{~}, @samp{.} and @samp{..}.
2214 @defun file-name-as-directory filename
2215 This function returns a string representing @var{filename} in a form
2216 that the operating system will interpret as the name of a directory (a
2217 directory name).  On most systems, this means appending a slash to the
2218 string (if it does not already end in one).
2220 @example
2221 @group
2222 (file-name-as-directory "~rms/lewis")
2223      @result{} "~rms/lewis/"
2224 @end group
2225 @end example
2226 @end defun
2228 @defun directory-name-p filename
2229 This function returns non-@code{nil} if @var{filename} ends with a
2230 directory separator character.  This is the forward slash @samp{/} on
2231 GNU and other POSIX-like systems; MS-Windows and MS-DOS recognize both
2232 the forward slash and the backslash @samp{\} as directory separators.
2233 @end defun
2235 @defun directory-file-name dirname
2236 This function returns a string representing @var{dirname} in a form
2237 that the operating system will interpret as the name of a file (a
2238 directory file name).  On most systems, this means removing the final
2239 directory separators from the string, unless the string consists
2240 entirely of directory separators.
2242 @example
2243 @group
2244 (directory-file-name "~lewis/")
2245      @result{} "~lewis"
2246 @end group
2247 @end example
2248 @end defun
2250   Given a directory name, you can combine it with a relative file name
2251 using @code{concat}:
2253 @example
2254 (concat @var{dirname} @var{relfile})
2255 @end example
2257 @noindent
2258 Be sure to verify that the file name is relative before doing that.
2259 If you use an absolute file name, the results could be syntactically
2260 invalid or refer to the wrong file.
2262   If you want to use a directory file name in making such a
2263 combination, you must first convert it to a directory name using
2264 @code{file-name-as-directory}:
2266 @example
2267 (concat (file-name-as-directory @var{dirfile}) @var{relfile})
2268 @end example
2270 @noindent
2271 Don't try concatenating a slash by hand, as in
2273 @example
2274 ;;; @r{Wrong!}
2275 (concat @var{dirfile} "/" @var{relfile})
2276 @end example
2278 @noindent
2279 because this is not portable.  Always use
2280 @code{file-name-as-directory}.
2282   To avoid the issues mentioned above, or if the @var{dirname} value
2283 might be nil (for example, from an element of @code{load-path}), use:
2285 @example
2286 (expand-file-name @var{relfile} @var{dirname})
2287 @end example
2289 However, @code{expand-file-name} expands leading @samp{~} in
2290 @var{relfile}, which may not be what you want.  @xref{File Name
2291 Expansion}.
2293   To convert a directory name to its abbreviation, use this
2294 function:
2296 @cindex file name abbreviations
2297 @cindex abbreviated file names
2298 @vindex directory-abbrev-alist
2299 @defun abbreviate-file-name filename
2300 @anchor{abbreviate-file-name}
2301 This function returns an abbreviated form of @var{filename}.  It
2302 applies the abbreviations specified in @code{directory-abbrev-alist}
2303 (@pxref{File Aliases,,File Aliases, emacs, The GNU Emacs Manual}),
2304 then substitutes @samp{~} for the user's home directory if the
2305 argument names a file in the home directory or one of its
2306 subdirectories.  If the home directory is a root directory, it is not
2307 replaced with @samp{~}, because this does not make the result shorter
2308 on many systems.
2310 You can use this function for directory names and for file names,
2311 because it recognizes abbreviations even as part of the name.
2312 @end defun
2314 @node File Name Expansion
2315 @subsection Functions that Expand Filenames
2316 @cindex expansion of file names
2318   @dfn{Expanding} a file name means converting a relative file name to
2319 an absolute one.  Since this is done relative to a default directory,
2320 you must specify the default directory as well as the file name
2321 to be expanded.  It also involves expanding abbreviations like
2322 @file{~/}
2323 @ifnottex
2324 (@pxref{abbreviate-file-name}),
2325 @end ifnottex
2326 and eliminating redundancies like @file{./} and @file{@var{name}/../}.
2328 @defun expand-file-name filename &optional directory
2329 This function converts @var{filename} to an absolute file name.  If
2330 @var{directory} is supplied, it is the default directory to start with
2331 if @var{filename} is relative and does not start with @samp{~}.
2332 (The value of @var{directory} should
2333 itself be an absolute directory name or directory file name; it may
2334 start with @samp{~}.)  Otherwise, the current buffer's value of
2335 @code{default-directory} is used.  For example:
2337 @example
2338 @group
2339 (expand-file-name "foo")
2340      @result{} "/xcssun/users/rms/lewis/foo"
2341 @end group
2342 @group
2343 (expand-file-name "../foo")
2344      @result{} "/xcssun/users/rms/foo"
2345 @end group
2346 @group
2347 (expand-file-name "foo" "/usr/spool/")
2348      @result{} "/usr/spool/foo"
2349 @end group
2350 @end example
2352 If the part of @var{filename} before the first slash is
2353 @samp{~}, it expands to the value of the @env{HOME} environment
2354 variable (usually your home directory).  If the part before the first
2355 slash is @samp{~@var{user}} and if @var{user} is a valid login name,
2356 it expands to @var{user}'s home directory.
2357 If you do not want this expansion for a relative @var{filename} that
2358 might begin with a literal @samp{~}, you can use @code{(concat
2359 (file-name-as-directory directory) filename)} instead of
2360 @code{(expand-file-name filename directory)}.
2362 Filenames containing @samp{.} or @samp{..} are simplified to their
2363 canonical form:
2365 @example
2366 @group
2367 (expand-file-name "bar/../foo")
2368      @result{} "/xcssun/users/rms/lewis/foo"
2369 @end group
2370 @end example
2372 In some cases, a leading @samp{..} component can remain in the output:
2374 @example
2375 @group
2376 (expand-file-name "../home" "/")
2377      @result{} "/../home"
2378 @end group
2379 @end example
2381 @noindent
2382 This is for the sake of filesystems that have the concept of a
2383 superroot above the root directory @file{/}.  On other filesystems,
2384 @file{/../} is interpreted exactly the same as @file{/}.
2386 Note that @code{expand-file-name} does @emph{not} expand environment
2387 variables; only @code{substitute-in-file-name} does that:
2389 @example
2390 @group
2391 (expand-file-name "$HOME/foo")
2392      @result{} "/xcssun/users/rms/lewis/$HOME/foo"
2393 @end group
2394 @end example
2396 Note also that @code{expand-file-name} does not follow symbolic links
2397 at any level.  This results in a difference between the way
2398 @code{file-truename} and @code{expand-file-name} treat @samp{..}.
2399 Assuming that @samp{/tmp/bar} is a symbolic link to the directory
2400 @samp{/tmp/foo/bar} we get:
2402 @example
2403 @group
2404 (file-truename "/tmp/bar/../myfile")
2405      @result{} "/tmp/foo/myfile"
2406 @end group
2407 @group
2408 (expand-file-name "/tmp/bar/../myfile")
2409      @result{} "/tmp/myfile"
2410 @end group
2411 @end example
2413 If you may need to follow symbolic links preceding @samp{..}, you
2414 should make sure to call @code{file-truename} without prior direct or
2415 indirect calls to @code{expand-file-name}.  @xref{Truenames}.
2416 @end defun
2418 @defvar default-directory
2419 The value of this buffer-local variable is the default directory for the
2420 current buffer.  It should be an absolute directory name; it may start
2421 with @samp{~}.  This variable is buffer-local in every buffer.
2423 @code{expand-file-name} uses the default directory when its second
2424 argument is @code{nil}.
2426 The value is always a string ending with a slash.
2428 @example
2429 @group
2430 default-directory
2431      @result{} "/user/lewis/manual/"
2432 @end group
2433 @end example
2434 @end defvar
2436 @defun substitute-in-file-name filename
2437 @anchor{Definition of substitute-in-file-name}
2438 This function replaces environment variable references in
2439 @var{filename} with the environment variable values.  Following
2440 standard Unix shell syntax, @samp{$} is the prefix to substitute an
2441 environment variable value.  If the input contains @samp{$$}, that is
2442 converted to @samp{$}; this gives the user a way to quote a
2443 @samp{$}.
2445 The environment variable name is the series of alphanumeric characters
2446 (including underscores) that follow the @samp{$}.  If the character following
2447 the @samp{$} is a @samp{@{}, then the variable name is everything up to the
2448 matching @samp{@}}.
2450 Calling @code{substitute-in-file-name} on output produced by
2451 @code{substitute-in-file-name} tends to give incorrect results.  For
2452 instance, use of @samp{$$} to quote a single @samp{$} won't work
2453 properly, and @samp{$} in an environment variable's value could lead
2454 to repeated substitution.  Therefore, programs that call this function
2455 and put the output where it will be passed to this function need to
2456 double all @samp{$} characters to prevent subsequent incorrect
2457 results.
2459 @c Wordy to avoid overfull hbox.  --rjc 15mar92
2460 Here we assume that the environment variable @env{HOME}, which holds
2461 the user's home directory, has value @samp{/xcssun/users/rms}.
2463 @example
2464 @group
2465 (substitute-in-file-name "$HOME/foo")
2466      @result{} "/xcssun/users/rms/foo"
2467 @end group
2468 @end example
2470 After substitution, if a @samp{~} or a @samp{/} appears immediately
2471 after another @samp{/}, the function discards everything before it (up
2472 through the immediately preceding @samp{/}).
2474 @example
2475 @group
2476 (substitute-in-file-name "bar/~/foo")
2477      @result{} "~/foo"
2478 @end group
2479 @group
2480 (substitute-in-file-name "/usr/local/$HOME/foo")
2481      @result{} "/xcssun/users/rms/foo"
2482      ;; @r{@file{/usr/local/} has been discarded.}
2483 @end group
2484 @end example
2486 @end defun
2488   Sometimes, it is not desired to expand file names.  In such cases,
2489 the file name can be quoted to suppress the expansion, and to handle
2490 the file name literally.  Quoting happens by prefixing the file name
2491 with @samp{/:}.
2493 @defmac file-name-quote name
2494 This macro adds the quotation prefix @samp{/:} to the file @var{name}.
2495 For a local file @var{name}, it prefixes @var{name} with @samp{/:}.
2496 If @var{name} is a remote file name, the local part of @var{name} is
2497 quoted.  If @var{name} is already a quoted file name, @var{name} is
2498 returned unchanged.
2500 @example
2501 @group
2502 (substitute-in-file-name (file-name-quote "bar/~/foo"))
2503      @result{} "/:bar/~/foo"
2504 @end group
2506 @group
2507 (substitute-in-file-name (file-name-quote "/ssh:host:bar/~/foo"))
2508      @result{} "/ssh:host:/:bar/~/foo"
2509 @end group
2510 @end example
2512 The macro cannot be used to suppress file name handlers from magic
2513 file names (@pxref{Magic File Names}).
2514 @end defmac
2516 @defmac file-name-unquote name
2517 This macro removes the quotation prefix @samp{/:} from the file
2518 @var{name}, if any. If @var{name} is a remote file name, the local
2519 part of @var{name} is unquoted.
2520 @end defmac
2522 @defmac file-name-quoted-p name
2523 This macro returns non-@code{nil}, when @var{name} is quoted with the
2524 prefix @samp{/:}.  If @var{name} is a remote file name, the local part
2525 of @var{name} is checked.
2526 @end defmac
2529 @node Unique File Names
2530 @subsection Generating Unique File Names
2531 @cindex unique file names
2532 @cindex temporary files
2534   Some programs need to write temporary files.  Here is the usual way to
2535 construct a name for such a file:
2537 @example
2538 (make-temp-file @var{name-of-application})
2539 @end example
2541 @noindent
2542 The job of @code{make-temp-file} is to prevent two different users or
2543 two different jobs from trying to use the exact same file name.
2545 @defun make-temp-file prefix &optional dir-flag suffix text
2546 This function creates a temporary file and returns its name.  Emacs
2547 creates the temporary file's name by adding to @var{prefix} some
2548 random characters that are different in each Emacs job.  The result is
2549 guaranteed to be a newly created file, containing @var{text} if that's
2550 given as a string and empty otherwise. On MS-DOS, this function
2551 can truncate the @var{string} prefix to fit into the 8+3 file-name
2552 limits.  If @var{prefix} is a relative file name, it is expanded
2553 against @code{temporary-file-directory}.
2555 @example
2556 @group
2557 (make-temp-file "foo")
2558      @result{} "/tmp/foo232J6v"
2559 @end group
2560 @end example
2562 When @code{make-temp-file} returns, the file has been created and is
2563 empty.  At that point, you should write the intended contents into the
2564 file.
2566 If @var{dir-flag} is non-@code{nil}, @code{make-temp-file} creates an
2567 empty directory instead of an empty file.  It returns the file name,
2568 not the directory name, of that directory.  @xref{Directory Names}.
2570 If @var{suffix} is non-@code{nil}, @code{make-temp-file} adds it at
2571 the end of the file name.
2573 If @var{text} is a string, @code{make-temp-file} inserts it in the file.
2575 To prevent conflicts among different libraries running in the same
2576 Emacs, each Lisp program that uses @code{make-temp-file} should have its
2577 own @var{prefix}.  The number added to the end of @var{prefix}
2578 distinguishes between the same application running in different Emacs
2579 jobs.  Additional added characters permit a large number of distinct
2580 names even in one Emacs job.
2581 @end defun
2583   The default directory for temporary files is controlled by the
2584 variable @code{temporary-file-directory}.  This variable gives the user
2585 a uniform way to specify the directory for all temporary files.  Some
2586 programs use @code{small-temporary-file-directory} instead, if that is
2587 non-@code{nil}.  To use it, you should expand the prefix against
2588 the proper directory before calling @code{make-temp-file}.
2590 @defopt temporary-file-directory
2591 @cindex @env{TMPDIR} environment variable
2592 @cindex @env{TMP} environment variable
2593 @cindex @env{TEMP} environment variable
2594 This variable specifies the directory name for creating temporary files.
2595 Its value should be a directory name (@pxref{Directory Names}), but it
2596 is good for Lisp programs to cope if the value is a directory's file
2597 name instead.  Using the value as the second argument to
2598 @code{expand-file-name} is a good way to achieve that.
2600 The default value is determined in a reasonable way for your operating
2601 system; it is based on the @env{TMPDIR}, @env{TMP} and @env{TEMP}
2602 environment variables, with a fall-back to a system-dependent name if
2603 none of these variables is defined.
2605 Even if you do not use @code{make-temp-file} to create the temporary
2606 file, you should still use this variable to decide which directory to
2607 put the file in.  However, if you expect the file to be small, you
2608 should use @code{small-temporary-file-directory} first if that is
2609 non-@code{nil}.
2610 @end defopt
2612 @defopt small-temporary-file-directory
2613 This variable specifies the directory name for
2614 creating certain temporary files, which are likely to be small.
2616 If you want to write a temporary file which is likely to be small, you
2617 should compute the directory like this:
2619 @example
2620 (make-temp-file
2621   (expand-file-name @var{prefix}
2622                     (or small-temporary-file-directory
2623                         temporary-file-directory)))
2624 @end example
2625 @end defopt
2627 @defun make-temp-name base-name
2628 This function generates a string that might be a unique file
2629 name.  The name starts with @var{base-name}, and has several random
2630 characters appended to it, which are different in each Emacs job.  It
2631 is like @code{make-temp-file} except that (i) it just constructs a
2632 name and does not create a file, (ii) @var{base-name} should be an
2633 absolute file name that is not magic, and (iii) if the returned file
2634 name is magic, it might name an existing file.  @xref{Magic File
2635 Names}.
2637 @strong{Warning:} In most cases, you should not use this function; use
2638 @code{make-temp-file} instead!  This function is susceptible to a race
2639 condition, between the @code{make-temp-name} call and the creation of
2640 the file, which in some cases may cause a security hole.
2641 @end defun
2643 Sometimes, it is necessary to create a temporary file on a remote host
2644 or a mounted directory.  The following two functions support this.
2646 @defun make-nearby-temp-file prefix &optional dir-flag suffix
2647 This function is similar to @code{make-temp-file}, but it creates a
2648 temporary file as close as possible to @code{default-directory}.  If
2649 @var{prefix} is a relative file name, and @code{default-directory} is
2650 a remote file name or located on a mounted file systems, the temporary
2651 file is created in the directory returned by the function
2652 @code{temporary-file-directory}.  Otherwise, the function
2653 @code{make-temp-file} is used.  @var{prefix}, @var{dir-flag} and
2654 @var{suffix} have the same meaning as in @code{make-temp-file}.
2656 @example
2657 @group
2658 (let ((default-directory "/ssh:remotehost:"))
2659   (make-nearby-temp-file "foo"))
2660      @result{} "/ssh:remotehost:/tmp/foo232J6v"
2661 @end group
2662 @end example
2663 @end defun
2665 @defun temporary-file-directory
2666 The directory for writing temporary files via
2667 @code{make-nearby-temp-file}.  In case of a remote
2668 @code{default-directory}, this is a directory for temporary files on
2669 that remote host.  If such a directory does not exist, or
2670 @code{default-directory} ought to be located on a mounted file system
2671 (see @code{mounted-file-systems}), the function returns
2672 @code{default-directory}.  For a non-remote and non-mounted
2673 @code{default-directory}, the value of the variable
2674 @code{temporary-file-directory} is returned.
2675 @end defun
2677 In order to extract the local part of the path name from a temporary
2678 file, @code{file-local-name} could be used.
2680 @node File Name Completion
2681 @subsection File Name Completion
2682 @cindex file name completion subroutines
2683 @cindex completion, file name
2685   This section describes low-level subroutines for completing a file
2686 name.  For higher level functions, see @ref{Reading File Names}.
2688 @defun file-name-all-completions partial-filename directory
2689 This function returns a list of all possible completions for a file
2690 whose name starts with @var{partial-filename} in directory
2691 @var{directory}.  The order of the completions is the order of the files
2692 in the directory, which is unpredictable and conveys no useful
2693 information.
2695 The argument @var{partial-filename} must be a file name containing no
2696 directory part and no slash (or backslash on some systems).  The current
2697 buffer's default directory is prepended to @var{directory}, if
2698 @var{directory} is not absolute.
2700 In the following example, suppose that @file{~rms/lewis} is the current
2701 default directory, and has five files whose names begin with @samp{f}:
2702 @file{foo}, @file{file~}, @file{file.c}, @file{file.c.~1~}, and
2703 @file{file.c.~2~}.
2705 @example
2706 @group
2707 (file-name-all-completions "f" "")
2708      @result{} ("foo" "file~" "file.c.~2~"
2709                 "file.c.~1~" "file.c")
2710 @end group
2712 @group
2713 (file-name-all-completions "fo" "")
2714      @result{} ("foo")
2715 @end group
2716 @end example
2717 @end defun
2719 @defun file-name-completion filename directory &optional predicate
2720 This function completes the file name @var{filename} in directory
2721 @var{directory}.  It returns the longest prefix common to all file names
2722 in directory @var{directory} that start with @var{filename}.  If
2723 @var{predicate} is non-@code{nil} then it ignores possible completions
2724 that don't satisfy @var{predicate}, after calling that function
2725 with one argument, the expanded absolute file name.
2727 If only one match exists and @var{filename} matches it exactly, the
2728 function returns @code{t}.  The function returns @code{nil} if directory
2729 @var{directory} contains no name starting with @var{filename}.
2731 In the following example, suppose that the current default directory
2732 has five files whose names begin with @samp{f}: @file{foo},
2733 @file{file~}, @file{file.c}, @file{file.c.~1~}, and
2734 @file{file.c.~2~}.
2736 @example
2737 @group
2738 (file-name-completion "fi" "")
2739      @result{} "file"
2740 @end group
2742 @group
2743 (file-name-completion "file.c.~1" "")
2744      @result{} "file.c.~1~"
2745 @end group
2747 @group
2748 (file-name-completion "file.c.~1~" "")
2749      @result{} t
2750 @end group
2752 @group
2753 (file-name-completion "file.c.~3" "")
2754      @result{} nil
2755 @end group
2756 @end example
2757 @end defun
2759 @defopt completion-ignored-extensions
2760 @code{file-name-completion} usually ignores file names that end in any
2761 string in this list.  It does not ignore them when all the possible
2762 completions end in one of these suffixes.  This variable has no effect
2763 on @code{file-name-all-completions}.
2765 A typical value might look like this:
2767 @example
2768 @group
2769 completion-ignored-extensions
2770      @result{} (".o" ".elc" "~" ".dvi")
2771 @end group
2772 @end example
2774 If an element of @code{completion-ignored-extensions} ends in a slash
2775 @samp{/}, it signals a directory.  The elements which do @emph{not} end
2776 in a slash will never match a directory; thus, the above value will not
2777 filter out a directory named @file{foo.elc}.
2778 @end defopt
2780 @node Standard File Names
2781 @subsection Standard File Names
2783   Sometimes, an Emacs Lisp program needs to specify a standard file
2784 name for a particular use---typically, to hold configuration data
2785 specified by the current user.  Usually, such files should be located
2786 in the directory specified by @code{user-emacs-directory}, which is
2787 @file{~/.emacs.d} by default (@pxref{Init File}).  For example, abbrev
2788 definitions are stored by default in @file{~/.emacs.d/abbrev_defs}.
2789 The easiest way to specify such a file name is to use the function
2790 @code{locate-user-emacs-file}.
2792 @defun locate-user-emacs-file base-name &optional old-name
2793 This function returns an absolute file name for an Emacs-specific
2794 configuration or data file.  The argument @file{base-name} should be a
2795 relative file name.  The return value is the absolute name of a file
2796 in the directory specified by @code{user-emacs-directory}; if that
2797 directory does not exist, this function creates it.
2799 If the optional argument @var{old-name} is non-@code{nil}, it
2800 specifies a file in the user's home directory,
2801 @file{~/@var{old-name}}.  If such a file exists, the return value is
2802 the absolute name of that file, instead of the file specified by
2803 @var{base-name}.  This argument is intended to be used by Emacs
2804 packages to provide backward compatibility.  For instance, prior to
2805 the introduction of @code{user-emacs-directory}, the abbrev file was
2806 located in @file{~/.abbrev_defs}.  Here is the definition of
2807 @code{abbrev-file-name}:
2809 @example
2810 (defcustom abbrev-file-name
2811   (locate-user-emacs-file "abbrev_defs" ".abbrev_defs")
2812   "Default name of file from which to read abbrevs."
2813   @dots{}
2814   :type 'file)
2815 @end example
2816 @end defun
2818   A lower-level function for standardizing file names, which
2819 @code{locate-user-emacs-file} uses as a subroutine, is
2820 @code{convert-standard-filename}.
2822 @defun convert-standard-filename filename
2823 This function returns a file name based on @var{filename}, which fits
2824 the conventions of the current operating system.
2826 On GNU and other POSIX-like systems, this simply returns @var{filename}.
2827 On other operating systems, it may enforce system-specific file name
2828 conventions; for example, on MS-DOS this function performs a variety
2829 of changes to enforce MS-DOS file name limitations, including
2830 converting any leading @samp{.} to @samp{_} and truncating to three
2831 characters after the @samp{.}.
2833 The recommended way to use this function is to specify a name which
2834 fits the conventions of GNU and Unix systems, and pass it to
2835 @code{convert-standard-filename}.
2836 @end defun
2838 @node Contents of Directories
2839 @section Contents of Directories
2840 @cindex directory-oriented functions
2841 @cindex file names in directory
2843   A directory is a kind of file that contains other files entered under
2844 various names.  Directories are a feature of the file system.
2846   Emacs can list the names of the files in a directory as a Lisp list,
2847 or display the names in a buffer using the @code{ls} shell command.  In
2848 the latter case, it can optionally display information about each file,
2849 depending on the options passed to the @code{ls} command.
2851 @defun directory-files directory &optional full-name match-regexp nosort
2852 This function returns a list of the names of the files in the directory
2853 @var{directory}.  By default, the list is in alphabetical order.
2855 If @var{full-name} is non-@code{nil}, the function returns the files'
2856 absolute file names.  Otherwise, it returns the names relative to
2857 the specified directory.
2859 If @var{match-regexp} is non-@code{nil}, this function returns only
2860 those file names that contain a match for that regular expression---the
2861 other file names are excluded from the list.  On case-insensitive
2862 filesystems, the regular expression matching is case-insensitive.
2864 @c Emacs 19 feature
2865 If @var{nosort} is non-@code{nil}, @code{directory-files} does not sort
2866 the list, so you get the file names in no particular order.  Use this if
2867 you want the utmost possible speed and don't care what order the files
2868 are processed in.  If the order of processing is visible to the user,
2869 then the user will probably be happier if you do sort the names.
2871 @example
2872 @group
2873 (directory-files "~lewis")
2874      @result{} ("#foo#" "#foo.el#" "." ".."
2875          "dired-mods.el" "files.texi"
2876          "files.texi.~1~")
2877 @end group
2878 @end example
2880 An error is signaled if @var{directory} is not the name of a directory
2881 that can be read.
2882 @end defun
2884 @defun directory-files-recursively directory regexp &optional include-directories
2885 Return all files under @var{directory} whose names match @var{regexp}.
2886 This function searches the specified @var{directory} and its
2887 sub-directories, recursively, for files whose basenames (i.e., without
2888 the leading directories) match the specified @var{regexp}, and returns
2889 a list of the absolute file names of the matching files
2890 (@pxref{Relative File Names, absolute file names}).  The file names
2891 are returned in depth-first order, meaning that files in some
2892 sub-directory are returned before the files in its parent directory.
2893 In addition, matching files found in each subdirectory are sorted
2894 alphabetically by their basenames.  By default, directories whose
2895 names match @var{regexp} are omitted from the list, but if the
2896 optional argument @var{include-directories} is non-@code{nil}, they
2897 are included.
2898 @end defun
2900 @defun directory-files-and-attributes directory &optional full-name match-regexp nosort id-format
2901 This is similar to @code{directory-files} in deciding which files
2902 to report on and how to report their names.  However, instead
2903 of returning a list of file names, it returns for each file a
2904 list @code{(@var{filename} . @var{attributes})}, where @var{attributes}
2905 is what @code{file-attributes} would return for that file.
2906 The optional argument @var{id-format} has the same meaning as the
2907 corresponding argument to @code{file-attributes} (@pxref{Definition
2908 of file-attributes}).
2909 @end defun
2911 @defun file-expand-wildcards pattern &optional full
2912 This function expands the wildcard pattern @var{pattern}, returning
2913 a list of file names that match it.
2915 If @var{pattern} is written as an absolute file name,
2916 the values are absolute also.
2918 If @var{pattern} is written as a relative file name, it is interpreted
2919 relative to the current default directory.  The file names returned are
2920 normally also relative to the current default directory.  However, if
2921 @var{full} is non-@code{nil}, they are absolute.
2922 @end defun
2924 @defun insert-directory file switches &optional wildcard full-directory-p
2925 This function inserts (in the current buffer) a directory listing for
2926 directory @var{file}, formatted with @code{ls} according to
2927 @var{switches}.  It leaves point after the inserted text.
2928 @var{switches} may be a string of options, or a list of strings
2929 representing individual options.
2931 The argument @var{file} may be either a directory or a file
2932 specification including wildcard characters.  If @var{wildcard} is
2933 non-@code{nil}, that means treat @var{file} as a file specification with
2934 wildcards.
2936 If @var{full-directory-p} is non-@code{nil}, that means the directory
2937 listing is expected to show the full contents of a directory.  You
2938 should specify @code{t} when @var{file} is a directory and switches do
2939 not contain @samp{-d}.  (The @samp{-d} option to @code{ls} says to
2940 describe a directory itself as a file, rather than showing its
2941 contents.)
2943 On most systems, this function works by running a directory listing
2944 program whose name is in the variable @code{insert-directory-program}.
2945 If @var{wildcard} is non-@code{nil}, it also runs the shell specified by
2946 @code{shell-file-name}, to expand the wildcards.
2948 MS-DOS and MS-Windows systems usually lack the standard Unix program
2949 @code{ls}, so this function emulates the standard Unix program @code{ls}
2950 with Lisp code.
2952 As a technical detail, when @var{switches} contains the long
2953 @samp{--dired} option, @code{insert-directory} treats it specially,
2954 for the sake of dired.  However, the normally equivalent short
2955 @samp{-D} option is just passed on to @code{insert-directory-program},
2956 as any other option.
2957 @end defun
2959 @defvar insert-directory-program
2960 This variable's value is the program to run to generate a directory listing
2961 for the function @code{insert-directory}.  It is ignored on systems
2962 which generate the listing with Lisp code.
2963 @end defvar
2965 @node Create/Delete Dirs
2966 @section Creating, Copying and Deleting Directories
2967 @cindex creating, copying and deleting directories
2968 @c Emacs 19 features
2970   Most Emacs Lisp file-manipulation functions get errors when used on
2971 files that are directories.  For example, you cannot delete a directory
2972 with @code{delete-file}.  These special functions exist to create and
2973 delete directories.
2975 @findex mkdir
2976 @deffn Command make-directory dirname &optional parents
2977 This command creates a directory named @var{dirname}.  If
2978 @var{parents} is non-@code{nil}, as is always the case in an
2979 interactive call, that means to create the parent directories first,
2980 if they don't already exist.
2982 @code{mkdir} is an alias for this.
2983 @end deffn
2985 @deffn Command copy-directory dirname newname &optional keep-time parents copy-contents
2986 This command copies the directory named @var{dirname} to
2987 @var{newname}.  If @var{newname} is a directory name,
2988 @var{dirname} will be copied to a subdirectory there.
2989 @xref{Directory Names}.
2991 It always sets the file modes of the copied files to match the
2992 corresponding original file.
2994 The third argument @var{keep-time} non-@code{nil} means to preserve the
2995 modification time of the copied files.  A prefix arg makes
2996 @var{keep-time} non-@code{nil}.
2998 The fourth argument @var{parents} says whether to
2999 create parent directories if they don't exist.  Interactively,
3000 this happens by default.
3002 The fifth argument @var{copy-contents}, if non-@code{nil}, means to
3003 copy the contents of @var{dirname} directly into @var{newname} if the
3004 latter is a directory name, instead of copying @var{dirname} into
3005 it as a subdirectory.
3006 @end deffn
3008 @cindex trash
3009 @vindex delete-by-moving-to-trash
3010 @deffn Command delete-directory dirname &optional recursive trash
3011 This command deletes the directory named @var{dirname}.  The function
3012 @code{delete-file} does not work for files that are directories; you
3013 must use @code{delete-directory} for them.  If @var{recursive} is
3014 @code{nil}, and the directory contains any files,
3015 @code{delete-directory} signals an error.
3016 If recursive is non-@code{nil}, there is no error merely because the
3017 directory or its files are deleted by some other process before
3018 @code{delete-directory} gets to them.
3020 @code{delete-directory} only follows symbolic links at the level of
3021 parent directories.
3023 If the optional argument @var{trash} is non-@code{nil} and the
3024 variable @code{delete-by-moving-to-trash} is non-@code{nil}, this
3025 command moves the file into the system Trash instead of deleting it.
3026 @xref{Misc File Ops,,Miscellaneous File Operations, emacs, The GNU
3027 Emacs Manual}.  When called interactively, @var{trash} is @code{t} if
3028 no prefix argument is given, and @code{nil} otherwise.
3029 @end deffn
3031 @node Magic File Names
3032 @section Making Certain File Names ``Magic''
3033 @cindex magic file names
3035   You can implement special handling for certain file names.  This is
3036 called making those names @dfn{magic}.  The principal use for this
3037 feature is in implementing access to remote files (@pxref{Remote Files,,
3038 Remote Files, emacs, The GNU Emacs Manual}).
3040   To define a kind of magic file name, you must supply a regular
3041 expression to define the class of names (all those that match the
3042 regular expression), plus a handler that implements all the primitive
3043 Emacs file operations for file names that match.
3045 @cindex file handler
3046 @vindex file-name-handler-alist
3047   The variable @code{file-name-handler-alist} holds a list of handlers,
3048 together with regular expressions that determine when to apply each
3049 handler.  Each element has this form:
3051 @example
3052 (@var{regexp} . @var{handler})
3053 @end example
3055 @noindent
3056 All the Emacs primitives for file access and file name transformation
3057 check the given file name against @code{file-name-handler-alist}.  If
3058 the file name matches @var{regexp}, the primitives handle that file by
3059 calling @var{handler}.
3061   The first argument given to @var{handler} is the name of the
3062 primitive, as a symbol; the remaining arguments are the arguments that
3063 were passed to that primitive.  (The first of these arguments is most
3064 often the file name itself.)  For example, if you do this:
3066 @example
3067 (file-exists-p @var{filename})
3068 @end example
3070 @noindent
3071 and @var{filename} has handler @var{handler}, then @var{handler} is
3072 called like this:
3074 @example
3075 (funcall @var{handler} 'file-exists-p @var{filename})
3076 @end example
3078   When a function takes two or more arguments that must be file names,
3079 it checks each of those names for a handler.  For example, if you do
3080 this:
3082 @example
3083 (expand-file-name @var{filename} @var{dirname})
3084 @end example
3086 @noindent
3087 then it checks for a handler for @var{filename} and then for a handler
3088 for @var{dirname}.  In either case, the @var{handler} is called like
3089 this:
3091 @example
3092 (funcall @var{handler} 'expand-file-name @var{filename} @var{dirname})
3093 @end example
3095 @noindent
3096 The @var{handler} then needs to figure out whether to handle
3097 @var{filename} or @var{dirname}.
3099   If the specified file name matches more than one handler, the one
3100 whose match starts last in the file name gets precedence.  This rule
3101 is chosen so that handlers for jobs such as uncompression are handled
3102 first, before handlers for jobs such as remote file access.
3104   Here are the operations that a magic file name handler gets to handle:
3106 @ifnottex
3107 @noindent
3108 @code{access-file}, @code{add-name-to-file},
3109 @code{byte-compiler-base-file-name},@*
3110 @code{copy-directory}, @code{copy-file},
3111 @code{delete-directory}, @code{delete-file},
3112 @code{diff-latest-backup-file},
3113 @code{directory-file-name},
3114 @code{directory-files},
3115 @code{directory-files-and-attributes},
3116 @code{dired-compress-file}, @code{dired-uncache},@*
3117 @code{expand-file-name},
3118 @code{file-accessible-directory-p},
3119 @code{file-acl},
3120 @code{file-attributes},
3121 @code{file-directory-p},
3122 @code{file-equal-p},
3123 @code{file-executable-p}, @code{file-exists-p},
3124 @code{file-in-directory-p},
3125 @code{file-local-copy},
3126 @code{file-modes}, @code{file-name-all-completions},
3127 @code{file-name-as-directory},
3128 @code{file-name-case-insensitive-p},
3129 @code{file-name-completion},
3130 @code{file-name-directory},
3131 @code{file-name-nondirectory},
3132 @code{file-name-sans-versions}, @code{file-newer-than-file-p},
3133 @code{file-notify-add-watch}, @code{file-notify-rm-watch},
3134 @code{file-notify-valid-p},
3135 @code{file-ownership-preserved-p},
3136 @code{file-readable-p}, @code{file-regular-p},
3137 @code{file-remote-p}, @code{file-selinux-context},
3138 @code{file-symlink-p}, @code{file-truename}, @code{file-writable-p},
3139 @code{find-backup-file-name},@*
3140 @code{get-file-buffer},
3141 @code{insert-directory},
3142 @code{insert-file-contents},@*
3143 @code{load},
3144 @code{make-auto-save-file-name},
3145 @code{make-directory},
3146 @code{make-directory-internal},
3147 @code{make-nearby-temp-file},
3148 @code{make-symbolic-link},@*
3149 @code{process-file},
3150 @code{rename-file}, @code{set-file-acl}, @code{set-file-modes},
3151 @code{set-file-selinux-context}, @code{set-file-times},
3152 @code{set-visited-file-modtime}, @code{shell-command},
3153 @code{start-file-process},
3154 @code{substitute-in-file-name},@*
3155 @code{temporary-file-directory},
3156 @code{unhandled-file-name-directory},
3157 @code{vc-registered},
3158 @code{verify-visited-file-modtime},@*
3159 @code{write-region}.
3160 @end ifnottex
3161 @iftex
3162 @noindent
3163 @flushleft
3164 @code{access-file}, @code{add-name-to-file},
3165 @code{byte-com@discretionary{}{}{}piler-base-file-name},
3166 @code{copy-directory}, @code{copy-file},
3167 @code{delete-directory}, @code{delete-file},
3168 @code{diff-latest-backup-file},
3169 @code{directory-file-name},
3170 @code{directory-files},
3171 @code{directory-files-and-at@discretionary{}{}{}tributes},
3172 @code{dired-compress-file}, @code{dired-uncache},
3173 @code{expand-file-name},
3174 @code{file-accessible-direc@discretionary{}{}{}tory-p},
3175 @code{file-acl},
3176 @code{file-attributes},
3177 @code{file-direc@discretionary{}{}{}tory-p},
3178 @code{file-equal-p},
3179 @code{file-executable-p}, @code{file-exists-p},
3180 @code{file-in-directory-p},
3181 @code{file-local-copy},
3182 @code{file-modes}, @code{file-name-all-completions},
3183 @code{file-name-as-directory},
3184 @code{file-name-case-insensitive-p},
3185 @code{file-name-completion},
3186 @code{file-name-directory},
3187 @code{file-name-nondirec@discretionary{}{}{}tory},
3188 @code{file-name-sans-versions}, @code{file-newer-than-file-p},
3189 @code{file-notify-add-watch}, @code{file-notify-rm-watch},
3190 @code{file-notify-valid-p},
3191 @code{file-ownership-pre@discretionary{}{}{}served-p},
3192 @code{file-readable-p}, @code{file-regular-p},
3193 @code{file-remote-p}, @code{file-selinux-context},
3194 @code{file-symlink-p}, @code{file-truename}, @code{file-writable-p},
3195 @code{find-backup-file-name},
3196 @code{get-file-buffer},
3197 @code{insert-directory},
3198 @code{insert-file-contents},
3199 @code{load},
3200 @code{make-auto-save-file-name},
3201 @code{make-direc@discretionary{}{}{}tory},
3202 @code{make-direc@discretionary{}{}{}tory-internal},
3203 @code{make-symbolic-link},
3204 @code{process-file},
3205 @code{rename-file}, @code{set-file-acl}, @code{set-file-modes},
3206 @code{set-file-selinux-context}, @code{set-file-times},
3207 @code{set-visited-file-modtime}, @code{shell-command},
3208 @code{start-file-process},
3209 @code{substitute-in-file-name},
3210 @code{unhandled-file-name-directory},
3211 @code{vc-regis@discretionary{}{}{}tered},
3212 @code{verify-visited-file-modtime},
3213 @code{write-region}.
3214 @end flushleft
3215 @end iftex
3217   Handlers for @code{insert-file-contents} typically need to clear the
3218 buffer's modified flag, with @code{(set-buffer-modified-p nil)}, if the
3219 @var{visit} argument is non-@code{nil}.  This also has the effect of
3220 unlocking the buffer if it is locked.
3222   The handler function must handle all of the above operations, and
3223 possibly others to be added in the future.  It need not implement all
3224 these operations itself---when it has nothing special to do for a
3225 certain operation, it can reinvoke the primitive, to handle the
3226 operation in the usual way.  It should always reinvoke the primitive
3227 for an operation it does not recognize.  Here's one way to do this:
3229 @smallexample
3230 (defun my-file-handler (operation &rest args)
3231   ;; @r{First check for the specific operations}
3232   ;; @r{that we have special handling for.}
3233   (cond ((eq operation 'insert-file-contents) @dots{})
3234         ((eq operation 'write-region) @dots{})
3235         @dots{}
3236         ;; @r{Handle any operation we don't know about.}
3237         (t (let ((inhibit-file-name-handlers
3238                   (cons 'my-file-handler
3239                         (and (eq inhibit-file-name-operation operation)
3240                              inhibit-file-name-handlers)))
3241                  (inhibit-file-name-operation operation))
3242              (apply operation args)))))
3243 @end smallexample
3245   When a handler function decides to call the ordinary Emacs primitive for
3246 the operation at hand, it needs to prevent the primitive from calling
3247 the same handler once again, thus leading to an infinite recursion.  The
3248 example above shows how to do this, with the variables
3249 @code{inhibit-file-name-handlers} and
3250 @code{inhibit-file-name-operation}.  Be careful to use them exactly as
3251 shown above; the details are crucial for proper behavior in the case of
3252 multiple handlers, and for operations that have two file names that may
3253 each have handlers.
3255 @kindex safe-magic (@r{property})
3256   Handlers that don't really do anything special for actual access to the
3257 file---such as the ones that implement completion of host names for
3258 remote file names---should have a non-@code{nil} @code{safe-magic}
3259 property.  For instance, Emacs normally protects directory names
3260 it finds in @code{PATH} from becoming magic, if they look like magic
3261 file names, by prefixing them with @samp{/:}.  But if the handler that
3262 would be used for them has a non-@code{nil} @code{safe-magic}
3263 property, the @samp{/:} is not added.
3265 @kindex operations (@r{property})
3266   A file name handler can have an @code{operations} property to
3267 declare which operations it handles in a nontrivial way.  If this
3268 property has a non-@code{nil} value, it should be a list of
3269 operations; then only those operations will call the handler.  This
3270 avoids inefficiency, but its main purpose is for autoloaded handler
3271 functions, so that they won't be loaded except when they have real
3272 work to do.
3274   Simply deferring all operations to the usual primitives does not
3275 work.  For instance, if the file name handler applies to
3276 @code{file-exists-p}, then it must handle @code{load} itself, because
3277 the usual @code{load} code won't work properly in that case.  However,
3278 if the handler uses the @code{operations} property to say it doesn't
3279 handle @code{file-exists-p}, then it need not handle @code{load}
3280 nontrivially.
3282 @defvar inhibit-file-name-handlers
3283 This variable holds a list of handlers whose use is presently inhibited
3284 for a certain operation.
3285 @end defvar
3287 @defvar inhibit-file-name-operation
3288 The operation for which certain handlers are presently inhibited.
3289 @end defvar
3291 @defun find-file-name-handler file operation
3292 This function returns the handler function for file name @var{file},
3293 or @code{nil} if there is none.  The argument @var{operation} should
3294 be the operation to be performed on the file---the value you will pass
3295 to the handler as its first argument when you call it.  If
3296 @var{operation} equals @code{inhibit-file-name-operation}, or if it is
3297 not found in the @code{operations} property of the handler, this
3298 function returns @code{nil}.
3299 @end defun
3301 @defun file-local-copy filename
3302 This function copies file @var{filename} to an ordinary non-magic file
3303 on the local machine, if it isn't on the local machine already.  Magic
3304 file names should handle the @code{file-local-copy} operation if they
3305 refer to files on other machines.  A magic file name that is used for
3306 other purposes than remote file access should not handle
3307 @code{file-local-copy}; then this function will treat the file as
3308 local.
3310 If @var{filename} is local, whether magic or not, this function does
3311 nothing and returns @code{nil}.  Otherwise it returns the file name
3312 of the local copy file.
3313 @end defun
3315 @defun file-remote-p filename &optional identification connected
3316 This function tests whether @var{filename} is a remote file.  If
3317 @var{filename} is local (not remote), the return value is @code{nil}.
3318 If @var{filename} is indeed remote, the return value is a string that
3319 identifies the remote system.
3321 This identifier string can include a host name and a user name, as
3322 well as characters designating the method used to access the remote
3323 system.  For example, the remote identifier string for the filename
3324 @code{/sudo::/some/file} is @code{/sudo:root@@localhost:}.
3326 If @code{file-remote-p} returns the same identifier for two different
3327 filenames, that means they are stored on the same file system and can
3328 be accessed locally with respect to each other.  This means, for
3329 example, that it is possible to start a remote process accessing both
3330 files at the same time.  Implementers of file handlers need to ensure
3331 this principle is valid.
3333 @var{identification} specifies which part of the identifier shall be
3334 returned as string.  @var{identification} can be the symbol
3335 @code{method}, @code{user} or @code{host}; any other value is handled
3336 like @code{nil} and means to return the complete identifier string.
3337 In the example above, the remote @code{user} identifier string would
3338 be @code{root}.
3340 If @var{connected} is non-@code{nil}, this function returns @code{nil}
3341 even if @var{filename} is remote, if Emacs has no network connection
3342 to its host.  This is useful when you want to avoid the delay of
3343 making connections when they don't exist.
3344 @end defun
3346 @defun unhandled-file-name-directory filename
3347 This function returns the name of a directory that is not magic.  For
3348 a non-magic @var{filename} it returns the corresponding directory name
3349 (@pxref{Directory Names}).  For a magic @var{filename}, it invokes the
3350 file name handler, which therefore decides what value to return.  If
3351 @var{filename} is not accessible from a local process, then the file
3352 name handler should indicate that by returning @code{nil}.
3354 This is useful for running a subprocess; every subprocess must have a
3355 non-magic directory to serve as its current directory, and this function
3356 is a good way to come up with one.
3357 @end defun
3359 @defun file-local-name filename
3360 This function returns the local part of file @var{filename}.  For a
3361 remote @var{filename}, it returns a file name which could be used
3362 directly as argument of a remote process.  If @var{filename} is local,
3363 this function returns the file name.
3364 @end defun
3366 @defopt remote-file-name-inhibit-cache
3367 The attributes of remote files can be cached for better performance.  If
3368 they are changed outside of Emacs's control, the cached values become
3369 invalid, and must be reread.
3371 When this variable is set to @code{nil}, cached values are never
3372 expired.  Use this setting with caution, only if you are sure nothing
3373 other than Emacs ever changes the remote files.  If it is set to
3374 @code{t}, cached values are never used.  This is the safest value, but
3375 could result in performance degradation.
3377 A compromise is to set it to a positive number.  This means that
3378 cached values are used for that amount of seconds since they were
3379 cached.  If a remote file is checked regularly, it might be a good
3380 idea to let-bind this variable to a value less than the time period
3381 between consecutive checks.  For example:
3383 @example
3384 (defun display-time-file-nonempty-p (file)
3385   (let ((remote-file-name-inhibit-cache
3386          (- display-time-interval 5)))
3387     (and (file-exists-p file)
3388          (< 0 (nth 7 (file-attributes
3389                        (file-chase-links file)))))))
3390 @end example
3391 @end defopt
3393 @node Format Conversion
3394 @section File Format Conversion
3396 @cindex file format conversion
3397 @cindex encoding file formats
3398 @cindex decoding file formats
3399 @cindex text properties in files
3400 @cindex saving text properties
3401   Emacs performs several steps to convert the data in a buffer (text,
3402 text properties, and possibly other information) to and from a
3403 representation suitable for storing into a file.  This section describes
3404 the fundamental functions that perform this @dfn{format conversion},
3405 namely @code{insert-file-contents} for reading a file into a buffer,
3406 and @code{write-region} for writing a buffer into a file.
3408 @menu
3409 * Overview: Format Conversion Overview.     @code{insert-file-contents} and @code{write-region}.
3410 * Round-Trip: Format Conversion Round-Trip. Using @code{format-alist}.
3411 * Piecemeal: Format Conversion Piecemeal.   Specifying non-paired conversion.
3412 @end menu
3414 @node Format Conversion Overview
3415 @subsection Overview
3416 @noindent
3417 The function @code{insert-file-contents}:
3419 @itemize
3420 @item initially, inserts bytes from the file into the buffer;
3421 @item decodes bytes to characters as appropriate;
3422 @item processes formats as defined by entries in @code{format-alist}; and
3423 @item calls functions in @code{after-insert-file-functions}.
3424 @end itemize
3426 @noindent
3427 The function @code{write-region}:
3429 @itemize
3430 @item initially, calls functions in @code{write-region-annotate-functions};
3431 @item processes formats as defined by entries in @code{format-alist};
3432 @item encodes characters to bytes as appropriate; and
3433 @item modifies the file with the bytes.
3434 @end itemize
3436   This shows the symmetry of the lowest-level operations; reading and
3437 writing handle things in opposite order.  The rest of this section
3438 describes the two facilities surrounding the three variables named
3439 above, as well as some related functions.  @ref{Coding Systems}, for
3440 details on character encoding and decoding.
3442 @node Format Conversion Round-Trip
3443 @subsection Round-Trip Specification
3445   The most general of the two facilities is controlled by the variable
3446 @code{format-alist}, a list of @dfn{file format} specifications, which
3447 describe textual representations used in files for the data in an Emacs
3448 buffer.  The descriptions for reading and writing are paired, which is
3449 why we call this ``round-trip'' specification
3450 (@pxref{Format Conversion Piecemeal}, for non-paired specification).
3452 @defvar format-alist
3453 This list contains one format definition for each defined file format.
3454 Each format definition is a list of this form:
3456 @example
3457 (@var{name} @var{doc-string} @var{regexp} @var{from-fn} @var{to-fn} @var{modify} @var{mode-fn} @var{preserve})
3458 @end example
3459 @end defvar
3461 @cindex format definition
3462 @noindent
3463 Here is what the elements in a format definition mean:
3465 @table @var
3466 @item name
3467 The name of this format.
3469 @item doc-string
3470 A documentation string for the format.
3472 @item regexp
3473 A regular expression which is used to recognize files represented in
3474 this format.  If @code{nil}, the format is never applied automatically.
3476 @item from-fn
3477 A shell command or function to decode data in this format (to convert
3478 file data into the usual Emacs data representation).
3480 A shell command is represented as a string; Emacs runs the command as a
3481 filter to perform the conversion.
3483 If @var{from-fn} is a function, it is called with two arguments, @var{begin}
3484 and @var{end}, which specify the part of the buffer it should convert.
3485 It should convert the text by editing it in place.  Since this can
3486 change the length of the text, @var{from-fn} should return the modified
3487 end position.
3489 One responsibility of @var{from-fn} is to make sure that the beginning
3490 of the file no longer matches @var{regexp}.  Otherwise it is likely to
3491 get called again.  Also, @var{from-fn} must not involve buffers or
3492 files other than the one being decoded, otherwise the internal buffer
3493 used for formatting might be overwritten.
3495 @item to-fn
3496 A shell command or function to encode data in this format---that is, to
3497 convert the usual Emacs data representation into this format.
3499 If @var{to-fn} is a string, it is a shell command; Emacs runs the
3500 command as a filter to perform the conversion.
3502 If @var{to-fn} is a function, it is called with three arguments:
3503 @var{begin} and @var{end}, which specify the part of the buffer it
3504 should convert, and @var{buffer}, which specifies which buffer.  There
3505 are two ways it can do the conversion:
3507 @itemize @bullet
3508 @item
3509 By editing the buffer in place.  In this case, @var{to-fn} should
3510 return the end-position of the range of text, as modified.
3512 @item
3513 By returning a list of annotations.  This is a list of elements of the
3514 form @code{(@var{position} . @var{string})}, where @var{position} is an
3515 integer specifying the relative position in the text to be written, and
3516 @var{string} is the annotation to add there.  The list must be sorted in
3517 order of position when @var{to-fn} returns it.
3519 When @code{write-region} actually writes the text from the buffer to the
3520 file, it intermixes the specified annotations at the corresponding
3521 positions.  All this takes place without modifying the buffer.
3522 @end itemize
3524 @var{to-fn} must not involve buffers or files other than the one being
3525 encoded, otherwise the internal buffer used for formatting might be
3526 overwritten.
3528 @item modify
3529 A flag, @code{t} if the encoding function modifies the buffer, and
3530 @code{nil} if it works by returning a list of annotations.
3532 @item mode-fn
3533 A minor-mode function to call after visiting a file converted from this
3534 format.  The function is called with one argument, the integer 1;
3535 that tells a minor-mode function to enable the mode.
3537 @item preserve
3538 A flag, @code{t} if @code{format-write-file} should not remove this format
3539 from @code{buffer-file-format}.
3540 @end table
3542 The function @code{insert-file-contents} automatically recognizes file
3543 formats when it reads the specified file.  It checks the text of the
3544 beginning of the file against the regular expressions of the format
3545 definitions, and if it finds a match, it calls the decoding function for
3546 that format.  Then it checks all the known formats over again.
3547 It keeps checking them until none of them is applicable.
3549 Visiting a file, with @code{find-file-noselect} or the commands that use
3550 it, performs conversion likewise (because it calls
3551 @code{insert-file-contents}); it also calls the mode function for each
3552 format that it decodes.  It stores a list of the format names in the
3553 buffer-local variable @code{buffer-file-format}.
3555 @defvar buffer-file-format
3556 This variable states the format of the visited file.  More precisely,
3557 this is a list of the file format names that were decoded in the course
3558 of visiting the current buffer's file.  It is always buffer-local in all
3559 buffers.
3560 @end defvar
3562 When @code{write-region} writes data into a file, it first calls the
3563 encoding functions for the formats listed in @code{buffer-file-format},
3564 in the order of appearance in the list.
3566 @deffn Command format-write-file file format &optional confirm
3567 This command writes the current buffer contents into the file @var{file}
3568 in a format based on @var{format}, which is a list of format names.  It
3569 constructs the actual format starting from @var{format}, then appending
3570 any elements from the value of @code{buffer-file-format} with a
3571 non-@code{nil} @var{preserve} flag (see above), if they are not already
3572 present in @var{format}.  It then updates @code{buffer-file-format} with
3573 this format, making it the default for future saves.  Except for the
3574 @var{format} argument, this command is similar to @code{write-file}.  In
3575 particular, @var{confirm} has the same meaning and interactive treatment
3576 as the corresponding argument to @code{write-file}.  @xref{Definition of
3577 write-file}.
3578 @end deffn
3580 @deffn Command format-find-file file format
3581 This command finds the file @var{file}, converting it according to
3582 format @var{format}.  It also makes @var{format} the default if the
3583 buffer is saved later.
3585 The argument @var{format} is a list of format names.  If @var{format} is
3586 @code{nil}, no conversion takes place.  Interactively, typing just
3587 @key{RET} for @var{format} specifies @code{nil}.
3588 @end deffn
3590 @deffn Command format-insert-file file format &optional beg end
3591 This command inserts the contents of file @var{file}, converting it
3592 according to format @var{format}.  If @var{beg} and @var{end} are
3593 non-@code{nil}, they specify which part of the file to read, as in
3594 @code{insert-file-contents} (@pxref{Reading from Files}).
3596 The return value is like what @code{insert-file-contents} returns: a
3597 list of the absolute file name and the length of the data inserted
3598 (after conversion).
3600 The argument @var{format} is a list of format names.  If @var{format} is
3601 @code{nil}, no conversion takes place.  Interactively, typing just
3602 @key{RET} for @var{format} specifies @code{nil}.
3603 @end deffn
3605 @defvar buffer-auto-save-file-format
3606 This variable specifies the format to use for auto-saving.  Its value is
3607 a list of format names, just like the value of
3608 @code{buffer-file-format}; however, it is used instead of
3609 @code{buffer-file-format} for writing auto-save files.  If the value
3610 is @code{t}, the default, auto-saving uses the same format as a
3611 regular save in the same buffer.  This variable is always buffer-local
3612 in all buffers.
3613 @end defvar
3615 @node Format Conversion Piecemeal
3616 @subsection Piecemeal Specification
3618   In contrast to the round-trip specification described in the previous
3619 subsection (@pxref{Format Conversion Round-Trip}), you can use the variables
3620 @code{after-insert-file-functions} and @code{write-region-annotate-functions}
3621 to separately control the respective reading and writing conversions.
3623   Conversion starts with one representation and produces another
3624 representation.  When there is only one conversion to do, there is no
3625 conflict about what to start with.  However, when there are multiple
3626 conversions involved, conflict may arise when two conversions need to
3627 start with the same data.
3629   This situation is best understood in the context of converting text
3630 properties during @code{write-region}.  For example, the character at
3631 position 42 in a buffer is @samp{X} with a text property @code{foo}.  If
3632 the conversion for @code{foo} is done by inserting into the buffer, say,
3633 @samp{FOO:}, then that changes the character at position 42 from
3634 @samp{X} to @samp{F}.  The next conversion will start with the wrong
3635 data straight away.
3637   To avoid conflict, cooperative conversions do not modify the buffer,
3638 but instead specify @dfn{annotations}, a list of elements of the form
3639 @code{(@var{position} . @var{string})}, sorted in order of increasing
3640 @var{position}.
3642   If there is more than one conversion, @code{write-region} merges their
3643 annotations destructively into one sorted list.  Later, when the text
3644 from the buffer is actually written to the file, it intermixes the
3645 specified annotations at the corresponding positions.  All this takes
3646 place without modifying the buffer.
3648 @c ??? What about "overriding" conversions like those allowed
3649 @c ??? for 'write-region-annotate-functions', below?  --ttn
3651   In contrast, when reading, the annotations intermixed with the text
3652 are handled immediately.  @code{insert-file-contents} sets point to
3653 the beginning of some text to be converted, then calls the conversion
3654 functions with the length of that text.  These functions should always
3655 return with point at the beginning of the inserted text.  This
3656 approach makes sense for reading because annotations removed by the
3657 first converter can't be mistakenly processed by a later converter.
3658 Each conversion function should scan for the annotations it
3659 recognizes, remove the annotation, modify the buffer text (to set a
3660 text property, for example), and return the updated length of the
3661 text, as it stands after those changes.  The value returned by one
3662 function becomes the argument to the next function.
3664 @defvar write-region-annotate-functions
3665 A list of functions for @code{write-region} to call.  Each function in
3666 the list is called with two arguments: the start and end of the region
3667 to be written.  These functions should not alter the contents of the
3668 buffer.  Instead, they should return annotations.
3670 As a special case, a function may return with a different buffer
3671 current.  Emacs takes this to mean that the current buffer contains
3672 altered text to be output.  It therefore changes the @var{start} and
3673 @var{end} arguments of the @code{write-region} call, giving them the
3674 values of @code{point-min} and @code{point-max} in the new buffer,
3675 respectively.  It also discards all previous annotations, because they
3676 should have been dealt with by this function.
3677 @end defvar
3679 @defvar write-region-post-annotation-function
3680 The value of this variable, if non-@code{nil}, should be a function.
3681 This function is called, with no arguments, after @code{write-region}
3682 has completed.
3684 If any function in @code{write-region-annotate-functions} returns with
3685 a different buffer current, Emacs calls
3686 @code{write-region-post-annotation-function} more than once.  Emacs
3687 calls it with the last buffer that was current, and again with the
3688 buffer before that, and so on back to the original buffer.
3690 Thus, a function in @code{write-region-annotate-functions} can create
3691 a buffer, give this variable the local value of @code{kill-buffer} in
3692 that buffer, set up the buffer with altered text, and make the buffer
3693 current.  The buffer will be killed after @code{write-region} is done.
3694 @end defvar
3696 @defvar after-insert-file-functions
3697 Each function in this list is called by @code{insert-file-contents}
3698 with one argument, the number of characters inserted, and with point
3699 at the beginning of the inserted text.  Each function should leave
3700 point unchanged, and return the new character count describing the
3701 inserted text as modified by the function.
3702 @c ??? The docstring mentions a handler from 'file-name-handler-alist'
3703 @c     "intercepting" 'insert-file-contents'.  Hmmm.  --ttn
3704 @end defvar
3706   We invite users to write Lisp programs to store and retrieve text
3707 properties in files, using these hooks, and thus to experiment with
3708 various data formats and find good ones.  Eventually we hope users
3709 will produce good, general extensions we can install in Emacs.
3711   We suggest not trying to handle arbitrary Lisp objects as text property
3712 names or values---because a program that general is probably difficult
3713 to write, and slow.  Instead, choose a set of possible data types that
3714 are reasonably flexible, and not too hard to encode.