delete-directory no longer errors when racing
[emacs.git] / doc / lispref / files.texi
blob62e0199f1ff091e492c1a5e15a15f50777e4457f
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2016 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 The optional @var{pred} argument controls which buffers to ask about
372 (or to save silently if @var{save-silently-p} is non-@code{nil}).
373 If it is @code{nil}, that means to ask only about file-visiting buffers.
374 If it is @code{t}, that means also offer to save certain other non-file
375 buffers---those that have a non-@code{nil} buffer-local value of
376 @code{buffer-offer-save} (@pxref{Killing Buffers}).  A user who says
377 @samp{yes} to saving a non-file buffer is asked to specify the file
378 name to use.  The @code{save-buffers-kill-emacs} function passes the
379 value @code{t} for @var{pred}.
381 If @var{pred} is neither @code{t} nor @code{nil}, then it should be
382 a function of no arguments.  It will be called in each buffer to decide
383 whether to offer to save that buffer.  If it returns a non-@code{nil}
384 value in a certain buffer, that means do offer to save that buffer.
385 @end deffn
387 @deffn Command write-file filename &optional confirm
388 @anchor{Definition of write-file}
389 This function writes the current buffer into file @var{filename}, makes
390 the buffer visit that file, and marks it not modified.  Then it renames
391 the buffer based on @var{filename}, appending a string like @samp{<2>}
392 if necessary to make a unique buffer name.  It does most of this work by
393 calling @code{set-visited-file-name} (@pxref{Buffer File Name}) and
394 @code{save-buffer}.
396 If @var{confirm} is non-@code{nil}, that means to ask for confirmation
397 before overwriting an existing file.  Interactively, confirmation is
398 required, unless the user supplies a prefix argument.
400 If @var{filename} is an existing directory, or a symbolic link to one,
401 @code{write-file} uses the name of the visited file, in directory
402 @var{filename}.  If the buffer is not visiting a file, it uses the
403 buffer name instead.
404 @end deffn
406   Saving a buffer runs several hooks.  It also performs format
407 conversion (@pxref{Format Conversion}).
409 @defvar write-file-functions
410 The value of this variable is a list of functions to be called before
411 writing out a buffer to its visited file.  If one of them returns
412 non-@code{nil}, the file is considered already written and the rest of
413 the functions are not called, nor is the usual code for writing the file
414 executed.
416 If a function in @code{write-file-functions} returns non-@code{nil}, it
417 is responsible for making a backup file (if that is appropriate).
418 To do so, execute the following code:
420 @example
421 (or buffer-backed-up (backup-buffer))
422 @end example
424 You might wish to save the file modes value returned by
425 @code{backup-buffer} and use that (if non-@code{nil}) to set the mode
426 bits of the file that you write.  This is what @code{save-buffer}
427 normally does.  @xref{Making Backups,, Making Backup Files}.
429 The hook functions in @code{write-file-functions} are also responsible
430 for encoding the data (if desired): they must choose a suitable coding
431 system and end-of-line conversion (@pxref{Lisp and Coding Systems}),
432 perform the encoding (@pxref{Explicit Encoding}), and set
433 @code{last-coding-system-used} to the coding system that was used
434 (@pxref{Encoding and I/O}).
436 If you set this hook locally in a buffer, it is assumed to be
437 associated with the file or the way the contents of the buffer were
438 obtained.  Thus the variable is marked as a permanent local, so that
439 changing the major mode does not alter a buffer-local value.  On the
440 other hand, calling @code{set-visited-file-name} will reset it.
441 If this is not what you want, you might like to use
442 @code{write-contents-functions} instead.
444 Even though this is not a normal hook, you can use @code{add-hook} and
445 @code{remove-hook} to manipulate the list.  @xref{Hooks}.
446 @end defvar
448 @c Emacs 19 feature
449 @defvar write-contents-functions
450 This works just like @code{write-file-functions}, but it is intended
451 for hooks that pertain to the buffer's contents, not to the particular
452 visited file or its location.  Such hooks are usually set up by major
453 modes, as buffer-local bindings for this variable.  This variable
454 automatically becomes buffer-local whenever it is set; switching to a
455 new major mode always resets this variable, but calling
456 @code{set-visited-file-name} does not.
458 If any of the functions in this hook returns non-@code{nil}, the file
459 is considered already written and the rest are not called and neither
460 are the functions in @code{write-file-functions}.
461 @end defvar
463 @defopt before-save-hook
464 This normal hook runs before a buffer is saved in its visited file,
465 regardless of whether that is done normally or by one of the hooks
466 described above.  For instance, the @file{copyright.el} program uses
467 this hook to make sure the file you are saving has the current year in
468 its copyright notice.
469 @end defopt
471 @c Emacs 19 feature
472 @defopt after-save-hook
473 This normal hook runs after a buffer has been saved in its visited file.
474 One use of this hook is in Fast Lock mode; it uses this hook to save the
475 highlighting information in a cache file.
476 @end defopt
478 @defopt file-precious-flag
479 If this variable is non-@code{nil}, then @code{save-buffer} protects
480 against I/O errors while saving by writing the new file to a temporary
481 name instead of the name it is supposed to have, and then renaming it to
482 the intended name after it is clear there are no errors.  This procedure
483 prevents problems such as a lack of disk space from resulting in an
484 invalid file.
486 As a side effect, backups are necessarily made by copying.  @xref{Rename
487 or Copy}.  Yet, at the same time, saving a precious file always breaks
488 all hard links between the file you save and other file names.
490 Some modes give this variable a non-@code{nil} buffer-local value
491 in particular buffers.
492 @end defopt
494 @defopt require-final-newline
495 This variable determines whether files may be written out that do
496 @emph{not} end with a newline.  If the value of the variable is
497 @code{t}, then @code{save-buffer} silently adds a newline at the end
498 of the buffer whenever it does not already end in one.  If the value
499 is @code{visit}, Emacs adds a missing newline just after it visits the
500 file.  If the value is @code{visit-save}, Emacs adds a missing newline
501 both on visiting and on saving.  For any other non-@code{nil} value,
502 @code{save-buffer} asks the user whether to add a newline each time
503 the case arises.
505 If the value of the variable is @code{nil}, then @code{save-buffer}
506 doesn't add newlines at all.  @code{nil} is the default value, but a few
507 major modes set it to @code{t} in particular buffers.
508 @end defopt
510   See also the function @code{set-visited-file-name} (@pxref{Buffer File
511 Name}).
513 @node Reading from Files
514 @section Reading from Files
515 @cindex reading from files
517   To copy the contents of a file into a buffer, use the function
518 @code{insert-file-contents}.  (Don't use the command
519 @code{insert-file} in a Lisp program, as that sets the mark.)
521 @defun insert-file-contents filename &optional visit beg end replace
522 This function inserts the contents of file @var{filename} into the
523 current buffer after point.  It returns a list of the absolute file name
524 and the length of the data inserted.  An error is signaled if
525 @var{filename} is not the name of a file that can be read.
527 This function checks the file contents against the defined file
528 formats, and converts the file contents if appropriate and also calls
529 the functions in the list @code{after-insert-file-functions}.
530 @xref{Format Conversion}.  Normally, one of the functions in the
531 @code{after-insert-file-functions} list determines the coding system
532 (@pxref{Coding Systems}) used for decoding the file's contents,
533 including end-of-line conversion.  However, if the file contains null
534 bytes, it is by default visited without any code conversions.
535 @xref{Lisp and Coding Systems, inhibit-null-byte-detection}.
537 If @var{visit} is non-@code{nil}, this function additionally marks the
538 buffer as unmodified and sets up various fields in the buffer so that it
539 is visiting the file @var{filename}: these include the buffer's visited
540 file name and its last save file modtime.  This feature is used by
541 @code{find-file-noselect} and you probably should not use it yourself.
543 If @var{beg} and @var{end} are non-@code{nil}, they should be numbers
544 that are byte offsets specifying the portion of the file to insert.
545 In this case, @var{visit} must be @code{nil}.  For example,
547 @example
548 (insert-file-contents filename nil 0 500)
549 @end example
551 @noindent
552 inserts the first 500 characters of a file.
554 If the argument @var{replace} is non-@code{nil}, it means to replace the
555 contents of the buffer (actually, just the accessible portion) with the
556 contents of the file.  This is better than simply deleting the buffer
557 contents and inserting the whole file, because (1) it preserves some
558 marker positions and (2) it puts less data in the undo list.
560 It is possible to read a special file (such as a FIFO or an I/O device)
561 with @code{insert-file-contents}, as long as @var{replace} and
562 @var{visit} are @code{nil}.
563 @end defun
565 @defun insert-file-contents-literally filename &optional visit beg end replace
566 This function works like @code{insert-file-contents} except that it
567 does not run @code{find-file-hook}, and does not do format decoding,
568 character code conversion, automatic uncompression, and so on.
569 @end defun
571 If you want to pass a file name to another process so that another
572 program can read the file, use the function @code{file-local-copy}; see
573 @ref{Magic File Names}.
575 @node Writing to Files
576 @section Writing to Files
577 @cindex writing to files
579   You can write the contents of a buffer, or part of a buffer, directly
580 to a file on disk using the @code{append-to-file} and
581 @code{write-region} functions.  Don't use these functions to write to
582 files that are being visited; that could cause confusion in the
583 mechanisms for visiting.
585 @deffn Command append-to-file start end filename
586 This function appends the contents of the region delimited by
587 @var{start} and @var{end} in the current buffer to the end of file
588 @var{filename}.  If that file does not exist, it is created.  This
589 function returns @code{nil}.
591 An error is signaled if @var{filename} specifies a nonwritable file,
592 or a nonexistent file in a directory where files cannot be created.
594 When called from Lisp, this function is completely equivalent to:
596 @example
597 (write-region start end filename t)
598 @end example
599 @end deffn
601 @deffn Command write-region start end filename &optional append visit lockname mustbenew
602 This function writes the region delimited by @var{start} and @var{end}
603 in the current buffer into the file specified by @var{filename}.
605 If @var{start} is @code{nil}, then the command writes the entire buffer
606 contents (@emph{not} just the accessible portion) to the file and
607 ignores @var{end}.
609 @c Emacs 19 feature
610 If @var{start} is a string, then @code{write-region} writes or appends
611 that string, rather than text from the buffer.  @var{end} is ignored in
612 this case.
614 If @var{append} is non-@code{nil}, then the specified text is appended
615 to the existing file contents (if any).  If @var{append} is a
616 number, @code{write-region} seeks to that byte offset from the start
617 of the file and writes the data from there.
619 If @var{mustbenew} is non-@code{nil}, then @code{write-region} asks
620 for confirmation if @var{filename} names an existing file.  If
621 @var{mustbenew} is the symbol @code{excl}, then @code{write-region}
622 does not ask for confirmation, but instead it signals an error
623 @code{file-already-exists} if the file already exists.
625 The test for an existing file, when @var{mustbenew} is @code{excl}, uses
626 a special system feature.  At least for files on a local disk, there is
627 no chance that some other program could create a file of the same name
628 before Emacs does, without Emacs's noticing.
630 If @var{visit} is @code{t}, then Emacs establishes an association
631 between the buffer and the file: the buffer is then visiting that file.
632 It also sets the last file modification time for the current buffer to
633 @var{filename}'s modtime, and marks the buffer as not modified.  This
634 feature is used by @code{save-buffer}, but you probably should not use
635 it yourself.
637 @c Emacs 19 feature
638 If @var{visit} is a string, it specifies the file name to visit.  This
639 way, you can write the data to one file (@var{filename}) while recording
640 the buffer as visiting another file (@var{visit}).  The argument
641 @var{visit} is used in the echo area message and also for file locking;
642 @var{visit} is stored in @code{buffer-file-name}.  This feature is used
643 to implement @code{file-precious-flag}; don't use it yourself unless you
644 really know what you're doing.
646 The optional argument @var{lockname}, if non-@code{nil}, specifies the
647 file name to use for purposes of locking and unlocking, overriding
648 @var{filename} and @var{visit} for that purpose.
650 The function @code{write-region} converts the data which it writes to
651 the appropriate file formats specified by @code{buffer-file-format}
652 and also calls the functions in the list
653 @code{write-region-annotate-functions}.
654 @xref{Format Conversion}.
656 Normally, @code{write-region} displays the message @samp{Wrote
657 @var{filename}} in the echo area.  This message is inhibited if
658 @var{visit} is neither @code{t} nor @code{nil} nor a string, or if
659 Emacs is operating in batch mode (@pxref{Batch Mode}).  This
660 feature is useful for programs that use files for internal purposes,
661 files that the user does not need to know about.
662 @end deffn
664 @defvar write-region-inhibit-fsync
665 If this variable's value is @code{nil}, @code{write-region} uses the
666 @code{fsync} system call after writing a file.  Although this slows
667 Emacs down, it lessens the risk of data loss after power failure.  If
668 the value is @code{t}, Emacs does not use @code{fsync}.  The default
669 value is @code{nil} when Emacs is interactive, and @code{t} when Emacs
670 runs in batch mode.  @xref{Files and Storage}.
671 @end defvar
673 @defmac with-temp-file file body@dots{}
674 @anchor{Definition of with-temp-file}
675 The @code{with-temp-file} macro evaluates the @var{body} forms with a
676 temporary buffer as the current buffer; then, at the end, it writes the
677 buffer contents into file @var{file}.  It kills the temporary buffer
678 when finished, restoring the buffer that was current before the
679 @code{with-temp-file} form.  Then it returns the value of the last form
680 in @var{body}.
682 The current buffer is restored even in case of an abnormal exit via
683 @code{throw} or error (@pxref{Nonlocal Exits}).
685 See also @code{with-temp-buffer} in @ref{Definition of
686 with-temp-buffer,, The Current Buffer}.
687 @end defmac
689 @node File Locks
690 @section File Locks
691 @cindex file locks
692 @cindex lock file
694   When two users edit the same file at the same time, they are likely
695 to interfere with each other.  Emacs tries to prevent this situation
696 from arising by recording a @dfn{file lock} when a file is being
697 modified.
698 Emacs can then detect the first attempt to modify a buffer visiting a
699 file that is locked by another Emacs job, and ask the user what to do.
700 The file lock is really a file, a symbolic link with a special name,
701 stored in the same directory as the file you are editing.  (On file
702 systems that do not support symbolic links, a regular file is used.)
704   When you access files using NFS, there may be a small probability that
705 you and another user will both lock the same file simultaneously.
706 If this happens, it is possible for the two users to make changes
707 simultaneously, but Emacs will still warn the user who saves second.
708 Also, the detection of modification of a buffer visiting a file changed
709 on disk catches some cases of simultaneous editing; see
710 @ref{Modification Time}.
712 @defun file-locked-p filename
713 This function returns @code{nil} if the file @var{filename} is not
714 locked.  It returns @code{t} if it is locked by this Emacs process, and
715 it returns the name of the user who has locked it if it is locked by
716 some other job.
718 @example
719 @group
720 (file-locked-p "foo")
721      @result{} nil
722 @end group
723 @end example
724 @end defun
726 @defun lock-buffer &optional filename
727 This function locks the file @var{filename}, if the current buffer is
728 modified.  The argument @var{filename} defaults to the current buffer's
729 visited file.  Nothing is done if the current buffer is not visiting a
730 file, or is not modified, or if the option @code{create-lockfiles} is
731 @code{nil}.
732 @end defun
734 @defun unlock-buffer
735 This function unlocks the file being visited in the current buffer,
736 if the buffer is modified.  If the buffer is not modified, then
737 the file should not be locked, so this function does nothing.  It also
738 does nothing if the current buffer is not visiting a file, or is not locked.
739 @end defun
741 @defopt create-lockfiles
742 If this variable is @code{nil}, Emacs does not lock files.
743 @end defopt
745 @defun ask-user-about-lock file other-user
746 This function is called when the user tries to modify @var{file}, but it
747 is locked by another user named @var{other-user}.  The default
748 definition of this function asks the user to say what to do.  The value
749 this function returns determines what Emacs does next:
751 @itemize @bullet
752 @item
753 A value of @code{t} says to grab the lock on the file.  Then
754 this user may edit the file and @var{other-user} loses the lock.
756 @item
757 A value of @code{nil} says to ignore the lock and let this
758 user edit the file anyway.
760 @item
761 @kindex file-locked
762 This function may instead signal a @code{file-locked} error, in which
763 case the change that the user was about to make does not take place.
765 The error message for this error looks like this:
767 @example
768 @error{} File is locked: @var{file} @var{other-user}
769 @end example
771 @noindent
772 where @code{file} is the name of the file and @var{other-user} is the
773 name of the user who has locked the file.
774 @end itemize
776 If you wish, you can replace the @code{ask-user-about-lock} function
777 with your own version that makes the decision in another way.
778 @end defun
780 @node Information about Files
781 @section Information about Files
782 @cindex file, information about
784   This section describes the functions for retrieving various types of
785 information about files (or directories or symbolic links), such as
786 whether a file is readable or writable, and its size.  These functions
787 all take arguments which are file names.  Except where noted, these
788 arguments need to specify existing files, or an error is signaled.
790 @cindex file names, trailing whitespace
791 @cindex trailing blanks in file names
792   Be careful with file names that end in spaces.  On some filesystems
793 (notably, MS-Windows), trailing whitespace characters in file names
794 are silently and automatically ignored.
796 @menu
797 * Testing Accessibility::   Is a given file readable?  Writable?
798 * Kinds of Files::          Is it a directory?  A symbolic link?
799 * Truenames::               Eliminating symbolic links from a file name.
800 * File Attributes::         File sizes, modification times, etc.
801 * Extended Attributes::     Extended file attributes for access control.
802 * Locating Files::          How to find a file in standard places.
803 @end menu
805 @node Testing Accessibility
806 @subsection Testing Accessibility
807 @cindex accessibility of a file
808 @cindex file accessibility
810   These functions test for permission to access a file for reading,
811 writing, or execution.  Unless explicitly stated otherwise, they
812 recursively follow symbolic links for their file name arguments, at
813 all levels (at the level of the file itself and at all levels of
814 parent directories).
816   On some operating systems, more complex sets of access permissions
817 can be specified, via mechanisms such as Access Control Lists (ACLs).
818 @xref{Extended Attributes}, for how to query and set those
819 permissions.
821 @defun file-exists-p filename
822 This function returns @code{t} if a file named @var{filename} appears
823 to exist.  This does not mean you can necessarily read the file, only
824 that you can find out its attributes.  (On Unix and GNU/Linux, this is
825 true if the file exists and you have execute permission on the
826 containing directories, regardless of the permissions of the file
827 itself.)
829 If the file does not exist, or if access control policies prevent you
830 from finding its attributes, this function returns @code{nil}.
832 Directories are files, so @code{file-exists-p} returns @code{t} when
833 given a directory name.  However, symbolic links are treated
834 specially; @code{file-exists-p} returns @code{t} for a symbolic link
835 name only if the target file exists.
836 @end defun
838 @defun file-readable-p filename
839 This function returns @code{t} if a file named @var{filename} exists
840 and you can read it.  It returns @code{nil} otherwise.
841 @end defun
843 @defun file-executable-p filename
844 This function returns @code{t} if a file named @var{filename} exists and
845 you can execute it.  It returns @code{nil} otherwise.  On Unix and
846 GNU/Linux, if the file is a directory, execute permission means you can
847 check the existence and attributes of files inside the directory, and
848 open those files if their modes permit.
849 @end defun
851 @defun file-writable-p filename
852 This function returns @code{t} if the file @var{filename} can be written
853 or created by you, and @code{nil} otherwise.  A file is writable if the
854 file exists and you can write it.  It is creatable if it does not exist,
855 but the specified directory does exist and you can write in that
856 directory.
858 In the example below, @file{foo} is not writable because the parent
859 directory does not exist, even though the user could create such a
860 directory.
862 @example
863 @group
864 (file-writable-p "~/no-such-dir/foo")
865      @result{} nil
866 @end group
867 @end example
868 @end defun
870 @defun file-accessible-directory-p dirname
871 This function returns @code{t} if you have permission to open existing
872 files in the directory whose name as a file is @var{dirname};
873 otherwise (or if there is no such directory), it returns @code{nil}.
874 The value of @var{dirname} may be either a directory name (such as
875 @file{/foo/}) or the file name of a file which is a directory
876 (such as @file{/foo}, without the final slash).
878 For example, from the following we deduce that any attempt to read a
879 file in @file{/foo/} will give an error:
881 @example
882 (file-accessible-directory-p "/foo")
883      @result{} nil
884 @end example
885 @end defun
887 @defun access-file filename string
888 This function opens file @var{filename} for reading, then closes it and
889 returns @code{nil}.  However, if the open fails, it signals an error
890 using @var{string} as the error message text.
891 @end defun
893 @defun file-ownership-preserved-p filename &optional group
894 This function returns @code{t} if deleting the file @var{filename} and
895 then creating it anew would keep the file's owner unchanged.  It also
896 returns @code{t} for nonexistent files.
898 If the optional argument @var{group} is non-@code{nil}, this function
899 also checks that the file's group would be unchanged.
901 If @var{filename} is a symbolic link, then, unlike the other functions
902 discussed here, @code{file-ownership-preserved-p} does @emph{not}
903 replace @var{filename} with its target.  However, it does recursively
904 follow symbolic links at all levels of parent directories.
905 @end defun
907 @defun file-modes filename
908 @cindex mode bits
909 @cindex file permissions
910 @cindex permissions, file
911 @cindex file modes
912 This function returns the @dfn{mode bits} of @var{filename}---an
913 integer summarizing its read, write, and execution permissions.
914 Symbolic links in @var{filename} are recursively followed at all
915 levels.  If the file does not exist, the return value is @code{nil}.
917 @xref{File permissions,,, coreutils, The @sc{gnu} @code{Coreutils}
918 Manual}, for a description of mode bits.  For example, if the
919 low-order bit is 1, the file is executable by all users; if the
920 second-lowest-order bit is 1, the file is writable by all users; etc.
921 The highest possible value is 4095 (7777 octal), meaning that everyone
922 has read, write, and execute permission, the @acronym{SUID} bit is set
923 for both others and group, and the sticky bit is set.
925 @xref{Changing Files}, for the @code{set-file-modes} function, which
926 can be used to set these permissions.
928 @example
929 @group
930 (file-modes "~/junk/diffs")
931      @result{} 492               ; @r{Decimal integer.}
932 @end group
933 @group
934 (format "%o" 492)
935      @result{} "754"             ; @r{Convert to octal.}
936 @end group
938 @group
939 (set-file-modes "~/junk/diffs" #o666)
940      @result{} nil
941 @end group
943 @group
944 $ ls -l diffs
945 -rw-rw-rw- 1 lewis lewis 3063 Oct 30 16:00 diffs
946 @end group
947 @end example
949 @cindex MS-DOS and file modes
950 @cindex file modes and MS-DOS
951 @strong{MS-DOS note:} On MS-DOS, there is no such thing as an
952 executable file mode bit.  So @code{file-modes} considers a file
953 executable if its name ends in one of the standard executable
954 extensions, such as @file{.com}, @file{.bat}, @file{.exe}, and some
955 others.  Files that begin with the Unix-standard @samp{#!} signature,
956 such as shell and Perl scripts, are also considered executable.
957 Directories are also reported as executable, for compatibility with
958 Unix.  These conventions are also followed by @code{file-attributes}
959 (@pxref{File Attributes}).
960 @end defun
962 @node Kinds of Files
963 @subsection Distinguishing Kinds of Files
964 @cindex file classification
965 @cindex classification of file types
967   This section describes how to distinguish various kinds of files, such
968 as directories, symbolic links, and ordinary files.
970 @defun file-symlink-p filename
971 @cindex file symbolic links
972 If the file @var{filename} is a symbolic link, the
973 @code{file-symlink-p} function returns its (non-recursive) link target
974 as a string.  (The link target string is not necessarily the full
975 absolute file name of the target; determining the full file name that
976 the link points to is nontrivial, see below.)  If the leading
977 directories of @var{filename} include symbolic links, this function
978 recursively follows them.
980 If the file @var{filename} is not a symbolic link, or does not exist,
981 @code{file-symlink-p} returns @code{nil}.
983 Here are a few examples of using this function:
985 @example
986 @group
987 (file-symlink-p "not-a-symlink")
988      @result{} nil
989 @end group
990 @group
991 (file-symlink-p "sym-link")
992      @result{} "not-a-symlink"
993 @end group
994 @group
995 (file-symlink-p "sym-link2")
996      @result{} "sym-link"
997 @end group
998 @group
999 (file-symlink-p "/bin")
1000      @result{} "/pub/bin"
1001 @end group
1002 @end example
1004 Note that in the third example, the function returned @file{sym-link},
1005 but did not proceed to resolve it, although that file is itself a
1006 symbolic link.  This is what we meant by ``non-recursive'' above---the
1007 process of following the symbolic links does not recurse if the link
1008 target is itself a link.
1010 The string that this function returns is what is recorded in the
1011 symbolic link; it may or may not include any leading directories.
1012 This function does @emph{not} expand the link target to produce a
1013 fully-qualified file name, and in particular does not use the leading
1014 directories, if any, of the @var{filename} argument if the link target
1015 is not an absolute file name.  Here's an example:
1017 @example
1018 @group
1019 (file-symlink-p "/foo/bar/baz")
1020      @result{} "some-file"
1021 @end group
1022 @end example
1024 @noindent
1025 Here, although @file{/foo/bar/baz} was given as a fully-qualified file
1026 name, the result is not, and in fact does not have any leading
1027 directories at all.  And since @file{some-file} might itself be a
1028 symbolic link, you cannot simply prepend leading directories to it,
1029 nor even naively use @code{expand-file-name} (@pxref{File Name
1030 Expansion}) to produce its absolute file name.
1032 For this reason, this function is seldom useful if you need to
1033 determine more than just the fact that a file is or isn't a symbolic
1034 link.  If you actually need the file name of the link target, use
1035 @code{file-chase-links} or @code{file-truename}, described in
1036 @ref{Truenames}.
1037 @end defun
1039 The next two functions recursively follow symbolic links at
1040 all levels for @var{filename}.
1042 @defun file-directory-p filename
1043 This function returns @code{t} if @var{filename} is the name of an
1044 existing directory, @code{nil} otherwise.
1046 @example
1047 @group
1048 (file-directory-p "~rms")
1049      @result{} t
1050 @end group
1051 @group
1052 (file-directory-p "~rms/lewis/files.texi")
1053      @result{} nil
1054 @end group
1055 @group
1056 (file-directory-p "~rms/lewis/no-such-file")
1057      @result{} nil
1058 @end group
1059 @group
1060 (file-directory-p "$HOME")
1061      @result{} nil
1062 @end group
1063 @group
1064 (file-directory-p
1065  (substitute-in-file-name "$HOME"))
1066      @result{} t
1067 @end group
1068 @end example
1069 @end defun
1071 @defun file-regular-p filename
1072 This function returns @code{t} if the file @var{filename} exists and is
1073 a regular file (not a directory, named pipe, terminal, or
1074 other I/O device).
1075 @end defun
1077 @node Truenames
1078 @subsection Truenames
1079 @cindex truename (of file)
1081   The @dfn{truename} of a file is the name that you get by following
1082 symbolic links at all levels until none remain, then simplifying away
1083 @samp{.}@: and @samp{..}@: appearing as name components.  This results
1084 in a sort of canonical name for the file.  A file does not always have a
1085 unique truename; the number of distinct truenames a file has is equal to
1086 the number of hard links to the file.  However, truenames are useful
1087 because they eliminate symbolic links as a cause of name variation.
1089 @defun file-truename filename
1090 This function returns the truename of the file @var{filename}.  If the
1091 argument is not an absolute file name, this function first expands it
1092 against @code{default-directory}.
1094 This function does not expand environment variables.  Only
1095 @code{substitute-in-file-name} does that.  @xref{Definition of
1096 substitute-in-file-name}.
1098 If you may need to follow symbolic links preceding @samp{..}@:
1099 appearing as a name component, call @code{file-truename} without prior
1100 direct or indirect calls to @code{expand-file-name}.  Otherwise, the
1101 file name component immediately preceding @samp{..} will be
1102 simplified away before @code{file-truename} is called.  To
1103 eliminate the need for a call to @code{expand-file-name},
1104 @code{file-truename} handles @samp{~} in the same way that
1105 @code{expand-file-name} does.  @xref{File Name Expansion,, Functions
1106 that Expand Filenames}.
1107 @end defun
1109 @defun file-chase-links filename &optional limit
1110 This function follows symbolic links, starting with @var{filename},
1111 until it finds a file name which is not the name of a symbolic link.
1112 Then it returns that file name.  This function does @emph{not} follow
1113 symbolic links at the level of parent directories.
1115 If you specify a number for @var{limit}, then after chasing through
1116 that many links, the function just returns what it has even if that is
1117 still a symbolic link.
1118 @end defun
1120   To illustrate the difference between @code{file-chase-links} and
1121 @code{file-truename}, suppose that @file{/usr/foo} is a symbolic link to
1122 the directory @file{/home/foo}, and @file{/home/foo/hello} is an
1123 ordinary file (or at least, not a symbolic link) or nonexistent.  Then
1124 we would have:
1126 @example
1127 (file-chase-links "/usr/foo/hello")
1128      ;; @r{This does not follow the links in the parent directories.}
1129      @result{} "/usr/foo/hello"
1130 (file-truename "/usr/foo/hello")
1131      ;; @r{Assuming that @file{/home} is not a symbolic link.}
1132      @result{} "/home/foo/hello"
1133 @end example
1135 @defun file-equal-p file1 file2
1136 This function returns @code{t} if the files @var{file1} and
1137 @var{file2} name the same file.  This is similar to comparing their
1138 truenames, except that remote file names are also handled in an
1139 appropriate manner.  If @var{file1} or @var{file2} does not exist, the
1140 return value is unspecified.
1141 @end defun
1143 @defun file-in-directory-p file dir
1144 This function returns @code{t} if @var{file} is a file in directory
1145 @var{dir}, or in a subdirectory of @var{dir}.  It also returns
1146 @code{t} if @var{file} and @var{dir} are the same directory.  It
1147 compares the truenames of the two directories.  If @var{dir} does not
1148 name an existing directory, the return value is @code{nil}.
1149 @end defun
1151 @node File Attributes
1152 @subsection File Attributes
1153 @cindex file attributes
1155   This section describes the functions for getting detailed
1156 information about a file, including the owner and group numbers, the
1157 number of names, the inode number, the size, and the times of access
1158 and modification.
1160 @defun file-newer-than-file-p filename1 filename2
1161 @cindex file age
1162 @cindex file modification time
1163 This function returns @code{t} if the file @var{filename1} is
1164 newer than file @var{filename2}.  If @var{filename1} does not
1165 exist, it returns @code{nil}.  If @var{filename1} does exist, but
1166 @var{filename2} does not, it returns @code{t}.
1168 In the following example, assume that the file @file{aug-19} was written
1169 on the 19th, @file{aug-20} was written on the 20th, and the file
1170 @file{no-file} doesn't exist at all.
1172 @example
1173 @group
1174 (file-newer-than-file-p "aug-19" "aug-20")
1175      @result{} nil
1176 @end group
1177 @group
1178 (file-newer-than-file-p "aug-20" "aug-19")
1179      @result{} t
1180 @end group
1181 @group
1182 (file-newer-than-file-p "aug-19" "no-file")
1183      @result{} t
1184 @end group
1185 @group
1186 (file-newer-than-file-p "no-file" "aug-19")
1187      @result{} nil
1188 @end group
1189 @end example
1190 @end defun
1192   If the @var{filename} argument to the next two functions is a
1193 symbolic link, then these function do @emph{not} replace it with its
1194 target.  However, they both recursively follow symbolic links at all
1195 levels of parent directories.
1197 @defun file-attributes filename &optional id-format
1198 @anchor{Definition of file-attributes}
1199 This function returns a list of attributes of file @var{filename}.  If
1200 the specified file cannot be opened, it returns @code{nil}.
1201 The optional parameter @var{id-format} specifies the preferred format
1202 of attributes @acronym{UID} and @acronym{GID} (see below)---the
1203 valid values are @code{'string} and @code{'integer}.  The latter is
1204 the default, but we plan to change that, so you should specify a
1205 non-@code{nil} value for @var{id-format} if you use the returned
1206 @acronym{UID} or @acronym{GID}.
1208 Accessor functions are provided to access the elements in this list.
1209 The accessors are mentioned along with the descriptions of the
1210 elements below.
1212 The elements of the list, in order, are:
1214 @enumerate 0
1215 @item
1216 @code{t} for a directory, a string for a symbolic link (the name
1217 linked to), or @code{nil} for a text file
1218 (@code{file-attribute-type}).
1220 @c Wordy so as to prevent an overfull hbox.  --rjc 15mar92
1221 @item
1222 The number of names the file has (@code{file-attribute-link-number}).
1223 Alternate names, also known as hard links, can be created by using the
1224 @code{add-name-to-file} function (@pxref{Changing Files}).
1226 @item
1227 The file's @acronym{UID}, normally as a string
1228 (@code{file-attribute-user-id}).  However, if it does not correspond
1229 to a named user, the value is a number.
1231 @item
1232 The file's @acronym{GID}, likewise (@code{file-attribute-group-id}).
1234 @item
1235 The time of last access, as a list of four integers
1236 @code{(@var{sec-high} @var{sec-low} @var{microsec} @var{picosec})}
1237 (@code{file-attribute-access-time}).  (This is similar to the value of
1238 @code{current-time}; see @ref{Time of Day}.)  Note that on some
1239 FAT-based filesystems, only the date of last access is recorded, so
1240 this time will always hold the midnight of the day of last access.
1242 @cindex modification time of file
1243 @item
1244 The time of last modification as a list of four integers (as above)
1245 (@code{file-attribute-modification-time}).  This is the last time when
1246 the file's contents were modified.
1248 @item
1249 The time of last status change as a list of four integers (as above)
1250 (@code{file-attribute-status-change-time}).  This is the time of the
1251 last change to the file's access mode bits, its owner and group, and
1252 other information recorded in the filesystem for the file, beyond the
1253 file's contents.
1255 @item
1256 The size of the file in bytes (@code{file-attribute-size}).  This is
1257 floating point if the size is too large to fit in a Lisp integer.
1259 @item
1260 The file's modes, as a string of ten letters or dashes, as in
1261 @samp{ls -l} (@code{file-attribute-modes}).
1263 @item
1264 An unspecified value, present for backward compatibility.
1266 @item
1267 The file's inode number (@code{file-attribute-inode-number}).  If
1268 possible, this is an integer.  If the inode number is too large to be
1269 represented as an integer in Emacs Lisp but dividing it by
1270 @math{2^{16}} yields a representable integer, then the value has the
1271 form @code{(@var{high} . @var{low})}, where @var{low} holds the low 16
1272 bits.  If the inode number is too wide for even that, the value is of
1273 the form @code{(@var{high} @var{middle} . @var{low})}, where
1274 @code{high} holds the high bits, @var{middle} the middle 24 bits, and
1275 @var{low} the low 16 bits.
1277 @item
1278 The filesystem number of the device that the file is on
1279 @code{file-attribute-device-number}).  Depending on the magnitude of
1280 the value, this can be either an integer or a cons cell, in the same
1281 manner as the inode number.  This element and the file's inode number
1282 together give enough information to distinguish any two files on the
1283 system---no two files can have the same values for both of these
1284 numbers.
1285 @end enumerate
1287 For example, here are the file attributes for @file{files.texi}:
1289 @example
1290 @group
1291 (file-attributes "files.texi" 'string)
1292      @result{}  (nil 1 "lh" "users"
1293           (20614 64019 50040 152000)
1294           (20000 23 0 0)
1295           (20614 64555 902289 872000)
1296           122295 "-rw-rw-rw-"
1297           t (5888 2 . 43978)
1298           (15479 . 46724))
1299 @end group
1300 @end example
1302 @noindent
1303 and here is how the result is interpreted:
1305 @table @code
1306 @item nil
1307 is neither a directory nor a symbolic link.
1309 @item 1
1310 has only one name (the name @file{files.texi} in the current default
1311 directory).
1313 @item "lh"
1314 is owned by the user with name @samp{lh}.
1316 @item "users"
1317 is in the group with name @samp{users}.
1319 @item (20614 64019 50040 152000)
1320 was last accessed on October 23, 2012, at 20:12:03.050040152 UTC.
1322 @item (20000 23 0 0)
1323 was last modified on July 15, 2001, at 08:53:43 UTC.
1325 @item (20614 64555 902289 872000)
1326 last had its status changed on October 23, 2012, at 20:20:59.902289872 UTC.
1328 @item 122295
1329 is 122295 bytes long.  (It may not contain 122295 characters, though,
1330 if some of the bytes belong to multibyte sequences, and also if the
1331 end-of-line format is CR-LF.)
1333 @item "-rw-rw-rw-"
1334 has a mode of read and write access for the owner, group, and world.
1336 @item t
1337 is merely a placeholder; it carries no information.
1339 @item (5888 2 . 43978)
1340 has an inode number of 6473924464520138.
1342 @item (15479 . 46724)
1343 is on the file-system device whose number is 1014478468.
1344 @end table
1345 @end defun
1347 @defun file-nlinks filename
1348 This function returns the number of names (i.e., hard links) that
1349 file @var{filename} has.  If the file does not exist, this function
1350 returns @code{nil}.  Note that symbolic links have no effect on this
1351 function, because they are not considered to be names of the files
1352 they link to.
1354 @example
1355 @group
1356 $ ls -l foo*
1357 -rw-rw-rw- 2 rms rms 4 Aug 19 01:27 foo
1358 -rw-rw-rw- 2 rms rms 4 Aug 19 01:27 foo1
1359 @end group
1361 @group
1362 (file-nlinks "foo")
1363      @result{} 2
1364 @end group
1365 @group
1366 (file-nlinks "doesnt-exist")
1367      @result{} nil
1368 @end group
1369 @end example
1370 @end defun
1372 @node Extended Attributes
1373 @subsection Extended File Attributes
1374 @cindex extended file attributes
1376 On some operating systems, each file can be associated with arbitrary
1377 @dfn{extended file attributes}.  At present, Emacs supports querying
1378 and setting two specific sets of extended file attributes: Access
1379 Control Lists (ACLs) and SELinux contexts.  These extended file
1380 attributes are used, on some systems, to impose more sophisticated
1381 file access controls than the basic Unix-style permissions
1382 discussed in the previous sections.
1384 @cindex access control list
1385 @cindex ACL entries
1386 @cindex SELinux context
1387   A detailed explanation of ACLs and SELinux is beyond the scope of
1388 this manual.  For our purposes, each file can be associated with an
1389 @dfn{ACL}, which specifies its properties under an ACL-based file
1390 control system, and/or an @dfn{SELinux context}, which specifies its
1391 properties under the SELinux system.
1393 @defun file-acl filename
1394 This function returns the ACL for the file @var{filename}.  The exact
1395 Lisp representation of the ACL is unspecified (and may change in
1396 future Emacs versions), but it is the same as what @code{set-file-acl}
1397 takes for its @var{acl} argument (@pxref{Changing Files}).
1399 The underlying ACL implementation is platform-specific; on GNU/Linux
1400 and BSD, Emacs uses the POSIX ACL interface, while on MS-Windows Emacs
1401 emulates the POSIX ACL interface with native file security APIs.
1403 If Emacs was not compiled with ACL support, or the file does not exist
1404 or is inaccessible, or Emacs was unable to determine the ACL entries
1405 for any other reason, then the return value is @code{nil}.
1406 @end defun
1408 @defun file-selinux-context filename
1409 This function returns the SELinux context of the file @var{filename},
1410 as a list of the form @code{(@var{user} @var{role} @var{type}
1411 @var{range})}.  The list elements are the context's user, role, type,
1412 and range respectively, as Lisp strings; see the SELinux documentation
1413 for details about what these actually mean.  The return value has the
1414 same form as what @code{set-file-selinux-context} takes for its
1415 @var{context} argument (@pxref{Changing Files}).
1417 If Emacs was not compiled with SELinux support, or the file does not
1418 exist or is inaccessible, or if the system does not support SELinux,
1419 then the return value is @code{(nil nil nil nil)}.
1420 @end defun
1422 @defun file-extended-attributes filename
1423 This function returns an alist of the Emacs-recognized extended
1424 attributes of file @var{filename}.  Currently, it serves as a
1425 convenient way to retrieve both the ACL and SELinux context; you can
1426 then call the function @code{set-file-extended-attributes}, with the
1427 returned alist as its second argument, to apply the same file access
1428 attributes to another file (@pxref{Changing Files}).
1430 One of the elements is @code{(acl . @var{acl})}, where @var{acl} has
1431 the same form returned by @code{file-acl}.
1433 Another element is @code{(selinux-context . @var{context})}, where
1434 @var{context} is the SELinux context, in the same form returned by
1435 @code{file-selinux-context}.
1436 @end defun
1438 @node Locating Files
1439 @subsection Locating Files in Standard Places
1440 @cindex locate file in path
1441 @cindex find file in path
1443   This section explains how to search for a file in a list of
1444 directories (a @dfn{path}), or for an executable file in the standard
1445 list of executable file directories.
1447   To search for a user-specific configuration file, @xref{Standard
1448 File Names}, for the @code{locate-user-emacs-file} function.
1450 @defun locate-file filename path &optional suffixes predicate
1451 This function searches for a file whose name is @var{filename} in a
1452 list of directories given by @var{path}, trying the suffixes in
1453 @var{suffixes}.  If it finds such a file, it returns the file's
1454 absolute file name (@pxref{Relative File Names}); otherwise it returns
1455 @code{nil}.
1457 The optional argument @var{suffixes} gives the list of file-name
1458 suffixes to append to @var{filename} when searching.
1459 @code{locate-file} tries each possible directory with each of these
1460 suffixes.  If @var{suffixes} is @code{nil}, or @code{("")}, then there
1461 are no suffixes, and @var{filename} is used only as-is.  Typical
1462 values of @var{suffixes} are @code{exec-suffixes} (@pxref{Subprocess
1463 Creation}), @code{load-suffixes}, @code{load-file-rep-suffixes} and
1464 the return value of the function @code{get-load-suffixes} (@pxref{Load
1465 Suffixes}).
1467 Typical values for @var{path} are @code{exec-path} (@pxref{Subprocess
1468 Creation}) when looking for executable programs, or @code{load-path}
1469 (@pxref{Library Search}) when looking for Lisp files.  If
1470 @var{filename} is absolute, @var{path} has no effect, but the suffixes
1471 in @var{suffixes} are still tried.
1473 The optional argument @var{predicate}, if non-@code{nil}, specifies a
1474 predicate function for testing whether a candidate file is suitable.
1475 The predicate is passed the candidate file name as its single
1476 argument.  If @var{predicate} is @code{nil} or omitted,
1477 @code{locate-file} uses @code{file-readable-p} as the predicate.
1478 @xref{Kinds of Files}, for other useful predicates, e.g.,
1479 @code{file-executable-p} and @code{file-directory-p}.
1481 For compatibility, @var{predicate} can also be one of the symbols
1482 @code{executable}, @code{readable}, @code{writable}, @code{exists}, or
1483 a list of one or more of these symbols.
1484 @end defun
1486 @defun executable-find program
1487 This function searches for the executable file of the named
1488 @var{program} and returns the absolute file name of the executable,
1489 including its file-name extensions, if any.  It returns @code{nil} if
1490 the file is not found.  The functions searches in all the directories
1491 in @code{exec-path}, and tries all the file-name extensions in
1492 @code{exec-suffixes} (@pxref{Subprocess Creation}).
1493 @end defun
1495 @node Changing Files
1496 @section Changing File Names and Attributes
1497 @c @cindex renaming files  Duplicates rename-file
1498 @cindex copying files
1499 @cindex deleting files
1500 @cindex linking files
1501 @cindex setting modes of files
1503   The functions in this section rename, copy, delete, link, and set
1504 the modes (permissions) of files.  They all signal a @code{file-error}
1505 error if they fail to perform their function, reporting the
1506 system-dependent error message that describes the reason for the
1507 failure.
1509   For performance, the operating system may cache or alias changes
1510 made by these functions instead of writing them immediately to
1511 secondary storage.  @xref{Files and Storage}.
1513   In the functions that have an argument @var{newname}, if a file by the
1514 name of @var{newname} already exists, the actions taken depend on the
1515 value of the argument @var{ok-if-already-exists}:
1517 @itemize @bullet
1518 @item
1519 Signal a @code{file-already-exists} error if
1520 @var{ok-if-already-exists} is @code{nil}.
1522 @item
1523 Request confirmation if @var{ok-if-already-exists} is a number.
1525 @item
1526 Replace the old file without confirmation if @var{ok-if-already-exists}
1527 is any other value.
1528 @end itemize
1530 The next four commands all recursively follow symbolic links at all
1531 levels of parent directories for their first argument, but, if that
1532 argument is itself a symbolic link, then only @code{copy-file}
1533 replaces it with its (recursive) target.
1535 @deffn Command add-name-to-file oldname newname &optional ok-if-already-exists
1536 @cindex file with multiple names
1537 @cindex file hard link
1538 This function gives the file named @var{oldname} the additional name
1539 @var{newname}.  This means that @var{newname} becomes a new hard
1540 link to @var{oldname}.
1542 In the first part of the following example, we list two files,
1543 @file{foo} and @file{foo3}.
1545 @example
1546 @group
1547 $ ls -li fo*
1548 81908 -rw-rw-rw- 1 rms rms 29 Aug 18 20:32 foo
1549 84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
1550 @end group
1551 @end example
1553 Now we create a hard link, by calling @code{add-name-to-file}, then list
1554 the files again.  This shows two names for one file, @file{foo} and
1555 @file{foo2}.
1557 @example
1558 @group
1559 (add-name-to-file "foo" "foo2")
1560      @result{} nil
1561 @end group
1563 @group
1564 $ ls -li fo*
1565 81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo
1566 81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo2
1567 84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
1568 @end group
1569 @end example
1571 Finally, we evaluate the following:
1573 @example
1574 (add-name-to-file "foo" "foo3" t)
1575 @end example
1577 @noindent
1578 and list the files again.  Now there are three names
1579 for one file: @file{foo}, @file{foo2}, and @file{foo3}.  The old
1580 contents of @file{foo3} are lost.
1582 @example
1583 @group
1584 (add-name-to-file "foo1" "foo3")
1585      @result{} nil
1586 @end group
1588 @group
1589 $ ls -li fo*
1590 81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo
1591 81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo2
1592 81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo3
1593 @end group
1594 @end example
1596 This function is meaningless on operating systems where multiple names
1597 for one file are not allowed.  Some systems implement multiple names
1598 by copying the file instead.
1600 See also @code{file-nlinks} in @ref{File Attributes}.
1601 @end deffn
1603 @deffn Command rename-file filename newname &optional ok-if-already-exists
1604 This command renames the file @var{filename} as @var{newname}.
1606 If @var{filename} has additional names aside from @var{filename}, it
1607 continues to have those names.  In fact, adding the name @var{newname}
1608 with @code{add-name-to-file} and then deleting @var{filename} has the
1609 same effect as renaming, aside from momentary intermediate states.
1610 @end deffn
1612 @deffn Command copy-file oldname newname &optional ok-if-exists time preserve-uid-gid preserve-extended-attributes
1613 This command copies the file @var{oldname} to @var{newname}.  An
1614 error is signaled if @var{oldname} does not exist.  If @var{newname}
1615 names a directory, it copies @var{oldname} into that directory,
1616 preserving its final name component.
1618 If @var{time} is non-@code{nil}, then this function gives the new file
1619 the same last-modified time that the old one has.  (This works on only
1620 some operating systems.)  If setting the time gets an error,
1621 @code{copy-file} signals a @code{file-date-error} error.  In an
1622 interactive call, a prefix argument specifies a non-@code{nil} value
1623 for @var{time}.
1625 If argument @var{preserve-uid-gid} is @code{nil}, we let the operating
1626 system decide the user and group ownership of the new file (this is
1627 usually set to the user running Emacs).  If @var{preserve-uid-gid} is
1628 non-@code{nil}, we attempt to copy the user and group ownership of the
1629 file.  This works only on some operating systems, and only if you have
1630 the correct permissions to do so.
1632 If the optional argument @var{preserve-permissions} is non-@code{nil},
1633 this function copies the file modes (or ``permissions'') of
1634 @var{oldname} to @var{newname}, as well as the Access Control List and
1635 SELinux context (if any).  @xref{Information about Files}.
1637 Otherwise, the file modes of @var{newname} are left unchanged if it is
1638 an existing file, and set to those of @var{oldname}, masked by the
1639 default file permissions (see @code{set-default-file-modes} below), if
1640 @var{newname} is to be newly created.  The Access Control List or
1641 SELinux context are not copied over in either case.
1642 @end deffn
1644 @deffn Command make-symbolic-link filename newname  &optional ok-if-exists
1645 @pindex ln
1646 @kindex file-already-exists
1647 This command makes a symbolic link to @var{filename}, named
1648 @var{newname}.  This is like the shell command @samp{ln -s
1649 @var{filename} @var{newname}}.
1651 This function is not available on systems that don't support symbolic
1652 links.
1653 @end deffn
1655 @cindex trash
1656 @vindex delete-by-moving-to-trash
1657 @deffn Command delete-file filename &optional trash
1658 @pindex rm
1659 This command deletes the file @var{filename}.  If the file has
1660 multiple names, it continues to exist under the other names.  If
1661 @var{filename} is a symbolic link, @code{delete-file} deletes only the
1662 symbolic link and not its target (though it does follow symbolic links
1663 at all levels of parent directories).
1665 A suitable kind of @code{file-error} error is signaled if the file
1666 does not exist, or is not deletable.  (On Unix and GNU/Linux, a file
1667 is deletable if its directory is writable.)
1669 If the optional argument @var{trash} is non-@code{nil} and the
1670 variable @code{delete-by-moving-to-trash} is non-@code{nil}, this
1671 command moves the file into the system Trash instead of deleting it.
1672 @xref{Misc File Ops,,Miscellaneous File Operations, emacs, The GNU
1673 Emacs Manual}.  When called interactively, @var{trash} is @code{t} if
1674 no prefix argument is given, and @code{nil} otherwise.
1676 See also @code{delete-directory} in @ref{Create/Delete Dirs}.
1677 @end deffn
1679 @cindex file permissions, setting
1680 @cindex permissions, file
1681 @cindex file modes, setting
1682 @deffn Command set-file-modes filename mode
1683 This function sets the @dfn{file mode} (or @dfn{permissions}) of
1684 @var{filename} to @var{mode}.  It recursively follows symbolic links
1685 at all levels for @var{filename}.
1687 If called non-interactively, @var{mode} must be an integer.  Only the
1688 lowest 12 bits of the integer are used; on most systems, only the
1689 lowest 9 bits are meaningful.  You can use the Lisp construct for
1690 octal numbers to enter @var{mode}.  For example,
1692 @example
1693 (set-file-modes #o644)
1694 @end example
1696 @noindent
1697 specifies that the file should be readable and writable for its owner,
1698 readable for group members, and readable for all other users.
1699 @xref{File permissions,,, coreutils, The @sc{gnu} @code{Coreutils}
1700 Manual}, for a description of mode bit specifications.
1702 Interactively, @var{mode} is read from the minibuffer using
1703 @code{read-file-modes} (see below), which lets the user type in either
1704 an integer or a string representing the permissions symbolically.
1706 @xref{File Attributes}, for the function @code{file-modes}, which
1707 returns the permissions of a file.
1708 @end deffn
1710 @defun set-default-file-modes mode
1711 @cindex umask
1712 This function sets the default permissions for new files created by
1713 Emacs and its subprocesses.  Every file created with Emacs initially
1714 has these permissions, or a subset of them (@code{write-region} will
1715 not grant execute permissions even if the default file permissions
1716 allow execution).  On Unix and GNU/Linux, the default permissions are
1717 given by the bitwise complement of the @samp{umask} value.
1719 The argument @var{mode} should be an integer which specifies the
1720 permissions, similar to @code{set-file-modes} above.  Only the lowest
1721 9 bits are meaningful.
1723 The default file permissions have no effect when you save a modified
1724 version of an existing file; saving a file preserves its existing
1725 permissions.
1726 @end defun
1728 @defmac with-file-modes mode body@dots{}
1729 This macro evaluates the @var{body} forms with the default
1730 permissions for new files temporarily set to @var{modes} (whose value
1731 is as for @code{set-file-modes} above).  When finished, it restores
1732 the original default file permissions, and returns the value of the
1733 last form in @var{body}.
1735 This is useful for creating private files, for example.
1736 @end defmac
1738 @defun default-file-modes
1739 This function returns the default file permissions, as an integer.
1740 @end defun
1742 @defun read-file-modes &optional prompt base-file
1743 This function reads a set of file mode bits from the minibuffer.  The
1744 first optional argument @var{prompt} specifies a non-default prompt.
1745 Second second optional argument @var{base-file} is the name of a file
1746 on whose permissions to base the mode bits that this function returns,
1747 if what the user types specifies mode bits relative to permissions of
1748 an existing file.
1750 If user input represents an octal number, this function returns that
1751 number.  If it is a complete symbolic specification of mode bits, as
1752 in @code{"u=rwx"}, the function converts it to the equivalent numeric
1753 value using @code{file-modes-symbolic-to-number} and returns the
1754 result.  If the specification is relative, as in @code{"o+g"}, then
1755 the permissions on which the specification is based are taken from the
1756 mode bits of @var{base-file}.  If @var{base-file} is omitted or
1757 @code{nil}, the function uses @code{0} as the base mode bits.  The
1758 complete and relative specifications can be combined, as in
1759 @code{"u+r,g+rx,o+r,g-w"}.  @xref{File permissions,,, coreutils, The
1760 @sc{gnu} @code{Coreutils} Manual}, for a description of file mode
1761 specifications.
1762 @end defun
1764 @defun file-modes-symbolic-to-number modes &optional base-modes
1765 This function converts a symbolic file mode specification in
1766 @var{modes} into the equivalent integer.  If the symbolic
1767 specification is based on an existing file, that file's mode bits are
1768 taken from the optional argument @var{base-modes}; if that argument is
1769 omitted or @code{nil}, it defaults to 0, i.e., no access rights at
1770 all.
1771 @end defun
1773 @defun set-file-times filename &optional time
1774 This function sets the access and modification times of @var{filename}
1775 to @var{time}.  The return value is @code{t} if the times are successfully
1776 set, otherwise it is @code{nil}.  @var{time} defaults to the current
1777 time and must be in the format returned by @code{current-time}
1778 (@pxref{Time of Day}).
1779 @end defun
1781 @defun set-file-extended-attributes filename attribute-alist
1782 This function sets the Emacs-recognized extended file attributes for
1783 @code{filename}.  The second argument @var{attribute-alist} should be
1784 an alist of the same form returned by @code{file-extended-attributes}.
1785 The return value is @code{t} if the attributes are successfully set,
1786 otherwise it is @code{nil}.
1787 @xref{Extended Attributes}.
1788 @end defun
1790 @defun set-file-selinux-context filename context
1791 This function sets the SELinux security context for @var{filename} to
1792 @var{context}.  The @var{context} argument should be a list
1793 @code{(@var{user} @var{role} @var{type} @var{range})}, where each
1794 element is a string.  @xref{Extended Attributes}.
1796 The function returns @code{t} if it succeeds in setting the SELinux
1797 context of @var{filename}.  It returns @code{nil} if the context was
1798 not set (e.g., if SELinux is disabled, or if Emacs was compiled
1799 without SELinux support).
1800 @end defun
1802 @defun set-file-acl filename acl
1803 This function sets the Access Control List for @var{filename} to
1804 @var{acl}.  The @var{acl} argument should have the same form returned
1805 by the function @code{file-acl}.  @xref{Extended Attributes}.
1807 The function returns @code{t} if it successfully sets the ACL of
1808 @var{filename}, @code{nil} otherwise.
1809 @end defun
1811 @node Files and Storage
1812 @section Files and Secondary Storage
1813 @cindex secondary storage
1815 After Emacs changes a file, there are two reasons the changes might
1816 not survive later failures of power or media, both having to do with
1817 efficiency.  First, the operating system might alias written data with
1818 data already stored elsewhere on secondary storage until one file or
1819 the other is later modified; this will lose both files if the only
1820 copy on secondary storage is lost due to media failure.  Second, the
1821 operating system might not write data to secondary storage
1822 immediately, which will lose the data if power is lost.
1824 @findex write-region
1825 Although both sorts of failures can largely be avoided by a suitably
1826 configured file system, such systems are typically more expensive or
1827 less efficient.  In more-typical systems, to survive media failure you
1828 can copy the file to a different device, and to survive a power
1829 failure you can use the @code{write-region} function with the
1830 @code{write-region-inhibit-fsync} variable set to @code{nil}.
1831 @xref{Writing to Files}.
1833 @node File Names
1834 @section File Names
1835 @cindex file names
1837   Files are generally referred to by their names, in Emacs as elsewhere.
1838 File names in Emacs are represented as strings.  The functions that
1839 operate on a file all expect a file name argument.
1841   In addition to operating on files themselves, Emacs Lisp programs
1842 often need to operate on file names; i.e., to take them apart and to use
1843 part of a name to construct related file names.  This section describes
1844 how to manipulate file names.
1846   The functions in this section do not actually access files, so they
1847 can operate on file names that do not refer to an existing file or
1848 directory.
1850 @findex cygwin-convert-file-name-from-windows
1851 @findex cygwin-convert-file-name-to-windows
1852 @cindex MS-Windows file-name syntax
1853 @cindex converting file names from/to MS-Windows syntax
1854   On MS-DOS and MS-Windows, these functions (like the function that
1855 actually operate on files) accept MS-DOS or MS-Windows file-name syntax,
1856 where backslashes separate the components, as well as Unix syntax; but
1857 they always return Unix syntax.  This enables Lisp programs to specify
1858 file names in Unix syntax and work properly on all systems without
1859 change.@footnote{In MS-Windows versions of Emacs compiled for the Cygwin
1860 environment, you can use the functions
1861 @code{cygwin-convert-file-name-to-windows} and
1862 @code{cygwin-convert-file-name-from-windows} to convert between the
1863 two file-name syntaxes.}
1865 @menu
1866 * File Name Components::  The directory part of a file name, and the rest.
1867 * Relative File Names::   Some file names are relative to a current directory.
1868 * Directory Names::       A directory's name as a directory
1869                             is different from its name as a file.
1870 * File Name Expansion::   Converting relative file names to absolute ones.
1871 * Unique File Names::     Generating names for temporary files.
1872 * File Name Completion::  Finding the completions for a given file name.
1873 * Standard File Names::   If your package uses a fixed file name,
1874                             how to handle various operating systems simply.
1875 @end menu
1877 @node File Name Components
1878 @subsection File Name Components
1879 @cindex directory part (of file name)
1880 @cindex nondirectory part (of file name)
1881 @cindex version number (in file name)
1883   The operating system groups files into directories.  To specify a
1884 file, you must specify the directory and the file's name within that
1885 directory.  Therefore, Emacs considers a file name as having two main
1886 parts: the @dfn{directory name} part, and the @dfn{nondirectory} part
1887 (or @dfn{file name within the directory}).  Either part may be empty.
1888 Concatenating these two parts reproduces the original file name.
1890   On most systems, the directory part is everything up to and including
1891 the last slash (backslash is also allowed in input on MS-DOS or
1892 MS-Windows); the nondirectory part is the rest.
1894   For some purposes, the nondirectory part is further subdivided into
1895 the name proper and the @dfn{version number}.  On most systems, only
1896 backup files have version numbers in their names.
1898 @defun file-name-directory filename
1899 This function returns the directory part of @var{filename}, as a
1900 directory name (@pxref{Directory Names}), or @code{nil} if
1901 @var{filename} does not include a directory part.
1903 On GNU and Unix systems, a string returned by this function always
1904 ends in a slash.  On MS-DOS it can also end in a colon.
1906 @example
1907 @group
1908 (file-name-directory "lewis/foo")  ; @r{Unix example}
1909      @result{} "lewis/"
1910 @end group
1911 @group
1912 (file-name-directory "foo")        ; @r{Unix example}
1913      @result{} nil
1914 @end group
1915 @end example
1916 @end defun
1918 @defun file-name-nondirectory filename
1919 This function returns the nondirectory part of @var{filename}.
1921 @example
1922 @group
1923 (file-name-nondirectory "lewis/foo")
1924      @result{} "foo"
1925 @end group
1926 @group
1927 (file-name-nondirectory "foo")
1928      @result{} "foo"
1929 @end group
1930 @group
1931 (file-name-nondirectory "lewis/")
1932      @result{} ""
1933 @end group
1934 @end example
1935 @end defun
1937 @defun file-name-sans-versions filename &optional keep-backup-version
1938 This function returns @var{filename} with any file version numbers,
1939 backup version numbers, or trailing tildes discarded.
1941 If @var{keep-backup-version} is non-@code{nil}, then true file version
1942 numbers understood as such by the file system are discarded from the
1943 return value, but backup version numbers are kept.
1945 @example
1946 @group
1947 (file-name-sans-versions "~rms/foo.~1~")
1948      @result{} "~rms/foo"
1949 @end group
1950 @group
1951 (file-name-sans-versions "~rms/foo~")
1952      @result{} "~rms/foo"
1953 @end group
1954 @group
1955 (file-name-sans-versions "~rms/foo")
1956      @result{} "~rms/foo"
1957 @end group
1958 @end example
1959 @end defun
1961 @defun file-name-extension filename &optional period
1962 This function returns @var{filename}'s final extension, if any,
1963 after applying @code{file-name-sans-versions} to remove any
1964 version/backup part.  The extension, in a file name, is the part that
1965 follows the last @samp{.} in the last name component (minus any
1966 version/backup part).
1968 This function returns @code{nil} for extensionless file names such as
1969 @file{foo}.  It returns @code{""} for null extensions, as in
1970 @file{foo.}.  If the last component of a file name begins with a
1971 @samp{.}, that @samp{.}  doesn't count as the beginning of an
1972 extension.  Thus, @file{.emacs}'s extension is @code{nil}, not
1973 @samp{.emacs}.
1975 If @var{period} is non-@code{nil}, then the returned value includes
1976 the period that delimits the extension, and if @var{filename} has no
1977 extension, the value is @code{""}.
1978 @end defun
1980 @defun file-name-sans-extension filename
1981 This function returns @var{filename} minus its extension, if any.  The
1982 version/backup part, if present, is only removed if the file has an
1983 extension.  For example,
1985 @example
1986 (file-name-sans-extension "foo.lose.c")
1987      @result{} "foo.lose"
1988 (file-name-sans-extension "big.hack/foo")
1989      @result{} "big.hack/foo"
1990 (file-name-sans-extension "/my/home/.emacs")
1991      @result{} "/my/home/.emacs"
1992 (file-name-sans-extension "/my/home/.emacs.el")
1993      @result{} "/my/home/.emacs"
1994 (file-name-sans-extension "~/foo.el.~3~")
1995      @result{} "~/foo"
1996 (file-name-sans-extension "~/foo.~3~")
1997      @result{} "~/foo.~3~"
1998 @end example
2000 Note that the @samp{.~3~} in the two last examples is the backup part,
2001 not an extension.
2002 @end defun
2004 @defun file-name-base &optional filename
2005 This function is the composition of @code{file-name-sans-extension}
2006 and @code{file-name-nondirectory}.  For example,
2008 @example
2009 (file-name-base "/my/home/foo.c")
2010     @result{} "foo"
2011 @end example
2013 The @var{filename} argument defaults to @code{buffer-file-name}.
2014 @end defun
2016 @node Relative File Names
2017 @subsection Absolute and Relative File Names
2018 @cindex absolute file name
2019 @cindex relative file name
2021   All the directories in the file system form a tree starting at the
2022 root directory.  A file name can specify all the directory names
2023 starting from the root of the tree; then it is called an
2024 @dfn{absolute} file name.  Or it can specify the position of the file
2025 in the tree relative to a default directory; then it is called a
2026 @dfn{relative} file name.  On Unix and GNU/Linux, an absolute file
2027 name starts with a @samp{/} or a @samp{~}
2028 (@pxref{abbreviate-file-name}), and a relative one does not.  On
2029 MS-DOS and MS-Windows, an absolute file name starts with a slash or a
2030 backslash, or with a drive specification @samp{@var{x}:/}, where
2031 @var{x} is the @dfn{drive letter}.
2033 @defun file-name-absolute-p filename
2034 This function returns @code{t} if file @var{filename} is an absolute
2035 file name, @code{nil} otherwise.
2037 @example
2038 @group
2039 (file-name-absolute-p "~rms/foo")
2040      @result{} t
2041 @end group
2042 @group
2043 (file-name-absolute-p "rms/foo")
2044      @result{} nil
2045 @end group
2046 @group
2047 (file-name-absolute-p "/user/rms/foo")
2048      @result{} t
2049 @end group
2050 @end example
2051 @end defun
2053   Given a possibly relative file name, you can convert it to an
2054 absolute name using @code{expand-file-name} (@pxref{File Name
2055 Expansion}).  This function converts absolute file names to relative
2056 names:
2058 @defun file-relative-name filename &optional directory
2059 This function tries to return a relative name that is equivalent to
2060 @var{filename}, assuming the result will be interpreted relative to
2061 @var{directory} (an absolute directory name or directory file name).
2062 If @var{directory} is omitted or @code{nil}, it defaults to the
2063 current buffer's default directory.
2065 On some operating systems, an absolute file name begins with a device
2066 name.  On such systems, @var{filename} has no relative equivalent based
2067 on @var{directory} if they start with two different device names.  In
2068 this case, @code{file-relative-name} returns @var{filename} in absolute
2069 form.
2071 @example
2072 (file-relative-name "/foo/bar" "/foo/")
2073      @result{} "bar"
2074 (file-relative-name "/foo/bar" "/hack/")
2075      @result{} "../foo/bar"
2076 @end example
2077 @end defun
2079 @node Directory Names
2080 @subsection Directory Names
2081 @cindex directory name
2082 @cindex directory file name
2083 @cindex file name of directory
2085   A @dfn{directory name} is the name of a directory.  A directory is
2086 actually a kind of file, so it has a file name (called the
2087 @dfn{directory file name}, which is related to the directory name but
2088 not identical to it.  (This is not quite the same as the usual Unix
2089 terminology.)  These two different names for the same entity are
2090 related by a syntactic transformation.  On GNU and Unix systems, this
2091 is simple: a directory name ends in a slash, whereas the directory
2092 file name lacks that slash.  On MS-DOS the relationship is more
2093 complicated.
2095   The difference between directory name and directory file name is
2096 subtle but crucial.  When an Emacs variable or function argument is
2097 described as being a directory name, a directory file name is not
2098 acceptable.  When @code{file-name-directory} returns a string, that is
2099 always a directory name.
2101   The following two functions convert between directory names and
2102 directory file names.  They do nothing special with environment
2103 variable substitutions such as @samp{$HOME}, and the constructs
2104 @samp{~}, @samp{.} and @samp{..}.
2106 @defun file-name-as-directory filename
2107 This function returns a string representing @var{filename} in a form
2108 that the operating system will interpret as the name of a directory (a
2109 directory name).  On most systems, this means appending a slash to the
2110 string (if it does not already end in one).
2112 @example
2113 @group
2114 (file-name-as-directory "~rms/lewis")
2115      @result{} "~rms/lewis/"
2116 @end group
2117 @end example
2118 @end defun
2120 @defun directory-name-p filename
2121 This function returns non-@code{nil} if @var{filename} ends with a
2122 directory separator character.  This is the forward slash @samp{/} on
2123 Unix and GNU systems; MS-Windows and MS-DOS recognize both the forward
2124 slash and the backslash @samp{\} as directory separators.
2125 @end defun
2127 @defun directory-file-name dirname
2128 This function returns a string representing @var{dirname} in a form
2129 that the operating system will interpret as the name of a file (a
2130 directory file name).  On most systems, this means removing the final
2131 slash (or backslash) from the string.
2133 @example
2134 @group
2135 (directory-file-name "~lewis/")
2136      @result{} "~lewis"
2137 @end group
2138 @end example
2139 @end defun
2141   Given a directory name, you can combine it with a relative file name
2142 using @code{concat}:
2144 @example
2145 (concat @var{dirname} @var{relfile})
2146 @end example
2148 @noindent
2149 Be sure to verify that the file name is relative before doing that.
2150 If you use an absolute file name, the results could be syntactically
2151 invalid or refer to the wrong file.
2153   If you want to use a directory file name in making such a
2154 combination, you must first convert it to a directory name using
2155 @code{file-name-as-directory}:
2157 @example
2158 (concat (file-name-as-directory @var{dirfile}) @var{relfile})
2159 @end example
2161 @noindent
2162 Don't try concatenating a slash by hand, as in
2164 @example
2165 ;;; @r{Wrong!}
2166 (concat @var{dirfile} "/" @var{relfile})
2167 @end example
2169 @noindent
2170 because this is not portable.  Always use
2171 @code{file-name-as-directory}.
2173   To avoid the issues mentioned above, or if the @var{dirname} value
2174 might be nil (for example, from an element of @code{load-path}), use:
2176 @example
2177 (expand-file-name @var{relfile} @var{dirname})
2178 @end example
2180   To convert a directory name to its abbreviation, use this
2181 function:
2183 @cindex file name abbreviations
2184 @cindex abbreviated file names
2185 @defun abbreviate-file-name filename
2186 @anchor{abbreviate-file-name}
2187 This function returns an abbreviated form of @var{filename}.  It
2188 applies the abbreviations specified in @code{directory-abbrev-alist}
2189 (@pxref{File Aliases,,File Aliases, emacs, The GNU Emacs Manual}),
2190 then substitutes @samp{~} for the user's home directory if the
2191 argument names a file in the home directory or one of its
2192 subdirectories.  If the home directory is a root directory, it is not
2193 replaced with @samp{~}, because this does not make the result shorter
2194 on many systems.
2196 You can use this function for directory names and for file names,
2197 because it recognizes abbreviations even as part of the name.
2198 @end defun
2200 @node File Name Expansion
2201 @subsection Functions that Expand Filenames
2202 @cindex expansion of file names
2204   @dfn{Expanding} a file name means converting a relative file name to
2205 an absolute one.  Since this is done relative to a default directory,
2206 you must specify the default directory name as well as the file name
2207 to be expanded.  It also involves expanding abbreviations like
2208 @file{~/}
2209 @ifnottex
2210 (@pxref{abbreviate-file-name}),
2211 @end ifnottex
2212 and eliminating redundancies like @file{./} and @file{@var{name}/../}.
2214 @defun expand-file-name filename &optional directory
2215 This function converts @var{filename} to an absolute file name.  If
2216 @var{directory} is supplied, it is the default directory to start with
2217 if @var{filename} is relative.  (The value of @var{directory} should
2218 itself be an absolute directory name or directory file name; it may
2219 start with @samp{~}.)  Otherwise, the current buffer's value of
2220 @code{default-directory} is used.  For example:
2222 @example
2223 @group
2224 (expand-file-name "foo")
2225      @result{} "/xcssun/users/rms/lewis/foo"
2226 @end group
2227 @group
2228 (expand-file-name "../foo")
2229      @result{} "/xcssun/users/rms/foo"
2230 @end group
2231 @group
2232 (expand-file-name "foo" "/usr/spool/")
2233      @result{} "/usr/spool/foo"
2234 @end group
2235 @end example
2237 If the part of the combined file name before the first slash is
2238 @samp{~}, it expands to the value of the @env{HOME} environment
2239 variable (usually your home directory).  If the part before the first
2240 slash is @samp{~@var{user}} and if @var{user} is a valid login name,
2241 it expands to @var{user}'s home directory.
2243 Filenames containing @samp{.} or @samp{..} are simplified to their
2244 canonical form:
2246 @example
2247 @group
2248 (expand-file-name "bar/../foo")
2249      @result{} "/xcssun/users/rms/lewis/foo"
2250 @end group
2251 @end example
2253 In some cases, a leading @samp{..} component can remain in the output:
2255 @example
2256 @group
2257 (expand-file-name "../home" "/")
2258      @result{} "/../home"
2259 @end group
2260 @end example
2262 @noindent
2263 This is for the sake of filesystems that have the concept of a
2264 superroot above the root directory @file{/}.  On other filesystems,
2265 @file{/../} is interpreted exactly the same as @file{/}.
2267 Note that @code{expand-file-name} does @emph{not} expand environment
2268 variables; only @code{substitute-in-file-name} does that:
2270 @example
2271 @group
2272 (expand-file-name "$HOME/foo")
2273      @result{} "/xcssun/users/rms/lewis/$HOME/foo"
2274 @end group
2275 @end example
2277 Note also that @code{expand-file-name} does not follow symbolic links
2278 at any level.  This results in a difference between the way
2279 @code{file-truename} and @code{expand-file-name} treat @samp{..}.
2280 Assuming that @samp{/tmp/bar} is a symbolic link to the directory
2281 @samp{/tmp/foo/bar} we get:
2283 @example
2284 @group
2285 (file-truename "/tmp/bar/../myfile")
2286      @result{} "/tmp/foo/myfile"
2287 @end group
2288 @group
2289 (expand-file-name "/tmp/bar/../myfile")
2290      @result{} "/tmp/myfile"
2291 @end group
2292 @end example
2294 If you may need to follow symbolic links preceding @samp{..}, you
2295 should make sure to call @code{file-truename} without prior direct or
2296 indirect calls to @code{expand-file-name}.  @xref{Truenames}.
2297 @end defun
2299 @defvar default-directory
2300 The value of this buffer-local variable is the default directory for the
2301 current buffer.  It should be an absolute directory name; it may start
2302 with @samp{~}.  This variable is buffer-local in every buffer.
2304 @code{expand-file-name} uses the default directory when its second
2305 argument is @code{nil}.
2307 The value is always a string ending with a slash.
2309 @example
2310 @group
2311 default-directory
2312      @result{} "/user/lewis/manual/"
2313 @end group
2314 @end example
2315 @end defvar
2317 @defun substitute-in-file-name filename
2318 @anchor{Definition of substitute-in-file-name}
2319 This function replaces environment variable references in
2320 @var{filename} with the environment variable values.  Following
2321 standard Unix shell syntax, @samp{$} is the prefix to substitute an
2322 environment variable value.  If the input contains @samp{$$}, that is
2323 converted to @samp{$}; this gives the user a way to quote a
2324 @samp{$}.
2326 The environment variable name is the series of alphanumeric characters
2327 (including underscores) that follow the @samp{$}.  If the character following
2328 the @samp{$} is a @samp{@{}, then the variable name is everything up to the
2329 matching @samp{@}}.
2331 Calling @code{substitute-in-file-name} on output produced by
2332 @code{substitute-in-file-name} tends to give incorrect results.  For
2333 instance, use of @samp{$$} to quote a single @samp{$} won't work
2334 properly, and @samp{$} in an environment variable's value could lead
2335 to repeated substitution.  Therefore, programs that call this function
2336 and put the output where it will be passed to this function need to
2337 double all @samp{$} characters to prevent subsequent incorrect
2338 results.
2340 @c Wordy to avoid overfull hbox.  --rjc 15mar92
2341 Here we assume that the environment variable @env{HOME}, which holds
2342 the user's home directory name, has value @samp{/xcssun/users/rms}.
2344 @example
2345 @group
2346 (substitute-in-file-name "$HOME/foo")
2347      @result{} "/xcssun/users/rms/foo"
2348 @end group
2349 @end example
2351 After substitution, if a @samp{~} or a @samp{/} appears immediately
2352 after another @samp{/}, the function discards everything before it (up
2353 through the immediately preceding @samp{/}).
2355 @example
2356 @group
2357 (substitute-in-file-name "bar/~/foo")
2358      @result{} "~/foo"
2359 @end group
2360 @group
2361 (substitute-in-file-name "/usr/local/$HOME/foo")
2362      @result{} "/xcssun/users/rms/foo"
2363      ;; @r{@file{/usr/local/} has been discarded.}
2364 @end group
2365 @end example
2367 @end defun
2369 @node Unique File Names
2370 @subsection Generating Unique File Names
2371 @cindex unique file names
2372 @cindex temporary files
2374   Some programs need to write temporary files.  Here is the usual way to
2375 construct a name for such a file:
2377 @example
2378 (make-temp-file @var{name-of-application})
2379 @end example
2381 @noindent
2382 The job of @code{make-temp-file} is to prevent two different users or
2383 two different jobs from trying to use the exact same file name.
2385 @defun make-temp-file prefix &optional dir-flag suffix
2386 This function creates a temporary file and returns its name.  Emacs
2387 creates the temporary file's name by adding to @var{prefix} some
2388 random characters that are different in each Emacs job.  The result is
2389 guaranteed to be a newly created empty file.  On MS-DOS, this function
2390 can truncate the @var{string} prefix to fit into the 8+3 file-name
2391 limits.  If @var{prefix} is a relative file name, it is expanded
2392 against @code{temporary-file-directory}.
2394 @example
2395 @group
2396 (make-temp-file "foo")
2397      @result{} "/tmp/foo232J6v"
2398 @end group
2399 @end example
2401 When @code{make-temp-file} returns, the file has been created and is
2402 empty.  At that point, you should write the intended contents into the
2403 file.
2405 If @var{dir-flag} is non-@code{nil}, @code{make-temp-file} creates an
2406 empty directory instead of an empty file.  It returns the file name,
2407 not the directory name, of that directory.  @xref{Directory Names}.
2409 If @var{suffix} is non-@code{nil}, @code{make-temp-file} adds it at
2410 the end of the file name.
2412 To prevent conflicts among different libraries running in the same
2413 Emacs, each Lisp program that uses @code{make-temp-file} should have its
2414 own @var{prefix}.  The number added to the end of @var{prefix}
2415 distinguishes between the same application running in different Emacs
2416 jobs.  Additional added characters permit a large number of distinct
2417 names even in one Emacs job.
2418 @end defun
2420   The default directory for temporary files is controlled by the
2421 variable @code{temporary-file-directory}.  This variable gives the user
2422 a uniform way to specify the directory for all temporary files.  Some
2423 programs use @code{small-temporary-file-directory} instead, if that is
2424 non-@code{nil}.  To use it, you should expand the prefix against
2425 the proper directory before calling @code{make-temp-file}.
2427 @defopt temporary-file-directory
2428 @cindex @env{TMPDIR} environment variable
2429 @cindex @env{TMP} environment variable
2430 @cindex @env{TEMP} environment variable
2431 This variable specifies the directory name for creating temporary files.
2432 Its value should be a directory name (@pxref{Directory Names}), but it
2433 is good for Lisp programs to cope if the value is a directory's file
2434 name instead.  Using the value as the second argument to
2435 @code{expand-file-name} is a good way to achieve that.
2437 The default value is determined in a reasonable way for your operating
2438 system; it is based on the @env{TMPDIR}, @env{TMP} and @env{TEMP}
2439 environment variables, with a fall-back to a system-dependent name if
2440 none of these variables is defined.
2442 Even if you do not use @code{make-temp-file} to create the temporary
2443 file, you should still use this variable to decide which directory to
2444 put the file in.  However, if you expect the file to be small, you
2445 should use @code{small-temporary-file-directory} first if that is
2446 non-@code{nil}.
2447 @end defopt
2449 @defopt small-temporary-file-directory
2450 This variable specifies the directory name for
2451 creating certain temporary files, which are likely to be small.
2453 If you want to write a temporary file which is likely to be small, you
2454 should compute the directory like this:
2456 @example
2457 (make-temp-file
2458   (expand-file-name @var{prefix}
2459                     (or small-temporary-file-directory
2460                         temporary-file-directory)))
2461 @end example
2462 @end defopt
2464 @defun make-temp-name base-name
2465 This function generates a string that can be used as a unique file
2466 name.  The name starts with @var{base-name}, and has several random
2467 characters appended to it, which are different in each Emacs job.  It
2468 is like @code{make-temp-file} except that (i) it just constructs a
2469 name, and does not create a file, and (ii) @var{base-name} should be
2470 an absolute file name (on MS-DOS, this function can truncate
2471 @var{base-name} to fit into the 8+3 file-name limits).
2473 @strong{Warning:} In most cases, you should not use this function; use
2474 @code{make-temp-file} instead!  This function is susceptible to a race
2475 condition, between the @code{make-temp-name} call and the creation of
2476 the file, which in some cases may cause a security hole.
2477 @end defun
2479 Sometimes, it is necessary to create a temporary file on a remote host
2480 or a mounted directory.  The following two functions support this.
2482 @defun make-nearby-temp-file prefix &optional dir-flag suffix
2483 This function is similar to @code{make-temp-file}, but it creates a
2484 temporary file as close as possible to @code{default-directory}.  If
2485 @var{prefix} is a relative file name, and @code{default-directory} is
2486 a remote file name or located on a mounted file systems, the temporary
2487 file is created in the directory returned by the function
2488 @code{temporary-file-directory}.  Otherwise, the function
2489 @code{make-temp-file} is used.  @var{prefix}, @var{dir-flag} and
2490 @var{suffix} have the same meaning as in @code{make-temp-file}.
2492 @example
2493 @group
2494 (let ((default-directory "/ssh:remotehost:"))
2495   (make-nearby-temp-file "foo"))
2496      @result{} "/ssh:remotehost:/tmp/foo232J6v"
2497 @end group
2498 @end example
2499 @end defun
2501 @defun temporary-file-directory
2502 The directory for writing temporary files via
2503 @code{make-nearby-temp-file}.  In case of a remote
2504 @code{default-directory}, this is a directory for temporary files on
2505 that remote host.  If such a directory does not exist, or
2506 @code{default-directory} ought to be located on a mounted file system
2507 (see @code{mounted-file-systems}), the function returns
2508 @code{default-directory}.  For a non-remote and non-mounted
2509 @code{default-directory}, the value of the variable
2510 @code{temporary-file-directory} is returned.
2511 @end defun
2513 In order to extract the local part of the path name from a temporary
2514 file, the following code could be used:
2516 @example
2517 @group
2518 (let ((tmpfile (make-nearby-temp-file "foo")))
2519   (or (file-remote-p tmpfile 'localname) tmpfile))
2520 @end group
2521 @end example
2523 @node File Name Completion
2524 @subsection File Name Completion
2525 @cindex file name completion subroutines
2526 @cindex completion, file name
2528   This section describes low-level subroutines for completing a file
2529 name.  For higher level functions, see @ref{Reading File Names}.
2531 @defun file-name-all-completions partial-filename directory
2532 This function returns a list of all possible completions for a file
2533 whose name starts with @var{partial-filename} in directory
2534 @var{directory}.  The order of the completions is the order of the files
2535 in the directory, which is unpredictable and conveys no useful
2536 information.
2538 The argument @var{partial-filename} must be a file name containing no
2539 directory part and no slash (or backslash on some systems).  The current
2540 buffer's default directory is prepended to @var{directory}, if
2541 @var{directory} is not absolute.
2543 In the following example, suppose that @file{~rms/lewis} is the current
2544 default directory, and has five files whose names begin with @samp{f}:
2545 @file{foo}, @file{file~}, @file{file.c}, @file{file.c.~1~}, and
2546 @file{file.c.~2~}.
2548 @example
2549 @group
2550 (file-name-all-completions "f" "")
2551      @result{} ("foo" "file~" "file.c.~2~"
2552                 "file.c.~1~" "file.c")
2553 @end group
2555 @group
2556 (file-name-all-completions "fo" "")
2557      @result{} ("foo")
2558 @end group
2559 @end example
2560 @end defun
2562 @defun file-name-completion filename directory &optional predicate
2563 This function completes the file name @var{filename} in directory
2564 @var{directory}.  It returns the longest prefix common to all file names
2565 in directory @var{directory} that start with @var{filename}.  If
2566 @var{predicate} is non-@code{nil} then it ignores possible completions
2567 that don't satisfy @var{predicate}, after calling that function
2568 with one argument, the expanded absolute file name.
2570 If only one match exists and @var{filename} matches it exactly, the
2571 function returns @code{t}.  The function returns @code{nil} if directory
2572 @var{directory} contains no name starting with @var{filename}.
2574 In the following example, suppose that the current default directory
2575 has five files whose names begin with @samp{f}: @file{foo},
2576 @file{file~}, @file{file.c}, @file{file.c.~1~}, and
2577 @file{file.c.~2~}.
2579 @example
2580 @group
2581 (file-name-completion "fi" "")
2582      @result{} "file"
2583 @end group
2585 @group
2586 (file-name-completion "file.c.~1" "")
2587      @result{} "file.c.~1~"
2588 @end group
2590 @group
2591 (file-name-completion "file.c.~1~" "")
2592      @result{} t
2593 @end group
2595 @group
2596 (file-name-completion "file.c.~3" "")
2597      @result{} nil
2598 @end group
2599 @end example
2600 @end defun
2602 @defopt completion-ignored-extensions
2603 @code{file-name-completion} usually ignores file names that end in any
2604 string in this list.  It does not ignore them when all the possible
2605 completions end in one of these suffixes.  This variable has no effect
2606 on @code{file-name-all-completions}.
2608 A typical value might look like this:
2610 @example
2611 @group
2612 completion-ignored-extensions
2613      @result{} (".o" ".elc" "~" ".dvi")
2614 @end group
2615 @end example
2617 If an element of @code{completion-ignored-extensions} ends in a slash
2618 @samp{/}, it signals a directory.  The elements which do @emph{not} end
2619 in a slash will never match a directory; thus, the above value will not
2620 filter out a directory named @file{foo.elc}.
2621 @end defopt
2623 @node Standard File Names
2624 @subsection Standard File Names
2626   Sometimes, an Emacs Lisp program needs to specify a standard file
2627 name for a particular use---typically, to hold configuration data
2628 specified by the current user.  Usually, such files should be located
2629 in the directory specified by @code{user-emacs-directory}, which is
2630 @file{~/.emacs.d} by default (@pxref{Init File}).  For example, abbrev
2631 definitions are stored by default in @file{~/.emacs.d/abbrev_defs}.
2632 The easiest way to specify such a file name is to use the function
2633 @code{locate-user-emacs-file}.
2635 @defun locate-user-emacs-file base-name &optional old-name
2636 This function returns an absolute file name for an Emacs-specific
2637 configuration or data file.  The argument @file{base-name} should be a
2638 relative file name.  The return value is the absolute name of a file
2639 in the directory specified by @code{user-emacs-directory}; if that
2640 directory does not exist, this function creates it.
2642 If the optional argument @var{old-name} is non-@code{nil}, it
2643 specifies a file in the user's home directory,
2644 @file{~/@var{old-name}}.  If such a file exists, the return value is
2645 the absolute name of that file, instead of the file specified by
2646 @var{base-name}.  This argument is intended to be used by Emacs
2647 packages to provide backward compatibility.  For instance, prior to
2648 the introduction of @code{user-emacs-directory}, the abbrev file was
2649 located in @file{~/.abbrev_defs}.  Here is the definition of
2650 @code{abbrev-file-name}:
2652 @example
2653 (defcustom abbrev-file-name
2654   (locate-user-emacs-file "abbrev_defs" ".abbrev_defs")
2655   "Default name of file from which to read abbrevs."
2656   @dots{}
2657   :type 'file)
2658 @end example
2659 @end defun
2661   A lower-level function for standardizing file names, which
2662 @code{locate-user-emacs-file} uses as a subroutine, is
2663 @code{convert-standard-filename}.
2665 @defun convert-standard-filename filename
2666 This function returns a file name based on @var{filename}, which fits
2667 the conventions of the current operating system.
2669 On GNU and Unix systems, this simply returns @var{filename}.  On other
2670 operating systems, it may enforce system-specific file name
2671 conventions; for example, on MS-DOS this function performs a variety
2672 of changes to enforce MS-DOS file name limitations, including
2673 converting any leading @samp{.} to @samp{_} and truncating to three
2674 characters after the @samp{.}.
2676 The recommended way to use this function is to specify a name which
2677 fits the conventions of GNU and Unix systems, and pass it to
2678 @code{convert-standard-filename}.
2679 @end defun
2681 @node Contents of Directories
2682 @section Contents of Directories
2683 @cindex directory-oriented functions
2684 @cindex file names in directory
2686   A directory is a kind of file that contains other files entered under
2687 various names.  Directories are a feature of the file system.
2689   Emacs can list the names of the files in a directory as a Lisp list,
2690 or display the names in a buffer using the @code{ls} shell command.  In
2691 the latter case, it can optionally display information about each file,
2692 depending on the options passed to the @code{ls} command.
2694 @defun directory-files directory &optional full-name match-regexp nosort
2695 This function returns a list of the names of the files in the directory
2696 @var{directory}.  By default, the list is in alphabetical order.
2698 If @var{full-name} is non-@code{nil}, the function returns the files'
2699 absolute file names.  Otherwise, it returns the names relative to
2700 the specified directory.
2702 If @var{match-regexp} is non-@code{nil}, this function returns only
2703 those file names that contain a match for that regular expression---the
2704 other file names are excluded from the list.  On case-insensitive
2705 filesystems, the regular expression matching is case-insensitive.
2707 @c Emacs 19 feature
2708 If @var{nosort} is non-@code{nil}, @code{directory-files} does not sort
2709 the list, so you get the file names in no particular order.  Use this if
2710 you want the utmost possible speed and don't care what order the files
2711 are processed in.  If the order of processing is visible to the user,
2712 then the user will probably be happier if you do sort the names.
2714 @example
2715 @group
2716 (directory-files "~lewis")
2717      @result{} ("#foo#" "#foo.el#" "." ".."
2718          "dired-mods.el" "files.texi"
2719          "files.texi.~1~")
2720 @end group
2721 @end example
2723 An error is signaled if @var{directory} is not the name of a directory
2724 that can be read.
2725 @end defun
2727 @defun directory-files-recursively directory regexp &optional include-directories
2728 Return all files under @var{directory} whose names match @var{regexp}.
2729 This function searches the specified @var{directory} and its
2730 sub-directories, recursively, for files whose basenames (i.e., without
2731 the leading directories) match the specified @var{regexp}, and returns
2732 a list of the absolute file names of the matching files
2733 (@pxref{Relative File Names, absolute file names}).  The file names
2734 are returned in depth-first order, meaning that files in some
2735 sub-directory are returned before the files in its parent directory.
2736 In addition, matching files found in each subdirectory are sorted
2737 alphabetically by their basenames.  By default, directories whose
2738 names match @var{regexp} are omitted from the list, but if the
2739 optional argument @var{include-directories} is non-@code{nil}, they
2740 are included.
2741 @end defun
2743 @defun directory-files-and-attributes directory &optional full-name match-regexp nosort id-format
2744 This is similar to @code{directory-files} in deciding which files
2745 to report on and how to report their names.  However, instead
2746 of returning a list of file names, it returns for each file a
2747 list @code{(@var{filename} . @var{attributes})}, where @var{attributes}
2748 is what @code{file-attributes} would return for that file.
2749 The optional argument @var{id-format} has the same meaning as the
2750 corresponding argument to @code{file-attributes} (@pxref{Definition
2751 of file-attributes}).
2752 @end defun
2754 @defun file-expand-wildcards pattern &optional full
2755 This function expands the wildcard pattern @var{pattern}, returning
2756 a list of file names that match it.
2758 If @var{pattern} is written as an absolute file name,
2759 the values are absolute also.
2761 If @var{pattern} is written as a relative file name, it is interpreted
2762 relative to the current default directory.  The file names returned are
2763 normally also relative to the current default directory.  However, if
2764 @var{full} is non-@code{nil}, they are absolute.
2765 @end defun
2767 @defun insert-directory file switches &optional wildcard full-directory-p
2768 This function inserts (in the current buffer) a directory listing for
2769 directory @var{file}, formatted with @code{ls} according to
2770 @var{switches}.  It leaves point after the inserted text.
2771 @var{switches} may be a string of options, or a list of strings
2772 representing individual options.
2774 The argument @var{file} may be either a directory name or a file
2775 specification including wildcard characters.  If @var{wildcard} is
2776 non-@code{nil}, that means treat @var{file} as a file specification with
2777 wildcards.
2779 If @var{full-directory-p} is non-@code{nil}, that means the directory
2780 listing is expected to show the full contents of a directory.  You
2781 should specify @code{t} when @var{file} is a directory and switches do
2782 not contain @samp{-d}.  (The @samp{-d} option to @code{ls} says to
2783 describe a directory itself as a file, rather than showing its
2784 contents.)
2786 On most systems, this function works by running a directory listing
2787 program whose name is in the variable @code{insert-directory-program}.
2788 If @var{wildcard} is non-@code{nil}, it also runs the shell specified by
2789 @code{shell-file-name}, to expand the wildcards.
2791 MS-DOS and MS-Windows systems usually lack the standard Unix program
2792 @code{ls}, so this function emulates the standard Unix program @code{ls}
2793 with Lisp code.
2795 As a technical detail, when @var{switches} contains the long
2796 @samp{--dired} option, @code{insert-directory} treats it specially,
2797 for the sake of dired.  However, the normally equivalent short
2798 @samp{-D} option is just passed on to @code{insert-directory-program},
2799 as any other option.
2800 @end defun
2802 @defvar insert-directory-program
2803 This variable's value is the program to run to generate a directory listing
2804 for the function @code{insert-directory}.  It is ignored on systems
2805 which generate the listing with Lisp code.
2806 @end defvar
2808 @node Create/Delete Dirs
2809 @section Creating, Copying and Deleting Directories
2810 @cindex creating, copying and deleting directories
2811 @c Emacs 19 features
2813   Most Emacs Lisp file-manipulation functions get errors when used on
2814 files that are directories.  For example, you cannot delete a directory
2815 with @code{delete-file}.  These special functions exist to create and
2816 delete directories.
2818 @findex mkdir
2819 @deffn Command make-directory dirname &optional parents
2820 This command creates a directory named @var{dirname}.  If
2821 @var{parents} is non-@code{nil}, as is always the case in an
2822 interactive call, that means to create the parent directories first,
2823 if they don't already exist.
2825 @code{mkdir} is an alias for this.
2826 @end deffn
2828 @deffn Command copy-directory dirname newname &optional keep-time parents copy-contents
2829 This command copies the directory named @var{dirname} to
2830 @var{newname}.  If @var{newname} names an existing directory,
2831 @var{dirname} will be copied to a subdirectory there.
2833 It always sets the file modes of the copied files to match the
2834 corresponding original file.
2836 The third argument @var{keep-time} non-@code{nil} means to preserve the
2837 modification time of the copied files.  A prefix arg makes
2838 @var{keep-time} non-@code{nil}.
2840 The fourth argument @var{parents} says whether to
2841 create parent directories if they don't exist.  Interactively,
2842 this happens by default.
2844 The fifth argument @var{copy-contents}, if non-@code{nil}, means to
2845 copy the contents of @var{dirname} directly into @var{newname} if the
2846 latter is an existing directory, instead of copying @var{dirname} into
2847 it as a subdirectory.
2848 @end deffn
2850 @cindex trash
2851 @vindex delete-by-moving-to-trash
2852 @deffn Command delete-directory dirname &optional recursive trash
2853 This command deletes the directory named @var{dirname}.  The function
2854 @code{delete-file} does not work for files that are directories; you
2855 must use @code{delete-directory} for them.  If @var{recursive} is
2856 @code{nil}, and the directory contains any files,
2857 @code{delete-directory} signals an error.
2858 If recursive is non-@code{nil}, there is no error merely because the
2859 directory or its files are deleted by some other process before
2860 @code{delete-directory} gets to them.
2862 @code{delete-directory} only follows symbolic links at the level of
2863 parent directories.
2865 If the optional argument @var{trash} is non-@code{nil} and the
2866 variable @code{delete-by-moving-to-trash} is non-@code{nil}, this
2867 command moves the file into the system Trash instead of deleting it.
2868 @xref{Misc File Ops,,Miscellaneous File Operations, emacs, The GNU
2869 Emacs Manual}.  When called interactively, @var{trash} is @code{t} if
2870 no prefix argument is given, and @code{nil} otherwise.
2871 @end deffn
2873 @node Magic File Names
2874 @section Making Certain File Names ``Magic''
2875 @cindex magic file names
2877   You can implement special handling for certain file names.  This is
2878 called making those names @dfn{magic}.  The principal use for this
2879 feature is in implementing access to remote files (@pxref{Remote Files,,
2880 Remote Files, emacs, The GNU Emacs Manual}).
2882   To define a kind of magic file name, you must supply a regular
2883 expression to define the class of names (all those that match the
2884 regular expression), plus a handler that implements all the primitive
2885 Emacs file operations for file names that match.
2887 @cindex file handler
2888 @vindex file-name-handler-alist
2889   The variable @code{file-name-handler-alist} holds a list of handlers,
2890 together with regular expressions that determine when to apply each
2891 handler.  Each element has this form:
2893 @example
2894 (@var{regexp} . @var{handler})
2895 @end example
2897 @noindent
2898 All the Emacs primitives for file access and file name transformation
2899 check the given file name against @code{file-name-handler-alist}.  If
2900 the file name matches @var{regexp}, the primitives handle that file by
2901 calling @var{handler}.
2903   The first argument given to @var{handler} is the name of the
2904 primitive, as a symbol; the remaining arguments are the arguments that
2905 were passed to that primitive.  (The first of these arguments is most
2906 often the file name itself.)  For example, if you do this:
2908 @example
2909 (file-exists-p @var{filename})
2910 @end example
2912 @noindent
2913 and @var{filename} has handler @var{handler}, then @var{handler} is
2914 called like this:
2916 @example
2917 (funcall @var{handler} 'file-exists-p @var{filename})
2918 @end example
2920   When a function takes two or more arguments that must be file names,
2921 it checks each of those names for a handler.  For example, if you do
2922 this:
2924 @example
2925 (expand-file-name @var{filename} @var{dirname})
2926 @end example
2928 @noindent
2929 then it checks for a handler for @var{filename} and then for a handler
2930 for @var{dirname}.  In either case, the @var{handler} is called like
2931 this:
2933 @example
2934 (funcall @var{handler} 'expand-file-name @var{filename} @var{dirname})
2935 @end example
2937 @noindent
2938 The @var{handler} then needs to figure out whether to handle
2939 @var{filename} or @var{dirname}.
2941   If the specified file name matches more than one handler, the one
2942 whose match starts last in the file name gets precedence.  This rule
2943 is chosen so that handlers for jobs such as uncompression are handled
2944 first, before handlers for jobs such as remote file access.
2946   Here are the operations that a magic file name handler gets to handle:
2948 @ifnottex
2949 @noindent
2950 @code{access-file}, @code{add-name-to-file},
2951 @code{byte-compiler-base-file-name},@*
2952 @code{copy-directory}, @code{copy-file},
2953 @code{delete-directory}, @code{delete-file},
2954 @code{diff-latest-backup-file},
2955 @code{directory-file-name},
2956 @code{directory-files},
2957 @code{directory-files-and-attributes},
2958 @code{dired-compress-file}, @code{dired-uncache},@*
2959 @code{expand-file-name},
2960 @code{file-accessible-directory-p},
2961 @code{file-acl},
2962 @code{file-attributes},
2963 @code{file-directory-p},
2964 @code{file-equal-p},
2965 @code{file-executable-p}, @code{file-exists-p},
2966 @code{file-in-directory-p},
2967 @code{file-local-copy},
2968 @code{file-modes}, @code{file-name-all-completions},
2969 @code{file-name-as-directory},
2970 @code{file-name-completion},
2971 @code{file-name-directory},
2972 @code{file-name-nondirectory},
2973 @code{file-name-sans-versions}, @code{file-newer-than-file-p},
2974 @code{file-notify-add-watch}, @code{file-notify-rm-watch},
2975 @code{file-notify-valid-p},
2976 @code{file-ownership-preserved-p},
2977 @code{file-readable-p}, @code{file-regular-p},
2978 @code{file-remote-p}, @code{file-selinux-context},
2979 @code{file-symlink-p}, @code{file-truename}, @code{file-writable-p},
2980 @code{find-backup-file-name},
2981 @c Not sure why it was here:   @code{find-file-noselect},@*
2982 @code{get-file-buffer},
2983 @code{insert-directory},
2984 @code{insert-file-contents},@*
2985 @code{load},
2986 @code{make-auto-save-file-name},
2987 @code{make-directory},
2988 @code{make-directory-internal},
2989 @code{make-nearby-temp-file},
2990 @code{make-symbolic-link},@*
2991 @code{process-file},
2992 @code{rename-file}, @code{set-file-acl}, @code{set-file-modes},
2993 @code{set-file-selinux-context}, @code{set-file-times},
2994 @code{set-visited-file-modtime}, @code{shell-command},
2995 @code{start-file-process},
2996 @code{substitute-in-file-name},@*
2997 @code{temporary-file-directory},
2998 @code{unhandled-file-name-directory},
2999 @code{vc-registered},
3000 @code{verify-visited-file-modtime},@*
3001 @code{write-region}.
3002 @end ifnottex
3003 @iftex
3004 @noindent
3005 @flushleft
3006 @code{access-file}, @code{add-name-to-file},
3007 @code{byte-com@discretionary{}{}{}piler-base-file-name},
3008 @code{copy-directory}, @code{copy-file},
3009 @code{delete-directory}, @code{delete-file},
3010 @code{diff-latest-backup-file},
3011 @code{directory-file-name},
3012 @code{directory-files},
3013 @code{directory-files-and-at@discretionary{}{}{}tributes},
3014 @code{dired-compress-file}, @code{dired-uncache},
3015 @code{expand-file-name},
3016 @code{file-accessible-direc@discretionary{}{}{}tory-p},
3017 @code{file-acl},
3018 @code{file-attributes},
3019 @code{file-direc@discretionary{}{}{}tory-p},
3020 @code{file-equal-p},
3021 @code{file-executable-p}, @code{file-exists-p},
3022 @code{file-in-directory-p},
3023 @code{file-local-copy},
3024 @code{file-modes}, @code{file-name-all-completions},
3025 @code{file-name-as-directory},
3026 @code{file-name-completion},
3027 @code{file-name-directory},
3028 @code{file-name-nondirec@discretionary{}{}{}tory},
3029 @code{file-name-sans-versions}, @code{file-newer-than-file-p},
3030 @code{file-notify-add-watch}, @code{file-notify-rm-watch},
3031 @code{file-notify-valid-p},
3032 @code{file-ownership-pre@discretionary{}{}{}served-p},
3033 @code{file-readable-p}, @code{file-regular-p},
3034 @code{file-remote-p}, @code{file-selinux-context},
3035 @code{file-symlink-p}, @code{file-truename}, @code{file-writable-p},
3036 @code{find-backup-file-name},
3037 @c Not sure why it was here:   @code{find-file-noselect},
3038 @code{get-file-buffer},
3039 @code{insert-directory},
3040 @code{insert-file-contents},
3041 @code{load},
3042 @code{make-auto-save-file-name},
3043 @code{make-direc@discretionary{}{}{}tory},
3044 @code{make-direc@discretionary{}{}{}tory-internal},
3045 @code{make-symbolic-link},
3046 @code{process-file},
3047 @code{rename-file}, @code{set-file-acl}, @code{set-file-modes},
3048 @code{set-file-selinux-context}, @code{set-file-times},
3049 @code{set-visited-file-modtime}, @code{shell-command},
3050 @code{start-file-process},
3051 @code{substitute-in-file-name},
3052 @code{unhandled-file-name-directory},
3053 @code{vc-regis@discretionary{}{}{}tered},
3054 @code{verify-visited-file-modtime},
3055 @code{write-region}.
3056 @end flushleft
3057 @end iftex
3059   Handlers for @code{insert-file-contents} typically need to clear the
3060 buffer's modified flag, with @code{(set-buffer-modified-p nil)}, if the
3061 @var{visit} argument is non-@code{nil}.  This also has the effect of
3062 unlocking the buffer if it is locked.
3064   The handler function must handle all of the above operations, and
3065 possibly others to be added in the future.  It need not implement all
3066 these operations itself---when it has nothing special to do for a
3067 certain operation, it can reinvoke the primitive, to handle the
3068 operation in the usual way.  It should always reinvoke the primitive
3069 for an operation it does not recognize.  Here's one way to do this:
3071 @smallexample
3072 (defun my-file-handler (operation &rest args)
3073   ;; @r{First check for the specific operations}
3074   ;; @r{that we have special handling for.}
3075   (cond ((eq operation 'insert-file-contents) @dots{})
3076         ((eq operation 'write-region) @dots{})
3077         @dots{}
3078         ;; @r{Handle any operation we don't know about.}
3079         (t (let ((inhibit-file-name-handlers
3080                   (cons 'my-file-handler
3081                         (and (eq inhibit-file-name-operation operation)
3082                              inhibit-file-name-handlers)))
3083                  (inhibit-file-name-operation operation))
3084              (apply operation args)))))
3085 @end smallexample
3087   When a handler function decides to call the ordinary Emacs primitive for
3088 the operation at hand, it needs to prevent the primitive from calling
3089 the same handler once again, thus leading to an infinite recursion.  The
3090 example above shows how to do this, with the variables
3091 @code{inhibit-file-name-handlers} and
3092 @code{inhibit-file-name-operation}.  Be careful to use them exactly as
3093 shown above; the details are crucial for proper behavior in the case of
3094 multiple handlers, and for operations that have two file names that may
3095 each have handlers.
3097 @kindex safe-magic (@r{property})
3098   Handlers that don't really do anything special for actual access to the
3099 file---such as the ones that implement completion of host names for
3100 remote file names---should have a non-@code{nil} @code{safe-magic}
3101 property.  For instance, Emacs normally protects directory names
3102 it finds in @code{PATH} from becoming magic, if they look like magic
3103 file names, by prefixing them with @samp{/:}.  But if the handler that
3104 would be used for them has a non-@code{nil} @code{safe-magic}
3105 property, the @samp{/:} is not added.
3107 @kindex operations (@r{property})
3108   A file name handler can have an @code{operations} property to
3109 declare which operations it handles in a nontrivial way.  If this
3110 property has a non-@code{nil} value, it should be a list of
3111 operations; then only those operations will call the handler.  This
3112 avoids inefficiency, but its main purpose is for autoloaded handler
3113 functions, so that they won't be loaded except when they have real
3114 work to do.
3116   Simply deferring all operations to the usual primitives does not
3117 work.  For instance, if the file name handler applies to
3118 @code{file-exists-p}, then it must handle @code{load} itself, because
3119 the usual @code{load} code won't work properly in that case.  However,
3120 if the handler uses the @code{operations} property to say it doesn't
3121 handle @code{file-exists-p}, then it need not handle @code{load}
3122 nontrivially.
3124 @defvar inhibit-file-name-handlers
3125 This variable holds a list of handlers whose use is presently inhibited
3126 for a certain operation.
3127 @end defvar
3129 @defvar inhibit-file-name-operation
3130 The operation for which certain handlers are presently inhibited.
3131 @end defvar
3133 @defun find-file-name-handler file operation
3134 This function returns the handler function for file name @var{file},
3135 or @code{nil} if there is none.  The argument @var{operation} should
3136 be the operation to be performed on the file---the value you will pass
3137 to the handler as its first argument when you call it.  If
3138 @var{operation} equals @code{inhibit-file-name-operation}, or if it is
3139 not found in the @code{operations} property of the handler, this
3140 function returns @code{nil}.
3141 @end defun
3143 @defun file-local-copy filename
3144 This function copies file @var{filename} to an ordinary non-magic file
3145 on the local machine, if it isn't on the local machine already.  Magic
3146 file names should handle the @code{file-local-copy} operation if they
3147 refer to files on other machines.  A magic file name that is used for
3148 other purposes than remote file access should not handle
3149 @code{file-local-copy}; then this function will treat the file as
3150 local.
3152 If @var{filename} is local, whether magic or not, this function does
3153 nothing and returns @code{nil}.  Otherwise it returns the file name
3154 of the local copy file.
3155 @end defun
3157 @defun file-remote-p filename &optional identification connected
3158 This function tests whether @var{filename} is a remote file.  If
3159 @var{filename} is local (not remote), the return value is @code{nil}.
3160 If @var{filename} is indeed remote, the return value is a string that
3161 identifies the remote system.
3163 This identifier string can include a host name and a user name, as
3164 well as characters designating the method used to access the remote
3165 system.  For example, the remote identifier string for the filename
3166 @code{/sudo::/some/file} is @code{/sudo:root@@localhost:}.
3168 If @code{file-remote-p} returns the same identifier for two different
3169 filenames, that means they are stored on the same file system and can
3170 be accessed locally with respect to each other.  This means, for
3171 example, that it is possible to start a remote process accessing both
3172 files at the same time.  Implementers of file handlers need to ensure
3173 this principle is valid.
3175 @var{identification} specifies which part of the identifier shall be
3176 returned as string.  @var{identification} can be the symbol
3177 @code{method}, @code{user} or @code{host}; any other value is handled
3178 like @code{nil} and means to return the complete identifier string.
3179 In the example above, the remote @code{user} identifier string would
3180 be @code{root}.
3182 If @var{connected} is non-@code{nil}, this function returns @code{nil}
3183 even if @var{filename} is remote, if Emacs has no network connection
3184 to its host.  This is useful when you want to avoid the delay of
3185 making connections when they don't exist.
3186 @end defun
3188 @defun unhandled-file-name-directory filename
3189 This function returns the name of a directory that is not magic.  For
3190 a non-magic @var{filename} it returns the corresponding directory name
3191 (@pxref{Directory Names}).  For a magic @var{filename}, it invokes the
3192 file name handler, which therefore decides what value to return.  If
3193 @var{filename} is not accessible from a local process, then the file
3194 name handler should indicate that by returning @code{nil}.
3196 This is useful for running a subprocess; every subprocess must have a
3197 non-magic directory to serve as its current directory, and this function
3198 is a good way to come up with one.
3199 @end defun
3201 @defopt remote-file-name-inhibit-cache
3202 The attributes of remote files can be cached for better performance.  If
3203 they are changed outside of Emacs's control, the cached values become
3204 invalid, and must be reread.
3206 When this variable is set to @code{nil}, cached values are never
3207 expired.  Use this setting with caution, only if you are sure nothing
3208 other than Emacs ever changes the remote files.  If it is set to
3209 @code{t}, cached values are never used.  This is the safest value, but
3210 could result in performance degradation.
3212 A compromise is to set it to a positive number.  This means that
3213 cached values are used for that amount of seconds since they were
3214 cached.  If a remote file is checked regularly, it might be a good
3215 idea to let-bind this variable to a value less than the time period
3216 between consecutive checks.  For example:
3218 @example
3219 (defun display-time-file-nonempty-p (file)
3220   (let ((remote-file-name-inhibit-cache
3221          (- display-time-interval 5)))
3222     (and (file-exists-p file)
3223          (< 0 (nth 7 (file-attributes
3224                        (file-chase-links file)))))))
3225 @end example
3226 @end defopt
3228 @node Format Conversion
3229 @section File Format Conversion
3231 @cindex file format conversion
3232 @cindex encoding file formats
3233 @cindex decoding file formats
3234 @cindex text properties in files
3235 @cindex saving text properties
3236   Emacs performs several steps to convert the data in a buffer (text,
3237 text properties, and possibly other information) to and from a
3238 representation suitable for storing into a file.  This section describes
3239 the fundamental functions that perform this @dfn{format conversion},
3240 namely @code{insert-file-contents} for reading a file into a buffer,
3241 and @code{write-region} for writing a buffer into a file.
3243 @menu
3244 * Overview: Format Conversion Overview.     @code{insert-file-contents} and @code{write-region}.
3245 * Round-Trip: Format Conversion Round-Trip. Using @code{format-alist}.
3246 * Piecemeal: Format Conversion Piecemeal.   Specifying non-paired conversion.
3247 @end menu
3249 @node Format Conversion Overview
3250 @subsection Overview
3251 @noindent
3252 The function @code{insert-file-contents}:
3254 @itemize
3255 @item initially, inserts bytes from the file into the buffer;
3256 @item decodes bytes to characters as appropriate;
3257 @item processes formats as defined by entries in @code{format-alist}; and
3258 @item calls functions in @code{after-insert-file-functions}.
3259 @end itemize
3261 @noindent
3262 The function @code{write-region}:
3264 @itemize
3265 @item initially, calls functions in @code{write-region-annotate-functions};
3266 @item processes formats as defined by entries in @code{format-alist};
3267 @item encodes characters to bytes as appropriate; and
3268 @item modifies the file with the bytes.
3269 @end itemize
3271   This shows the symmetry of the lowest-level operations; reading and
3272 writing handle things in opposite order.  The rest of this section
3273 describes the two facilities surrounding the three variables named
3274 above, as well as some related functions.  @ref{Coding Systems}, for
3275 details on character encoding and decoding.
3277 @node Format Conversion Round-Trip
3278 @subsection Round-Trip Specification
3280   The most general of the two facilities is controlled by the variable
3281 @code{format-alist}, a list of @dfn{file format} specifications, which
3282 describe textual representations used in files for the data in an Emacs
3283 buffer.  The descriptions for reading and writing are paired, which is
3284 why we call this ``round-trip'' specification
3285 (@pxref{Format Conversion Piecemeal}, for non-paired specification).
3287 @defvar format-alist
3288 This list contains one format definition for each defined file format.
3289 Each format definition is a list of this form:
3291 @example
3292 (@var{name} @var{doc-string} @var{regexp} @var{from-fn} @var{to-fn} @var{modify} @var{mode-fn} @var{preserve})
3293 @end example
3294 @end defvar
3296 @cindex format definition
3297 @noindent
3298 Here is what the elements in a format definition mean:
3300 @table @var
3301 @item name
3302 The name of this format.
3304 @item doc-string
3305 A documentation string for the format.
3307 @item regexp
3308 A regular expression which is used to recognize files represented in
3309 this format.  If @code{nil}, the format is never applied automatically.
3311 @item from-fn
3312 A shell command or function to decode data in this format (to convert
3313 file data into the usual Emacs data representation).
3315 A shell command is represented as a string; Emacs runs the command as a
3316 filter to perform the conversion.
3318 If @var{from-fn} is a function, it is called with two arguments, @var{begin}
3319 and @var{end}, which specify the part of the buffer it should convert.
3320 It should convert the text by editing it in place.  Since this can
3321 change the length of the text, @var{from-fn} should return the modified
3322 end position.
3324 One responsibility of @var{from-fn} is to make sure that the beginning
3325 of the file no longer matches @var{regexp}.  Otherwise it is likely to
3326 get called again.  Also, @var{from-fn} must not involve buffers or
3327 files other than the one being decoded, otherwise the internal buffer
3328 used for formatting might be overwritten.
3330 @item to-fn
3331 A shell command or function to encode data in this format---that is, to
3332 convert the usual Emacs data representation into this format.
3334 If @var{to-fn} is a string, it is a shell command; Emacs runs the
3335 command as a filter to perform the conversion.
3337 If @var{to-fn} is a function, it is called with three arguments:
3338 @var{begin} and @var{end}, which specify the part of the buffer it
3339 should convert, and @var{buffer}, which specifies which buffer.  There
3340 are two ways it can do the conversion:
3342 @itemize @bullet
3343 @item
3344 By editing the buffer in place.  In this case, @var{to-fn} should
3345 return the end-position of the range of text, as modified.
3347 @item
3348 By returning a list of annotations.  This is a list of elements of the
3349 form @code{(@var{position} . @var{string})}, where @var{position} is an
3350 integer specifying the relative position in the text to be written, and
3351 @var{string} is the annotation to add there.  The list must be sorted in
3352 order of position when @var{to-fn} returns it.
3354 When @code{write-region} actually writes the text from the buffer to the
3355 file, it intermixes the specified annotations at the corresponding
3356 positions.  All this takes place without modifying the buffer.
3357 @end itemize
3359 @var{to-fn} must not involve buffers or files other than the one being
3360 encoded, otherwise the internal buffer used for formatting might be
3361 overwritten.
3363 @item modify
3364 A flag, @code{t} if the encoding function modifies the buffer, and
3365 @code{nil} if it works by returning a list of annotations.
3367 @item mode-fn
3368 A minor-mode function to call after visiting a file converted from this
3369 format.  The function is called with one argument, the integer 1;
3370 that tells a minor-mode function to enable the mode.
3372 @item preserve
3373 A flag, @code{t} if @code{format-write-file} should not remove this format
3374 from @code{buffer-file-format}.
3375 @end table
3377 The function @code{insert-file-contents} automatically recognizes file
3378 formats when it reads the specified file.  It checks the text of the
3379 beginning of the file against the regular expressions of the format
3380 definitions, and if it finds a match, it calls the decoding function for
3381 that format.  Then it checks all the known formats over again.
3382 It keeps checking them until none of them is applicable.
3384 Visiting a file, with @code{find-file-noselect} or the commands that use
3385 it, performs conversion likewise (because it calls
3386 @code{insert-file-contents}); it also calls the mode function for each
3387 format that it decodes.  It stores a list of the format names in the
3388 buffer-local variable @code{buffer-file-format}.
3390 @defvar buffer-file-format
3391 This variable states the format of the visited file.  More precisely,
3392 this is a list of the file format names that were decoded in the course
3393 of visiting the current buffer's file.  It is always buffer-local in all
3394 buffers.
3395 @end defvar
3397 When @code{write-region} writes data into a file, it first calls the
3398 encoding functions for the formats listed in @code{buffer-file-format},
3399 in the order of appearance in the list.
3401 @deffn Command format-write-file file format &optional confirm
3402 This command writes the current buffer contents into the file @var{file}
3403 in a format based on @var{format}, which is a list of format names.  It
3404 constructs the actual format starting from @var{format}, then appending
3405 any elements from the value of @code{buffer-file-format} with a
3406 non-@code{nil} @var{preserve} flag (see above), if they are not already
3407 present in @var{format}.  It then updates @code{buffer-file-format} with
3408 this format, making it the default for future saves.  Except for the
3409 @var{format} argument, this command is similar to @code{write-file}.  In
3410 particular, @var{confirm} has the same meaning and interactive treatment
3411 as the corresponding argument to @code{write-file}.  @xref{Definition of
3412 write-file}.
3413 @end deffn
3415 @deffn Command format-find-file file format
3416 This command finds the file @var{file}, converting it according to
3417 format @var{format}.  It also makes @var{format} the default if the
3418 buffer is saved later.
3420 The argument @var{format} is a list of format names.  If @var{format} is
3421 @code{nil}, no conversion takes place.  Interactively, typing just
3422 @key{RET} for @var{format} specifies @code{nil}.
3423 @end deffn
3425 @deffn Command format-insert-file file format &optional beg end
3426 This command inserts the contents of file @var{file}, converting it
3427 according to format @var{format}.  If @var{beg} and @var{end} are
3428 non-@code{nil}, they specify which part of the file to read, as in
3429 @code{insert-file-contents} (@pxref{Reading from Files}).
3431 The return value is like what @code{insert-file-contents} returns: a
3432 list of the absolute file name and the length of the data inserted
3433 (after conversion).
3435 The argument @var{format} is a list of format names.  If @var{format} is
3436 @code{nil}, no conversion takes place.  Interactively, typing just
3437 @key{RET} for @var{format} specifies @code{nil}.
3438 @end deffn
3440 @defvar buffer-auto-save-file-format
3441 This variable specifies the format to use for auto-saving.  Its value is
3442 a list of format names, just like the value of
3443 @code{buffer-file-format}; however, it is used instead of
3444 @code{buffer-file-format} for writing auto-save files.  If the value
3445 is @code{t}, the default, auto-saving uses the same format as a
3446 regular save in the same buffer.  This variable is always buffer-local
3447 in all buffers.
3448 @end defvar
3450 @node Format Conversion Piecemeal
3451 @subsection Piecemeal Specification
3453   In contrast to the round-trip specification described in the previous
3454 subsection (@pxref{Format Conversion Round-Trip}), you can use the variables
3455 @code{after-insert-file-functions} and @code{write-region-annotate-functions}
3456 to separately control the respective reading and writing conversions.
3458   Conversion starts with one representation and produces another
3459 representation.  When there is only one conversion to do, there is no
3460 conflict about what to start with.  However, when there are multiple
3461 conversions involved, conflict may arise when two conversions need to
3462 start with the same data.
3464   This situation is best understood in the context of converting text
3465 properties during @code{write-region}.  For example, the character at
3466 position 42 in a buffer is @samp{X} with a text property @code{foo}.  If
3467 the conversion for @code{foo} is done by inserting into the buffer, say,
3468 @samp{FOO:}, then that changes the character at position 42 from
3469 @samp{X} to @samp{F}.  The next conversion will start with the wrong
3470 data straight away.
3472   To avoid conflict, cooperative conversions do not modify the buffer,
3473 but instead specify @dfn{annotations}, a list of elements of the form
3474 @code{(@var{position} . @var{string})}, sorted in order of increasing
3475 @var{position}.
3477   If there is more than one conversion, @code{write-region} merges their
3478 annotations destructively into one sorted list.  Later, when the text
3479 from the buffer is actually written to the file, it intermixes the
3480 specified annotations at the corresponding positions.  All this takes
3481 place without modifying the buffer.
3483 @c ??? What about "overriding" conversions like those allowed
3484 @c ??? for 'write-region-annotate-functions', below?  --ttn
3486   In contrast, when reading, the annotations intermixed with the text
3487 are handled immediately.  @code{insert-file-contents} sets point to
3488 the beginning of some text to be converted, then calls the conversion
3489 functions with the length of that text.  These functions should always
3490 return with point at the beginning of the inserted text.  This
3491 approach makes sense for reading because annotations removed by the
3492 first converter can't be mistakenly processed by a later converter.
3493 Each conversion function should scan for the annotations it
3494 recognizes, remove the annotation, modify the buffer text (to set a
3495 text property, for example), and return the updated length of the
3496 text, as it stands after those changes.  The value returned by one
3497 function becomes the argument to the next function.
3499 @defvar write-region-annotate-functions
3500 A list of functions for @code{write-region} to call.  Each function in
3501 the list is called with two arguments: the start and end of the region
3502 to be written.  These functions should not alter the contents of the
3503 buffer.  Instead, they should return annotations.
3505 As a special case, a function may return with a different buffer
3506 current.  Emacs takes this to mean that the current buffer contains
3507 altered text to be output.  It therefore changes the @var{start} and
3508 @var{end} arguments of the @code{write-region} call, giving them the
3509 values of @code{point-min} and @code{point-max} in the new buffer,
3510 respectively.  It also discards all previous annotations, because they
3511 should have been dealt with by this function.
3512 @end defvar
3514 @defvar write-region-post-annotation-function
3515 The value of this variable, if non-@code{nil}, should be a function.
3516 This function is called, with no arguments, after @code{write-region}
3517 has completed.
3519 If any function in @code{write-region-annotate-functions} returns with
3520 a different buffer current, Emacs calls
3521 @code{write-region-post-annotation-function} more than once.  Emacs
3522 calls it with the last buffer that was current, and again with the
3523 buffer before that, and so on back to the original buffer.
3525 Thus, a function in @code{write-region-annotate-functions} can create
3526 a buffer, give this variable the local value of @code{kill-buffer} in
3527 that buffer, set up the buffer with altered text, and make the buffer
3528 current.  The buffer will be killed after @code{write-region} is done.
3529 @end defvar
3531 @defvar after-insert-file-functions
3532 Each function in this list is called by @code{insert-file-contents}
3533 with one argument, the number of characters inserted, and with point
3534 at the beginning of the inserted text.  Each function should leave
3535 point unchanged, and return the new character count describing the
3536 inserted text as modified by the function.
3537 @c ??? The docstring mentions a handler from 'file-name-handler-alist'
3538 @c     "intercepting" 'insert-file-contents'.  Hmmm.  --ttn
3539 @end defvar
3541   We invite users to write Lisp programs to store and retrieve text
3542 properties in files, using these hooks, and thus to experiment with
3543 various data formats and find good ones.  Eventually we hope users
3544 will produce good, general extensions we can install in Emacs.
3546   We suggest not trying to handle arbitrary Lisp objects as text property
3547 names or values---because a program that general is probably difficult
3548 to write, and slow.  Instead, choose a set of possible data types that
3549 are reasonably flexible, and not too hard to encode.