merge emacs-23
[bpt/emacs.git] / doc / lispref / files.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998, 1999, 2001,
4 @c 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
5 @c Free Software Foundation, Inc.
6 @c See the file elisp.texi for copying conditions.
7 @setfilename ../../info/files
8 @node Files, Backups and Auto-Saving, Documentation, Top
9 @comment node-name, next, previous, up
10 @chapter Files
11
12 In Emacs, you can find, create, view, save, and otherwise work with
13 files and file directories. This chapter describes most of the
14 file-related functions of Emacs Lisp, but a few others are described in
15 @ref{Buffers}, and those related to backups and auto-saving are
16 described in @ref{Backups and Auto-Saving}.
17
18 Many of the file functions take one or more arguments that are file
19 names. A file name is actually a string. Most of these functions
20 expand file name arguments by calling @code{expand-file-name}, so that
21 @file{~} is handled correctly, as are relative file names (including
22 @samp{../}). These functions don't recognize environment variable
23 substitutions such as @samp{$HOME}. @xref{File Name Expansion}.
24
25 When file I/O functions signal Lisp errors, they usually use the
26 condition @code{file-error} (@pxref{Handling Errors}). The error
27 message is in most cases obtained from the operating system, according
28 to locale @code{system-message-locale}, and decoded using coding system
29 @code{locale-coding-system} (@pxref{Locales}).
30
31 @menu
32 * Visiting Files:: Reading files into Emacs buffers for editing.
33 * Saving Buffers:: Writing changed buffers back into files.
34 * Reading from Files:: Reading files into buffers without visiting.
35 * Writing to Files:: Writing new files from parts of buffers.
36 * File Locks:: Locking and unlocking files, to prevent
37 simultaneous editing by two people.
38 * Information about Files:: Testing existence, accessibility, size of files.
39 * Changing Files:: Renaming files, changing protection, etc.
40 * File Names:: Decomposing and expanding file names.
41 * Contents of Directories:: Getting a list of the files in a directory.
42 * Create/Delete Dirs:: Creating and Deleting Directories.
43 * Magic File Names:: Defining "magic" special handling
44 for certain file names.
45 * Format Conversion:: Conversion to and from various file formats.
46 @end menu
47
48 @node Visiting Files
49 @section Visiting Files
50 @cindex finding files
51 @cindex visiting files
52
53 Visiting a file means reading a file into a buffer. Once this is
54 done, we say that the buffer is @dfn{visiting} that file, and call the
55 file ``the visited file'' of the buffer.
56
57 A file and a buffer are two different things. A file is information
58 recorded permanently in the computer (unless you delete it). A buffer,
59 on the other hand, is information inside of Emacs that will vanish at
60 the end of the editing session (or when you kill the buffer). Usually,
61 a buffer contains information that you have copied from a file; then we
62 say the buffer is visiting that file. The copy in the buffer is what
63 you modify with editing commands. Such changes to the buffer do not
64 change the file; therefore, to make the changes permanent, you must
65 @dfn{save} the buffer, which means copying the altered buffer contents
66 back into the file.
67
68 In spite of the distinction between files and buffers, people often
69 refer to a file when they mean a buffer and vice-versa. Indeed, we say,
70 ``I am editing a file,'' rather than, ``I am editing a buffer that I
71 will soon save as a file of the same name.'' Humans do not usually need
72 to make the distinction explicit. When dealing with a computer program,
73 however, it is good to keep the distinction in mind.
74
75 @menu
76 * Visiting Functions:: The usual interface functions for visiting.
77 * Subroutines of Visiting:: Lower-level subroutines that they use.
78 @end menu
79
80 @node Visiting Functions
81 @subsection Functions for Visiting Files
82
83 This section describes the functions normally used to visit files.
84 For historical reasons, these functions have names starting with
85 @samp{find-} rather than @samp{visit-}. @xref{Buffer File Name}, for
86 functions and variables that access the visited file name of a buffer or
87 that find an existing buffer by its visited file name.
88
89 In a Lisp program, if you want to look at the contents of a file but
90 not alter it, the fastest way is to use @code{insert-file-contents} in a
91 temporary buffer. Visiting the file is not necessary and takes longer.
92 @xref{Reading from Files}.
93
94 @deffn Command find-file filename &optional wildcards
95 This command selects a buffer visiting the file @var{filename},
96 using an existing buffer if there is one, and otherwise creating a
97 new buffer and reading the file into it. It also returns that buffer.
98
99 Aside from some technical details, the body of the @code{find-file}
100 function is basically equivalent to:
101
102 @smallexample
103 (switch-to-buffer (find-file-noselect filename nil nil wildcards))
104 @end smallexample
105
106 @noindent
107 (See @code{switch-to-buffer} in @ref{Displaying Buffers}.)
108
109 If @var{wildcards} is non-@code{nil}, which is always true in an
110 interactive call, then @code{find-file} expands wildcard characters in
111 @var{filename} and visits all the matching files.
112
113 When @code{find-file} is called interactively, it prompts for
114 @var{filename} in the minibuffer.
115 @end deffn
116
117 @defun find-file-noselect filename &optional nowarn rawfile wildcards
118 This function is the guts of all the file-visiting functions. It
119 returns a buffer visiting the file @var{filename}. You may make the
120 buffer current or display it in a window if you wish, but this
121 function does not do so.
122
123 The function returns an existing buffer if there is one; otherwise it
124 creates a new buffer and reads the file into it. When
125 @code{find-file-noselect} uses an existing buffer, it first verifies
126 that the file has not changed since it was last visited or saved in
127 that buffer. If the file has changed, this function asks the user
128 whether to reread the changed file. If the user says @samp{yes}, any
129 edits previously made in the buffer are lost.
130
131 Reading the file involves decoding the file's contents (@pxref{Coding
132 Systems}), including end-of-line conversion, and format conversion
133 (@pxref{Format Conversion}). If @var{wildcards} is non-@code{nil},
134 then @code{find-file-noselect} expands wildcard characters in
135 @var{filename} and visits all the matching files.
136
137 This function displays warning or advisory messages in various peculiar
138 cases, unless the optional argument @var{nowarn} is non-@code{nil}. For
139 example, if it needs to create a buffer, and there is no file named
140 @var{filename}, it displays the message @samp{(New file)} in the echo
141 area, and leaves the buffer empty.
142
143 The @code{find-file-noselect} function normally calls
144 @code{after-find-file} after reading the file (@pxref{Subroutines of
145 Visiting}). That function sets the buffer major mode, parses local
146 variables, warns the user if there exists an auto-save file more recent
147 than the file just visited, and finishes by running the functions in
148 @code{find-file-hook}.
149
150 If the optional argument @var{rawfile} is non-@code{nil}, then
151 @code{after-find-file} is not called, and the
152 @code{find-file-not-found-functions} are not run in case of failure.
153 What's more, a non-@code{nil} @var{rawfile} value suppresses coding
154 system conversion and format conversion.
155
156 The @code{find-file-noselect} function usually returns the buffer that
157 is visiting the file @var{filename}. But, if wildcards are actually
158 used and expanded, it returns a list of buffers that are visiting the
159 various files.
160
161 @example
162 @group
163 (find-file-noselect "/etc/fstab")
164 @result{} #<buffer fstab>
165 @end group
166 @end example
167 @end defun
168
169 @deffn Command find-file-other-window filename &optional wildcards
170 This command selects a buffer visiting the file @var{filename}, but
171 does so in a window other than the selected window. It may use another
172 existing window or split a window; see @ref{Displaying Buffers}.
173
174 When this command is called interactively, it prompts for
175 @var{filename}.
176 @end deffn
177
178 @deffn Command find-file-read-only filename &optional wildcards
179 This command selects a buffer visiting the file @var{filename}, like
180 @code{find-file}, but it marks the buffer as read-only. @xref{Read Only
181 Buffers}, for related functions and variables.
182
183 When this command is called interactively, it prompts for
184 @var{filename}.
185 @end deffn
186
187 @deffn Command view-file filename
188 This command visits @var{filename} using View mode, returning to the
189 previous buffer when you exit View mode. View mode is a minor mode that
190 provides commands to skim rapidly through the file, but does not let you
191 modify the text. Entering View mode runs the normal hook
192 @code{view-mode-hook}. @xref{Hooks}.
193
194 When @code{view-file} is called interactively, it prompts for
195 @var{filename}.
196 @end deffn
197
198 @defopt find-file-wildcards
199 If this variable is non-@code{nil}, then the various @code{find-file}
200 commands check for wildcard characters and visit all the files that
201 match them (when invoked interactively or when their @var{wildcards}
202 argument is non-@code{nil}). If this option is @code{nil}, then
203 the @code{find-file} commands ignore their @var{wildcards} argument
204 and never treat wildcard characters specially.
205 @end defopt
206
207 @defopt find-file-hook
208 The value of this variable is a list of functions to be called after a
209 file is visited. The file's local-variables specification (if any) will
210 have been processed before the hooks are run. The buffer visiting the
211 file is current when the hook functions are run.
212
213 This variable is a normal hook. @xref{Hooks}.
214 @end defopt
215
216 @defvar find-file-not-found-functions
217 The value of this variable is a list of functions to be called when
218 @code{find-file} or @code{find-file-noselect} is passed a nonexistent
219 file name. @code{find-file-noselect} calls these functions as soon as
220 it detects a nonexistent file. It calls them in the order of the list,
221 until one of them returns non-@code{nil}. @code{buffer-file-name} is
222 already set up.
223
224 This is not a normal hook because the values of the functions are
225 used, and in many cases only some of the functions are called.
226 @end defvar
227
228 @node Subroutines of Visiting
229 @comment node-name, next, previous, up
230 @subsection Subroutines of Visiting
231
232 The @code{find-file-noselect} function uses two important subroutines
233 which are sometimes useful in user Lisp code: @code{create-file-buffer}
234 and @code{after-find-file}. This section explains how to use them.
235
236 @defun create-file-buffer filename
237 This function creates a suitably named buffer for visiting
238 @var{filename}, and returns it. It uses @var{filename} (sans directory)
239 as the name if that name is free; otherwise, it appends a string such as
240 @samp{<2>} to get an unused name. See also @ref{Creating Buffers}.
241
242 @strong{Please note:} @code{create-file-buffer} does @emph{not}
243 associate the new buffer with a file and does not select the buffer.
244 It also does not use the default major mode.
245
246 @example
247 @group
248 (create-file-buffer "foo")
249 @result{} #<buffer foo>
250 @end group
251 @group
252 (create-file-buffer "foo")
253 @result{} #<buffer foo<2>>
254 @end group
255 @group
256 (create-file-buffer "foo")
257 @result{} #<buffer foo<3>>
258 @end group
259 @end example
260
261 This function is used by @code{find-file-noselect}.
262 It uses @code{generate-new-buffer} (@pxref{Creating Buffers}).
263 @end defun
264
265 @defun after-find-file &optional error warn noauto after-find-file-from-revert-buffer nomodes
266 This function sets the buffer major mode, and parses local variables
267 (@pxref{Auto Major Mode}). It is called by @code{find-file-noselect}
268 and by the default revert function (@pxref{Reverting}).
269
270 @cindex new file message
271 @cindex file open error
272 If reading the file got an error because the file does not exist, but
273 its directory does exist, the caller should pass a non-@code{nil} value
274 for @var{error}. In that case, @code{after-find-file} issues a warning:
275 @samp{(New file)}. For more serious errors, the caller should usually not
276 call @code{after-find-file}.
277
278 If @var{warn} is non-@code{nil}, then this function issues a warning
279 if an auto-save file exists and is more recent than the visited file.
280
281 If @var{noauto} is non-@code{nil}, that says not to enable or disable
282 Auto-Save mode. The mode remains enabled if it was enabled before.
283
284 If @var{after-find-file-from-revert-buffer} is non-@code{nil}, that
285 means this call was from @code{revert-buffer}. This has no direct
286 effect, but some mode functions and hook functions check the value
287 of this variable.
288
289 If @var{nomodes} is non-@code{nil}, that means don't alter the buffer's
290 major mode, don't process local variables specifications in the file,
291 and don't run @code{find-file-hook}. This feature is used by
292 @code{revert-buffer} in some cases.
293
294 The last thing @code{after-find-file} does is call all the functions
295 in the list @code{find-file-hook}.
296 @end defun
297
298 @node Saving Buffers
299 @section Saving Buffers
300 @cindex saving buffers
301
302 When you edit a file in Emacs, you are actually working on a buffer
303 that is visiting that file---that is, the contents of the file are
304 copied into the buffer and the copy is what you edit. Changes to the
305 buffer do not change the file until you @dfn{save} the buffer, which
306 means copying the contents of the buffer into the file.
307
308 @deffn Command save-buffer &optional backup-option
309 This function saves the contents of the current buffer in its visited
310 file if the buffer has been modified since it was last visited or saved.
311 Otherwise it does nothing.
312
313 @code{save-buffer} is responsible for making backup files. Normally,
314 @var{backup-option} is @code{nil}, and @code{save-buffer} makes a backup
315 file only if this is the first save since visiting the file. Other
316 values for @var{backup-option} request the making of backup files in
317 other circumstances:
318
319 @itemize @bullet
320 @item
321 With an argument of 4 or 64, reflecting 1 or 3 @kbd{C-u}'s, the
322 @code{save-buffer} function marks this version of the file to be
323 backed up when the buffer is next saved.
324
325 @item
326 With an argument of 16 or 64, reflecting 2 or 3 @kbd{C-u}'s, the
327 @code{save-buffer} function unconditionally backs up the previous
328 version of the file before saving it.
329
330 @item
331 With an argument of 0, unconditionally do @emph{not} make any backup file.
332 @end itemize
333 @end deffn
334
335 @deffn Command save-some-buffers &optional save-silently-p pred
336 @anchor{Definition of save-some-buffers}
337 This command saves some modified file-visiting buffers. Normally it
338 asks the user about each buffer. But if @var{save-silently-p} is
339 non-@code{nil}, it saves all the file-visiting buffers without querying
340 the user.
341
342 The optional @var{pred} argument controls which buffers to ask about
343 (or to save silently if @var{save-silently-p} is non-@code{nil}).
344 If it is @code{nil}, that means to ask only about file-visiting buffers.
345 If it is @code{t}, that means also offer to save certain other non-file
346 buffers---those that have a non-@code{nil} buffer-local value of
347 @code{buffer-offer-save} (@pxref{Killing Buffers}). A user who says
348 @samp{yes} to saving a non-file buffer is asked to specify the file
349 name to use. The @code{save-buffers-kill-emacs} function passes the
350 value @code{t} for @var{pred}.
351
352 If @var{pred} is neither @code{t} nor @code{nil}, then it should be
353 a function of no arguments. It will be called in each buffer to decide
354 whether to offer to save that buffer. If it returns a non-@code{nil}
355 value in a certain buffer, that means do offer to save that buffer.
356 @end deffn
357
358 @deffn Command write-file filename &optional confirm
359 @anchor{Definition of write-file}
360 This function writes the current buffer into file @var{filename}, makes
361 the buffer visit that file, and marks it not modified. Then it renames
362 the buffer based on @var{filename}, appending a string like @samp{<2>}
363 if necessary to make a unique buffer name. It does most of this work by
364 calling @code{set-visited-file-name} (@pxref{Buffer File Name}) and
365 @code{save-buffer}.
366
367 If @var{confirm} is non-@code{nil}, that means to ask for confirmation
368 before overwriting an existing file. Interactively, confirmation is
369 required, unless the user supplies a prefix argument.
370
371 If @var{filename} is an existing directory, or a symbolic link to one,
372 @code{write-file} uses the name of the visited file, in directory
373 @var{filename}. If the buffer is not visiting a file, it uses the
374 buffer name instead.
375 @end deffn
376
377 Saving a buffer runs several hooks. It also performs format
378 conversion (@pxref{Format Conversion}).
379
380 @defvar write-file-functions
381 The value of this variable is a list of functions to be called before
382 writing out a buffer to its visited file. If one of them returns
383 non-@code{nil}, the file is considered already written and the rest of
384 the functions are not called, nor is the usual code for writing the file
385 executed.
386
387 If a function in @code{write-file-functions} returns non-@code{nil}, it
388 is responsible for making a backup file (if that is appropriate).
389 To do so, execute the following code:
390
391 @example
392 (or buffer-backed-up (backup-buffer))
393 @end example
394
395 You might wish to save the file modes value returned by
396 @code{backup-buffer} and use that (if non-@code{nil}) to set the mode
397 bits of the file that you write. This is what @code{save-buffer}
398 normally does. @xref{Making Backups,, Making Backup Files}.
399
400 The hook functions in @code{write-file-functions} are also responsible
401 for encoding the data (if desired): they must choose a suitable coding
402 system and end-of-line conversion (@pxref{Lisp and Coding Systems}),
403 perform the encoding (@pxref{Explicit Encoding}), and set
404 @code{last-coding-system-used} to the coding system that was used
405 (@pxref{Encoding and I/O}).
406
407 If you set this hook locally in a buffer, it is assumed to be
408 associated with the file or the way the contents of the buffer were
409 obtained. Thus the variable is marked as a permanent local, so that
410 changing the major mode does not alter a buffer-local value. On the
411 other hand, calling @code{set-visited-file-name} will reset it.
412 If this is not what you want, you might like to use
413 @code{write-contents-functions} instead.
414
415 Even though this is not a normal hook, you can use @code{add-hook} and
416 @code{remove-hook} to manipulate the list. @xref{Hooks}.
417 @end defvar
418
419 @c Emacs 19 feature
420 @defvar write-contents-functions
421 This works just like @code{write-file-functions}, but it is intended
422 for hooks that pertain to the buffer's contents, not to the particular
423 visited file or its location. Such hooks are usually set up by major
424 modes, as buffer-local bindings for this variable. This variable
425 automatically becomes buffer-local whenever it is set; switching to a
426 new major mode always resets this variable, but calling
427 @code{set-visited-file-name} does not.
428
429 If any of the functions in this hook returns non-@code{nil}, the file
430 is considered already written and the rest are not called and neither
431 are the functions in @code{write-file-functions}.
432 @end defvar
433
434 @defopt before-save-hook
435 This normal hook runs before a buffer is saved in its visited file,
436 regardless of whether that is done normally or by one of the hooks
437 described above. For instance, the @file{copyright.el} program uses
438 this hook to make sure the file you are saving has the current year in
439 its copyright notice.
440 @end defopt
441
442 @c Emacs 19 feature
443 @defopt after-save-hook
444 This normal hook runs after a buffer has been saved in its visited file.
445 One use of this hook is in Fast Lock mode; it uses this hook to save the
446 highlighting information in a cache file.
447 @end defopt
448
449 @defopt file-precious-flag
450 If this variable is non-@code{nil}, then @code{save-buffer} protects
451 against I/O errors while saving by writing the new file to a temporary
452 name instead of the name it is supposed to have, and then renaming it to
453 the intended name after it is clear there are no errors. This procedure
454 prevents problems such as a lack of disk space from resulting in an
455 invalid file.
456
457 As a side effect, backups are necessarily made by copying. @xref{Rename
458 or Copy}. Yet, at the same time, saving a precious file always breaks
459 all hard links between the file you save and other file names.
460
461 Some modes give this variable a non-@code{nil} buffer-local value
462 in particular buffers.
463 @end defopt
464
465 @defopt require-final-newline
466 This variable determines whether files may be written out that do
467 @emph{not} end with a newline. If the value of the variable is
468 @code{t}, then @code{save-buffer} silently adds a newline at the end of
469 the file whenever the buffer being saved does not already end in one.
470 If the value of the variable is non-@code{nil}, but not @code{t}, then
471 @code{save-buffer} asks the user whether to add a newline each time the
472 case arises.
473
474 If the value of the variable is @code{nil}, then @code{save-buffer}
475 doesn't add newlines at all. @code{nil} is the default value, but a few
476 major modes set it to @code{t} in particular buffers.
477 @end defopt
478
479 See also the function @code{set-visited-file-name} (@pxref{Buffer File
480 Name}).
481
482 @node Reading from Files
483 @comment node-name, next, previous, up
484 @section Reading from Files
485 @cindex reading from files
486
487 You can copy a file from the disk and insert it into a buffer
488 using the @code{insert-file-contents} function. Don't use the user-level
489 command @code{insert-file} in a Lisp program, as that sets the mark.
490
491 @defun insert-file-contents filename &optional visit beg end replace
492 This function inserts the contents of file @var{filename} into the
493 current buffer after point. It returns a list of the absolute file name
494 and the length of the data inserted. An error is signaled if
495 @var{filename} is not the name of a file that can be read.
496
497 The function @code{insert-file-contents} checks the file contents
498 against the defined file formats, and converts the file contents if
499 appropriate and also calls the functions in
500 the list @code{after-insert-file-functions}. @xref{Format Conversion}.
501 Normally, one of the functions in the
502 @code{after-insert-file-functions} list determines the coding system
503 (@pxref{Coding Systems}) used for decoding the file's contents,
504 including end-of-line conversion. However, if the file contains null
505 bytes, it is by default visited without any code conversions; see
506 @ref{Lisp and Coding Systems, inhibit-null-byte-detection}, for how to
507 control this behavior.
508
509 If @var{visit} is non-@code{nil}, this function additionally marks the
510 buffer as unmodified and sets up various fields in the buffer so that it
511 is visiting the file @var{filename}: these include the buffer's visited
512 file name and its last save file modtime. This feature is used by
513 @code{find-file-noselect} and you probably should not use it yourself.
514
515 If @var{beg} and @var{end} are non-@code{nil}, they should be integers
516 specifying the portion of the file to insert. In this case, @var{visit}
517 must be @code{nil}. For example,
518
519 @example
520 (insert-file-contents filename nil 0 500)
521 @end example
522
523 @noindent
524 inserts the first 500 characters of a file.
525
526 If the argument @var{replace} is non-@code{nil}, it means to replace the
527 contents of the buffer (actually, just the accessible portion) with the
528 contents of the file. This is better than simply deleting the buffer
529 contents and inserting the whole file, because (1) it preserves some
530 marker positions and (2) it puts less data in the undo list.
531
532 It is possible to read a special file (such as a FIFO or an I/O device)
533 with @code{insert-file-contents}, as long as @var{replace} and
534 @var{visit} are @code{nil}.
535 @end defun
536
537 @defun insert-file-contents-literally filename &optional visit beg end replace
538 This function works like @code{insert-file-contents} except that it does
539 not do format decoding (@pxref{Format Conversion}), does not do
540 character code conversion (@pxref{Coding Systems}), does not run
541 @code{find-file-hook}, does not perform automatic uncompression, and so
542 on.
543 @end defun
544
545 If you want to pass a file name to another process so that another
546 program can read the file, use the function @code{file-local-copy}; see
547 @ref{Magic File Names}.
548
549 @node Writing to Files
550 @comment node-name, next, previous, up
551 @section Writing to Files
552 @cindex writing to files
553
554 You can write the contents of a buffer, or part of a buffer, directly
555 to a file on disk using the @code{append-to-file} and
556 @code{write-region} functions. Don't use these functions to write to
557 files that are being visited; that could cause confusion in the
558 mechanisms for visiting.
559
560 @deffn Command append-to-file start end filename
561 This function appends the contents of the region delimited by
562 @var{start} and @var{end} in the current buffer to the end of file
563 @var{filename}. If that file does not exist, it is created. This
564 function returns @code{nil}.
565
566 An error is signaled if @var{filename} specifies a nonwritable file,
567 or a nonexistent file in a directory where files cannot be created.
568
569 When called from Lisp, this function is completely equivalent to:
570
571 @example
572 (write-region start end filename t)
573 @end example
574 @end deffn
575
576 @deffn Command write-region start end filename &optional append visit lockname mustbenew
577 This function writes the region delimited by @var{start} and @var{end}
578 in the current buffer into the file specified by @var{filename}.
579
580 If @var{start} is @code{nil}, then the command writes the entire buffer
581 contents (@emph{not} just the accessible portion) to the file and
582 ignores @var{end}.
583
584 @c Emacs 19 feature
585 If @var{start} is a string, then @code{write-region} writes or appends
586 that string, rather than text from the buffer. @var{end} is ignored in
587 this case.
588
589 If @var{append} is non-@code{nil}, then the specified text is appended
590 to the existing file contents (if any). If @var{append} is an
591 integer, @code{write-region} seeks to that byte offset from the start
592 of the file and writes the data from there.
593
594 If @var{mustbenew} is non-@code{nil}, then @code{write-region} asks
595 for confirmation if @var{filename} names an existing file. If
596 @var{mustbenew} is the symbol @code{excl}, then @code{write-region}
597 does not ask for confirmation, but instead it signals an error
598 @code{file-already-exists} if the file already exists.
599
600 The test for an existing file, when @var{mustbenew} is @code{excl}, uses
601 a special system feature. At least for files on a local disk, there is
602 no chance that some other program could create a file of the same name
603 before Emacs does, without Emacs's noticing.
604
605 If @var{visit} is @code{t}, then Emacs establishes an association
606 between the buffer and the file: the buffer is then visiting that file.
607 It also sets the last file modification time for the current buffer to
608 @var{filename}'s modtime, and marks the buffer as not modified. This
609 feature is used by @code{save-buffer}, but you probably should not use
610 it yourself.
611
612 @c Emacs 19 feature
613 If @var{visit} is a string, it specifies the file name to visit. This
614 way, you can write the data to one file (@var{filename}) while recording
615 the buffer as visiting another file (@var{visit}). The argument
616 @var{visit} is used in the echo area message and also for file locking;
617 @var{visit} is stored in @code{buffer-file-name}. This feature is used
618 to implement @code{file-precious-flag}; don't use it yourself unless you
619 really know what you're doing.
620
621 The optional argument @var{lockname}, if non-@code{nil}, specifies the
622 file name to use for purposes of locking and unlocking, overriding
623 @var{filename} and @var{visit} for that purpose.
624
625 The function @code{write-region} converts the data which it writes to
626 the appropriate file formats specified by @code{buffer-file-format}
627 and also calls the functions in the list
628 @code{write-region-annotate-functions}.
629 @xref{Format Conversion}.
630
631 Normally, @code{write-region} displays the message @samp{Wrote
632 @var{filename}} in the echo area. If @var{visit} is neither @code{t}
633 nor @code{nil} nor a string, then this message is inhibited. This
634 feature is useful for programs that use files for internal purposes,
635 files that the user does not need to know about.
636 @end deffn
637
638 @defmac with-temp-file file body@dots{}
639 @anchor{Definition of with-temp-file}
640 The @code{with-temp-file} macro evaluates the @var{body} forms with a
641 temporary buffer as the current buffer; then, at the end, it writes the
642 buffer contents into file @var{file}. It kills the temporary buffer
643 when finished, restoring the buffer that was current before the
644 @code{with-temp-file} form. Then it returns the value of the last form
645 in @var{body}.
646
647 The current buffer is restored even in case of an abnormal exit via
648 @code{throw} or error (@pxref{Nonlocal Exits}).
649
650 See also @code{with-temp-buffer} in @ref{Definition of
651 with-temp-buffer,, The Current Buffer}.
652 @end defmac
653
654 @node File Locks
655 @section File Locks
656 @cindex file locks
657 @cindex lock file
658
659 When two users edit the same file at the same time, they are likely
660 to interfere with each other. Emacs tries to prevent this situation
661 from arising by recording a @dfn{file lock} when a file is being
662 modified. (File locks are not implemented on Microsoft systems.)
663 Emacs can then detect the first attempt to modify a buffer visiting a
664 file that is locked by another Emacs job, and ask the user what to do.
665 The file lock is really a file, a symbolic link with a special name,
666 stored in the same directory as the file you are editing.
667
668 When you access files using NFS, there may be a small probability that
669 you and another user will both lock the same file ``simultaneously.''
670 If this happens, it is possible for the two users to make changes
671 simultaneously, but Emacs will still warn the user who saves second.
672 Also, the detection of modification of a buffer visiting a file changed
673 on disk catches some cases of simultaneous editing; see
674 @ref{Modification Time}.
675
676 @defun file-locked-p filename
677 This function returns @code{nil} if the file @var{filename} is not
678 locked. It returns @code{t} if it is locked by this Emacs process, and
679 it returns the name of the user who has locked it if it is locked by
680 some other job.
681
682 @example
683 @group
684 (file-locked-p "foo")
685 @result{} nil
686 @end group
687 @end example
688 @end defun
689
690 @defun lock-buffer &optional filename
691 This function locks the file @var{filename}, if the current buffer is
692 modified. The argument @var{filename} defaults to the current buffer's
693 visited file. Nothing is done if the current buffer is not visiting a
694 file, or is not modified, or if the system does not support locking.
695 @end defun
696
697 @defun unlock-buffer
698 This function unlocks the file being visited in the current buffer,
699 if the buffer is modified. If the buffer is not modified, then
700 the file should not be locked, so this function does nothing. It also
701 does nothing if the current buffer is not visiting a file, or if the
702 system does not support locking.
703 @end defun
704
705 File locking is not supported on some systems. On systems that do not
706 support it, the functions @code{lock-buffer}, @code{unlock-buffer} and
707 @code{file-locked-p} do nothing and return @code{nil}.
708
709 @defun ask-user-about-lock file other-user
710 This function is called when the user tries to modify @var{file}, but it
711 is locked by another user named @var{other-user}. The default
712 definition of this function asks the user to say what to do. The value
713 this function returns determines what Emacs does next:
714
715 @itemize @bullet
716 @item
717 A value of @code{t} says to grab the lock on the file. Then
718 this user may edit the file and @var{other-user} loses the lock.
719
720 @item
721 A value of @code{nil} says to ignore the lock and let this
722 user edit the file anyway.
723
724 @item
725 @kindex file-locked
726 This function may instead signal a @code{file-locked} error, in which
727 case the change that the user was about to make does not take place.
728
729 The error message for this error looks like this:
730
731 @example
732 @error{} File is locked: @var{file} @var{other-user}
733 @end example
734
735 @noindent
736 where @code{file} is the name of the file and @var{other-user} is the
737 name of the user who has locked the file.
738 @end itemize
739
740 If you wish, you can replace the @code{ask-user-about-lock} function
741 with your own version that makes the decision in another way. The code
742 for its usual definition is in @file{userlock.el}.
743 @end defun
744
745 @node Information about Files
746 @section Information about Files
747 @cindex file, information about
748
749 The functions described in this section all operate on strings that
750 designate file names. With a few exceptions, all the functions have
751 names that begin with the word @samp{file}. These functions all
752 return information about actual files or directories, so their
753 arguments must all exist as actual files or directories unless
754 otherwise noted.
755
756 @menu
757 * Testing Accessibility:: Is a given file readable? Writable?
758 * Kinds of Files:: Is it a directory? A symbolic link?
759 * Truenames:: Eliminating symbolic links from a file name.
760 * File Attributes:: How large is it? Any other names? Etc.
761 * Locating Files:: How to find a file in standard places.
762 @end menu
763
764 @node Testing Accessibility
765 @comment node-name, next, previous, up
766 @subsection Testing Accessibility
767 @cindex accessibility of a file
768 @cindex file accessibility
769
770 These functions test for permission to access a file in specific
771 ways. Unless explicitly stated otherwise, they recursively follow
772 symbolic links for their file name arguments, at all levels (at the
773 level of the file itself and at all levels of parent directories).
774
775 @defun file-exists-p filename
776 This function returns @code{t} if a file named @var{filename} appears
777 to exist. This does not mean you can necessarily read the file, only
778 that you can find out its attributes. (On Unix and GNU/Linux, this is
779 true if the file exists and you have execute permission on the
780 containing directories, regardless of the protection of the file
781 itself.)
782
783 If the file does not exist, or if fascist access control policies
784 prevent you from finding the attributes of the file, this function
785 returns @code{nil}.
786
787 Directories are files, so @code{file-exists-p} returns @code{t} when
788 given a directory name. However, symbolic links are treated
789 specially; @code{file-exists-p} returns @code{t} for a symbolic link
790 name only if the target file exists.
791 @end defun
792
793 @defun file-readable-p filename
794 This function returns @code{t} if a file named @var{filename} exists
795 and you can read it. It returns @code{nil} otherwise.
796
797 @example
798 @group
799 (file-readable-p "files.texi")
800 @result{} t
801 @end group
802 @group
803 (file-exists-p "/usr/spool/mqueue")
804 @result{} t
805 @end group
806 @group
807 (file-readable-p "/usr/spool/mqueue")
808 @result{} nil
809 @end group
810 @end example
811 @end defun
812
813 @c Emacs 19 feature
814 @defun file-executable-p filename
815 This function returns @code{t} if a file named @var{filename} exists and
816 you can execute it. It returns @code{nil} otherwise. On Unix and
817 GNU/Linux, if the file is a directory, execute permission means you can
818 check the existence and attributes of files inside the directory, and
819 open those files if their modes permit.
820 @end defun
821
822 @defun file-writable-p filename
823 This function returns @code{t} if the file @var{filename} can be written
824 or created by you, and @code{nil} otherwise. A file is writable if the
825 file exists and you can write it. It is creatable if it does not exist,
826 but the specified directory does exist and you can write in that
827 directory.
828
829 In the third example below, @file{foo} is not writable because the
830 parent directory does not exist, even though the user could create such
831 a directory.
832
833 @example
834 @group
835 (file-writable-p "~/foo")
836 @result{} t
837 @end group
838 @group
839 (file-writable-p "/foo")
840 @result{} nil
841 @end group
842 @group
843 (file-writable-p "~/no-such-dir/foo")
844 @result{} nil
845 @end group
846 @end example
847 @end defun
848
849 @c Emacs 19 feature
850 @defun file-accessible-directory-p dirname
851 This function returns @code{t} if you have permission to open existing
852 files in the directory whose name as a file is @var{dirname};
853 otherwise (or if there is no such directory), it returns @code{nil}.
854 The value of @var{dirname} may be either a directory name (such as
855 @file{/foo/}) or the file name of a file which is a directory
856 (such as @file{/foo}, without the final slash).
857
858 Example: after the following,
859
860 @example
861 (file-accessible-directory-p "/foo")
862 @result{} nil
863 @end example
864
865 @noindent
866 we can deduce that any attempt to read a file in @file{/foo/} will
867 give an error.
868 @end defun
869
870 @defun access-file filename string
871 This function opens file @var{filename} for reading, then closes it and
872 returns @code{nil}. However, if the open fails, it signals an error
873 using @var{string} as the error message text.
874 @end defun
875
876 @defun file-ownership-preserved-p filename
877 This function returns @code{t} if deleting the file @var{filename} and
878 then creating it anew would keep the file's owner unchanged. It also
879 returns @code{t} for nonexistent files.
880
881 If @var{filename} is a symbolic link, then, unlike the other functions
882 discussed here, @code{file-ownership-preserved-p} does @emph{not}
883 replace @var{filename} with its target. However, it does recursively
884 follow symbolic links at all levels of parent directories.
885 @end defun
886
887 @defun file-newer-than-file-p filename1 filename2
888 @cindex file age
889 @cindex file modification time
890 This function returns @code{t} if the file @var{filename1} is
891 newer than file @var{filename2}. If @var{filename1} does not
892 exist, it returns @code{nil}. If @var{filename1} does exist, but
893 @var{filename2} does not, it returns @code{t}.
894
895 In the following example, assume that the file @file{aug-19} was written
896 on the 19th, @file{aug-20} was written on the 20th, and the file
897 @file{no-file} doesn't exist at all.
898
899 @example
900 @group
901 (file-newer-than-file-p "aug-19" "aug-20")
902 @result{} nil
903 @end group
904 @group
905 (file-newer-than-file-p "aug-20" "aug-19")
906 @result{} t
907 @end group
908 @group
909 (file-newer-than-file-p "aug-19" "no-file")
910 @result{} t
911 @end group
912 @group
913 (file-newer-than-file-p "no-file" "aug-19")
914 @result{} nil
915 @end group
916 @end example
917
918 You can use @code{file-attributes} to get a file's last modification
919 time as a list of two numbers. @xref{File Attributes}.
920 @end defun
921
922 @node Kinds of Files
923 @comment node-name, next, previous, up
924 @subsection Distinguishing Kinds of Files
925
926 This section describes how to distinguish various kinds of files, such
927 as directories, symbolic links, and ordinary files.
928
929 @defun file-symlink-p filename
930 @cindex file symbolic links
931 If the file @var{filename} is a symbolic link, the
932 @code{file-symlink-p} function returns the (non-recursive) link target
933 as a string. (Determining the file name that the link points to from
934 the target is nontrivial.) First, this function recursively follows
935 symbolic links at all levels of parent directories.
936
937 If the file @var{filename} is not a symbolic link (or there is no such file),
938 @code{file-symlink-p} returns @code{nil}.
939
940 @example
941 @group
942 (file-symlink-p "foo")
943 @result{} nil
944 @end group
945 @group
946 (file-symlink-p "sym-link")
947 @result{} "foo"
948 @end group
949 @group
950 (file-symlink-p "sym-link2")
951 @result{} "sym-link"
952 @end group
953 @group
954 (file-symlink-p "/bin")
955 @result{} "/pub/bin"
956 @end group
957 @end example
958
959 @c !!! file-symlink-p: should show output of ls -l for comparison
960 @end defun
961
962 The next two functions recursively follow symbolic links at
963 all levels for @var{filename}.
964
965 @defun file-directory-p filename
966 This function returns @code{t} if @var{filename} is the name of an
967 existing directory, @code{nil} otherwise.
968
969 @example
970 @group
971 (file-directory-p "~rms")
972 @result{} t
973 @end group
974 @group
975 (file-directory-p "~rms/lewis/files.texi")
976 @result{} nil
977 @end group
978 @group
979 (file-directory-p "~rms/lewis/no-such-file")
980 @result{} nil
981 @end group
982 @group
983 (file-directory-p "$HOME")
984 @result{} nil
985 @end group
986 @group
987 (file-directory-p
988 (substitute-in-file-name "$HOME"))
989 @result{} t
990 @end group
991 @end example
992 @end defun
993
994 @defun file-regular-p filename
995 This function returns @code{t} if the file @var{filename} exists and is
996 a regular file (not a directory, named pipe, terminal, or
997 other I/O device).
998 @end defun
999
1000 @node Truenames
1001 @subsection Truenames
1002 @cindex truename (of file)
1003
1004 @c Emacs 19 features
1005 The @dfn{truename} of a file is the name that you get by following
1006 symbolic links at all levels until none remain, then simplifying away
1007 @samp{.}@: and @samp{..}@: appearing as name components. This results
1008 in a sort of canonical name for the file. A file does not always have a
1009 unique truename; the number of distinct truenames a file has is equal to
1010 the number of hard links to the file. However, truenames are useful
1011 because they eliminate symbolic links as a cause of name variation.
1012
1013 @defun file-truename filename
1014 The function @code{file-truename} returns the truename of the file
1015 @var{filename}. The argument must be an absolute file name.
1016
1017 This function does not expand environment variables. Only
1018 @code{substitute-in-file-name} does that. @xref{Definition of
1019 substitute-in-file-name}.
1020
1021 If you may need to follow symbolic links preceding @samp{..}@:
1022 appearing as a name component, you should make sure to call
1023 @code{file-truename} without prior direct or indirect calls to
1024 @code{expand-file-name}, as otherwise the file name component
1025 immediately preceding @samp{..} will be ``simplified away'' before
1026 @code{file-truename} is called. To eliminate the need for a call to
1027 @code{expand-file-name}, @code{file-truename} handles @samp{~} in the
1028 same way that @code{expand-file-name} does. @xref{File Name
1029 Expansion,, Functions that Expand Filenames}.
1030 @end defun
1031
1032 @defun file-chase-links filename &optional limit
1033 This function follows symbolic links, starting with @var{filename},
1034 until it finds a file name which is not the name of a symbolic link.
1035 Then it returns that file name. This function does @emph{not} follow
1036 symbolic links at the level of parent directories.
1037
1038 If you specify a number for @var{limit}, then after chasing through
1039 that many links, the function just returns what it has even if that is
1040 still a symbolic link.
1041 @end defun
1042
1043 To illustrate the difference between @code{file-chase-links} and
1044 @code{file-truename}, suppose that @file{/usr/foo} is a symbolic link to
1045 the directory @file{/home/foo}, and @file{/home/foo/hello} is an
1046 ordinary file (or at least, not a symbolic link) or nonexistent. Then
1047 we would have:
1048
1049 @example
1050 (file-chase-links "/usr/foo/hello")
1051 ;; @r{This does not follow the links in the parent directories.}
1052 @result{} "/usr/foo/hello"
1053 (file-truename "/usr/foo/hello")
1054 ;; @r{Assuming that @file{/home} is not a symbolic link.}
1055 @result{} "/home/foo/hello"
1056 @end example
1057
1058 @xref{Buffer File Name}, for related information.
1059
1060 @node File Attributes
1061 @comment node-name, next, previous, up
1062 @subsection Other Information about Files
1063
1064 This section describes the functions for getting detailed information
1065 about a file, other than its contents. This information includes the
1066 mode bits that control access permission, the owner and group numbers,
1067 the number of names, the inode number, the size, and the times of access
1068 and modification.
1069
1070 @defun file-modes filename
1071 @cindex permission
1072 @cindex file attributes
1073 This function returns the mode bits of @var{filename}, as an integer.
1074 The mode bits are also called the file permissions, and they specify
1075 access control in the usual Unix fashion. If the low-order bit is 1,
1076 then the file is executable by all users, if the second-lowest-order bit
1077 is 1, then the file is writable by all users, etc.
1078
1079 The highest value returnable is 4095 (7777 octal), meaning that
1080 everyone has read, write, and execute permission, that the @acronym{SUID} bit
1081 is set for both others and group, and that the sticky bit is set.
1082
1083 If @var{filename} does not exist, @code{file-modes} returns @code{nil}.
1084
1085 This function recursively follows symbolic links at all levels.
1086
1087 @example
1088 @group
1089 (file-modes "~/junk/diffs")
1090 @result{} 492 ; @r{Decimal integer.}
1091 @end group
1092 @group
1093 (format "%o" 492)
1094 @result{} "754" ; @r{Convert to octal.}
1095 @end group
1096
1097 @group
1098 (set-file-modes "~/junk/diffs" 438)
1099 @result{} nil
1100 @end group
1101
1102 @group
1103 (format "%o" 438)
1104 @result{} "666" ; @r{Convert to octal.}
1105 @end group
1106
1107 @group
1108 % ls -l diffs
1109 -rw-rw-rw- 1 lewis 0 3063 Oct 30 16:00 diffs
1110 @end group
1111 @end example
1112 @end defun
1113
1114 If the @var{filename} argument to the next two functions is a symbolic
1115 link, then these function do @emph{not} replace it with its target.
1116 However, they both recursively follow symbolic links at all levels of
1117 parent directories.
1118
1119 @defun file-nlinks filename
1120 This functions returns the number of names (i.e., hard links) that
1121 file @var{filename} has. If the file does not exist, then this function
1122 returns @code{nil}. Note that symbolic links have no effect on this
1123 function, because they are not considered to be names of the files they
1124 link to.
1125
1126 @example
1127 @group
1128 % ls -l foo*
1129 -rw-rw-rw- 2 rms 4 Aug 19 01:27 foo
1130 -rw-rw-rw- 2 rms 4 Aug 19 01:27 foo1
1131 @end group
1132
1133 @group
1134 (file-nlinks "foo")
1135 @result{} 2
1136 @end group
1137 @group
1138 (file-nlinks "doesnt-exist")
1139 @result{} nil
1140 @end group
1141 @end example
1142 @end defun
1143
1144 @defun file-attributes filename &optional id-format
1145 @anchor{Definition of file-attributes}
1146 This function returns a list of attributes of file @var{filename}. If
1147 the specified file cannot be opened, it returns @code{nil}.
1148 The optional parameter @var{id-format} specifies the preferred format
1149 of attributes @acronym{UID} and @acronym{GID} (see below)---the
1150 valid values are @code{'string} and @code{'integer}. The latter is
1151 the default, but we plan to change that, so you should specify a
1152 non-@code{nil} value for @var{id-format} if you use the returned
1153 @acronym{UID} or @acronym{GID}.
1154
1155 The elements of the list, in order, are:
1156
1157 @enumerate 0
1158 @item
1159 @code{t} for a directory, a string for a symbolic link (the name
1160 linked to), or @code{nil} for a text file.
1161
1162 @c Wordy so as to prevent an overfull hbox. --rjc 15mar92
1163 @item
1164 The number of names the file has. Alternate names, also known as hard
1165 links, can be created by using the @code{add-name-to-file} function
1166 (@pxref{Changing Files}).
1167
1168 @item
1169 The file's @acronym{UID}, normally as a string. However, if it does
1170 not correspond to a named user, the value is an integer or a floating
1171 point number.
1172
1173 @item
1174 The file's @acronym{GID}, likewise.
1175
1176 @item
1177 The time of last access, as a list of two integers.
1178 The first integer has the high-order 16 bits of time,
1179 the second has the low 16 bits. (This is similar to the
1180 value of @code{current-time}; see @ref{Time of Day}.) Note that on
1181 some FAT-based filesystems, only the date of last access is recorded,
1182 so this time will always hold the midnight of the day of last access.
1183
1184 @cindex modification time of file
1185 @item
1186 The time of last modification as a list of two integers (as above).
1187 This is the last time when the file's contents were modified.
1188
1189 @item
1190 The time of last status change as a list of two integers (as above).
1191 This is the time of the last change to the file's access mode bits,
1192 its owner and group, and other information recorded in the filesystem
1193 for the file, beyond the file's contents.
1194
1195 @item
1196 The size of the file in bytes. If the size is too large to fit in a
1197 Lisp integer, this is a floating point number.
1198
1199 @item
1200 The file's modes, as a string of ten letters or dashes,
1201 as in @samp{ls -l}.
1202
1203 @item
1204 @code{t} if the file's @acronym{GID} would change if file were
1205 deleted and recreated; @code{nil} otherwise.
1206
1207 @item
1208 The file's inode number. If possible, this is an integer. If the
1209 inode number is too large to be represented as an integer in Emacs
1210 Lisp, but still fits into a 32-bit integer, then the value has the
1211 form @code{(@var{high} . @var{low})}, where @var{low} holds the low 16
1212 bits. If the inode is wider than 32 bits, the value is of the form
1213 @code{(@var{high} @var{middle} . @var{low})}, where @code{high} holds
1214 the high 24 bits, @var{middle} the next 24 bits, and @var{low} the low
1215 16 bits.
1216
1217 @item
1218 The filesystem number of the device that the file is on. Depending on
1219 the magnitude of the value, this can be either an integer or a cons
1220 cell, in the same manner as the inode number. This element and the
1221 file's inode number together give enough information to distinguish
1222 any two files on the system---no two files can have the same values
1223 for both of these numbers.
1224 @end enumerate
1225
1226 For example, here are the file attributes for @file{files.texi}:
1227
1228 @example
1229 @group
1230 (file-attributes "files.texi" 'string)
1231 @result{} (nil 1 "lh" "users"
1232 (19145 42977)
1233 (19141 59576)
1234 (18340 17300)
1235 122295 "-rw-rw-rw-"
1236 nil (5888 2 . 43978)
1237 (15479 . 46724))
1238 @end group
1239 @end example
1240
1241 @noindent
1242 and here is how the result is interpreted:
1243
1244 @table @code
1245 @item nil
1246 is neither a directory nor a symbolic link.
1247
1248 @item 1
1249 has only one name (the name @file{files.texi} in the current default
1250 directory).
1251
1252 @item "lh"
1253 is owned by the user with name "lh".
1254
1255 @item "users"
1256 is in the group with name "users".
1257
1258 @item (19145 42977)
1259 was last accessed on Oct 5 2009, at 10:01:37.
1260
1261 @item (19141 59576)
1262 last had its contents modified on Oct 2 2009, at 13:49:12.
1263
1264 @item (18340 17300)
1265 last had its status changed on Feb 2 2008, at 12:19:00.
1266
1267 @item 122295
1268 is 122295 bytes long. (It may not contain 122295 characters, though,
1269 if some of the bytes belong to multibyte sequences, and also if the
1270 end-of-line format is CR-LF.)
1271
1272 @item "-rw-rw-rw-"
1273 has a mode of read and write access for the owner, group, and world.
1274
1275 @item nil
1276 would retain the same @acronym{GID} if it were recreated.
1277
1278 @item (5888 2 . 43978)
1279 has an inode number of 6473924464520138.
1280
1281 @item (15479 . 46724)
1282 is on the file-system device whose number is 1014478468.
1283 @end table
1284 @end defun
1285
1286 @cindex MS-DOS and file modes
1287 @cindex file modes and MS-DOS
1288 On MS-DOS, there is no such thing as an ``executable'' file mode bit.
1289 So Emacs considers a file executable if its name ends in one of the
1290 standard executable extensions, such as @file{.com}, @file{.bat},
1291 @file{.exe}, and some others. Files that begin with the Unix-standard
1292 @samp{#!} signature, such as shell and Perl scripts, are also considered
1293 as executable files. This is reflected in the values returned by
1294 @code{file-modes} and @code{file-attributes}. Directories are also
1295 reported with executable bit set, for compatibility with Unix.
1296
1297 @node Locating Files
1298 @subsection How to Locate Files in Standard Places
1299 @cindex locate file in path
1300 @cindex find file in path
1301
1302 This section explains how to search for a file in a list of
1303 directories (a @dfn{path}). One example is when you need to look for
1304 a program's executable file, e.g., to find out whether a given program
1305 is installed on the user's system. Another example is the search for
1306 Lisp libraries (@pxref{Library Search}). Such searches generally need
1307 to try various possible file name extensions, in addition to various
1308 possible directories. Emacs provides a function for such a
1309 generalized search for a file.
1310
1311 @defun locate-file filename path &optional suffixes predicate
1312 This function searches for a file whose name is @var{filename} in a
1313 list of directories given by @var{path}, trying the suffixes in
1314 @var{suffixes}. If it finds such a file, it returns the full
1315 @dfn{absolute file name} of the file (@pxref{Relative File Names});
1316 otherwise it returns @code{nil}.
1317
1318 The optional argument @var{suffixes} gives the list of file-name
1319 suffixes to append to @var{filename} when searching.
1320 @code{locate-file} tries each possible directory with each of these
1321 suffixes. If @var{suffixes} is @code{nil}, or @code{("")}, then there
1322 are no suffixes, and @var{filename} is used only as-is. Typical
1323 values of @var{suffixes} are @code{exec-suffixes} (@pxref{Subprocess
1324 Creation, exec-suffixes}), @code{load-suffixes},
1325 @code{load-file-rep-suffixes} and the return value of the function
1326 @code{get-load-suffixes} (@pxref{Load Suffixes}).
1327
1328 Typical values for @var{path} are @code{exec-path} (@pxref{Subprocess
1329 Creation, exec-path}) when looking for executable programs or
1330 @code{load-path} (@pxref{Library Search, load-path}) when looking for
1331 Lisp files. If @var{filename} is absolute, @var{path} has no effect,
1332 but the suffixes in @var{suffixes} are still tried.
1333
1334 The optional argument @var{predicate}, if non-@code{nil}, specifies
1335 the predicate function to use for testing whether a candidate file is
1336 suitable. The predicate function is passed the candidate file name as
1337 its single argument. If @var{predicate} is @code{nil} or unspecified,
1338 @code{locate-file} uses @code{file-readable-p} as the default
1339 predicate. Useful non-default predicates include
1340 @code{file-executable-p}, @code{file-directory-p}, and other
1341 predicates described in @ref{Kinds of Files}.
1342
1343 For compatibility, @var{predicate} can also be one of the symbols
1344 @code{executable}, @code{readable}, @code{writable}, @code{exists}, or
1345 a list of one or more of these symbols.
1346 @end defun
1347
1348 @defun executable-find program
1349 This function searches for the executable file of the named
1350 @var{program} and returns the full absolute name of the executable,
1351 including its file-name extensions, if any. It returns @code{nil} if
1352 the file is not found. The functions searches in all the directories
1353 in @code{exec-path} and tries all the file-name extensions in
1354 @code{exec-suffixes}.
1355 @end defun
1356
1357 @node Changing Files
1358 @section Changing File Names and Attributes
1359 @c @cindex renaming files Duplicates rename-file
1360 @cindex copying files
1361 @cindex deleting files
1362 @cindex linking files
1363 @cindex setting modes of files
1364
1365 The functions in this section rename, copy, delete, link, and set the
1366 modes of files.
1367
1368 In the functions that have an argument @var{newname}, if a file by the
1369 name of @var{newname} already exists, the actions taken depend on the
1370 value of the argument @var{ok-if-already-exists}:
1371
1372 @itemize @bullet
1373 @item
1374 Signal a @code{file-already-exists} error if
1375 @var{ok-if-already-exists} is @code{nil}.
1376
1377 @item
1378 Request confirmation if @var{ok-if-already-exists} is a number.
1379
1380 @item
1381 Replace the old file without confirmation if @var{ok-if-already-exists}
1382 is any other value.
1383 @end itemize
1384
1385 The next four commands all recursively follow symbolic links at all
1386 levels of parent directories for their first argument, but, if that
1387 argument is itself a symbolic link, then only @code{copy-file}
1388 replaces it with its (recursive) target.
1389
1390 @deffn Command add-name-to-file oldname newname &optional ok-if-already-exists
1391 @cindex file with multiple names
1392 @cindex file hard link
1393 This function gives the file named @var{oldname} the additional name
1394 @var{newname}. This means that @var{newname} becomes a new ``hard
1395 link'' to @var{oldname}.
1396
1397 In the first part of the following example, we list two files,
1398 @file{foo} and @file{foo3}.
1399
1400 @example
1401 @group
1402 % ls -li fo*
1403 81908 -rw-rw-rw- 1 rms 29 Aug 18 20:32 foo
1404 84302 -rw-rw-rw- 1 rms 24 Aug 18 20:31 foo3
1405 @end group
1406 @end example
1407
1408 Now we create a hard link, by calling @code{add-name-to-file}, then list
1409 the files again. This shows two names for one file, @file{foo} and
1410 @file{foo2}.
1411
1412 @example
1413 @group
1414 (add-name-to-file "foo" "foo2")
1415 @result{} nil
1416 @end group
1417
1418 @group
1419 % ls -li fo*
1420 81908 -rw-rw-rw- 2 rms 29 Aug 18 20:32 foo
1421 81908 -rw-rw-rw- 2 rms 29 Aug 18 20:32 foo2
1422 84302 -rw-rw-rw- 1 rms 24 Aug 18 20:31 foo3
1423 @end group
1424 @end example
1425
1426 Finally, we evaluate the following:
1427
1428 @example
1429 (add-name-to-file "foo" "foo3" t)
1430 @end example
1431
1432 @noindent
1433 and list the files again. Now there are three names
1434 for one file: @file{foo}, @file{foo2}, and @file{foo3}. The old
1435 contents of @file{foo3} are lost.
1436
1437 @example
1438 @group
1439 (add-name-to-file "foo1" "foo3")
1440 @result{} nil
1441 @end group
1442
1443 @group
1444 % ls -li fo*
1445 81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo
1446 81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo2
1447 81908 -rw-rw-rw- 3 rms 29 Aug 18 20:32 foo3
1448 @end group
1449 @end example
1450
1451 This function is meaningless on operating systems where multiple names
1452 for one file are not allowed. Some systems implement multiple names
1453 by copying the file instead.
1454
1455 See also @code{file-nlinks} in @ref{File Attributes}.
1456 @end deffn
1457
1458 @deffn Command rename-file filename newname &optional ok-if-already-exists
1459 This command renames the file @var{filename} as @var{newname}.
1460
1461 If @var{filename} has additional names aside from @var{filename}, it
1462 continues to have those names. In fact, adding the name @var{newname}
1463 with @code{add-name-to-file} and then deleting @var{filename} has the
1464 same effect as renaming, aside from momentary intermediate states.
1465 @end deffn
1466
1467 @deffn Command copy-file oldname newname &optional ok-if-exists time preserve-uid-gid
1468 This command copies the file @var{oldname} to @var{newname}. An
1469 error is signaled if @var{oldname} does not exist. If @var{newname}
1470 names a directory, it copies @var{oldname} into that directory,
1471 preserving its final name component.
1472
1473 If @var{time} is non-@code{nil}, then this function gives the new file
1474 the same last-modified time that the old one has. (This works on only
1475 some operating systems.) If setting the time gets an error,
1476 @code{copy-file} signals a @code{file-date-error} error. In an
1477 interactive call, a prefix argument specifies a non-@code{nil} value
1478 for @var{time}.
1479
1480 This function copies the file modes, too.
1481
1482 If argument @var{preserve-uid-gid} is @code{nil}, we let the operating
1483 system decide the user and group ownership of the new file (this is
1484 usually set to the user running Emacs). If @var{preserve-uid-gid} is
1485 non-@code{nil}, we attempt to copy the user and group ownership of the
1486 file. This works only on some operating systems, and only if you have
1487 the correct permissions to do so.
1488 @end deffn
1489
1490 @deffn Command make-symbolic-link filename newname &optional ok-if-exists
1491 @pindex ln
1492 @kindex file-already-exists
1493 This command makes a symbolic link to @var{filename}, named
1494 @var{newname}. This is like the shell command @samp{ln -s
1495 @var{filename} @var{newname}}.
1496
1497 This function is not available on systems that don't support symbolic
1498 links.
1499 @end deffn
1500
1501 @deffn Command delete-file filename
1502 @pindex rm
1503 This command deletes the file @var{filename}, like the shell command
1504 @samp{rm @var{filename}}. If the file has multiple names, it continues
1505 to exist under the other names.
1506
1507 A suitable kind of @code{file-error} error is signaled if the file does
1508 not exist, or is not deletable. (On Unix and GNU/Linux, a file is
1509 deletable if its directory is writable.)
1510
1511 If @var{filename} is a symbolic link, @code{delete-file} does not
1512 replace it with its target, but it does follow symbolic links at all
1513 levels of parent directories.
1514
1515 See also @code{delete-directory} in @ref{Create/Delete Dirs}.
1516 @end deffn
1517
1518 @deffn Command set-file-modes filename mode
1519 This function sets mode bits of @var{filename} to @var{mode} (which
1520 must be an integer when the function is called non-interactively).
1521 Only the low 12 bits of @var{mode} are used.
1522
1523 Interactively, @var{mode} is read from the minibuffer using
1524 @code{read-file-modes}, which accepts mode bits either as a number or
1525 as a character string representing the mode bits symbolically. See
1526 the description of @code{read-file-modes} below for the supported
1527 forms of symbolic notation for mode bits.
1528
1529 This function recursively follows symbolic links at all levels for
1530 @var{filename}.
1531 @end deffn
1532
1533 @c Emacs 19 feature
1534 @defun set-default-file-modes mode
1535 @cindex umask
1536 This function sets the default file protection for new files created by
1537 Emacs and its subprocesses. Every file created with Emacs initially has
1538 this protection, or a subset of it (@code{write-region} will not give a
1539 file execute permission even if the default file protection allows
1540 execute permission). On Unix and GNU/Linux, the default protection is
1541 the bitwise complement of the ``umask'' value.
1542
1543 The argument @var{mode} must be an integer. On most systems, only the
1544 low 9 bits of @var{mode} are meaningful. You can use the Lisp construct
1545 for octal character codes to enter @var{mode}; for example,
1546
1547 @example
1548 (set-default-file-modes ?\644)
1549 @end example
1550
1551 Saving a modified version of an existing file does not count as creating
1552 the file; it preserves the existing file's mode, whatever that is. So
1553 the default file protection has no effect.
1554 @end defun
1555
1556 @defun default-file-modes
1557 This function returns the current default protection value.
1558 @end defun
1559
1560 @defun read-file-modes &optional prompt base-file
1561 This function reads file mode bits from the minibuffer. The optional
1562 argument @var{prompt} specifies a non-default prompt. Second optional
1563 argument @var{base-file} is the name of a file on whose permissions to
1564 base the mode bits that this function returns, if what the user types
1565 specifies mode bits relative to permissions of an existing file.
1566
1567 If user input represents an octal number, this function returns that
1568 number. If it is a complete symbolic specification of mode bits, as
1569 in @code{"u=rwx"}, the function converts it to the equivalent numeric
1570 value using @code{file-modes-symbolic-to-number} and returns the
1571 result. If the specification is relative, as in @code{"o+g"}, then
1572 the permissions on which the specification is based are taken from the
1573 mode bits of @var{base-file}. If @var{base-file} is omitted or
1574 @code{nil}, the function uses @code{0} as the base mode bits. The
1575 complete and relative specifications can be combined, as in
1576 @code{"u+r,g+rx,o+r,g-w"}. @xref{File Permissions,,, coreutils, The
1577 @sc{gnu} @code{Coreutils} Manual}, for detailed description of
1578 symbolic mode bits specifications.
1579 @end defun
1580
1581 @defun file-modes-symbolic-to-number modes &optional base-modes
1582 This subroutine converts a symbolic specification of file mode bits in
1583 @var{modes} into the equivalent numeric value. If the symbolic
1584 specification is based on an existing file, that file's mode bits are
1585 taken from the optional argument @var{base-modes}; if that argument is
1586 omitted or @code{nil}, it defaults to zero, i.e.@: no access rights at
1587 all.
1588 @end defun
1589
1590 @defun set-file-times filename &optional time
1591 This function sets the access and modification times of @var{filename}
1592 to @var{time}. The return value is @code{t} if the times are successfully
1593 set, otherwise it is @code{nil}. @var{time} defaults to the current
1594 time and must be in the format returned by @code{current-time}
1595 (@pxref{Time of Day}).
1596 @end defun
1597
1598 @node File Names
1599 @section File Names
1600 @cindex file names
1601
1602 Files are generally referred to by their names, in Emacs as elsewhere.
1603 File names in Emacs are represented as strings. The functions that
1604 operate on a file all expect a file name argument.
1605
1606 In addition to operating on files themselves, Emacs Lisp programs
1607 often need to operate on file names; i.e., to take them apart and to use
1608 part of a name to construct related file names. This section describes
1609 how to manipulate file names.
1610
1611 The functions in this section do not actually access files, so they
1612 can operate on file names that do not refer to an existing file or
1613 directory.
1614
1615 On MS-DOS and MS-Windows, these functions (like the function that
1616 actually operate on files) accept MS-DOS or MS-Windows file-name syntax,
1617 where backslashes separate the components, as well as Unix syntax; but
1618 they always return Unix syntax. This enables Lisp programs to specify
1619 file names in Unix syntax and work properly on all systems without
1620 change.
1621
1622 @menu
1623 * File Name Components:: The directory part of a file name, and the rest.
1624 * Relative File Names:: Some file names are relative to a current directory.
1625 * Directory Names:: A directory's name as a directory
1626 is different from its name as a file.
1627 * File Name Expansion:: Converting relative file names to absolute ones.
1628 * Unique File Names:: Generating names for temporary files.
1629 * File Name Completion:: Finding the completions for a given file name.
1630 * Standard File Names:: If your package uses a fixed file name,
1631 how to handle various operating systems simply.
1632 @end menu
1633
1634 @node File Name Components
1635 @subsection File Name Components
1636 @cindex directory part (of file name)
1637 @cindex nondirectory part (of file name)
1638 @cindex version number (in file name)
1639
1640 The operating system groups files into directories. To specify a
1641 file, you must specify the directory and the file's name within that
1642 directory. Therefore, Emacs considers a file name as having two main
1643 parts: the @dfn{directory name} part, and the @dfn{nondirectory} part
1644 (or @dfn{file name within the directory}). Either part may be empty.
1645 Concatenating these two parts reproduces the original file name.
1646
1647 On most systems, the directory part is everything up to and including
1648 the last slash (backslash is also allowed in input on MS-DOS or
1649 MS-Windows); the nondirectory part is the rest.
1650
1651 For some purposes, the nondirectory part is further subdivided into
1652 the name proper and the @dfn{version number}. On most systems, only
1653 backup files have version numbers in their names.
1654
1655 @defun file-name-directory filename
1656 This function returns the directory part of @var{filename}, as a
1657 directory name (@pxref{Directory Names}), or @code{nil} if
1658 @var{filename} does not include a directory part.
1659
1660 On GNU and Unix systems, a string returned by this function always
1661 ends in a slash. On MS-DOS it can also end in a colon.
1662
1663 @example
1664 @group
1665 (file-name-directory "lewis/foo") ; @r{Unix example}
1666 @result{} "lewis/"
1667 @end group
1668 @group
1669 (file-name-directory "foo") ; @r{Unix example}
1670 @result{} nil
1671 @end group
1672 @end example
1673 @end defun
1674
1675 @defun file-name-nondirectory filename
1676 This function returns the nondirectory part of @var{filename}.
1677
1678 @example
1679 @group
1680 (file-name-nondirectory "lewis/foo")
1681 @result{} "foo"
1682 @end group
1683 @group
1684 (file-name-nondirectory "foo")
1685 @result{} "foo"
1686 @end group
1687 @group
1688 (file-name-nondirectory "lewis/")
1689 @result{} ""
1690 @end group
1691 @end example
1692 @end defun
1693
1694 @defun file-name-sans-versions filename &optional keep-backup-version
1695 This function returns @var{filename} with any file version numbers,
1696 backup version numbers, or trailing tildes discarded.
1697
1698 If @var{keep-backup-version} is non-@code{nil}, then true file version
1699 numbers understood as such by the file system are discarded from the
1700 return value, but backup version numbers are kept.
1701
1702 @example
1703 @group
1704 (file-name-sans-versions "~rms/foo.~1~")
1705 @result{} "~rms/foo"
1706 @end group
1707 @group
1708 (file-name-sans-versions "~rms/foo~")
1709 @result{} "~rms/foo"
1710 @end group
1711 @group
1712 (file-name-sans-versions "~rms/foo")
1713 @result{} "~rms/foo"
1714 @end group
1715 @end example
1716 @end defun
1717
1718 @defun file-name-extension filename &optional period
1719 This function returns @var{filename}'s final ``extension,'' if any,
1720 after applying @code{file-name-sans-versions} to remove any
1721 version/backup part. The extension, in a file name, is the part that
1722 follows the last @samp{.} in the last name component (minus any
1723 version/backup part).
1724
1725 This function returns @code{nil} for extensionless file names such as
1726 @file{foo}. It returns @code{""} for null extensions, as in
1727 @file{foo.}. If the last component of a file name begins with a
1728 @samp{.}, that @samp{.} doesn't count as the beginning of an
1729 extension. Thus, @file{.emacs}'s ``extension'' is @code{nil}, not
1730 @samp{.emacs}.
1731
1732 If @var{period} is non-@code{nil}, then the returned value includes
1733 the period that delimits the extension, and if @var{filename} has no
1734 extension, the value is @code{""}.
1735 @end defun
1736
1737 @defun file-name-sans-extension filename
1738 This function returns @var{filename} minus its extension, if any. The
1739 version/backup part, if present, is only removed if the file has an
1740 extension. For example,
1741
1742 @example
1743 (file-name-sans-extension "foo.lose.c")
1744 @result{} "foo.lose"
1745 (file-name-sans-extension "big.hack/foo")
1746 @result{} "big.hack/foo"
1747 (file-name-sans-extension "/my/home/.emacs")
1748 @result{} "/my/home/.emacs"
1749 (file-name-sans-extension "/my/home/.emacs.el")
1750 @result{} "/my/home/.emacs"
1751 (file-name-sans-extension "~/foo.el.~3~")
1752 @result{} "~/foo"
1753 (file-name-sans-extension "~/foo.~3~")
1754 @result{} "~/foo.~3~"
1755 @end example
1756
1757 Note that the @samp{.~3~} in the two last examples is the backup part,
1758 not an extension.
1759 @end defun
1760
1761 @ignore
1762 Andrew Innes says that this
1763
1764 @c @defvar directory-sep-char
1765 This variable holds the character that Emacs normally uses to separate
1766 file name components. The default value is @code{?/}, but on MS-Windows
1767 you can set it to @code{?\\}; then the functions that transform file names
1768 use backslashes in their output.
1769
1770 File names using backslashes work as input to Lisp primitives even on
1771 MS-DOS and MS-Windows, even if @code{directory-sep-char} has its default
1772 value of @code{?/}.
1773 @end defvar
1774 @end ignore
1775
1776 @node Relative File Names
1777 @subsection Absolute and Relative File Names
1778 @cindex absolute file name
1779 @cindex relative file name
1780
1781 All the directories in the file system form a tree starting at the
1782 root directory. A file name can specify all the directory names
1783 starting from the root of the tree; then it is called an @dfn{absolute}
1784 file name. Or it can specify the position of the file in the tree
1785 relative to a default directory; then it is called a @dfn{relative} file
1786 name. On Unix and GNU/Linux, an absolute file name starts with a slash
1787 or a tilde (@samp{~}), and a relative one does not. On MS-DOS and
1788 MS-Windows, an absolute file name starts with a slash or a backslash, or
1789 with a drive specification @samp{@var{x}:/}, where @var{x} is the
1790 @dfn{drive letter}.
1791
1792 @defun file-name-absolute-p filename
1793 This function returns @code{t} if file @var{filename} is an absolute
1794 file name, @code{nil} otherwise.
1795
1796 @example
1797 @group
1798 (file-name-absolute-p "~rms/foo")
1799 @result{} t
1800 @end group
1801 @group
1802 (file-name-absolute-p "rms/foo")
1803 @result{} nil
1804 @end group
1805 @group
1806 (file-name-absolute-p "/user/rms/foo")
1807 @result{} t
1808 @end group
1809 @end example
1810 @end defun
1811
1812 Given a possibly relative file name, you can convert it to an
1813 absolute name using @code{expand-file-name} (@pxref{File Name
1814 Expansion}). This function converts absolute file names to relative
1815 names:
1816
1817 @defun file-relative-name filename &optional directory
1818 This function tries to return a relative name that is equivalent to
1819 @var{filename}, assuming the result will be interpreted relative to
1820 @var{directory} (an absolute directory name or directory file name).
1821 If @var{directory} is omitted or @code{nil}, it defaults to the
1822 current buffer's default directory.
1823
1824 On some operating systems, an absolute file name begins with a device
1825 name. On such systems, @var{filename} has no relative equivalent based
1826 on @var{directory} if they start with two different device names. In
1827 this case, @code{file-relative-name} returns @var{filename} in absolute
1828 form.
1829
1830 @example
1831 (file-relative-name "/foo/bar" "/foo/")
1832 @result{} "bar"
1833 (file-relative-name "/foo/bar" "/hack/")
1834 @result{} "../foo/bar"
1835 @end example
1836 @end defun
1837
1838 @node Directory Names
1839 @comment node-name, next, previous, up
1840 @subsection Directory Names
1841 @cindex directory name
1842 @cindex file name of directory
1843
1844 A @dfn{directory name} is the name of a directory. A directory is
1845 actually a kind of file, so it has a file name, which is related to
1846 the directory name but not identical to it. (This is not quite the
1847 same as the usual Unix terminology.) These two different names for
1848 the same entity are related by a syntactic transformation. On GNU and
1849 Unix systems, this is simple: a directory name ends in a slash,
1850 whereas the directory's name as a file lacks that slash. On MS-DOS
1851 the relationship is more complicated.
1852
1853 The difference between a directory name and its name as a file is
1854 subtle but crucial. When an Emacs variable or function argument is
1855 described as being a directory name, a file name of a directory is not
1856 acceptable. When @code{file-name-directory} returns a string, that is
1857 always a directory name.
1858
1859 The following two functions convert between directory names and file
1860 names. They do nothing special with environment variable substitutions
1861 such as @samp{$HOME}, and the constructs @samp{~}, @samp{.} and @samp{..}.
1862
1863 @defun file-name-as-directory filename
1864 This function returns a string representing @var{filename} in a form
1865 that the operating system will interpret as the name of a directory. On
1866 most systems, this means appending a slash to the string (if it does not
1867 already end in one).
1868
1869 @example
1870 @group
1871 (file-name-as-directory "~rms/lewis")
1872 @result{} "~rms/lewis/"
1873 @end group
1874 @end example
1875 @end defun
1876
1877 @defun directory-file-name dirname
1878 This function returns a string representing @var{dirname} in a form that
1879 the operating system will interpret as the name of a file. On most
1880 systems, this means removing the final slash (or backslash) from the
1881 string.
1882
1883 @example
1884 @group
1885 (directory-file-name "~lewis/")
1886 @result{} "~lewis"
1887 @end group
1888 @end example
1889 @end defun
1890
1891 Given a directory name, you can combine it with a relative file name
1892 using @code{concat}:
1893
1894 @example
1895 (concat @var{dirname} @var{relfile})
1896 @end example
1897
1898 @noindent
1899 Be sure to verify that the file name is relative before doing that.
1900 If you use an absolute file name, the results could be syntactically
1901 invalid or refer to the wrong file.
1902
1903 If you want to use a directory file name in making such a
1904 combination, you must first convert it to a directory name using
1905 @code{file-name-as-directory}:
1906
1907 @example
1908 (concat (file-name-as-directory @var{dirfile}) @var{relfile})
1909 @end example
1910
1911 @noindent
1912 Don't try concatenating a slash by hand, as in
1913
1914 @example
1915 ;;; @r{Wrong!}
1916 (concat @var{dirfile} "/" @var{relfile})
1917 @end example
1918
1919 @noindent
1920 because this is not portable. Always use
1921 @code{file-name-as-directory}.
1922
1923 To convert a directory name to its abbreviation, use this
1924 function:
1925
1926 @defun abbreviate-file-name filename
1927 @anchor{Definition of abbreviate-file-name}
1928 This function returns an abbreviated form of @var{filename}. It
1929 applies the abbreviations specified in @code{directory-abbrev-alist}
1930 (@pxref{File Aliases,,File Aliases, emacs, The GNU Emacs Manual}),
1931 then substitutes @samp{~} for the user's home directory if the
1932 argument names a file in the home directory or one of its
1933 subdirectories. If the home directory is a root directory, it is not
1934 replaced with @samp{~}, because this does not make the result shorter
1935 on many systems.
1936
1937 You can use this function for directory names and for file names,
1938 because it recognizes abbreviations even as part of the name.
1939 @end defun
1940
1941 @node File Name Expansion
1942 @subsection Functions that Expand Filenames
1943 @cindex expansion of file names
1944
1945 @dfn{Expansion} of a file name means converting a relative file name
1946 to an absolute one. Since this is done relative to a default directory,
1947 you must specify the default directory name as well as the file name to
1948 be expanded. Expansion also simplifies file names by eliminating
1949 redundancies such as @file{./} and @file{@var{name}/../}.
1950
1951 @defun expand-file-name filename &optional directory
1952 This function converts @var{filename} to an absolute file name. If
1953 @var{directory} is supplied, it is the default directory to start with
1954 if @var{filename} is relative. (The value of @var{directory} should
1955 itself be an absolute directory name or directory file name; it may
1956 start with @samp{~}.) Otherwise, the current buffer's value of
1957 @code{default-directory} is used. For example:
1958
1959 @example
1960 @group
1961 (expand-file-name "foo")
1962 @result{} "/xcssun/users/rms/lewis/foo"
1963 @end group
1964 @group
1965 (expand-file-name "../foo")
1966 @result{} "/xcssun/users/rms/foo"
1967 @end group
1968 @group
1969 (expand-file-name "foo" "/usr/spool/")
1970 @result{} "/usr/spool/foo"
1971 @end group
1972 @group
1973 (expand-file-name "$HOME/foo")
1974 @result{} "/xcssun/users/rms/lewis/$HOME/foo"
1975 @end group
1976 @end example
1977
1978 If the part of the combined file name before the first slash is
1979 @samp{~}, it expands to the value of the @env{HOME} environment
1980 variable (usually your home directory). If the part before the first
1981 slash is @samp{~@var{user}} and if @var{user} is a valid login name,
1982 it expands to @var{user}'s home directory.
1983
1984 Filenames containing @samp{.} or @samp{..} are simplified to their
1985 canonical form:
1986
1987 @example
1988 @group
1989 (expand-file-name "bar/../foo")
1990 @result{} "/xcssun/users/rms/lewis/foo"
1991 @end group
1992 @end example
1993
1994 In some cases, a leading @samp{..} component can remain in the output:
1995
1996 @example
1997 @group
1998 (expand-file-name "../home" "/")
1999 @result{} "/../home"
2000 @end group
2001 @end example
2002
2003 @noindent
2004 This is for the sake of filesystems that have the concept of a
2005 ``superroot'' above the root directory @file{/}. On other filesystems,
2006 @file{/../} is interpreted exactly the same as @file{/}.
2007
2008 Note that @code{expand-file-name} does @emph{not} expand environment
2009 variables; only @code{substitute-in-file-name} does that.
2010
2011 Note also that @code{expand-file-name} does not follow symbolic links
2012 at any level. This results in a difference between the way
2013 @code{file-truename} and @code{expand-file-name} treat @samp{..}.
2014 Assuming that @samp{/tmp/bar} is a symbolic link to the directory
2015 @samp{/tmp/foo/bar} we get:
2016
2017 @example
2018 @group
2019 (file-truename "/tmp/bar/../myfile")
2020 @result{} "/tmp/foo/myfile"
2021 @end group
2022 @group
2023 (expand-file-name "/tmp/bar/../myfile")
2024 @result{} "/tmp/myfile"
2025 @end group
2026 @end example
2027
2028 If you may need to follow symbolic links preceding @samp{..}, you
2029 should make sure to call @code{file-truename} without prior direct or
2030 indirect calls to @code{expand-file-name}. @xref{Truenames}.
2031 @end defun
2032
2033 @defvar default-directory
2034 The value of this buffer-local variable is the default directory for the
2035 current buffer. It should be an absolute directory name; it may start
2036 with @samp{~}. This variable is buffer-local in every buffer.
2037
2038 @code{expand-file-name} uses the default directory when its second
2039 argument is @code{nil}.
2040
2041 The value is always a string ending with a slash.
2042
2043 @example
2044 @group
2045 default-directory
2046 @result{} "/user/lewis/manual/"
2047 @end group
2048 @end example
2049 @end defvar
2050
2051 @defun substitute-in-file-name filename
2052 @anchor{Definition of substitute-in-file-name}
2053 This function replaces environment variable references in
2054 @var{filename} with the environment variable values. Following
2055 standard Unix shell syntax, @samp{$} is the prefix to substitute an
2056 environment variable value. If the input contains @samp{$$}, that is
2057 converted to @samp{$}; this gives the user a way to ``quote'' a
2058 @samp{$}.
2059
2060 The environment variable name is the series of alphanumeric characters
2061 (including underscores) that follow the @samp{$}. If the character following
2062 the @samp{$} is a @samp{@{}, then the variable name is everything up to the
2063 matching @samp{@}}.
2064
2065 Calling @code{substitute-in-file-name} on output produced by
2066 @code{substitute-in-file-name} tends to give incorrect results. For
2067 instance, use of @samp{$$} to quote a single @samp{$} won't work
2068 properly, and @samp{$} in an environment variable's value could lead
2069 to repeated substitution. Therefore, programs that call this function
2070 and put the output where it will be passed to this function need to
2071 double all @samp{$} characters to prevent subsequent incorrect
2072 results.
2073
2074 @c Wordy to avoid overfull hbox. --rjc 15mar92
2075 Here we assume that the environment variable @code{HOME}, which holds
2076 the user's home directory name, has value @samp{/xcssun/users/rms}.
2077
2078 @example
2079 @group
2080 (substitute-in-file-name "$HOME/foo")
2081 @result{} "/xcssun/users/rms/foo"
2082 @end group
2083 @end example
2084
2085 After substitution, if a @samp{~} or a @samp{/} appears immediately
2086 after another @samp{/}, the function discards everything before it (up
2087 through the immediately preceding @samp{/}).
2088
2089 @example
2090 @group
2091 (substitute-in-file-name "bar/~/foo")
2092 @result{} "~/foo"
2093 @end group
2094 @group
2095 (substitute-in-file-name "/usr/local/$HOME/foo")
2096 @result{} "/xcssun/users/rms/foo"
2097 ;; @r{@file{/usr/local/} has been discarded.}
2098 @end group
2099 @end example
2100
2101 @end defun
2102
2103 @node Unique File Names
2104 @subsection Generating Unique File Names
2105
2106 Some programs need to write temporary files. Here is the usual way to
2107 construct a name for such a file:
2108
2109 @example
2110 (make-temp-file @var{name-of-application})
2111 @end example
2112
2113 @noindent
2114 The job of @code{make-temp-file} is to prevent two different users or
2115 two different jobs from trying to use the exact same file name.
2116
2117 @defun make-temp-file prefix &optional dir-flag suffix
2118 This function creates a temporary file and returns its name. Emacs
2119 creates the temporary file's name by adding to @var{prefix} some
2120 random characters that are different in each Emacs job. The result is
2121 guaranteed to be a newly created empty file. On MS-DOS, this function
2122 can truncate the @var{string} prefix to fit into the 8+3 file-name
2123 limits. If @var{prefix} is a relative file name, it is expanded
2124 against @code{temporary-file-directory}.
2125
2126 @example
2127 @group
2128 (make-temp-file "foo")
2129 @result{} "/tmp/foo232J6v"
2130 @end group
2131 @end example
2132
2133 When @code{make-temp-file} returns, the file has been created and is
2134 empty. At that point, you should write the intended contents into the
2135 file.
2136
2137 If @var{dir-flag} is non-@code{nil}, @code{make-temp-file} creates an
2138 empty directory instead of an empty file. It returns the file name,
2139 not the directory name, of that directory. @xref{Directory Names}.
2140
2141 If @var{suffix} is non-@code{nil}, @code{make-temp-file} adds it at
2142 the end of the file name.
2143
2144 To prevent conflicts among different libraries running in the same
2145 Emacs, each Lisp program that uses @code{make-temp-file} should have its
2146 own @var{prefix}. The number added to the end of @var{prefix}
2147 distinguishes between the same application running in different Emacs
2148 jobs. Additional added characters permit a large number of distinct
2149 names even in one Emacs job.
2150 @end defun
2151
2152 The default directory for temporary files is controlled by the
2153 variable @code{temporary-file-directory}. This variable gives the user
2154 a uniform way to specify the directory for all temporary files. Some
2155 programs use @code{small-temporary-file-directory} instead, if that is
2156 non-@code{nil}. To use it, you should expand the prefix against
2157 the proper directory before calling @code{make-temp-file}.
2158
2159 In older Emacs versions where @code{make-temp-file} does not exist,
2160 you should use @code{make-temp-name} instead:
2161
2162 @example
2163 (make-temp-name
2164 (expand-file-name @var{name-of-application}
2165 temporary-file-directory))
2166 @end example
2167
2168 @defun make-temp-name string
2169 This function generates a string that can be used as a unique file
2170 name. The name starts with @var{string}, and has several random
2171 characters appended to it, which are different in each Emacs job. It
2172 is like @code{make-temp-file} except that it just constructs a name,
2173 and does not create a file. Another difference is that @var{string}
2174 should be an absolute file name. On MS-DOS, this function can
2175 truncate the @var{string} prefix to fit into the 8+3 file-name limits.
2176 @end defun
2177
2178 @defopt temporary-file-directory
2179 @cindex @code{TMPDIR} environment variable
2180 @cindex @code{TMP} environment variable
2181 @cindex @code{TEMP} environment variable
2182 This variable specifies the directory name for creating temporary files.
2183 Its value should be a directory name (@pxref{Directory Names}), but it
2184 is good for Lisp programs to cope if the value is a directory's file
2185 name instead. Using the value as the second argument to
2186 @code{expand-file-name} is a good way to achieve that.
2187
2188 The default value is determined in a reasonable way for your operating
2189 system; it is based on the @code{TMPDIR}, @code{TMP} and @code{TEMP}
2190 environment variables, with a fall-back to a system-dependent name if
2191 none of these variables is defined.
2192
2193 Even if you do not use @code{make-temp-file} to create the temporary
2194 file, you should still use this variable to decide which directory to
2195 put the file in. However, if you expect the file to be small, you
2196 should use @code{small-temporary-file-directory} first if that is
2197 non-@code{nil}.
2198 @end defopt
2199
2200 @defopt small-temporary-file-directory
2201 This variable specifies the directory name for
2202 creating certain temporary files, which are likely to be small.
2203
2204 If you want to write a temporary file which is likely to be small, you
2205 should compute the directory like this:
2206
2207 @example
2208 (make-temp-file
2209 (expand-file-name @var{prefix}
2210 (or small-temporary-file-directory
2211 temporary-file-directory)))
2212 @end example
2213 @end defopt
2214
2215 @node File Name Completion
2216 @subsection File Name Completion
2217 @cindex file name completion subroutines
2218 @cindex completion, file name
2219
2220 This section describes low-level subroutines for completing a file
2221 name. For higher level functions, see @ref{Reading File Names}.
2222
2223 @defun file-name-all-completions partial-filename directory
2224 This function returns a list of all possible completions for a file
2225 whose name starts with @var{partial-filename} in directory
2226 @var{directory}. The order of the completions is the order of the files
2227 in the directory, which is unpredictable and conveys no useful
2228 information.
2229
2230 The argument @var{partial-filename} must be a file name containing no
2231 directory part and no slash (or backslash on some systems). The current
2232 buffer's default directory is prepended to @var{directory}, if
2233 @var{directory} is not absolute.
2234
2235 In the following example, suppose that @file{~rms/lewis} is the current
2236 default directory, and has five files whose names begin with @samp{f}:
2237 @file{foo}, @file{file~}, @file{file.c}, @file{file.c.~1~}, and
2238 @file{file.c.~2~}.@refill
2239
2240 @example
2241 @group
2242 (file-name-all-completions "f" "")
2243 @result{} ("foo" "file~" "file.c.~2~"
2244 "file.c.~1~" "file.c")
2245 @end group
2246
2247 @group
2248 (file-name-all-completions "fo" "")
2249 @result{} ("foo")
2250 @end group
2251 @end example
2252 @end defun
2253
2254 @defun file-name-completion filename directory &optional predicate
2255 This function completes the file name @var{filename} in directory
2256 @var{directory}. It returns the longest prefix common to all file names
2257 in directory @var{directory} that start with @var{filename}. If
2258 @var{predicate} is non-@code{nil} then it ignores possible completions
2259 that don't satisfy @var{predicate}, after calling that function
2260 with one argument, the expanded absolute file name.
2261
2262 If only one match exists and @var{filename} matches it exactly, the
2263 function returns @code{t}. The function returns @code{nil} if directory
2264 @var{directory} contains no name starting with @var{filename}.
2265
2266 In the following example, suppose that the current default directory
2267 has five files whose names begin with @samp{f}: @file{foo},
2268 @file{file~}, @file{file.c}, @file{file.c.~1~}, and
2269 @file{file.c.~2~}.@refill
2270
2271 @example
2272 @group
2273 (file-name-completion "fi" "")
2274 @result{} "file"
2275 @end group
2276
2277 @group
2278 (file-name-completion "file.c.~1" "")
2279 @result{} "file.c.~1~"
2280 @end group
2281
2282 @group
2283 (file-name-completion "file.c.~1~" "")
2284 @result{} t
2285 @end group
2286
2287 @group
2288 (file-name-completion "file.c.~3" "")
2289 @result{} nil
2290 @end group
2291 @end example
2292 @end defun
2293
2294 @defopt completion-ignored-extensions
2295 @code{file-name-completion} usually ignores file names that end in any
2296 string in this list. It does not ignore them when all the possible
2297 completions end in one of these suffixes. This variable has no effect
2298 on @code{file-name-all-completions}.@refill
2299
2300 A typical value might look like this:
2301
2302 @example
2303 @group
2304 completion-ignored-extensions
2305 @result{} (".o" ".elc" "~" ".dvi")
2306 @end group
2307 @end example
2308
2309 If an element of @code{completion-ignored-extensions} ends in a slash
2310 @samp{/}, it signals a directory. The elements which do @emph{not} end
2311 in a slash will never match a directory; thus, the above value will not
2312 filter out a directory named @file{foo.elc}.
2313 @end defopt
2314
2315 @node Standard File Names
2316 @subsection Standard File Names
2317
2318 Most of the file names used in Lisp programs are entered by the user.
2319 But occasionally a Lisp program needs to specify a standard file name
2320 for a particular use---typically, to hold customization information
2321 about each user. For example, abbrev definitions are stored (by
2322 default) in the file @file{~/.abbrev_defs}; the @code{completion}
2323 package stores completions in the file @file{~/.completions}. These are
2324 two of the many standard file names used by parts of Emacs for certain
2325 purposes.
2326
2327 Various operating systems have their own conventions for valid file
2328 names and for which file names to use for user profile data. A Lisp
2329 program which reads a file using a standard file name ought to use, on
2330 each type of system, a file name suitable for that system. The function
2331 @code{convert-standard-filename} makes this easy to do.
2332
2333 @defun convert-standard-filename filename
2334 This function alters the file name @var{filename} to fit the conventions
2335 of the operating system in use, and returns the result as a new string.
2336 @end defun
2337
2338 The recommended way to specify a standard file name in a Lisp program
2339 is to choose a name which fits the conventions of GNU and Unix systems,
2340 usually with a nondirectory part that starts with a period, and pass it
2341 to @code{convert-standard-filename} instead of using it directly. Here
2342 is an example from the @code{completion} package:
2343
2344 @example
2345 (defvar save-completions-file-name
2346 (convert-standard-filename "~/.completions")
2347 "*The file name to save completions to.")
2348 @end example
2349
2350 On GNU and Unix systems, and on some other systems as well,
2351 @code{convert-standard-filename} returns its argument unchanged. On
2352 some other systems, it alters the name to fit the system's conventions.
2353
2354 For example, on MS-DOS the alterations made by this function include
2355 converting a leading @samp{.} to @samp{_}, converting a @samp{_} in the
2356 middle of the name to @samp{.} if there is no other @samp{.}, inserting
2357 a @samp{.} after eight characters if there is none, and truncating to
2358 three characters after the @samp{.}. (It makes other changes as well.)
2359 Thus, @file{.abbrev_defs} becomes @file{_abbrev.def}, and
2360 @file{.completions} becomes @file{_complet.ion}.
2361
2362 @node Contents of Directories
2363 @section Contents of Directories
2364 @cindex directory-oriented functions
2365 @cindex file names in directory
2366
2367 A directory is a kind of file that contains other files entered under
2368 various names. Directories are a feature of the file system.
2369
2370 Emacs can list the names of the files in a directory as a Lisp list,
2371 or display the names in a buffer using the @code{ls} shell command. In
2372 the latter case, it can optionally display information about each file,
2373 depending on the options passed to the @code{ls} command.
2374
2375 @defun directory-files directory &optional full-name match-regexp nosort
2376 This function returns a list of the names of the files in the directory
2377 @var{directory}. By default, the list is in alphabetical order.
2378
2379 If @var{full-name} is non-@code{nil}, the function returns the files'
2380 absolute file names. Otherwise, it returns the names relative to
2381 the specified directory.
2382
2383 If @var{match-regexp} is non-@code{nil}, this function returns only
2384 those file names that contain a match for that regular expression---the
2385 other file names are excluded from the list. On case-insensitive
2386 filesystems, the regular expression matching is case-insensitive.
2387
2388 @c Emacs 19 feature
2389 If @var{nosort} is non-@code{nil}, @code{directory-files} does not sort
2390 the list, so you get the file names in no particular order. Use this if
2391 you want the utmost possible speed and don't care what order the files
2392 are processed in. If the order of processing is visible to the user,
2393 then the user will probably be happier if you do sort the names.
2394
2395 @example
2396 @group
2397 (directory-files "~lewis")
2398 @result{} ("#foo#" "#foo.el#" "." ".."
2399 "dired-mods.el" "files.texi"
2400 "files.texi.~1~")
2401 @end group
2402 @end example
2403
2404 An error is signaled if @var{directory} is not the name of a directory
2405 that can be read.
2406 @end defun
2407
2408 @defun directory-files-and-attributes directory &optional full-name match-regexp nosort id-format
2409 This is similar to @code{directory-files} in deciding which files
2410 to report on and how to report their names. However, instead
2411 of returning a list of file names, it returns for each file a
2412 list @code{(@var{filename} . @var{attributes})}, where @var{attributes}
2413 is what @code{file-attributes} would return for that file.
2414 The optional argument @var{id-format} has the same meaning as the
2415 corresponding argument to @code{file-attributes} (@pxref{Definition
2416 of file-attributes}).
2417 @end defun
2418
2419 @defun file-expand-wildcards pattern &optional full
2420 This function expands the wildcard pattern @var{pattern}, returning
2421 a list of file names that match it.
2422
2423 If @var{pattern} is written as an absolute file name,
2424 the values are absolute also.
2425
2426 If @var{pattern} is written as a relative file name, it is interpreted
2427 relative to the current default directory. The file names returned are
2428 normally also relative to the current default directory. However, if
2429 @var{full} is non-@code{nil}, they are absolute.
2430 @end defun
2431
2432 @defun insert-directory file switches &optional wildcard full-directory-p
2433 This function inserts (in the current buffer) a directory listing for
2434 directory @var{file}, formatted with @code{ls} according to
2435 @var{switches}. It leaves point after the inserted text.
2436 @var{switches} may be a string of options, or a list of strings
2437 representing individual options.
2438
2439 The argument @var{file} may be either a directory name or a file
2440 specification including wildcard characters. If @var{wildcard} is
2441 non-@code{nil}, that means treat @var{file} as a file specification with
2442 wildcards.
2443
2444 If @var{full-directory-p} is non-@code{nil}, that means the directory
2445 listing is expected to show the full contents of a directory. You
2446 should specify @code{t} when @var{file} is a directory and switches do
2447 not contain @samp{-d}. (The @samp{-d} option to @code{ls} says to
2448 describe a directory itself as a file, rather than showing its
2449 contents.)
2450
2451 On most systems, this function works by running a directory listing
2452 program whose name is in the variable @code{insert-directory-program}.
2453 If @var{wildcard} is non-@code{nil}, it also runs the shell specified by
2454 @code{shell-file-name}, to expand the wildcards.
2455
2456 MS-DOS and MS-Windows systems usually lack the standard Unix program
2457 @code{ls}, so this function emulates the standard Unix program @code{ls}
2458 with Lisp code.
2459
2460 As a technical detail, when @var{switches} contains the long
2461 @samp{--dired} option, @code{insert-directory} treats it specially,
2462 for the sake of dired. However, the normally equivalent short
2463 @samp{-D} option is just passed on to @code{insert-directory-program},
2464 as any other option.
2465 @end defun
2466
2467 @defvar insert-directory-program
2468 This variable's value is the program to run to generate a directory listing
2469 for the function @code{insert-directory}. It is ignored on systems
2470 which generate the listing with Lisp code.
2471 @end defvar
2472
2473 @node Create/Delete Dirs
2474 @section Creating, Copying and Deleting Directories
2475 @cindex creating, copying and deleting directories
2476 @c Emacs 19 features
2477
2478 Most Emacs Lisp file-manipulation functions get errors when used on
2479 files that are directories. For example, you cannot delete a directory
2480 with @code{delete-file}. These special functions exist to create and
2481 delete directories.
2482
2483 @findex mkdir
2484 @deffn Command make-directory dirname &optional parents
2485 This command creates a directory named @var{dirname}. If
2486 @var{parents} is non-@code{nil}, as is always the case in an
2487 interactive call, that means to create the parent directories first,
2488 if they don't already exist.
2489
2490 @code{mkdir} is an alias for this.
2491 @end deffn
2492
2493 @deffn Command copy-directory dirname newname &optional keep-time parents
2494 This command copies the directory named @var{dirname} to
2495 @var{newname}. If @var{newname} names an existing directory,
2496 @var{dirname} will be copied to a subdirectory there.
2497
2498 It always sets the file modes of the copied files to match the
2499 corresponding original file.
2500
2501 The third arg @var{keep-time} non-@code{nil} means to preserve the
2502 modification time of the copied files. A prefix arg makes
2503 @var{keep-time} non-@code{nil}.
2504
2505 Noninteractively, the last argument @var{parents} says whether to
2506 create parent directories if they don't exist. Interactively,
2507 this happens by default.
2508 @end deffn
2509
2510 @deffn Command delete-directory dirname &optional recursive
2511 This command deletes the directory named @var{dirname}. The function
2512 @code{delete-file} does not work for files that are directories; you
2513 must use @code{delete-directory} for them. If @var{recursive} is
2514 @code{nil}, and the directory contains any files,
2515 @code{delete-directory} signals an error.
2516
2517 @code{delete-directory} only follows symbolic links at the level of
2518 parent directories.
2519 @end deffn
2520
2521 @node Magic File Names
2522 @section Making Certain File Names ``Magic''
2523 @cindex magic file names
2524
2525 @c Emacs 19 feature
2526 You can implement special handling for certain file names. This is
2527 called making those names @dfn{magic}. The principal use for this
2528 feature is in implementing remote file names (@pxref{Remote Files,,
2529 Remote Files, emacs, The GNU Emacs Manual}).
2530
2531 To define a kind of magic file name, you must supply a regular
2532 expression to define the class of names (all those that match the
2533 regular expression), plus a handler that implements all the primitive
2534 Emacs file operations for file names that do match.
2535
2536 @vindex file-name-handler-alist
2537 The variable @code{file-name-handler-alist} holds a list of handlers,
2538 together with regular expressions that determine when to apply each
2539 handler. Each element has this form:
2540
2541 @example
2542 (@var{regexp} . @var{handler})
2543 @end example
2544
2545 @noindent
2546 All the Emacs primitives for file access and file name transformation
2547 check the given file name against @code{file-name-handler-alist}. If
2548 the file name matches @var{regexp}, the primitives handle that file by
2549 calling @var{handler}.
2550
2551 The first argument given to @var{handler} is the name of the
2552 primitive, as a symbol; the remaining arguments are the arguments that
2553 were passed to that primitive. (The first of these arguments is most
2554 often the file name itself.) For example, if you do this:
2555
2556 @example
2557 (file-exists-p @var{filename})
2558 @end example
2559
2560 @noindent
2561 and @var{filename} has handler @var{handler}, then @var{handler} is
2562 called like this:
2563
2564 @example
2565 (funcall @var{handler} 'file-exists-p @var{filename})
2566 @end example
2567
2568 When a function takes two or more arguments that must be file names,
2569 it checks each of those names for a handler. For example, if you do
2570 this:
2571
2572 @example
2573 (expand-file-name @var{filename} @var{dirname})
2574 @end example
2575
2576 @noindent
2577 then it checks for a handler for @var{filename} and then for a handler
2578 for @var{dirname}. In either case, the @var{handler} is called like
2579 this:
2580
2581 @example
2582 (funcall @var{handler} 'expand-file-name @var{filename} @var{dirname})
2583 @end example
2584
2585 @noindent
2586 The @var{handler} then needs to figure out whether to handle
2587 @var{filename} or @var{dirname}.
2588
2589 If the specified file name matches more than one handler, the one
2590 whose match starts last in the file name gets precedence. This rule
2591 is chosen so that handlers for jobs such as uncompression are handled
2592 first, before handlers for jobs such as remote file access.
2593
2594 Here are the operations that a magic file name handler gets to handle:
2595
2596 @ifnottex
2597 @noindent
2598 @code{access-file}, @code{add-name-to-file},
2599 @code{byte-compiler-base-file-name},@*
2600 @code{copy-directory}, @code{copy-file},
2601 @code{delete-directory}, @code{delete-file},
2602 @code{diff-latest-backup-file},
2603 @code{directory-file-name},
2604 @code{directory-files},
2605 @code{directory-files-and-attributes},
2606 @code{dired-compress-file}, @code{dired-uncache},@*
2607 @code{expand-file-name},
2608 @code{file-accessible-directory-p},
2609 @code{file-attributes},
2610 @code{file-directory-p},
2611 @code{file-executable-p}, @code{file-exists-p},
2612 @code{file-local-copy}, @code{file-remote-p},
2613 @code{file-modes}, @code{file-name-all-completions},
2614 @code{file-name-as-directory},
2615 @code{file-name-completion},
2616 @code{file-name-directory},
2617 @code{file-name-nondirectory},
2618 @code{file-name-sans-versions}, @code{file-newer-than-file-p},
2619 @code{file-ownership-preserved-p},
2620 @code{file-readable-p}, @code{file-regular-p}, @code{file-symlink-p},
2621 @code{file-truename}, @code{file-writable-p},
2622 @code{find-backup-file-name},
2623 @c Not sure why it was here: @code{find-file-noselect},@*
2624 @code{get-file-buffer},
2625 @code{insert-directory},
2626 @code{insert-file-contents},@*
2627 @code{load},
2628 @code{make-auto-save-file-name},
2629 @code{make-directory},
2630 @code{make-directory-internal},
2631 @code{make-symbolic-link},@*
2632 @code{process-file},
2633 @code{rename-file}, @code{set-file-modes}, @code{set-file-times},
2634 @code{set-visited-file-modtime}, @code{shell-command},
2635 @code{start-file-process},
2636 @code{substitute-in-file-name},@*
2637 @code{unhandled-file-name-directory},
2638 @code{vc-registered},
2639 @code{verify-visited-file-modtime},@*
2640 @code{write-region}.
2641 @end ifnottex
2642 @iftex
2643 @noindent
2644 @flushleft
2645 @code{access-file}, @code{add-name-to-file},
2646 @code{byte-com@discretionary{}{}{}piler-base-file-name},
2647 @code{copy-directory}, @code{copy-file},
2648 @code{delete-directory}, @code{delete-file},
2649 @code{diff-latest-backup-file},
2650 @code{directory-file-name},
2651 @code{directory-files},
2652 @code{directory-files-and-at@discretionary{}{}{}tributes},
2653 @code{dired-compress-file}, @code{dired-uncache},
2654 @code{expand-file-name},
2655 @code{file-accessible-direc@discretionary{}{}{}tory-p},
2656 @code{file-attributes},
2657 @code{file-direct@discretionary{}{}{}ory-p},
2658 @code{file-executable-p}, @code{file-exists-p},
2659 @code{file-local-copy}, @code{file-remote-p},
2660 @code{file-modes}, @code{file-name-all-completions},
2661 @code{file-name-as-directory},
2662 @code{file-name-completion},
2663 @code{file-name-directory},
2664 @code{file-name-nondirec@discretionary{}{}{}tory},
2665 @code{file-name-sans-versions}, @code{file-newer-than-file-p},
2666 @code{file-ownership-pre@discretionary{}{}{}served-p},
2667 @code{file-readable-p}, @code{file-regular-p}, @code{file-symlink-p},
2668 @code{file-truename}, @code{file-writable-p},
2669 @code{find-backup-file-name},
2670 @c Not sure why it was here: @code{find-file-noselect},
2671 @code{get-file-buffer},
2672 @code{insert-directory},
2673 @code{insert-file-contents},
2674 @code{load}, @code{make-direc@discretionary{}{}{}tory},
2675 @code{make-direc@discretionary{}{}{}tory-internal},
2676 @code{make-symbolic-link},
2677 @code{process-file},
2678 @code{rename-file}, @code{set-file-modes},
2679 @code{set-visited-file-modtime}, @code{shell-command},
2680 @code{start-file-process},
2681 @code{substitute-in-file-name},
2682 @code{unhandled-file-name-directory},
2683 @code{vc-regis@discretionary{}{}{}tered},
2684 @code{verify-visited-file-modtime},
2685 @code{write-region}.
2686 @end flushleft
2687 @end iftex
2688
2689 Handlers for @code{insert-file-contents} typically need to clear the
2690 buffer's modified flag, with @code{(set-buffer-modified-p nil)}, if the
2691 @var{visit} argument is non-@code{nil}. This also has the effect of
2692 unlocking the buffer if it is locked.
2693
2694 The handler function must handle all of the above operations, and
2695 possibly others to be added in the future. It need not implement all
2696 these operations itself---when it has nothing special to do for a
2697 certain operation, it can reinvoke the primitive, to handle the
2698 operation ``in the usual way.'' It should always reinvoke the primitive
2699 for an operation it does not recognize. Here's one way to do this:
2700
2701 @smallexample
2702 (defun my-file-handler (operation &rest args)
2703 ;; @r{First check for the specific operations}
2704 ;; @r{that we have special handling for.}
2705 (cond ((eq operation 'insert-file-contents) @dots{})
2706 ((eq operation 'write-region) @dots{})
2707 @dots{}
2708 ;; @r{Handle any operation we don't know about.}
2709 (t (let ((inhibit-file-name-handlers
2710 (cons 'my-file-handler
2711 (and (eq inhibit-file-name-operation operation)
2712 inhibit-file-name-handlers)))
2713 (inhibit-file-name-operation operation))
2714 (apply operation args)))))
2715 @end smallexample
2716
2717 When a handler function decides to call the ordinary Emacs primitive for
2718 the operation at hand, it needs to prevent the primitive from calling
2719 the same handler once again, thus leading to an infinite recursion. The
2720 example above shows how to do this, with the variables
2721 @code{inhibit-file-name-handlers} and
2722 @code{inhibit-file-name-operation}. Be careful to use them exactly as
2723 shown above; the details are crucial for proper behavior in the case of
2724 multiple handlers, and for operations that have two file names that may
2725 each have handlers.
2726
2727 @kindex safe-magic (@r{property})
2728 Handlers that don't really do anything special for actual access to the
2729 file---such as the ones that implement completion of host names for
2730 remote file names---should have a non-@code{nil} @code{safe-magic}
2731 property. For instance, Emacs normally ``protects'' directory names
2732 it finds in @code{PATH} from becoming magic, if they look like magic
2733 file names, by prefixing them with @samp{/:}. But if the handler that
2734 would be used for them has a non-@code{nil} @code{safe-magic}
2735 property, the @samp{/:} is not added.
2736
2737 @kindex operations (@r{property})
2738 A file name handler can have an @code{operations} property to
2739 declare which operations it handles in a nontrivial way. If this
2740 property has a non-@code{nil} value, it should be a list of
2741 operations; then only those operations will call the handler. This
2742 avoids inefficiency, but its main purpose is for autoloaded handler
2743 functions, so that they won't be loaded except when they have real
2744 work to do.
2745
2746 Simply deferring all operations to the usual primitives does not
2747 work. For instance, if the file name handler applies to
2748 @code{file-exists-p}, then it must handle @code{load} itself, because
2749 the usual @code{load} code won't work properly in that case. However,
2750 if the handler uses the @code{operations} property to say it doesn't
2751 handle @code{file-exists-p}, then it need not handle @code{load}
2752 nontrivially.
2753
2754 @defvar inhibit-file-name-handlers
2755 This variable holds a list of handlers whose use is presently inhibited
2756 for a certain operation.
2757 @end defvar
2758
2759 @defvar inhibit-file-name-operation
2760 The operation for which certain handlers are presently inhibited.
2761 @end defvar
2762
2763 @defun find-file-name-handler file operation
2764 This function returns the handler function for file name @var{file},
2765 or @code{nil} if there is none. The argument @var{operation} should
2766 be the operation to be performed on the file---the value you will pass
2767 to the handler as its first argument when you call it. If
2768 @var{operation} equals @code{inhibit-file-name-operation}, or if it is
2769 not found in the @code{operations} property of the handler, this
2770 function returns @code{nil}.
2771 @end defun
2772
2773 @defun file-local-copy filename
2774 This function copies file @var{filename} to an ordinary non-magic file
2775 on the local machine, if it isn't on the local machine already. Magic
2776 file names should handle the @code{file-local-copy} operation if they
2777 refer to files on other machines. A magic file name that is used for
2778 other purposes than remote file access should not handle
2779 @code{file-local-copy}; then this function will treat the file as
2780 local.
2781
2782 If @var{filename} is local, whether magic or not, this function does
2783 nothing and returns @code{nil}. Otherwise it returns the file name
2784 of the local copy file.
2785 @end defun
2786
2787 @defun file-remote-p filename &optional identification connected
2788 This function tests whether @var{filename} is a remote file. If
2789 @var{filename} is local (not remote), the return value is @code{nil}.
2790 If @var{filename} is indeed remote, the return value is a string that
2791 identifies the remote system.
2792
2793 This identifier string can include a host name and a user name, as
2794 well as characters designating the method used to access the remote
2795 system. For example, the remote identifier string for the filename
2796 @code{/sudo::/some/file} is @code{/sudo:root@@localhost:}.
2797
2798 If @code{file-remote-p} returns the same identifier for two different
2799 filenames, that means they are stored on the same file system and can
2800 be accessed locally with respect to each other. This means, for
2801 example, that it is possible to start a remote process accessing both
2802 files at the same time. Implementors of file handlers need to ensure
2803 this principle is valid.
2804
2805 @var{identification} specifies which part of the identifier shall be
2806 returned as string. @var{identification} can be the symbol
2807 @code{method}, @code{user} or @code{host}; any other value is handled
2808 like @code{nil} and means to return the complete identifier string.
2809 In the example above, the remote @code{user} identifier string would
2810 be @code{root}.
2811
2812 If @var{connected} is non-@code{nil}, this function returns @code{nil}
2813 even if @var{filename} is remote, if Emacs has no network connection
2814 to its host. This is useful when you want to avoid the delay of
2815 making connections when they don't exist.
2816 @end defun
2817
2818 @defun unhandled-file-name-directory filename
2819 This function returns the name of a directory that is not magic. It
2820 uses the directory part of @var{filename} if that is not magic. For a
2821 magic file name, it invokes the file name handler, which therefore
2822 decides what value to return. If @var{filename} is not accessible
2823 from a local process, then the file name handler should indicate it by
2824 returning @code{nil}.
2825
2826 This is useful for running a subprocess; every subprocess must have a
2827 non-magic directory to serve as its current directory, and this function
2828 is a good way to come up with one.
2829 @end defun
2830
2831 @node Format Conversion
2832 @section File Format Conversion
2833
2834 @cindex file format conversion
2835 @cindex encoding file formats
2836 @cindex decoding file formats
2837 @cindex text properties in files
2838 @cindex saving text properties
2839 Emacs performs several steps to convert the data in a buffer (text,
2840 text properties, and possibly other information) to and from a
2841 representation suitable for storing into a file. This section describes
2842 the fundamental functions that perform this @dfn{format conversion},
2843 namely @code{insert-file-contents} for reading a file into a buffer,
2844 and @code{write-region} for writing a buffer into a file.
2845
2846 @menu
2847 * Overview: Format Conversion Overview. @code{insert-file-contents} and @code{write-region}.
2848 * Round-Trip: Format Conversion Round-Trip. Using @code{format-alist}.
2849 * Piecemeal: Format Conversion Piecemeal. Specifying non-paired conversion.
2850 @end menu
2851
2852 @node Format Conversion Overview
2853 @subsection Overview
2854 @noindent
2855 The function @code{insert-file-contents}:
2856
2857 @itemize
2858 @item initially, inserts bytes from the file into the buffer;
2859 @item decodes bytes to characters as appropriate;
2860 @item processes formats as defined by entries in @code{format-alist}; and
2861 @item calls functions in @code{after-insert-file-functions}.
2862 @end itemize
2863
2864 @noindent
2865 The function @code{write-region}:
2866
2867 @itemize
2868 @item initially, calls functions in @code{write-region-annotate-functions};
2869 @item processes formats as defined by entries in @code{format-alist};
2870 @item encodes characters to bytes as appropriate; and
2871 @item modifies the file with the bytes.
2872 @end itemize
2873
2874 This shows the symmetry of the lowest-level operations; reading and
2875 writing handle things in opposite order. The rest of this section
2876 describes the two facilities surrounding the three variables named
2877 above, as well as some related functions. @ref{Coding Systems}, for
2878 details on character encoding and decoding.
2879
2880 @node Format Conversion Round-Trip
2881 @subsection Round-Trip Specification
2882
2883 The most general of the two facilities is controlled by the variable
2884 @code{format-alist}, a list of @dfn{file format} specifications, which
2885 describe textual representations used in files for the data in an Emacs
2886 buffer. The descriptions for reading and writing are paired, which is
2887 why we call this ``round-trip'' specification
2888 (@pxref{Format Conversion Piecemeal}, for non-paired specification).
2889
2890 @defvar format-alist
2891 This list contains one format definition for each defined file format.
2892 Each format definition is a list of this form:
2893
2894 @example
2895 (@var{name} @var{doc-string} @var{regexp} @var{from-fn} @var{to-fn} @var{modify} @var{mode-fn} @var{preserve})
2896 @end example
2897 @end defvar
2898
2899 @cindex format definition
2900 @noindent
2901 Here is what the elements in a format definition mean:
2902
2903 @table @var
2904 @item name
2905 The name of this format.
2906
2907 @item doc-string
2908 A documentation string for the format.
2909
2910 @item regexp
2911 A regular expression which is used to recognize files represented in
2912 this format. If @code{nil}, the format is never applied automatically.
2913
2914 @item from-fn
2915 A shell command or function to decode data in this format (to convert
2916 file data into the usual Emacs data representation).
2917
2918 A shell command is represented as a string; Emacs runs the command as a
2919 filter to perform the conversion.
2920
2921 If @var{from-fn} is a function, it is called with two arguments, @var{begin}
2922 and @var{end}, which specify the part of the buffer it should convert.
2923 It should convert the text by editing it in place. Since this can
2924 change the length of the text, @var{from-fn} should return the modified
2925 end position.
2926
2927 One responsibility of @var{from-fn} is to make sure that the beginning
2928 of the file no longer matches @var{regexp}. Otherwise it is likely to
2929 get called again.
2930
2931 @item to-fn
2932 A shell command or function to encode data in this format---that is, to
2933 convert the usual Emacs data representation into this format.
2934
2935 If @var{to-fn} is a string, it is a shell command; Emacs runs the
2936 command as a filter to perform the conversion.
2937
2938 If @var{to-fn} is a function, it is called with three arguments:
2939 @var{begin} and @var{end}, which specify the part of the buffer it
2940 should convert, and @var{buffer}, which specifies which buffer. There
2941 are two ways it can do the conversion:
2942
2943 @itemize @bullet
2944 @item
2945 By editing the buffer in place. In this case, @var{to-fn} should
2946 return the end-position of the range of text, as modified.
2947
2948 @item
2949 By returning a list of annotations. This is a list of elements of the
2950 form @code{(@var{position} . @var{string})}, where @var{position} is an
2951 integer specifying the relative position in the text to be written, and
2952 @var{string} is the annotation to add there. The list must be sorted in
2953 order of position when @var{to-fn} returns it.
2954
2955 When @code{write-region} actually writes the text from the buffer to the
2956 file, it intermixes the specified annotations at the corresponding
2957 positions. All this takes place without modifying the buffer.
2958 @end itemize
2959
2960 @item modify
2961 A flag, @code{t} if the encoding function modifies the buffer, and
2962 @code{nil} if it works by returning a list of annotations.
2963
2964 @item mode-fn
2965 A minor-mode function to call after visiting a file converted from this
2966 format. The function is called with one argument, the integer 1;
2967 that tells a minor-mode function to enable the mode.
2968
2969 @item preserve
2970 A flag, @code{t} if @code{format-write-file} should not remove this format
2971 from @code{buffer-file-format}.
2972 @end table
2973
2974 The function @code{insert-file-contents} automatically recognizes file
2975 formats when it reads the specified file. It checks the text of the
2976 beginning of the file against the regular expressions of the format
2977 definitions, and if it finds a match, it calls the decoding function for
2978 that format. Then it checks all the known formats over again.
2979 It keeps checking them until none of them is applicable.
2980
2981 Visiting a file, with @code{find-file-noselect} or the commands that use
2982 it, performs conversion likewise (because it calls
2983 @code{insert-file-contents}); it also calls the mode function for each
2984 format that it decodes. It stores a list of the format names in the
2985 buffer-local variable @code{buffer-file-format}.
2986
2987 @defvar buffer-file-format
2988 This variable states the format of the visited file. More precisely,
2989 this is a list of the file format names that were decoded in the course
2990 of visiting the current buffer's file. It is always buffer-local in all
2991 buffers.
2992 @end defvar
2993
2994 When @code{write-region} writes data into a file, it first calls the
2995 encoding functions for the formats listed in @code{buffer-file-format},
2996 in the order of appearance in the list.
2997
2998 @deffn Command format-write-file file format &optional confirm
2999 This command writes the current buffer contents into the file @var{file}
3000 in a format based on @var{format}, which is a list of format names. It
3001 constructs the actual format starting from @var{format}, then appending
3002 any elements from the value of @code{buffer-file-format} with a non-nil
3003 @var{preserve} flag (see above), if they are not already present in
3004 @var{format}. It then updates @code{buffer-file-format} with this
3005 format, making it the default for future saves. Except for the
3006 @var{format} argument, this command is similar to @code{write-file}. In
3007 particular, @var{confirm} has the same meaning and interactive treatment
3008 as the corresponding argument to @code{write-file}. @xref{Definition of
3009 write-file}.
3010 @end deffn
3011
3012 @deffn Command format-find-file file format
3013 This command finds the file @var{file}, converting it according to
3014 format @var{format}. It also makes @var{format} the default if the
3015 buffer is saved later.
3016
3017 The argument @var{format} is a list of format names. If @var{format} is
3018 @code{nil}, no conversion takes place. Interactively, typing just
3019 @key{RET} for @var{format} specifies @code{nil}.
3020 @end deffn
3021
3022 @deffn Command format-insert-file file format &optional beg end
3023 This command inserts the contents of file @var{file}, converting it
3024 according to format @var{format}. If @var{beg} and @var{end} are
3025 non-@code{nil}, they specify which part of the file to read, as in
3026 @code{insert-file-contents} (@pxref{Reading from Files}).
3027
3028 The return value is like what @code{insert-file-contents} returns: a
3029 list of the absolute file name and the length of the data inserted
3030 (after conversion).
3031
3032 The argument @var{format} is a list of format names. If @var{format} is
3033 @code{nil}, no conversion takes place. Interactively, typing just
3034 @key{RET} for @var{format} specifies @code{nil}.
3035 @end deffn
3036
3037 @defvar buffer-auto-save-file-format
3038 This variable specifies the format to use for auto-saving. Its value is
3039 a list of format names, just like the value of
3040 @code{buffer-file-format}; however, it is used instead of
3041 @code{buffer-file-format} for writing auto-save files. If the value
3042 is @code{t}, the default, auto-saving uses the same format as a
3043 regular save in the same buffer. This variable is always buffer-local
3044 in all buffers.
3045 @end defvar
3046
3047 @node Format Conversion Piecemeal
3048 @subsection Piecemeal Specification
3049
3050 In contrast to the round-trip specification described in the previous
3051 subsection (@pxref{Format Conversion Round-Trip}), you can use the variables
3052 @code{after-insert-file-functions} and @code{write-region-annotate-functions}
3053 to separately control the respective reading and writing conversions.
3054
3055 Conversion starts with one representation and produces another
3056 representation. When there is only one conversion to do, there is no
3057 conflict about what to start with. However, when there are multiple
3058 conversions involved, conflict may arise when two conversions need to
3059 start with the same data.
3060
3061 This situation is best understood in the context of converting text
3062 properties during @code{write-region}. For example, the character at
3063 position 42 in a buffer is @samp{X} with a text property @code{foo}. If
3064 the conversion for @code{foo} is done by inserting into the buffer, say,
3065 @samp{FOO:}, then that changes the character at position 42 from
3066 @samp{X} to @samp{F}. The next conversion will start with the wrong
3067 data straight away.
3068
3069 To avoid conflict, cooperative conversions do not modify the buffer,
3070 but instead specify @dfn{annotations}, a list of elements of the form
3071 @code{(@var{position} . @var{string})}, sorted in order of increasing
3072 @var{position}.
3073
3074 If there is more than one conversion, @code{write-region} merges their
3075 annotations destructively into one sorted list. Later, when the text
3076 from the buffer is actually written to the file, it intermixes the
3077 specified annotations at the corresponding positions. All this takes
3078 place without modifying the buffer.
3079
3080 @c ??? What about ``overriding'' conversions like those allowed
3081 @c ??? for `write-region-annotate-functions', below? --ttn
3082
3083 In contrast, when reading, the annotations intermixed with the text
3084 are handled immediately. @code{insert-file-contents} sets point to
3085 the beginning of some text to be converted, then calls the conversion
3086 functions with the length of that text. These functions should always
3087 return with point at the beginning of the inserted text. This
3088 approach makes sense for reading because annotations removed by the
3089 first converter can't be mistakenly processed by a later converter.
3090 Each conversion function should scan for the annotations it
3091 recognizes, remove the annotation, modify the buffer text (to set a
3092 text property, for example), and return the updated length of the
3093 text, as it stands after those changes. The value returned by one
3094 function becomes the argument to the next function.
3095
3096 @defvar write-region-annotate-functions
3097 A list of functions for @code{write-region} to call. Each function in
3098 the list is called with two arguments: the start and end of the region
3099 to be written. These functions should not alter the contents of the
3100 buffer. Instead, they should return annotations.
3101
3102 As a special case, a function may return with a different buffer
3103 current. Emacs takes this to mean that the current buffer contains
3104 altered text to be output. It therefore changes the @var{start} and
3105 @var{end} arguments of the @code{write-region} call, giving them the
3106 values of @code{point-min} and @code{point-max} in the new buffer,
3107 respectively. It also discards all previous annotations, because they
3108 should have been dealt with by this function.
3109 @end defvar
3110
3111 @defvar write-region-post-annotation-function
3112 The value of this variable, if non-@code{nil}, should be a function.
3113 This function is called, with no arguments, after @code{write-region}
3114 has completed.
3115
3116 If any function in @code{write-region-annotate-functions} returns with
3117 a different buffer current, Emacs calls
3118 @code{write-region-post-annotation-function} more than once. Emacs
3119 calls it with the last buffer that was current, and again with the
3120 buffer before that, and so on back to the original buffer.
3121
3122 Thus, a function in @code{write-region-annotate-functions} can create
3123 a buffer, give this variable the local value of @code{kill-buffer} in
3124 that buffer, set up the buffer with altered text, and make the buffer
3125 current. The buffer will be killed after @code{write-region} is done.
3126 @end defvar
3127
3128 @defvar after-insert-file-functions
3129 Each function in this list is called by @code{insert-file-contents}
3130 with one argument, the number of characters inserted, and with point
3131 at the beginning of the inserted text. Each function should leave
3132 point unchanged, and return the new character count describing the
3133 inserted text as modified by the function.
3134 @c ??? The docstring mentions a handler from `file-name-handler-alist'
3135 @c "intercepting" `insert-file-contents'. Hmmm. --ttn
3136 @end defvar
3137
3138 We invite users to write Lisp programs to store and retrieve text
3139 properties in files, using these hooks, and thus to experiment with
3140 various data formats and find good ones. Eventually we hope users
3141 will produce good, general extensions we can install in Emacs.
3142
3143 We suggest not trying to handle arbitrary Lisp objects as text property
3144 names or values---because a program that general is probably difficult
3145 to write, and slow. Instead, choose a set of possible data types that
3146 are reasonably flexible, and not too hard to encode.
3147
3148 @ignore
3149 arch-tag: 141f74ce-6ae3-40dc-a6c4-ef83fc4ec35c
3150 @end ignore