root/trunk/lispref/files.texi

Revision 4220, 110.5 kB (checked in by miyoshi, 6 months ago)

Sync up with Emacs22.2.

Line 
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  Free Software Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @setfilename ../info/files
7 @node Files, Backups and Auto-Saving, Documentation, Top
8 @comment  node-name,  next,  previous,  up
9 @chapter Files
10
11   In Emacs, you can find, create, view, save, and otherwise work with
12 files and file directories.  This chapter describes most of the
13 file-related functions of Emacs Lisp, but a few others are described in
14 @ref{Buffers}, and those related to backups and auto-saving are
15 described in @ref{Backups and Auto-Saving}.
16
17   Many of the file functions take one or more arguments that are file
18 names.  A file name is actually a string.  Most of these functions
19 expand file name arguments by calling @code{expand-file-name}, so that
20 @file{~} is handled correctly, as are relative file names (including
21 @samp{../}).  These functions don't recognize environment variable
22 substitutions such as @samp{$HOME}.  @xref{File Name Expansion}.
23
24   When file I/O functions signal Lisp errors, they usually use the
25 condition @code{file-error} (@pxref{Handling Errors}).  The error
26 message is in most cases obtained from the operating system, according
27 to locale @code{system-message-locale}, and decoded using coding system
28 @code{locale-coding-system} (@pxref{Locales}).
29
30 @menu
31 * Visiting Files::           Reading files into Emacs buffers for editing.
32 * Saving Buffers::           Writing changed buffers back into files.
33 * Reading from Files::       Reading files into buffers without visiting.
34 * Writing to Files::         Writing new files from parts of buffers.
35 * File Locks::               Locking and unlocking files, to prevent
36                                simultaneous editing by two people.
37 * Information about Files::  Testing existence, accessibility, size of files.
38 * Changing Files::           Renaming files, changing protection, etc.
39 * File Names::               Decomposing and expanding file names.
40 * Contents of Directories::  Getting a list of the files in a directory.
41 * Create/Delete Dirs::       Creating and Deleting Directories.
42 * Magic File Names::         Defining "magic" special handling
43                                for certain file names.
44 * Format Conversion::        Conversion to and from various file formats.
45 @end menu
46
47 @node Visiting Files
48 @section Visiting Files
49 @cindex finding files
50 @cindex visiting files
51
52   Visiting a file means reading a file into a buffer.  Once this is
53 done, we say that the buffer is @dfn{visiting} that file, and call the
54 file ``the visited file'' of the buffer.
55
56   A file and a buffer are two different things.  A file is information
57 recorded permanently in the computer (unless you delete it).  A buffer,
58 on the other hand, is information inside of Emacs that will vanish at
59 the end of the editing session (or when you kill the buffer).  Usually,
60 a buffer contains information that you have copied from a file; then we
61 say the buffer is visiting that file.  The copy in the buffer is what
62 you modify with editing commands.  Such changes to the buffer do not
63 change the file; therefore, to make the changes permanent, you must
64 @dfn{save} the buffer, which means copying the altered buffer contents
65 back into the file.
66
67   In spite of the distinction between files and buffers, people often
68 refer to a file when they mean a buffer and vice-versa.  Indeed, we say,
69 ``I am editing a file,'' rather than, ``I am editing a buffer that I
70 will soon save as a file of the same name.''  Humans do not usually need
71 to make the distinction explicit.  When dealing with a computer program,
72 however, it is good to keep the distinction in mind.
73
74 @menu
75 * Visiting Functions::         The usual interface functions for visiting.
76 * Subroutines of Visiting::    Lower-level subroutines that they use.
77 @end menu
78
79 @node Visiting Functions
80 @subsection Functions for Visiting Files
81
82   This section describes the functions normally used to visit files.
83 For historical reasons, these functions have names starting with
84 @samp{find-} rather than @samp{visit-}.  @xref{Buffer File Name}, for
85 functions and variables that access the visited file name of a buffer or
86 that find an existing buffer by its visited file name.
87
88   In a Lisp program, if you want to look at the contents of a file but
89 not alter it, the fastest way is to use @code{insert-file-contents} in a
90 temporary buffer.  Visiting the file is not necessary and takes longer.
91 @xref{Reading from Files}.
92
93 @deffn Command find-file filename &optional wildcards
94 This command selects a buffer visiting the file @var{filename},
95 using an existing buffer if there is one, and otherwise creating a
96 new buffer and reading the file into it.  It also returns that buffer.
97
98 Aside from some technical details, the body of the @code{find-file}
99 function is basically equivalent to:
100
101 @smallexample
102 (switch-to-buffer (find-file-noselect filename nil nil wildcards))
103 @end smallexample
104
105 @noindent
106 (See @code{switch-to-buffer} in @ref{Displaying Buffers}.)
107
108 If @var{wildcards} is non-@code{nil}, which is always true in an
109 interactive call, then @code{find-file} expands wildcard characters in
110 @var{filename} and visits all the matching files.
111
112 When @code{find-file} is called interactively, it prompts for
113 @var{filename} in the minibuffer.
114 @end deffn
115
116 @defun find-file-noselect filename &optional nowarn rawfile wildcards
117 This function is the guts of all the file-visiting functions.  It
118 returns a buffer visiting the file @var{filename}.  You may make the
119 buffer current or display it in a window if you wish, but this
120 function does not do so.
121
122 The function returns an existing buffer if there is one; otherwise it
123 creates a new buffer and reads the file into it.  When
124 @code{find-file-noselect} uses an existing buffer, it first verifies
125 that the file has not changed since it was last visited or saved in
126 that buffer.  If the file has changed, this function asks the user
127 whether to reread the changed file.  If the user says @samp{yes}, any
128 edits previously made in the buffer are lost.
129
130 Reading the file involves decoding the file's contents (@pxref{Coding
131 Systems}), including end-of-line conversion, and format conversion
132 (@pxref{Format Conversion}).  If @var{wildcards} is non-@code{nil},
133 then @code{find-file-noselect} expands wildcard characters in
134 @var{filename} and visits all the matching files.
135
136 This function displays warning or advisory messages in various peculiar
137 cases, unless the optional argument @var{nowarn} is non-@code{nil}.  For
138 example, if it needs to create a buffer, and there is no file named
139 @var{filename}, it displays the message @samp{(New file)} in the echo
140 area, and leaves the buffer empty.
141
142 The @code{find-file-noselect} function normally calls
143 @code{after-find-file} after reading the file (@pxref{Subroutines of
144 Visiting}).  That function sets the buffer major mode, parses local
145 variables, warns the user if there exists an auto-save file more recent
146 than the file just visited, and finishes by running the functions in
147 @code{find-file-hook}.
148
149 If the optional argument @var{rawfile} is non-@code{nil}, then
150 @code{after-find-file} is not called, and the
151 @code{find-file-not-found-functions} are not run in case of failure.
152 What's more, a non-@code{nil} @var{rawfile} value suppresses coding
153 system conversion and format conversion.
154
155 The @code{find-file-noselect} function usually returns the buffer that
156 is visiting the file @var{filename}.  But, if wildcards are actually
157 used and expanded, it returns a list of buffers that are visiting the
158 various files.
159
160 @example
161 @group
162 (find-file-noselect "/etc/fstab")
163      @result{} #<buffer fstab>
164 @end group
165 @end example
166 @end defun
167
168 @deffn Command find-file-other-window filename &optional wildcards
169 This command selects a buffer visiting the file @var{filename}, but
170 does so in a window other than the selected window.  It may use another
171 existing window or split a window; see @ref{Displaying Buffers}.
172
173 When this command is called interactively, it prompts for
174 @var{filename}.
175 @end deffn
176
177 @deffn Command find-file-read-only filename &optional wildcards
178 This command selects a buffer visiting the file @var{filename}, like
179 @code{find-file}, but it marks the buffer as read-only.  @xref{Read Only
180 Buffers}, for related functions and variables.
181
182 When this command is called interactively, it prompts for
183 @var{filename}.
184 @end deffn
185
186 @deffn Command view-file filename
187 This command visits @var{filename} using View mode, returning to the
188 previous buffer when you exit View mode.  View mode is a minor mode that
189 provides commands to skim rapidly through the file, but does not let you
190 modify the text.  Entering View mode runs the normal hook
191 @code{view-mode-hook}.  @xref{Hooks}.
192
193 When @code{view-file} is called interactively, it prompts for
194 @var{filename}.
195 @end deffn
196
197 @defopt find-file-wildcards
198 If this variable is non-@code{nil}, then the various @code{find-file}
199 commands check for wildcard characters and visit all the files that
200 match them (when invoked interactively or when their @var{wildcards}
201 argument is non-@code{nil}).  If this option is @code{nil}, then
202 the @code{find-file} commands ignore their @var{wildcards} argument
203 and never treat wildcard characters specially.
204 @end defopt
205
206 @defvar find-file-hook
207 The value of this variable is a list of functions to be called after a
208 file is visited.  The file's local-variables specification (if any) will
209 have been processed before the hooks are run.  The buffer visiting the
210 file is current when the hook functions are run.
211
212 This variable is a normal hook.  @xref{Hooks}.
213 @end defvar
214
215 @defvar find-file-not-found-functions
216 The value of this variable is a list of functions to be called when
217 @code{find-file} or @code{find-file-noselect} is passed a nonexistent
218 file name.  @code{find-file-noselect} calls these functions as soon as
219 it detects a nonexistent file.  It calls them in the order of the list,
220 until one of them returns non-@code{nil}.  @code{buffer-file-name} is
221 already set up.
222
223 This is not a normal hook because the values of the functions are
224 used, and in many cases only some of the functions are called.
225 @end defvar
226
227 @node Subroutines of Visiting
228 @comment  node-name,  next,  previous,  up
229 @subsection Subroutines of Visiting
230
231   The @code{find-file-noselect} function uses two important subroutines
232 which are sometimes useful in user Lisp code: @code{create-file-buffer}
233 and @code{after-find-file}.  This section explains how to use them.
234
235 @defun create-file-buffer filename
236 This function creates a suitably named buffer for visiting
237 @var{filename}, and returns it.  It uses @var{filename} (sans directory)
238 as the name if that name is free; otherwise, it appends a string such as
239 @samp{<2>} to get an unused name.  See also @ref{Creating Buffers}.
240
241 @strong{Please note:} @code{create-file-buffer} does @emph{not}
242 associate the new buffer with a file and does not select the buffer.
243 It also does not use the default major mode.
244
245 @example
246 @group
247 (create-file-buffer "foo")
248      @result{} #<buffer foo>
249 @end group
250 @group
251 (create-file-buffer "foo")
252      @result{} #<buffer foo<2>>
253 @end group
254 @group
255 (create-file-buffer "foo")
256      @result{} #<buffer foo<3>>
257 @end group
258 @end example
259
260 This function is used by @code{find-file-noselect}.
261 It uses @code{generate-new-buffer} (@pxref{Creating Buffers}).
262 @end defun
263
264 @defun after-find-file &optional error warn noauto after-find-file-from-revert-buffer nomodes
265 This function sets the buffer major mode, and parses local variables
266 (@pxref{Auto Major Mode}).  It is called by @code{find-file-noselect}
267 and by the default revert function (@pxref{Reverting}).
268
269 @cindex new file message
270 @cindex file open error
271 If reading the file got an error because the file does not exist, but
272 its directory does exist, the caller should pass a non-@code{nil} value
273 for @var{error}.  In that case, @code{after-find-file} issues a warning:
274 @samp{(New file)}.  For more serious errors, the caller should usually not
275 call @code{after-find-file}.
276
277 If @var{warn} is non-@code{nil}, then this function issues a warning
278 if an auto-save file exists and is more recent than the visited file.
279
280 If @var{noauto} is non-@code{nil}, that says not to enable or disable
281 Auto-Save mode.  The mode remains enabled if it was enabled before.
282
283 If @var{after-find-file-from-revert-buffer} is non-@code{nil}, that
284 means this call was from @code{revert-buffer}.  This has no direct
285 effect, but some mode functions and hook functions check the value
286 of this variable.
287
288 If @var{nomodes} is non-@code{nil}, that means don't alter the buffer's
289 major mode, don't process local variables specifications in the file,
290 and don't run @code{find-file-hook}.  This feature is used by
291 @code{revert-buffer} in some cases.
292
293 The last thing @code{after-find-file} does is call all the functions
294 in the list @code{find-file-hook}.
295 @end defun
296
297 @node Saving Buffers
298 @section Saving Buffers
299 @cindex saving buffers
300
301   When you edit a file in Emacs, you are actually working on a buffer
302 that is visiting that file---that is, the contents of the file are
303 copied into the buffer and the copy is what you edit.  Changes to the
304 buffer do not change the file until you @dfn{save} the buffer, which
305 means copying the contents of the buffer into the file.
306
307 @deffn Command save-buffer &optional backup-option
308 This function saves the contents of the current buffer in its visited
309 file if the buffer has been modified since it was last visited or saved.
310 Otherwise it does nothing.
311
312 @code{save-buffer} is responsible for making backup files.  Normally,
313 @var{backup-option} is @code{nil}, and @code{save-buffer} makes a backup
314 file only if this is the first save since visiting the file.  Other
315 values for @var{backup-option} request the making of backup files in
316 other circumstances:
317
318 @itemize @bullet
319 @item
320 With an argument of 4 or 64, reflecting 1 or 3 @kbd{C-u}'s, the
321 @code{save-buffer} function marks this version of the file to be
322 backed up when the buffer is next saved.
323
324 @item
325 With an argument of 16 or 64, reflecting 2 or 3 @kbd{C-u}'s, the
326 @code{save-buffer} function unconditionally backs up the previous
327 version of the file before saving it.
328
329 @item
330 With an argument of 0, unconditionally do @emph{not} make any backup file.
331 @end itemize
332 @end deffn
333
334 @deffn Command save-some-buffers &optional save-silently-p pred
335 @anchor{Definition of save-some-buffers}
336 This command saves some modified file-visiting buffers.  Normally it
337 asks the user about each buffer.  But if @var{save-silently-p} is
338 non-@code{nil}, it saves all the file-visiting buffers without querying
339 the user.
340
341 The optional @var{pred} argument controls which buffers to ask about
342 (or to save silently if @var{save-silently-p} is non-@code{nil}).
343 If it is @code{nil}, that means to ask only about file-visiting buffers.
344 If it is @code{t}, that means also offer to save certain other non-file
345 buffers---those that have a non-@code{nil} buffer-local value of
346 @code{buffer-offer-save} (@pxref{Killing Buffers}).  A user who says
347 @samp{yes} to saving a non-file buffer is asked to specify the file
348 name to use.  The @code{save-buffers-kill-emacs} function passes the
349 value @code{t} for @var{pred}.
350
351 If @var{pred} is neither @code{t} nor @code{nil}, then it should be
352 a function of no arguments.  It will be called in each buffer to decide
353 whether to offer to save that buffer.  If it returns a non-@code{nil}
354 value in a certain buffer, that means do offer to save that buffer.
355 @end deffn
356
357 @deffn Command write-file filename &optional confirm
358 @anchor{Definition of write-file}
359 This function writes the current buffer into file @var{filename}, makes
360 the buffer visit that file, and marks it not modified.  Then it renames
361 the buffer based on @var{filename}, appending a string like @samp{<2>}
362 if necessary to make a unique buffer name.  It does most of this work by
363 calling @code{set-visited-file-name} (@pxref{Buffer File Name}) and
364 @code{save-buffer}.
365
366 If @var{confirm} is non-@code{nil}, that means to ask for confirmation
367 before overwriting an existing file.  Interactively, confirmation is
368 required, unless the user supplies a prefix argument.
369
370 If @var{filename} is an existing directory, or a symbolic link to one,
371 @code{write-file} uses the name of the visited file, in directory
372 @var{filename}.  If the buffer is not visiting a file, it uses the
373 buffer name instead.
374 @end deffn
375
376   Saving a buffer runs several hooks.  It also performs format
377 conversion (@pxref{Format Conversion}), and may save text properties in
378 ``annotations'' (@pxref{Saving Properties}).
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.  @xref{Format Conversion}.  It also calls the functions in
500 the list @code{after-insert-file-functions}; see @ref{Saving
501 Properties}.  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.
505
506 If @var{visit} is non-@code{nil}, this function additionally marks the
507 buffer as unmodified and sets up various fields in the buffer so that it
508 is visiting the file @var{filename}: these include the buffer's visited
509 file name and its last save file modtime.  This feature is used by
510 @code{find-file-noselect} and you probably should not use it yourself.
511
512 If @var{beg} and @var{end} are non-@code{nil}, they should be integers
513 specifying the portion of the file to insert.  In this case, @var{visit}
514 must be @code{nil}.  For example,
515
516 @example
517 (insert-file-contents filename nil 0 500)
518 @end example
519
520 @noindent
521 inserts the first 500 characters of a file.
522
523 If the argument @var{replace} is non-@code{nil}, it means to replace the
524 contents of the buffer (actually, just the accessible portion) with the
525 contents of the file.  This is better than simply deleting the buffer
526 contents and inserting the whole file, because (1) it preserves some
527 marker positions and (2) it puts less data in the undo list.
528
529 It is possible to read a special file (such as a FIFO or an I/O device)
530 with @code{insert-file-contents}, as long as @var{replace} and
531 @var{visit} are @code{nil}.
532 @end defun
533
534 @defun insert-file-contents-literally filename &optional visit beg end replace
535 This function works like @code{insert-file-contents} except that it does
536 not do format decoding (@pxref{Format Conversion}), does not do
537 character code conversion (@pxref{Coding Systems}), does not run
538 @code{find-file-hook}, does not perform automatic uncompression, and so
539 on.
540 @end defun
541
542 If you want to pass a file name to another process so that another
543 program can read the file, use the function @code{file-local-copy}; see
544 @ref{Magic File Names}.
545
546 @node Writing to Files
547 @comment  node-name,  next,  previous,  up
548 @section Writing to Files
549 @cindex writing to files
550
551   You can write the contents of a buffer, or part of a buffer, directly
552 to a file on disk using the @code{append-to-file} and
553 @code{write-region} functions.  Don't use these functions to write to
554 files that are being visited; that could cause confusion in the
555 mechanisms for visiting.
556
557 @deffn Command append-to-file start end filename
558 This function appends the contents of the region delimited by
559 @var{start} and @var{end} in the current buffer to the end of file
560 @var{filename}.  If that file does not exist, it is created.  This
561 function returns @code{nil}.
562
563 An error is signaled if @var{filename} specifies a nonwritable file,
564 or a nonexistent file in a directory where files cannot be created.
565
566 When called from Lisp, this function is completely equivalent to:
567
568 @example
569 (write-region start end filename t)
570 @end example
571 @end deffn
572
573 @deffn Command write-region start end filename &optional append visit lockname mustbenew
574 This function writes the region delimited by @var{start} and @var{end}
575 in the current buffer into the file specified by @var{filename}.
576
577 If @var{start} is @code{nil}, then the command writes the entire buffer
578 contents (@emph{not} just the accessible portion) to the file and
579 ignores @var{end}.
580
581 @c Emacs 19 feature
582 If @var{start} is a string, then @code{write-region} writes or appends
583 that string, rather than text from the buffer.  @var{end} is ignored in
584 this case.
585
586 If @var{append} is non-@code{nil}, then the specified text is appended
587 to the existing file contents (if any).  If @var{append} is an
588 integer, @code{write-region} seeks to that byte offset from the start
589 of the file and writes the data from there.
590
591 If @var{mustbenew} is non-@code{nil}, then @code{write-region} asks
592 for confirmation if @var{filename} names an existing file.  If
593 @var{mustbenew} is the symbol @code{excl}, then @code{write-region}
594 does not ask for confirmation, but instead it signals an error
595 @code{file-already-exists} if the file already exists.
596
597 The test for an existing file, when @var{mustbenew} is @code{excl}, uses
598 a special system feature.  At least for files on a local disk, there is
599 no chance that some other program could create a file of the same name
600 before Emacs does, without Emacs's noticing.
601
602 If @var{visit} is @code{t}, then Emacs establishes an association
603 between the buffer and the file: the buffer is then visiting that file.
604 It also sets the last file modification time for the current buffer to
605 @var{filename}'s modtime, and marks the buffer as not modified.  This
606 feature is used by @code{save-buffer}, but you probably should not use
607 it yourself.
608
609 @c Emacs 19 feature
610 If @var{visit} is a string, it specifies the file name to visit.  This
611 way, you can write the data to one file (@var{filename}) while recording
612 the buffer as visiting another file (@var{visit}).  The argument
613 @var{visit} is used in the echo area message and also for file locking;
614 @var{visit} is stored in @code{buffer-file-name}.  This feature is used
615 to implement @code{file-precious-flag}; don't use it yourself unless you
616 really know what you're doing.
617
618 The optional argument @var{lockname}, if non-@code{nil}, specifies the
619 file name to use for purposes of locking and unlocking, overriding
620 @var{filename} and @var{visit} for that purpose.
621
622 The function @code{write-region} converts the data which it writes to
623 the appropriate file formats specified by @code{buffer-file-format}.
624 @xref{Format Conversion}.  It also calls the functions in the list
625 @code{write-region-annotate-functions}; see @ref{Saving Properties}.
626
627 Normally, @code{write-region} displays the message @samp{Wrote
628 @var{filename}} in the echo area.  If @var{visit} is neither @code{t}
629 nor @code{nil} nor a string, then this message is inhibited.  This
630 feature is useful for programs that use files for internal purposes,
631 files that the user does not need to know about.
632 @end deffn
633
634 @defmac with-temp-file file body@dots{}
635 @anchor{Definition of with-temp-file}
636 The @code{with-temp-file} macro evaluates the @var{body} forms with a
637 temporary buffer as the current buffer; then, at the end, it writes the
638 buffer contents into file @var{file}.  It kills the temporary buffer
639 when finished, restoring the buffer that was current before the
640 @code{with-temp-file} form.  Then it returns the value of the last form
641 in @var{body}.
642
643 The current buffer is restored even in case of an abnormal exit via
644 @code{throw} or error (@pxref{Nonlocal Exits}).
645
646 See also @code{with-temp-buffer} in @ref{Definition of
647 with-temp-buffer,, The Current Buffer}.
648 @end defmac
649
650 @node File Locks
651 @section File Locks
652 @cindex file locks
653 @cindex lock file
654
655   When two users edit the same file at the same time, they are likely
656 to interfere with each other.  Emacs tries to prevent this situation
657 from arising by recording a @dfn{file lock} when a file is being
658 modified.  (File locks are not implemented on Microsoft systems.)
659 Emacs can then detect the first attempt to modify a buffer visiting a
660 file that is locked by another Emacs job, and ask the user what to do.
661 The file lock is really a file, a symbolic link with a special name,
662 stored in the same directory as the file you are editing.
663
664   When you access files using NFS, there may be a small probability that
665 you and another user will both lock the same file ``simultaneously.''
666 If this happens, it is possible for the two users to make changes
667 simultaneously, but Emacs will still warn the user who saves second.
668 Also, the detection of modification of a buffer visiting a file changed
669 on disk catches some cases of simultaneous editing; see
670 @ref{Modification Time}.
671
672 @defun file-locked-p filename
673 This function returns @code{nil} if the file @var{filename} is not
674 locked.  It returns @code{t} if it is locked by this Emacs process, and
675 it returns the name of the user who has locked it if it is locked by
676 some other job.
677
678 @example
679 @group
680 (file-locked-p "foo")
681      @result{} nil
682 @end group
683 @end example
684 @end defun
685
686 @defun lock-buffer &optional filename
687 This function locks the file @var{filename}, if the current buffer is
688 modified.  The argument @var{filename} defaults to the current buffer's
689 visited file.  Nothing is done if the current buffer is not visiting a
690 file, or is not modified, or if the system does not support locking.
691 @end defun
692
693 @defun unlock-buffer
694 This function unlocks the file being visited in the current buffer,
695 if the buffer is modified.  If the buffer is not modified, then
696 the file should not be locked, so this function does nothing.  It also
697 does nothing if the current buffer is not visiting a file, or if the
698 system does not support locking.
699 @end defun
700
701   File locking is not supported on some systems.  On systems that do not
702 support it, the functions @code{lock-buffer}, @code{unlock-buffer} and
703 @code{file-locked-p} do nothing and return @code{nil}.
704
705 @defun ask-user-about-lock file other-user
706 This function is called when the user tries to modify @var{file}, but it
707 is locked by another user named @var{other-user}.  The default
708 definition of this function asks the user to say what to do.  The value
709 this function returns determines what Emacs does next:
710
711 @itemize @bullet
712 @item
713 A value of @code{t} says to grab the lock on the file.  Then
714 this user may edit the file and @var{other-user} loses the lock.
715
716 @item
717 A value of @code{nil} says to ignore the lock and let this
718 user edit the file anyway.
719
720 @item
721 @kindex file-locked
722 This function may instead signal a @code{file-locked} error, in which
723 case the change that the user was about to make does not take place.
724
725 The error message for this error looks like this:
726
727 @example
728 @error{} File is locked: @var{file} @var{other-user}
729 @end example
730
731 @noindent
732 where @code{file} is the name of the file and @var{other-user} is the
733 name of the user who has locked the file.
734 @end itemize
735
736 If you wish, you can replace the @code{ask-user-about-lock} function
737 with your own version that makes the decision in another way.  The code
738 for its usual definition is in @file{userlock.el}.
739 @end defun
740
741 @node Information about Files
742 @section Information about Files
743 @cindex file, information about
744
745   The functions described in this section all operate on strings that
746 designate file names.  With a few exceptions, all the functions have
747 names that begin with the word @samp{file}.  These functions all
748 return information about actual files or directories, so their
749 arguments must all exist as actual files or directories unless
750 otherwise noted.
751
752 @menu
753 * Testing Accessibility::   Is a given file readable?  Writable?
754 * Kinds of Files::          Is it a directory?  A symbolic link?
755 * Truenames::               Eliminating symbolic links from a file name.
756 * File Attributes::         How large is it?  Any other names?  Etc.
757 * Locating Files::          How to find a file in standard places.
758 @end menu
759
760 @node Testing Accessibility
761 @comment  node-name,  next,  previous,  up
762 @subsection Testing Accessibility
763 @cindex accessibility of a file
764 @cindex file accessibility
765
766   These functions test for permission to access a file in specific
767 ways.  Unless explicitly stated otherwise, they recursively follow
768 symbolic links for their file name arguments, at all levels (at the
769 level of the file itself and at all levels of parent directories).
770
771 @defun file-exists-p filename
772 This function returns @code{t} if a file named @var{filename} appears
773 to exist.  This does not mean you can necessarily read the file, only
774 that you can find out its attributes.  (On Unix and GNU/Linux, this is
775 true if the file exists and you have execute permission on the
776 containing directories, regardless of the protection of the file
777 itself.)
778
779 If the file does not exist, or if fascist access control policies
780 prevent you from finding the attributes of the file, this function
781 returns @code{nil}.
782
783 Directories are files, so @code{file-exists-p} returns @code{t} when
784 given a directory name.  However, symbolic links are treated
785 specially; @code{file-exists-p} returns @code{t} for a symbolic link
786 name only if the target file exists.
787 @end defun
788
789 @defun file-readable-p filename
790 This function returns @code{t} if a file named @var{filename} exists
791 and you can read it.  It returns @code{nil} otherwise.
792
793 @example
794 @group
795 (file-readable-p "files.texi")
796      @result{} t
797 @end group
798 @group
799 (file-exists-p "/usr/spool/mqueue")
800      @result{} t
801 @end group
802 @group
803 (file-readable-p "/usr/spool/mqueue")
804      @result{} nil
805 @end group
806 @end example
807 @end defun
808
809 @c Emacs 19 feature
810 @defun file-executable-p filename
811 This function returns @code{t} if a file named @var{filename} exists and
812 you can execute it.  It returns @code{nil} otherwise.  On Unix and
813 GNU/Linux, if the file is a directory, execute permission means you can
814 check the existence and attributes of files inside the directory, and
815 open those files if their modes permit.
816 @end defun
817
818 @defun file-writable-p filename
819 This function returns @code{t} if the file @var{filename} can be written
820 or created by you, and @code{nil} otherwise.  A file is writable if the
821 file exists and you can write it.  It is creatable if it does not exist,
822 but the specified directory does exist and you can write in that
823 directory.
824
825 In the third example below, @file{foo} is not writable because the
826 parent directory does not exist, even though the user could create such
827 a directory.
828
829 @example
830 @group
831 (file-writable-p "~/foo")
832      @result{} t
833 @end group
834 @group
835 (file-writable-p "/foo")
836      @result{} nil
837 @end group
838 @group
839 (file-writable-p "~/no-such-dir/foo")
840      @result{} nil
841 @end group
842 @end example
843 @end defun
844
845 @c Emacs 19 feature
846 @defun file-accessible-directory-p dirname
847 This function returns @code{t} if you have permission to open existing
848 files in the directory whose name as a file is @var{dirname};
849 otherwise (or if there is no such directory), it returns @code{nil}.
850 The value of @var{dirname} may be either a directory name (such as
851 @file{/foo/}) or the file name of a file which is a directory
852 (such as @file{/foo}, without the final slash).
853
854 Example: after the following,
855
856 @example
857 (file-accessible-directory-p "/foo")
858      @result{} nil
859 @end example
860
861 @noindent
862 we can deduce that any attempt to read a file in @file{/foo/} will
863 give an error.
864 @end defun
865
866 @defun access-file filename string
867 This function opens file @var{filename} for reading, then closes it and
868 returns @code{nil}.  However, if the open fails, it signals an error
869 using @var{string} as the error message text.
870 @end defun
871
872 @defun file-ownership-preserved-p filename
873 This function returns @code{t} if deleting the file @var{filename} and
874 then creating it anew would keep the file's owner unchanged.  It also
875 returns @code{t} for nonexistent files.
876
877 If @var{filename} is a symbolic link, then, unlike the other functions
878 discussed here, @code{file-ownership-preserved-p} does @emph{not}
879 replace @var{filename} with its target.  However, it does recursively
880 follow symbolic links at all levels of parent directories.
881 @end defun
882
883 @defun file-newer-than-file-p filename1 filename2
884 @cindex file age
885 @cindex file modification time
886 This function returns @code{t} if the file @var{filename1} is
887 newer than file @var{filename2}.  If @var{filename1} does not
888 exist, it returns @code{nil}.  If @var{filename1} does exist, but
889 @var{filename2} does not, it returns @code{t}.
890
891 In the following example, assume that the file @file{aug-19} was written
892 on the 19th, @file{aug-20} was written on the 20th, and the file
893 @file{no-file} doesn't exist at all.
894
895 @example
896 @group
897 (file-newer-than-file-p "aug-19" "aug-20")
898      @result{} nil
899 @end group
900 @group
901 (file-newer-than-file-p "aug-20" "aug-19")
902      @result{} t
903 @end group
904 @group
905 (file-newer-than-file-p "aug-19" "no-file")
906      @result{} t
907 @end group
908 @group
909 (file-newer-than-file-p "no-file" "aug-19")
910      @result{} nil
911 @end group
912 @end example
913
914 You can use @code{file-attributes} to get a file's last modification
915 time as a list of two numbers.  @xref{File Attributes}.
916 @end defun
917
918 @node Kinds of Files
919 @comment  node-name,  next,  previous,  up
920 @subsection Distinguishing Kinds of Files
921
922   This section describes how to distinguish various kinds of files, such
923 as directories, symbolic links, and ordinary files.
924
925 @defun file-symlink-p filename
926 @cindex file symbolic links
927 If the file @var{filename} is a symbolic link, the
928 @code{file-symlink-p} function returns the (non-recursive) link target
929 as a string.  (Determining the file name that the link points to from
930 the target is nontrivial.)  First, this function recursively follows
931 symbolic links at all levels of parent directories.
932
933 If the file @var{filename} is not a symbolic link (or there is no such file),
934 @code{file-symlink-p} returns @code{nil}.
935
936 @example
937 @group
938 (file-symlink-p "foo")
939      @result{} nil
940 @end group
941 @group
942 (file-symlink-p "sym-link")
943      @result{} "foo"
944 @end group
945 @group
946 (file-symlink-p "sym-link2")
947      @result{} "sym-link"
948 @end group
949 @group
950 (file-symlink-p "/bin")
951      @result{} "/pub/bin"
952 @end group
953 @end example
954
955 @c !!! file-symlink-p: should show output of ls -l for comparison
956 @end defun
957
958 The next two functions recursively follow symbolic links at
959 all levels for @var{filename}.
960
961 @defun file-directory-p filename
962 This function returns @code{t} if @var{filename} is the name of an
963 existing directory, @code{nil} otherwise.
964
965 @example
966 @group
967 (file-directory-p "~rms")
968      @result{} t
969 @end group
970 @group
971 (file-directory-p "~rms/lewis/files.texi")
972      @result{} nil
973 @end group
974 @group
975 (file-directory-p "~rms/lewis/no-such-file")
976      @result{} nil
977 @end group
978 @group
979 (file-directory-p "$HOME")
980      @result{} nil
981 @end group
982 @group
983 (file-directory-p
984  (substitute-in-file-name "$HOME"))
985      @result{} t
986 @end group
987 @end example
988 @end defun
989
990 @defun file-regular-p filename
991 This function returns @code{t} if the file @var{filename} exists and is
992 a regular file (not a directory, named pipe, terminal, or
993 other I/O device).
994 @end defun
995
996 @node Truenames
997 @subsection Truenames
998 @cindex truename (of file)
999
1000 @c Emacs 19 features
1001   The @dfn{truename} of a file is the name that you get by following
1002 symbolic links at all levels until none remain, then simplifying away
1003 @samp{.}@: and @samp{..}@: appearing as name components.  This results
1004 in a sort of canonical name for the file.  A file does not always have a
1005 unique truename; the number of distinct truenames a file has is equal to
1006 the number of hard links to the file.  However, truenames are useful
1007 because they eliminate symbolic links as a cause of name variation.
1008
1009 @defun file-truename filename
1010 The function @code{file-truename} returns the truename of the file
1011 @var{filename}.  The argument must be an absolute file name.
1012
1013 This function does not expand environment variables.  Only
1014 @code{substitute-in-file-name} does that.  @xref{Definition of
1015 substitute-in-file-name}.
1016
1017 If you may need to follow symbolic links preceding @samp{..}@:
1018 appearing as a name component, you should make sure to call
1019 @code{file-truename} without prior direct or indirect calls to
1020 @code{expand-file-name}, as otherwise the file name component
1021 immediately preceding @samp{..} will be ``simplified away'' before
1022 @code{file-truename} is called.  To eliminate the need for a call to
1023 @code{expand-file-name}, @code{file-truename} handles @samp{~} in the
1024 same way that @code{expand-file-name} does.  @xref{File Name
1025 Expansion,, Functions that Expand Filenames}.
1026 @end defun
1027
1028 @defun file-chase-links filename &optional limit
1029 This function follows symbolic links, starting with @var{filename},
1030 until it finds a file name which is not the name of a symbolic link.
1031 Then it returns that file name.  This function does @emph{not} follow
1032 symbolic links at the level of parent directories.
1033
1034 If you specify a number for @var{limit}, then after chasing through
1035 that many links, the function just returns what it has even if that is
1036 still a symbolic link.
1037 @end defun
1038
1039   To illustrate the difference between @code{file-chase-links} and
1040 @code{file-truename}, suppose that @file{/usr/foo} is a symbolic link to
1041 the directory @file{/home/foo}, and @file{/home/foo/hello} is an
1042 ordinary file (or at least, not a symbolic link) or nonexistent.  Then
1043 we would have:
1044
1045 @example
1046 (file-chase-links "/usr/foo/hello")
1047      ;; @r{This does not follow the links in the parent directories.}
1048      @result{} "/usr/foo/hello"
1049 (file-truename "/usr/foo/hello")
1050      ;; @r{Assuming that @file{/home} is not a symbolic link.}
1051      @result{} "/home/foo/hello"
1052 @end example
1053
1054   @xref{Buffer File Name}, for related information.
1055
1056 @node File Attributes
1057 @comment  node-name,  next,  previous,  up
1058 @subsection Other Information about Files
1059
1060   This section describes the functions for getting detailed information
1061 about a file, other than its contents.  This information includes the
1062 mode bits that control access permission, the owner and group numbers,
1063 the number of names, the inode number, the size, and the times of access
1064 and modification.
1065
1066 @defun file-modes filename
1067 @cindex permission
1068 @cindex file attributes
1069 This function returns the mode bits of @var{filename}, as an integer.
1070 The mode bits are also called the file permissions, and they specify
1071 access control in the usual Unix fashion.  If the low-order bit is 1,
1072 then the file is executable by all users, if the second-lowest-order bit
1073 is 1, then the file is writable by all users, etc.
1074
1075 The highest value returnable is 4095 (7777 octal), meaning that
1076 everyone has read, write, and execute permission, that the @acronym{SUID} bit
1077 is set for both others and group, and that the sticky bit is set.
1078
1079 If @var{filename} does not exist, @code{file-modes} returns @code{nil}.
1080
1081 This function recursively follows symbolic links at all levels.
1082
1083 @example
1084 @group
1085 (file-modes "~/junk/diffs")
1086      @result{} 492               ; @r{Decimal integer.}
1087 @end group
1088 @group
1089 (format "%o" 492)
1090      @result{} "754"             ; @r{Convert to octal.}
1091 @end group
1092
1093 @group
1094 (set-file-modes "~/junk/diffs" 438)
1095      @result{} nil
1096 @end group
1097
1098 @group
1099 (format "%o" 438)
1100      @result{} "666"             ; @r{Convert to octal.}
1101 @end group
1102
1103 @group
1104 % ls -l diffs
1105   -rw-rw-rw-  1 lewis 0 3063 Oct 30 16:00 diffs
1106 @end group
1107 @end example
1108 @end defun
1109
1110 If the @var{filename} argument to the next two functions is a symbolic
1111 link, then these function do @emph{not} replace it with its target.
1112 However, they both recursively follow symbolic links at all levels of
1113 parent directories.
1114
1115 @defun file-nlinks filename
1116 This functions returns the number of names (i.e., hard links) that
1117 file @var{filename} has.  If the file does not exist, then this function
1118 returns @code{nil}.  Note that symbolic links have no effect on this
1119 function, because they are not considered to be names of the files they
1120 link to.
1121
1122 @example
1123 @group
1124 % ls -l foo*
1125 -rw-rw-rw-  2 rms       4 Aug 19 01:27 foo
1126 -rw-rw-rw-  2 rms       4 Aug 19 01:27 foo1
1127 @end group
1128
1129 @group
1130 (file-nlinks "foo")
1131      @result{} 2
1132 @end group
1133 @group
1134 (file-nlinks "doesnt-exist")
1135      @result{} nil
1136 @end group
1137 @end example
1138 @end defun
1139
1140 @defun file-attributes filename &optional id-format
1141 @anchor{Definition of file-attributes}
1142 This function returns a list of attributes of file @var{filename}.  If
1143 the specified file cannot be opened, it returns @code{nil}.
1144 The optional parameter @var{id-format} specifies the preferred format
1145 of attributes @acronym{UID} and @acronym{GID} (see below)---the
1146 valid values are @code{'string} and @code{'integer}.  The latter is
1147 the default, but we plan to change that, so you should specify a
1148 non-@code{nil} value for @var{id-format} if you use the returned
1149 @acronym{UID} or @acronym{GID}.
1150
1151 The elements of the list, in order, are:
1152
1153 @enumerate 0
1154 @item
1155 @code{t} for a directory, a string for a symbolic link (the name
1156 linked to), or @code{nil} for a text file.
1157
1158 @c Wordy so as to prevent an overfull hbox.  --rjc 15mar92
1159 @item
1160 The number of names the file has.  Alternate names, also known as hard
1161 links, can be created by using the @code{add-name-to-file} function
1162 (@pxref{Changing Files}).
1163
1164 @item
1165 The file's @acronym{UID}, normally as a string.  However, if it does
1166 not correspond to a named user, the value is an integer or a floating
1167 point number.
1168
1169 @item
1170 The file's @acronym{GID}, likewise.
1171
1172 @item
1173 The time of last access, as a list of two integers.
1174 The first integer has the high-order 16 bits of time,
1175 the second has the low 16 bits.  (This is similar to the
1176 value of @code{current-time}; see @ref{Time of Day}.)
1177
1178 @item
1179 The time of last modification as a list of two integers (as above).
1180 @cindex modification time of file
1181
1182 @item
1183 The time of last status change as a list of two integers (as above).
1184
1185 @item
1186 The size of the file in bytes.  If the size is too large to fit in a
1187 Lisp integer, this is a floating point number.
1188
1189 @item
1190 The file's modes, as a string of ten letters or dashes,
1191 as in @samp{ls -l}.
1192
1193 @item
1194 @code{t} if the file's @acronym{GID} would change if file were
1195 deleted and recreated; @code{nil} otherwise.
1196
1197 @item
1198 The file's inode number.  If possible, this is an integer.  If the inode
1199 number is too large to be represented as an integer in Emacs Lisp, then
1200 the value has the form @code{(@var{high} . @var{low})}, where @var{low}
1201 holds the low 16 bits.
1202
1203 @item
1204 The file system number of the file system that the file is in.
1205 Depending on the magnitude of the value, this can be either an integer
1206 or a cons cell, in the same manner as the inode number.  This element
1207 and the file's inode number together give enough information to
1208 distinguish any two files on the system---no two files can have the same
1209 values for both of these numbers.
1210 @end enumerate