1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2012 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 #include <sys/types.h>
36 #ifdef HAVE_LIBSELINUX
37 #include <selinux/selinux.h>
38 #include <selinux/context.h>
42 #include "intervals.h"
44 #include "character.h"
47 #include "blockinput.h"
49 #include "dispextern.h"
55 #endif /* not WINDOWSNT */
59 #include <sys/param.h>
64 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
65 redirector allows the six letters between 'Z' and 'a' as well. */
67 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
70 #define IS_DRIVE(x) isalpha ((unsigned char) (x))
72 /* Need to lower-case the drive letter, or else expanded
73 filenames will sometimes compare unequal, because
74 `expand-file-name' doesn't always down-case the drive letter. */
75 #define DRIVE_LETTER(x) (tolower ((unsigned char) (x)))
86 #ifndef FILE_SYSTEM_CASE
87 #define FILE_SYSTEM_CASE(filename) (filename)
90 /* Nonzero during writing of auto-save files */
91 static int auto_saving
;
93 /* Nonzero umask during creation of auto-save directories */
94 static int auto_saving_dir_umask
;
96 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
97 a new file with the same mode as the original */
98 static int auto_save_mode_bits
;
100 /* Set by auto_save_1 if an error occurred during the last auto-save. */
101 static int auto_save_error_occurred
;
103 /* The symbol bound to coding-system-for-read when
104 insert-file-contents is called for recovering a file. This is not
105 an actual coding system name, but just an indicator to tell
106 insert-file-contents to use `emacs-mule' with a special flag for
107 auto saving and recovering a file. */
108 static Lisp_Object Qauto_save_coding
;
110 /* Property name of a file name handler,
111 which gives a list of operations it handles.. */
112 static Lisp_Object Qoperations
;
114 /* Lisp functions for translating file formats */
115 static Lisp_Object Qformat_decode
, Qformat_annotate_function
;
117 /* Lisp function for setting buffer-file-coding-system and the
118 multibyteness of the current buffer after inserting a file. */
119 static Lisp_Object Qafter_insert_file_set_coding
;
121 static Lisp_Object Qwrite_region_annotate_functions
;
122 /* Each time an annotation function changes the buffer, the new buffer
124 static Lisp_Object Vwrite_region_annotation_buffers
;
129 static Lisp_Object Qdelete_by_moving_to_trash
;
131 /* Lisp function for moving files to trash. */
132 static Lisp_Object Qmove_file_to_trash
;
134 /* Lisp function for recursively copying directories. */
135 static Lisp_Object Qcopy_directory
;
137 /* Lisp function for recursively deleting directories. */
138 static Lisp_Object Qdelete_directory
;
143 Lisp_Object Qfile_error
;
144 static Lisp_Object Qfile_already_exists
, Qfile_date_error
;
145 static Lisp_Object Qexcl
;
146 Lisp_Object Qfile_name_history
;
148 static Lisp_Object Qcar_less_than_car
;
150 static Lisp_Object
Fmake_symbolic_link (Lisp_Object
, Lisp_Object
, Lisp_Object
);
151 static int a_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
152 Lisp_Object
*, struct coding_system
*);
153 static int e_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
154 struct coding_system
*);
158 report_file_error (const char *string
, Lisp_Object data
)
160 Lisp_Object errstring
;
164 synchronize_system_messages_locale ();
165 str
= strerror (errorno
);
166 errstring
= code_convert_string_norecord (make_unibyte_string (str
,
168 Vlocale_coding_system
, 0);
174 xsignal (Qfile_already_exists
, Fcons (errstring
, data
));
177 /* System error messages are capitalized. Downcase the initial
178 unless it is followed by a slash. (The slash case caters to
179 error messages that begin with "I/O" or, in German, "E/A".) */
180 if (STRING_MULTIBYTE (errstring
)
181 && ! EQ (Faref (errstring
, make_number (1)), make_number ('/')))
185 str
= SSDATA (errstring
);
186 c
= STRING_CHAR ((unsigned char *) str
);
187 Faset (errstring
, make_number (0), make_number (downcase (c
)));
190 xsignal (Qfile_error
,
191 Fcons (build_string (string
), Fcons (errstring
, data
)));
196 close_file_unwind (Lisp_Object fd
)
198 emacs_close (XFASTINT (fd
));
202 /* Restore point, having saved it as a marker. */
205 restore_point_unwind (Lisp_Object location
)
207 Fgoto_char (location
);
208 Fset_marker (location
, Qnil
, Qnil
);
213 static Lisp_Object Qexpand_file_name
;
214 static Lisp_Object Qsubstitute_in_file_name
;
215 static Lisp_Object Qdirectory_file_name
;
216 static Lisp_Object Qfile_name_directory
;
217 static Lisp_Object Qfile_name_nondirectory
;
218 static Lisp_Object Qunhandled_file_name_directory
;
219 static Lisp_Object Qfile_name_as_directory
;
220 static Lisp_Object Qcopy_file
;
221 static Lisp_Object Qmake_directory_internal
;
222 static Lisp_Object Qmake_directory
;
223 static Lisp_Object Qdelete_directory_internal
;
224 Lisp_Object Qdelete_file
;
225 static Lisp_Object Qrename_file
;
226 static Lisp_Object Qadd_name_to_file
;
227 static Lisp_Object Qmake_symbolic_link
;
228 Lisp_Object Qfile_exists_p
;
229 static Lisp_Object Qfile_executable_p
;
230 static Lisp_Object Qfile_readable_p
;
231 static Lisp_Object Qfile_writable_p
;
232 static Lisp_Object Qfile_symlink_p
;
233 static Lisp_Object Qaccess_file
;
234 Lisp_Object Qfile_directory_p
;
235 static Lisp_Object Qfile_regular_p
;
236 static Lisp_Object Qfile_accessible_directory_p
;
237 static Lisp_Object Qfile_modes
;
238 static Lisp_Object Qset_file_modes
;
239 static Lisp_Object Qset_file_times
;
240 static Lisp_Object Qfile_selinux_context
;
241 static Lisp_Object Qset_file_selinux_context
;
242 static Lisp_Object Qfile_newer_than_file_p
;
243 Lisp_Object Qinsert_file_contents
;
244 Lisp_Object Qwrite_region
;
245 static Lisp_Object Qverify_visited_file_modtime
;
246 static Lisp_Object Qset_visited_file_modtime
;
248 DEFUN ("find-file-name-handler", Ffind_file_name_handler
,
249 Sfind_file_name_handler
, 2, 2, 0,
250 doc
: /* Return FILENAME's handler function for OPERATION, if it has one.
251 Otherwise, return nil.
252 A file name is handled if one of the regular expressions in
253 `file-name-handler-alist' matches it.
255 If OPERATION equals `inhibit-file-name-operation', then we ignore
256 any handlers that are members of `inhibit-file-name-handlers',
257 but we still do run any other handlers. This lets handlers
258 use the standard functions without calling themselves recursively. */)
259 (Lisp_Object filename
, Lisp_Object operation
)
261 /* This function must not munge the match data. */
262 Lisp_Object chain
, inhibited_handlers
, result
;
266 CHECK_STRING (filename
);
268 if (EQ (operation
, Vinhibit_file_name_operation
))
269 inhibited_handlers
= Vinhibit_file_name_handlers
;
271 inhibited_handlers
= Qnil
;
273 for (chain
= Vfile_name_handler_alist
; CONSP (chain
);
274 chain
= XCDR (chain
))
280 Lisp_Object string
= XCAR (elt
);
282 Lisp_Object handler
= XCDR (elt
);
283 Lisp_Object operations
= Qnil
;
285 if (SYMBOLP (handler
))
286 operations
= Fget (handler
, Qoperations
);
289 && (match_pos
= fast_string_match (string
, filename
)) > pos
290 && (NILP (operations
) || ! NILP (Fmemq (operation
, operations
))))
294 handler
= XCDR (elt
);
295 tem
= Fmemq (handler
, inhibited_handlers
);
309 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
311 doc
: /* Return the directory component in file name FILENAME.
312 Return nil if FILENAME does not include a directory.
313 Otherwise return a directory name.
314 Given a Unix syntax file name, returns a string ending in slash. */)
315 (Lisp_Object filename
)
318 register const char *beg
;
322 register const char *p
;
325 CHECK_STRING (filename
);
327 /* If the file name has special constructs in it,
328 call the corresponding file handler. */
329 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
331 return call2 (handler
, Qfile_name_directory
, filename
);
333 filename
= FILE_SYSTEM_CASE (filename
);
335 beg
= (char *) alloca (SBYTES (filename
) + 1);
336 memcpy (beg
, SSDATA (filename
), SBYTES (filename
) + 1);
338 beg
= SSDATA (filename
);
340 p
= beg
+ SBYTES (filename
);
342 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
344 /* only recognize drive specifier at the beginning */
346 /* handle the "/:d:foo" and "/:foo" cases correctly */
347 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
348 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
355 /* Expansion of "c:" to drive and default directory. */
358 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
359 char *res
= alloca (MAXPATHLEN
+ 1);
362 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
364 strncpy (res
, beg
, 2);
369 if (getdefdir (toupper ((unsigned char) *beg
) - 'A' + 1, r
))
371 if (!IS_DIRECTORY_SEP (res
[strlen (res
) - 1]))
374 p
= beg
+ strlen (beg
);
377 dostounix_filename (beg
);
380 return make_specified_string (beg
, -1, p
- beg
, STRING_MULTIBYTE (filename
));
383 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
384 Sfile_name_nondirectory
, 1, 1, 0,
385 doc
: /* Return file name FILENAME sans its directory.
386 For example, in a Unix-syntax file name,
387 this is everything after the last slash,
388 or the entire name if it contains no slash. */)
389 (Lisp_Object filename
)
391 register const char *beg
, *p
, *end
;
394 CHECK_STRING (filename
);
396 /* If the file name has special constructs in it,
397 call the corresponding file handler. */
398 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
400 return call2 (handler
, Qfile_name_nondirectory
, filename
);
402 beg
= SSDATA (filename
);
403 end
= p
= beg
+ SBYTES (filename
);
405 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
407 /* only recognize drive specifier at beginning */
409 /* handle the "/:d:foo" case correctly */
410 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
415 return make_specified_string (p
, -1, end
- p
, STRING_MULTIBYTE (filename
));
418 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
419 Sunhandled_file_name_directory
, 1, 1, 0,
420 doc
: /* Return a directly usable directory name somehow associated with FILENAME.
421 A `directly usable' directory name is one that may be used without the
422 intervention of any file handler.
423 If FILENAME is a directly usable file itself, return
424 \(file-name-directory FILENAME).
425 If FILENAME refers to a file which is not accessible from a local process,
426 then this should return nil.
427 The `call-process' and `start-process' functions use this function to
428 get a current directory to run processes in. */)
429 (Lisp_Object filename
)
433 /* If the file name has special constructs in it,
434 call the corresponding file handler. */
435 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
437 return call2 (handler
, Qunhandled_file_name_directory
, filename
);
439 return Ffile_name_directory (filename
);
444 file_name_as_directory (char *out
, const char *in
)
446 ptrdiff_t len
= strlen (in
);
458 /* For Unix syntax, Append a slash if necessary */
459 if (!IS_DIRECTORY_SEP (out
[len
- 1]))
461 out
[len
] = DIRECTORY_SEP
;
465 dostounix_filename (out
);
470 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
471 Sfile_name_as_directory
, 1, 1, 0,
472 doc
: /* Return a string representing the file name FILE interpreted as a directory.
473 This operation exists because a directory is also a file, but its name as
474 a directory is different from its name as a file.
475 The result can be used as the value of `default-directory'
476 or passed as second argument to `expand-file-name'.
477 For a Unix-syntax file name, just appends a slash. */)
487 /* If the file name has special constructs in it,
488 call the corresponding file handler. */
489 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
491 return call2 (handler
, Qfile_name_as_directory
, file
);
493 buf
= (char *) alloca (SBYTES (file
) + 10);
494 file_name_as_directory (buf
, SSDATA (file
));
495 return make_specified_string (buf
, -1, strlen (buf
),
496 STRING_MULTIBYTE (file
));
500 * Convert from directory name to filename.
501 * On UNIX, it's simple: just make sure there isn't a terminating /
503 * Value is nonzero if the string output is different from the input.
507 directory_file_name (char *src
, char *dst
)
513 /* Process as Unix format: just remove any final slash.
514 But leave "/" unchanged; do not change it to "". */
517 && IS_DIRECTORY_SEP (dst
[slen
- 1])
519 && !IS_ANY_SEP (dst
[slen
- 2])
524 dostounix_filename (dst
);
529 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
531 doc
: /* Returns the file name of the directory named DIRECTORY.
532 This is the name of the file that holds the data for the directory DIRECTORY.
533 This operation exists because a directory is also a file, but its name as
534 a directory is different from its name as a file.
535 In Unix-syntax, this function just removes the final slash. */)
536 (Lisp_Object directory
)
541 CHECK_STRING (directory
);
543 if (NILP (directory
))
546 /* If the file name has special constructs in it,
547 call the corresponding file handler. */
548 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
550 return call2 (handler
, Qdirectory_file_name
, directory
);
552 buf
= (char *) alloca (SBYTES (directory
) + 20);
553 directory_file_name (SSDATA (directory
), buf
);
554 return make_specified_string (buf
, -1, strlen (buf
),
555 STRING_MULTIBYTE (directory
));
558 static const char make_temp_name_tbl
[64] =
560 'A','B','C','D','E','F','G','H',
561 'I','J','K','L','M','N','O','P',
562 'Q','R','S','T','U','V','W','X',
563 'Y','Z','a','b','c','d','e','f',
564 'g','h','i','j','k','l','m','n',
565 'o','p','q','r','s','t','u','v',
566 'w','x','y','z','0','1','2','3',
567 '4','5','6','7','8','9','-','_'
570 static unsigned make_temp_name_count
, make_temp_name_count_initialized_p
;
572 /* Value is a temporary file name starting with PREFIX, a string.
574 The Emacs process number forms part of the result, so there is
575 no danger of generating a name being used by another process.
576 In addition, this function makes an attempt to choose a name
577 which has no existing file. To make this work, PREFIX should be
578 an absolute file name.
580 BASE64_P non-zero means add the pid as 3 characters in base64
581 encoding. In this case, 6 characters will be added to PREFIX to
582 form the file name. Otherwise, if Emacs is running on a system
583 with long file names, add the pid as a decimal number.
585 This function signals an error if no unique file name could be
589 make_temp_name (Lisp_Object prefix
, int base64_p
)
595 char pidbuf
[INT_BUFSIZE_BOUND (printmax_t
)];
598 CHECK_STRING (prefix
);
600 /* VAL is created by adding 6 characters to PREFIX. The first
601 three are the PID of this process, in base 64, and the second
602 three are incremented if the file already exists. This ensures
603 262144 unique file names per PID per PREFIX. */
609 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
610 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
611 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
616 #ifdef HAVE_LONG_FILE_NAMES
617 pidlen
= sprintf (pidbuf
, "%"pMd
, pid
);
619 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
620 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
621 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
626 len
= SBYTES (prefix
); clen
= SCHARS (prefix
);
627 val
= make_uninit_multibyte_string (clen
+ 3 + pidlen
, len
+ 3 + pidlen
);
628 if (!STRING_MULTIBYTE (prefix
))
629 STRING_SET_UNIBYTE (val
);
631 memcpy (data
, SSDATA (prefix
), len
);
634 memcpy (p
, pidbuf
, pidlen
);
637 /* Here we try to minimize useless stat'ing when this function is
638 invoked many times successively with the same PREFIX. We achieve
639 this by initializing count to a random value, and incrementing it
642 We don't want make-temp-name to be called while dumping,
643 because then make_temp_name_count_initialized_p would get set
644 and then make_temp_name_count would not be set when Emacs starts. */
646 if (!make_temp_name_count_initialized_p
)
648 make_temp_name_count
= time (NULL
);
649 make_temp_name_count_initialized_p
= 1;
655 unsigned num
= make_temp_name_count
;
657 p
[0] = make_temp_name_tbl
[num
& 63], num
>>= 6;
658 p
[1] = make_temp_name_tbl
[num
& 63], num
>>= 6;
659 p
[2] = make_temp_name_tbl
[num
& 63], num
>>= 6;
661 /* Poor man's congruential RN generator. Replace with
662 ++make_temp_name_count for debugging. */
663 make_temp_name_count
+= 25229;
664 make_temp_name_count
%= 225307;
666 if (stat (data
, &ignored
) < 0)
668 /* We want to return only if errno is ENOENT. */
672 /* The error here is dubious, but there is little else we
673 can do. The alternatives are to return nil, which is
674 as bad as (and in many cases worse than) throwing the
675 error, or to ignore the error, which will likely result
676 in looping through 225307 stat's, which is not only
677 dog-slow, but also useless since eventually nil would
678 have to be returned anyway. */
679 report_file_error ("Cannot create temporary name for prefix",
680 Fcons (prefix
, Qnil
));
687 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
688 doc
: /* Generate temporary file name (string) starting with PREFIX (a string).
689 The Emacs process number forms part of the result,
690 so there is no danger of generating a name being used by another process.
692 In addition, this function makes an attempt to choose a name
693 which has no existing file. To make this work,
694 PREFIX should be an absolute file name.
696 There is a race condition between calling `make-temp-name' and creating the
697 file which opens all kinds of security holes. For that reason, you should
698 probably use `make-temp-file' instead, except in three circumstances:
700 * If you are creating the file in the user's home directory.
701 * If you are creating a directory rather than an ordinary file.
702 * If you are taking special precautions as `make-temp-file' does. */)
705 return make_temp_name (prefix
, 0);
710 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
711 doc
: /* Convert filename NAME to absolute, and canonicalize it.
712 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
713 \(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
714 the current buffer's value of `default-directory' is used.
715 NAME should be a string that is a valid file name for the underlying
717 File name components that are `.' are removed, and
718 so are file name components followed by `..', along with the `..' itself;
719 note that these simplifications are done without checking the resulting
720 file names in the file system.
721 Multiple consecutive slashes are collapsed into a single slash,
722 except at the beginning of the file name when they are significant (e.g.,
723 UNC file names on MS-Windows.)
724 An initial `~/' expands to your home directory.
725 An initial `~USER/' expands to USER's home directory.
726 See also the function `substitute-in-file-name'.
728 For technical reasons, this function can return correct but
729 non-intuitive results for the root directory; for instance,
730 \(expand-file-name ".." "/") returns "/..". For this reason, use
731 \(directory-file-name (file-name-directory dirname)) to traverse a
732 filesystem tree, not (expand-file-name ".." dirname). */)
733 (Lisp_Object name
, Lisp_Object default_directory
)
735 /* These point to SDATA and need to be careful with string-relocation
736 during GC (via DECODE_FILE). */
739 /* This should only point to alloca'd data. */
746 int collapse_newdir
= 1;
750 Lisp_Object handler
, result
;
756 /* If the file name has special constructs in it,
757 call the corresponding file handler. */
758 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
760 return call3 (handler
, Qexpand_file_name
, name
, default_directory
);
762 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
763 if (NILP (default_directory
))
764 default_directory
= BVAR (current_buffer
, directory
);
765 if (! STRINGP (default_directory
))
768 /* "/" is not considered a root directory on DOS_NT, so using "/"
769 here causes an infinite recursion in, e.g., the following:
771 (let (default-directory)
772 (expand-file-name "a"))
774 To avoid this, we set default_directory to the root of the
776 default_directory
= build_string (emacs_root_dir ());
778 default_directory
= build_string ("/");
782 if (!NILP (default_directory
))
784 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
786 return call3 (handler
, Qexpand_file_name
, name
, default_directory
);
790 char *o
= SSDATA (default_directory
);
792 /* Make sure DEFAULT_DIRECTORY is properly expanded.
793 It would be better to do this down below where we actually use
794 default_directory. Unfortunately, calling Fexpand_file_name recursively
795 could invoke GC, and the strings might be relocated. This would
796 be annoying because we have pointers into strings lying around
797 that would need adjusting, and people would add new pointers to
798 the code and forget to adjust them, resulting in intermittent bugs.
799 Putting this call here avoids all that crud.
801 The EQ test avoids infinite recursion. */
802 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
803 /* Save time in some common cases - as long as default_directory
804 is not relative, it can be canonicalized with name below (if it
805 is needed at all) without requiring it to be expanded now. */
807 /* Detect MSDOS file names with drive specifiers. */
808 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1])
809 && IS_DIRECTORY_SEP (o
[2]))
811 /* Detect Windows file names in UNC format. */
812 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
814 #else /* not DOS_NT */
815 /* Detect Unix absolute file names (/... alone is not absolute on
817 && ! (IS_DIRECTORY_SEP (o
[0]))
818 #endif /* not DOS_NT */
824 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
828 name
= FILE_SYSTEM_CASE (name
);
829 multibyte
= STRING_MULTIBYTE (name
);
830 if (multibyte
!= STRING_MULTIBYTE (default_directory
))
833 default_directory
= string_to_multibyte (default_directory
);
836 name
= string_to_multibyte (name
);
841 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
842 nm
= (char *) alloca (SBYTES (name
) + 1);
843 memcpy (nm
, SSDATA (name
), SBYTES (name
) + 1);
846 /* Note if special escape prefix is present, but remove for now. */
847 if (nm
[0] == '/' && nm
[1] == ':')
853 /* Find and remove drive specifier if present; this makes nm absolute
854 even if the rest of the name appears to be relative. Only look for
855 drive specifier at the beginning. */
856 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
858 drive
= (unsigned char) nm
[0];
863 /* If we see "c://somedir", we want to strip the first slash after the
864 colon when stripping the drive letter. Otherwise, this expands to
866 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
869 /* Discard any previous drive specifier if nm is now in UNC format. */
870 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
874 #endif /* WINDOWSNT */
877 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
878 none are found, we can probably return right away. We will avoid
879 allocating a new string if name is already fully expanded. */
881 IS_DIRECTORY_SEP (nm
[0])
883 && drive
&& !is_escaped
886 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
890 /* If it turns out that the filename we want to return is just a
891 suffix of FILENAME, we don't need to go through and edit
892 things; we just need to construct a new string using data
893 starting at the middle of FILENAME. If we set lose to a
894 non-zero value, that means we've discovered that we can't do
901 /* Since we know the name is absolute, we can assume that each
902 element starts with a "/". */
904 /* "." and ".." are hairy. */
905 if (IS_DIRECTORY_SEP (p
[0])
907 && (IS_DIRECTORY_SEP (p
[2])
909 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
912 /* We want to replace multiple `/' in a row with a single
915 && IS_DIRECTORY_SEP (p
[0])
916 && IS_DIRECTORY_SEP (p
[1]))
923 /* Make sure directories are all separated with /, but
924 avoid allocation of a new string when not required. */
925 dostounix_filename (nm
);
927 if (IS_DIRECTORY_SEP (nm
[1]))
929 if (strcmp (nm
, SSDATA (name
)) != 0)
930 name
= make_specified_string (nm
, -1, strlen (nm
), multibyte
);
934 /* drive must be set, so this is okay */
935 if (strcmp (nm
- 2, SSDATA (name
)) != 0)
939 name
= make_specified_string (nm
, -1, p
- nm
, multibyte
);
940 temp
[0] = DRIVE_LETTER (drive
);
941 name
= concat2 (build_string (temp
), name
);
944 #else /* not DOS_NT */
945 if (strcmp (nm
, SSDATA (name
)) == 0)
947 return make_specified_string (nm
, -1, strlen (nm
), multibyte
);
948 #endif /* not DOS_NT */
952 /* At this point, nm might or might not be an absolute file name. We
953 need to expand ~ or ~user if present, otherwise prefix nm with
954 default_directory if nm is not absolute, and finally collapse /./
955 and /foo/../ sequences.
957 We set newdir to be the appropriate prefix if one is needed:
958 - the relevant user directory if nm starts with ~ or ~user
959 - the specified drive's working dir (DOS/NT only) if nm does not
961 - the value of default_directory.
963 Note that these prefixes are not guaranteed to be absolute (except
964 for the working dir of a drive). Therefore, to ensure we always
965 return an absolute name, if the final prefix is not absolute we
966 append it to the current working directory. */
970 if (nm
[0] == '~') /* prefix ~ */
972 if (IS_DIRECTORY_SEP (nm
[1])
973 || nm
[1] == 0) /* ~ by itself */
977 if (!(newdir
= egetenv ("HOME")))
980 /* egetenv may return a unibyte string, which will bite us since
981 we expect the directory to be multibyte. */
982 tem
= build_string (newdir
);
983 if (!STRING_MULTIBYTE (tem
))
985 hdir
= DECODE_FILE (tem
);
986 newdir
= SSDATA (hdir
);
992 else /* ~user/filename */
995 for (p
= nm
; *p
&& (!IS_DIRECTORY_SEP (*p
)); p
++);
996 o
= alloca (p
- nm
+ 1);
997 memcpy (o
, nm
, p
- nm
);
1001 pw
= (struct passwd
*) getpwnam (o
+ 1);
1005 newdir
= pw
->pw_dir
;
1008 collapse_newdir
= 0;
1012 /* If we don't find a user of that name, leave the name
1013 unchanged; don't move nm forward to p. */
1018 /* On DOS and Windows, nm is absolute if a drive name was specified;
1019 use the drive's current directory as the prefix if needed. */
1020 if (!newdir
&& drive
)
1022 /* Get default directory if needed to make nm absolute. */
1024 if (!IS_DIRECTORY_SEP (nm
[0]))
1026 adir
= alloca (MAXPATHLEN
+ 1);
1027 if (!getdefdir (toupper (drive
) - 'A' + 1, adir
))
1032 /* Either nm starts with /, or drive isn't mounted. */
1034 adir
[0] = DRIVE_LETTER (drive
);
1043 /* Finally, if no prefix has been specified and nm is not absolute,
1044 then it must be expanded relative to default_directory. */
1048 /* /... alone is not absolute on DOS and Windows. */
1049 && !IS_DIRECTORY_SEP (nm
[0])
1052 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1056 newdir
= SSDATA (default_directory
);
1058 /* Note if special escape prefix is present, but remove for now. */
1059 if (newdir
[0] == '/' && newdir
[1] == ':')
1070 /* First ensure newdir is an absolute name. */
1072 /* Detect MSDOS file names with drive specifiers. */
1073 ! (IS_DRIVE (newdir
[0])
1074 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1076 /* Detect Windows file names in UNC format. */
1077 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1081 /* Effectively, let newdir be (expand-file-name newdir cwd).
1082 Because of the admonition against calling expand-file-name
1083 when we have pointers into lisp strings, we accomplish this
1084 indirectly by prepending newdir to nm if necessary, and using
1085 cwd (or the wd of newdir's drive) as the new newdir. */
1087 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1089 drive
= (unsigned char) newdir
[0];
1092 if (!IS_DIRECTORY_SEP (nm
[0]))
1094 char * tmp
= alloca (strlen (newdir
) + strlen (nm
) + 2);
1095 file_name_as_directory (tmp
, newdir
);
1099 adir
= alloca (MAXPATHLEN
+ 1);
1102 if (!getdefdir (toupper (drive
) - 'A' + 1, adir
))
1110 /* Strip off drive name from prefix, if present. */
1111 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1117 /* Keep only a prefix from newdir if nm starts with slash
1118 (//server/share for UNC, nothing otherwise). */
1119 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1122 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1124 char *adir
= strcpy (alloca (strlen (newdir
) + 1), newdir
);
1126 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1128 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1141 /* Get rid of any slash at the end of newdir, unless newdir is
1142 just / or // (an incomplete UNC name). */
1143 length
= strlen (newdir
);
1144 if (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1146 && !(length
== 2 && IS_DIRECTORY_SEP (newdir
[0]))
1150 char *temp
= (char *) alloca (length
);
1151 memcpy (temp
, newdir
, length
- 1);
1152 temp
[length
- 1] = 0;
1160 /* Now concatenate the directory and name to new space in the stack frame */
1161 tlen
+= strlen (nm
) + 1;
1163 /* Reserve space for drive specifier and escape prefix, since either
1164 or both may need to be inserted. (The Microsoft x86 compiler
1165 produces incorrect code if the following two lines are combined.) */
1166 target
= (char *) alloca (tlen
+ 4);
1168 #else /* not DOS_NT */
1169 target
= (char *) alloca (tlen
);
1170 #endif /* not DOS_NT */
1175 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1178 /* If newdir is effectively "C:/", then the drive letter will have
1179 been stripped and newdir will be "/". Concatenating with an
1180 absolute directory in nm produces "//", which will then be
1181 incorrectly treated as a network share. Ignore newdir in
1182 this case (keeping the drive letter). */
1183 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1184 && newdir
[1] == '\0'))
1186 strcpy (target
, newdir
);
1189 file_name_as_directory (target
, newdir
);
1192 strcat (target
, nm
);
1194 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1202 if (!IS_DIRECTORY_SEP (*p
))
1206 else if (p
[1] == '.'
1207 && (IS_DIRECTORY_SEP (p
[2])
1210 /* If "/." is the entire filename, keep the "/". Otherwise,
1211 just delete the whole "/.". */
1212 if (o
== target
&& p
[2] == '\0')
1216 else if (p
[1] == '.' && p
[2] == '.'
1217 /* `/../' is the "superroot" on certain file systems.
1218 Turned off on DOS_NT systems because they have no
1219 "superroot" and because this causes us to produce
1220 file names like "d:/../foo" which fail file-related
1221 functions of the underlying OS. (To reproduce, try a
1222 long series of "../../" in default_directory, longer
1223 than the number of levels from the root.) */
1227 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1232 while (o
!= target
&& (--o
) && !IS_DIRECTORY_SEP (*o
))
1235 /* Don't go below server level in UNC filenames. */
1236 if (o
== target
+ 1 && IS_DIRECTORY_SEP (*o
)
1237 && IS_DIRECTORY_SEP (*target
))
1241 /* Keep initial / only if this is the whole name. */
1242 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1246 else if (p
> target
&& IS_DIRECTORY_SEP (p
[1]))
1247 /* Collapse multiple `/' in a row. */
1256 /* At last, set drive name. */
1258 /* Except for network file name. */
1259 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1260 #endif /* WINDOWSNT */
1262 if (!drive
) abort ();
1264 target
[0] = DRIVE_LETTER (drive
);
1267 /* Reinsert the escape prefix if required. */
1274 dostounix_filename (target
);
1277 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1280 /* Again look to see if the file name has special constructs in it
1281 and perhaps call the corresponding file handler. This is needed
1282 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1283 the ".." component gives us "/user@host:/bar/../baz" which needs
1284 to be expanded again. */
1285 handler
= Ffind_file_name_handler (result
, Qexpand_file_name
);
1286 if (!NILP (handler
))
1287 return call3 (handler
, Qexpand_file_name
, result
, default_directory
);
1293 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1294 This is the old version of expand-file-name, before it was thoroughly
1295 rewritten for Emacs 10.31. We leave this version here commented-out,
1296 because the code is very complex and likely to have subtle bugs. If
1297 bugs _are_ found, it might be of interest to look at the old code and
1298 see what did it do in the relevant situation.
1300 Don't remove this code: it's true that it will be accessible
1301 from the repository, but a few years from deletion, people will
1302 forget it is there. */
1304 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1305 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1306 "Convert FILENAME to absolute, and canonicalize it.\n\
1307 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1308 \(does not start with slash); if DEFAULT is nil or missing,\n\
1309 the current buffer's value of default-directory is used.\n\
1310 Filenames containing `.' or `..' as components are simplified;\n\
1311 initial `~/' expands to your home directory.\n\
1312 See also the function `substitute-in-file-name'.")
1314 Lisp_Object name
, defalt
;
1318 register unsigned char *newdir
, *p
, *o
;
1320 unsigned char *target
;
1324 CHECK_STRING (name
);
1327 /* If nm is absolute, flush ...// and detect /./ and /../.
1328 If no /./ or /../ we can return right away. */
1335 if (p
[0] == '/' && p
[1] == '/'
1338 if (p
[0] == '/' && p
[1] == '~')
1339 nm
= p
+ 1, lose
= 1;
1340 if (p
[0] == '/' && p
[1] == '.'
1341 && (p
[2] == '/' || p
[2] == 0
1342 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1348 if (nm
== SDATA (name
))
1350 return build_string (nm
);
1354 /* Now determine directory to start with and put it in NEWDIR */
1358 if (nm
[0] == '~') /* prefix ~ */
1359 if (nm
[1] == '/' || nm
[1] == 0)/* ~/filename */
1361 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1362 newdir
= (unsigned char *) "";
1365 else /* ~user/filename */
1367 /* Get past ~ to user */
1368 unsigned char *user
= nm
+ 1;
1369 /* Find end of name. */
1370 unsigned char *ptr
= (unsigned char *) strchr (user
, '/');
1371 ptrdiff_t len
= ptr
? ptr
- user
: strlen (user
);
1372 /* Copy the user name into temp storage. */
1373 o
= (unsigned char *) alloca (len
+ 1);
1374 memcpy (o
, user
, len
);
1377 /* Look up the user name. */
1379 pw
= (struct passwd
*) getpwnam (o
+ 1);
1382 error ("\"%s\" isn't a registered user", o
+ 1);
1384 newdir
= (unsigned char *) pw
->pw_dir
;
1386 /* Discard the user name from NM. */
1390 if (nm
[0] != '/' && !newdir
)
1393 defalt
= current_buffer
->directory
;
1394 CHECK_STRING (defalt
);
1395 newdir
= SDATA (defalt
);
1398 /* Now concatenate the directory and name to new space in the stack frame */
1400 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1401 target
= (unsigned char *) alloca (tlen
);
1406 if (nm
[0] == 0 || nm
[0] == '/')
1407 strcpy (target
, newdir
);
1409 file_name_as_directory (target
, newdir
);
1412 strcat (target
, nm
);
1414 /* Now canonicalize by removing /. and /foo/.. if they appear */
1425 else if (!strncmp (p
, "//", 2)
1431 else if (p
[0] == '/' && p
[1] == '.'
1432 && (p
[2] == '/' || p
[2] == 0))
1434 else if (!strncmp (p
, "/..", 3)
1435 /* `/../' is the "superroot" on certain file systems. */
1437 && (p
[3] == '/' || p
[3] == 0))
1439 while (o
!= target
&& *--o
!= '/')
1441 if (o
== target
&& *o
== '/')
1451 return make_string (target
, o
- target
);
1455 /* If /~ or // appears, discard everything through first slash. */
1457 file_name_absolute_p (const char *filename
)
1460 (IS_DIRECTORY_SEP (*filename
) || *filename
== '~'
1462 || (IS_DRIVE (*filename
) && IS_DEVICE_SEP (filename
[1])
1463 && IS_DIRECTORY_SEP (filename
[2]))
1469 search_embedded_absfilename (char *nm
, char *endp
)
1473 for (p
= nm
+ 1; p
< endp
; p
++)
1476 || IS_DIRECTORY_SEP (p
[-1]))
1477 && file_name_absolute_p (p
)
1478 #if defined (WINDOWSNT) || defined (CYGWIN)
1479 /* // at start of file name is meaningful in Apollo,
1480 WindowsNT and Cygwin systems. */
1481 && !(IS_DIRECTORY_SEP (p
[0]) && p
- 1 == nm
)
1482 #endif /* not (WINDOWSNT || CYGWIN) */
1485 for (s
= p
; *s
&& (!IS_DIRECTORY_SEP (*s
)); s
++);
1486 if (p
[0] == '~' && s
> p
+ 1) /* we've got "/~something/" */
1488 char *o
= alloca (s
- p
+ 1);
1490 memcpy (o
, p
, s
- p
);
1493 /* If we have ~user and `user' exists, discard
1494 everything up to ~. But if `user' does not exist, leave
1495 ~user alone, it might be a literal file name. */
1497 pw
= getpwnam (o
+ 1);
1509 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
1510 Ssubstitute_in_file_name
, 1, 1, 0,
1511 doc
: /* Substitute environment variables referred to in FILENAME.
1512 `$FOO' where FOO is an environment variable name means to substitute
1513 the value of that variable. The variable name should be terminated
1514 with a character not a letter, digit or underscore; otherwise, enclose
1515 the entire variable name in braces.
1517 If `/~' appears, all of FILENAME through that `/' is discarded.
1518 If `//' appears, everything up to and including the first of
1519 those `/' is discarded. */)
1520 (Lisp_Object filename
)
1524 register char *s
, *p
, *o
, *x
, *endp
;
1525 char *target
= NULL
;
1527 int substituted
= 0;
1530 Lisp_Object handler
;
1532 CHECK_STRING (filename
);
1534 multibyte
= STRING_MULTIBYTE (filename
);
1536 /* If the file name has special constructs in it,
1537 call the corresponding file handler. */
1538 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
1539 if (!NILP (handler
))
1540 return call2 (handler
, Qsubstitute_in_file_name
, filename
);
1542 /* Always work on a copy of the string, in case GC happens during
1543 decode of environment variables, causing the original Lisp_String
1544 data to be relocated. */
1545 nm
= (char *) alloca (SBYTES (filename
) + 1);
1546 memcpy (nm
, SDATA (filename
), SBYTES (filename
) + 1);
1549 dostounix_filename (nm
);
1550 substituted
= (strcmp (nm
, SDATA (filename
)) != 0);
1552 endp
= nm
+ SBYTES (filename
);
1554 /* If /~ or // appears, discard everything through first slash. */
1555 p
= search_embedded_absfilename (nm
, endp
);
1557 /* Start over with the new string, so we check the file-name-handler
1558 again. Important with filenames like "/home/foo//:/hello///there"
1559 which would substitute to "/:/hello///there" rather than "/there". */
1560 return Fsubstitute_in_file_name
1561 (make_specified_string (p
, -1, endp
- p
, multibyte
));
1563 /* See if any variables are substituted into the string
1564 and find the total length of their values in `total' */
1566 for (p
= nm
; p
!= endp
;)
1576 /* "$$" means a single "$" */
1585 while (p
!= endp
&& *p
!= '}') p
++;
1586 if (*p
!= '}') goto missingclose
;
1592 while (p
!= endp
&& (isalnum (*p
) || *p
== '_')) p
++;
1596 /* Copy out the variable name */
1597 target
= (char *) alloca (s
- o
+ 1);
1598 strncpy (target
, o
, s
- o
);
1601 strupr (target
); /* $home == $HOME etc. */
1604 /* Get variable value */
1605 o
= egetenv (target
);
1608 /* Don't try to guess a maximum length - UTF8 can use up to
1609 four bytes per character. This code is unlikely to run
1610 in a situation that requires performance, so decoding the
1611 env variables twice should be acceptable. Note that
1612 decoding may cause a garbage collect. */
1613 Lisp_Object orig
, decoded
;
1614 orig
= make_unibyte_string (o
, strlen (o
));
1615 decoded
= DECODE_FILE (orig
);
1616 total
+= SBYTES (decoded
);
1626 /* If substitution required, recopy the string and do it */
1627 /* Make space in stack frame for the new copy */
1628 xnm
= (char *) alloca (SBYTES (filename
) + total
+ 1);
1631 /* Copy the rest of the name through, replacing $ constructs with values */
1648 while (p
!= endp
&& *p
!= '}') p
++;
1649 if (*p
!= '}') goto missingclose
;
1655 while (p
!= endp
&& (isalnum (*p
) || *p
== '_')) p
++;
1659 /* Copy out the variable name */
1660 target
= (char *) alloca (s
- o
+ 1);
1661 strncpy (target
, o
, s
- o
);
1664 strupr (target
); /* $home == $HOME etc. */
1667 /* Get variable value */
1668 o
= egetenv (target
);
1672 strcpy (x
, target
); x
+= strlen (target
);
1676 Lisp_Object orig
, decoded
;
1677 ptrdiff_t orig_length
, decoded_length
;
1678 orig_length
= strlen (o
);
1679 orig
= make_unibyte_string (o
, orig_length
);
1680 decoded
= DECODE_FILE (orig
);
1681 decoded_length
= SBYTES (decoded
);
1682 strncpy (x
, SSDATA (decoded
), decoded_length
);
1683 x
+= decoded_length
;
1685 /* If environment variable needed decoding, return value
1686 needs to be multibyte. */
1687 if (decoded_length
!= orig_length
1688 || strncmp (SSDATA (decoded
), o
, orig_length
))
1695 /* If /~ or // appears, discard everything through first slash. */
1696 while ((p
= search_embedded_absfilename (xnm
, x
)))
1697 /* This time we do not start over because we've already expanded envvars
1698 and replaced $$ with $. Maybe we should start over as well, but we'd
1699 need to quote some $ to $$ first. */
1702 return make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1705 error ("Bad format environment-variable substitution");
1707 error ("Missing \"}\" in environment-variable substitution");
1709 error ("Substituting nonexistent environment variable \"%s\"", target
);
1715 /* A slightly faster and more convenient way to get
1716 (directory-file-name (expand-file-name FOO)). */
1719 expand_and_dir_to_file (Lisp_Object filename
, Lisp_Object defdir
)
1721 register Lisp_Object absname
;
1723 absname
= Fexpand_file_name (filename
, defdir
);
1725 /* Remove final slash, if any (unless this is the root dir).
1726 stat behaves differently depending! */
1727 if (SCHARS (absname
) > 1
1728 && IS_DIRECTORY_SEP (SREF (absname
, SBYTES (absname
) - 1))
1729 && !IS_DEVICE_SEP (SREF (absname
, SBYTES (absname
)-2)))
1730 /* We cannot take shortcuts; they might be wrong for magic file names. */
1731 absname
= Fdirectory_file_name (absname
);
1735 /* Signal an error if the file ABSNAME already exists.
1736 If INTERACTIVE is nonzero, ask the user whether to proceed,
1737 and bypass the error if the user says to go ahead.
1738 QUERYSTRING is a name for the action that is being considered
1741 *STATPTR is used to store the stat information if the file exists.
1742 If the file does not exist, STATPTR->st_mode is set to 0.
1743 If STATPTR is null, we don't store into it.
1745 If QUICK is nonzero, we ask for y or n, not yes or no. */
1748 barf_or_query_if_file_exists (Lisp_Object absname
, const char *querystring
,
1749 int interactive
, struct stat
*statptr
, int quick
)
1751 register Lisp_Object tem
, encoded_filename
;
1752 struct stat statbuf
;
1753 struct gcpro gcpro1
;
1755 encoded_filename
= ENCODE_FILE (absname
);
1757 /* stat is a good way to tell whether the file exists,
1758 regardless of what access permissions it has. */
1759 if (lstat (SSDATA (encoded_filename
), &statbuf
) >= 0)
1761 if (S_ISDIR (statbuf
.st_mode
))
1762 xsignal2 (Qfile_error
,
1763 build_string ("File is a directory"), absname
);
1766 xsignal2 (Qfile_already_exists
,
1767 build_string ("File already exists"), absname
);
1769 tem
= format2 ("File %s already exists; %s anyway? ",
1770 absname
, build_string (querystring
));
1772 tem
= call1 (intern ("y-or-n-p"), tem
);
1774 tem
= do_yes_or_no_p (tem
);
1777 xsignal2 (Qfile_already_exists
,
1778 build_string ("File already exists"), absname
);
1785 statptr
->st_mode
= 0;
1790 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 6,
1791 "fCopy file: \nGCopy %s to file: \np\nP",
1792 doc
: /* Copy FILE to NEWNAME. Both args must be strings.
1793 If NEWNAME names a directory, copy FILE there.
1795 This function always sets the file modes of the output file to match
1798 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1799 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1800 signal a `file-already-exists' error without overwriting. If
1801 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1802 about overwriting; this is what happens in interactive use with M-x.
1803 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1806 Fourth arg KEEP-TIME non-nil means give the output file the same
1807 last-modified time as the old one. (This works on only some systems.)
1809 A prefix arg makes KEEP-TIME non-nil.
1811 If PRESERVE-UID-GID is non-nil, we try to transfer the
1812 uid and gid of FILE to NEWNAME.
1814 If PRESERVE-SELINUX-CONTEXT is non-nil and SELinux is enabled
1815 on the system, we copy the SELinux context of FILE to NEWNAME. */)
1816 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
, Lisp_Object keep_time
, Lisp_Object preserve_uid_gid
, Lisp_Object preserve_selinux_context
)
1820 char buf
[16 * 1024];
1821 struct stat st
, out_st
;
1822 Lisp_Object handler
;
1823 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1824 ptrdiff_t count
= SPECPDL_INDEX ();
1825 int input_file_statable_p
;
1826 Lisp_Object encoded_file
, encoded_newname
;
1828 security_context_t con
;
1829 int fail
, conlength
= 0;
1832 encoded_file
= encoded_newname
= Qnil
;
1833 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
1834 CHECK_STRING (file
);
1835 CHECK_STRING (newname
);
1837 if (!NILP (Ffile_directory_p (newname
)))
1838 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
1840 newname
= Fexpand_file_name (newname
, Qnil
);
1842 file
= Fexpand_file_name (file
, Qnil
);
1844 /* If the input file name has special constructs in it,
1845 call the corresponding file handler. */
1846 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
1847 /* Likewise for output file name. */
1849 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
1850 if (!NILP (handler
))
1851 RETURN_UNGCPRO (call7 (handler
, Qcopy_file
, file
, newname
,
1852 ok_if_already_exists
, keep_time
, preserve_uid_gid
,
1853 preserve_selinux_context
));
1855 encoded_file
= ENCODE_FILE (file
);
1856 encoded_newname
= ENCODE_FILE (newname
);
1858 if (NILP (ok_if_already_exists
)
1859 || INTEGERP (ok_if_already_exists
))
1860 barf_or_query_if_file_exists (newname
, "copy to it",
1861 INTEGERP (ok_if_already_exists
), &out_st
, 0);
1862 else if (stat (SSDATA (encoded_newname
), &out_st
) < 0)
1866 if (!CopyFile (SDATA (encoded_file
),
1867 SDATA (encoded_newname
),
1869 report_file_error ("Copying file", Fcons (file
, Fcons (newname
, Qnil
)));
1870 /* CopyFile retains the timestamp by default. */
1871 else if (NILP (keep_time
))
1877 EMACS_GET_TIME (now
);
1878 filename
= SDATA (encoded_newname
);
1880 /* Ensure file is writable while its modified time is set. */
1881 attributes
= GetFileAttributes (filename
);
1882 SetFileAttributes (filename
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
1883 if (set_file_times (filename
, now
, now
))
1885 /* Restore original attributes. */
1886 SetFileAttributes (filename
, attributes
);
1887 xsignal2 (Qfile_date_error
,
1888 build_string ("Cannot set file date"), newname
);
1890 /* Restore original attributes. */
1891 SetFileAttributes (filename
, attributes
);
1893 #else /* not WINDOWSNT */
1895 ifd
= emacs_open (SSDATA (encoded_file
), O_RDONLY
, 0);
1899 report_file_error ("Opening input file", Fcons (file
, Qnil
));
1901 record_unwind_protect (close_file_unwind
, make_number (ifd
));
1903 /* We can only copy regular files and symbolic links. Other files are not
1905 input_file_statable_p
= (fstat (ifd
, &st
) >= 0);
1908 if (!NILP (preserve_selinux_context
) && is_selinux_enabled ())
1910 conlength
= fgetfilecon (ifd
, &con
);
1911 if (conlength
== -1)
1912 report_file_error ("Doing fgetfilecon", Fcons (file
, Qnil
));
1916 if (out_st
.st_mode
!= 0
1917 && st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
1920 report_file_error ("Input and output files are the same",
1921 Fcons (file
, Fcons (newname
, Qnil
)));
1924 if (input_file_statable_p
)
1926 if (!(S_ISREG (st
.st_mode
)) && !(S_ISLNK (st
.st_mode
)))
1928 #if defined (EISDIR)
1929 /* Get a better looking error message. */
1932 report_file_error ("Non-regular file", Fcons (file
, Qnil
));
1937 /* System's default file type was set to binary by _fmode in emacs.c. */
1938 ofd
= emacs_open (SDATA (encoded_newname
),
1939 O_WRONLY
| O_TRUNC
| O_CREAT
1940 | (NILP (ok_if_already_exists
) ? O_EXCL
: 0),
1941 S_IREAD
| S_IWRITE
);
1942 #else /* not MSDOS */
1944 int new_mask
= 0666;
1945 if (input_file_statable_p
)
1947 if (!NILP (preserve_uid_gid
))
1949 new_mask
&= st
.st_mode
;
1951 ofd
= emacs_open (SSDATA (encoded_newname
),
1952 (O_WRONLY
| O_TRUNC
| O_CREAT
1953 | (NILP (ok_if_already_exists
) ? O_EXCL
: 0)),
1956 #endif /* not MSDOS */
1958 report_file_error ("Opening output file", Fcons (newname
, Qnil
));
1960 record_unwind_protect (close_file_unwind
, make_number (ofd
));
1964 while ((n
= emacs_read (ifd
, buf
, sizeof buf
)) > 0)
1965 if (emacs_write (ofd
, buf
, n
) != n
)
1966 report_file_error ("I/O error", Fcons (newname
, Qnil
));
1970 /* Preserve the original file modes, and if requested, also its
1972 if (input_file_statable_p
)
1974 int mode_mask
= 07777;
1975 if (!NILP (preserve_uid_gid
))
1977 /* Attempt to change owner and group. If that doesn't work
1978 attempt to change just the group, as that is sometimes allowed.
1979 Adjust the mode mask to eliminate setuid or setgid bits
1980 that are inappropriate if the owner and group are wrong. */
1981 if (fchown (ofd
, st
.st_uid
, st
.st_gid
) != 0)
1983 mode_mask
&= ~06000;
1984 if (fchown (ofd
, -1, st
.st_gid
) == 0)
1988 if (fchmod (ofd
, st
.st_mode
& mode_mask
) != 0)
1989 report_file_error ("Doing chmod", Fcons (newname
, Qnil
));
1991 #endif /* not MSDOS */
1996 /* Set the modified context back to the file. */
1997 fail
= fsetfilecon (ofd
, con
);
1999 report_file_error ("Doing fsetfilecon", Fcons (newname
, Qnil
));
2005 /* Closing the output clobbers the file times on some systems. */
2006 if (emacs_close (ofd
) < 0)
2007 report_file_error ("I/O error", Fcons (newname
, Qnil
));
2009 if (input_file_statable_p
)
2011 if (!NILP (keep_time
))
2013 EMACS_TIME atime
, mtime
;
2014 EMACS_SET_SECS_USECS (atime
, st
.st_atime
, 0);
2015 EMACS_SET_SECS_USECS (mtime
, st
.st_mtime
, 0);
2016 if (set_file_times (SSDATA (encoded_newname
),
2018 xsignal2 (Qfile_date_error
,
2019 build_string ("Cannot set file date"), newname
);
2026 if (input_file_statable_p
)
2028 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2029 and if it can't, it tells so. Otherwise, under MSDOS we usually
2030 get only the READ bit, which will make the copied file read-only,
2031 so it's better not to chmod at all. */
2032 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2033 chmod (SDATA (encoded_newname
), st
.st_mode
& 07777);
2036 #endif /* not WINDOWSNT */
2038 /* Discard the unwind protects. */
2039 specpdl_ptr
= specpdl
+ count
;
2045 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2046 Smake_directory_internal
, 1, 1, 0,
2047 doc
: /* Create a new directory named DIRECTORY. */)
2048 (Lisp_Object directory
)
2051 Lisp_Object handler
;
2052 Lisp_Object encoded_dir
;
2054 CHECK_STRING (directory
);
2055 directory
= Fexpand_file_name (directory
, Qnil
);
2057 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2058 if (!NILP (handler
))
2059 return call2 (handler
, Qmake_directory_internal
, directory
);
2061 encoded_dir
= ENCODE_FILE (directory
);
2063 dir
= SSDATA (encoded_dir
);
2066 if (mkdir (dir
) != 0)
2068 if (mkdir (dir
, 0777 & ~auto_saving_dir_umask
) != 0)
2070 report_file_error ("Creating directory", list1 (directory
));
2075 DEFUN ("delete-directory-internal", Fdelete_directory_internal
,
2076 Sdelete_directory_internal
, 1, 1, 0,
2077 doc
: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2078 (Lisp_Object directory
)
2081 Lisp_Object encoded_dir
;
2083 CHECK_STRING (directory
);
2084 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2085 encoded_dir
= ENCODE_FILE (directory
);
2086 dir
= SSDATA (encoded_dir
);
2088 if (rmdir (dir
) != 0)
2089 report_file_error ("Removing directory", list1 (directory
));
2094 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 2,
2095 "(list (read-file-name \
2096 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2097 \"Move file to trash: \" \"Delete file: \") \
2098 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2099 (null current-prefix-arg))",
2100 doc
: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2101 If file has multiple names, it continues to exist with the other names.
2102 TRASH non-nil means to trash the file instead of deleting, provided
2103 `delete-by-moving-to-trash' is non-nil.
2105 When called interactively, TRASH is t if no prefix argument is given.
2106 With a prefix argument, TRASH is nil. */)
2107 (Lisp_Object filename
, Lisp_Object trash
)
2109 Lisp_Object handler
;
2110 Lisp_Object encoded_file
;
2111 struct gcpro gcpro1
;
2114 if (!NILP (Ffile_directory_p (filename
))
2115 && NILP (Ffile_symlink_p (filename
)))
2116 xsignal2 (Qfile_error
,
2117 build_string ("Removing old name: is a directory"),
2120 filename
= Fexpand_file_name (filename
, Qnil
);
2122 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2123 if (!NILP (handler
))
2124 return call3 (handler
, Qdelete_file
, filename
, trash
);
2126 if (delete_by_moving_to_trash
&& !NILP (trash
))
2127 return call1 (Qmove_file_to_trash
, filename
);
2129 encoded_file
= ENCODE_FILE (filename
);
2131 if (0 > unlink (SSDATA (encoded_file
)))
2132 report_file_error ("Removing old name", list1 (filename
));
2137 internal_delete_file_1 (Lisp_Object ignore
)
2142 /* Delete file FILENAME, returning 1 if successful and 0 if failed.
2143 This ignores `delete-by-moving-to-trash'. */
2146 internal_delete_file (Lisp_Object filename
)
2150 tem
= internal_condition_case_2 (Fdelete_file
, filename
, Qnil
,
2151 Qt
, internal_delete_file_1
);
2155 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2156 "fRename file: \nGRename %s to file: \np",
2157 doc
: /* Rename FILE as NEWNAME. Both args must be strings.
2158 If file has names other than FILE, it continues to have those names.
2159 Signals a `file-already-exists' error if a file NEWNAME already exists
2160 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2161 A number as third arg means request confirmation if NEWNAME already exists.
2162 This is what happens in interactive use with M-x. */)
2163 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2165 Lisp_Object handler
;
2166 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
2167 Lisp_Object encoded_file
, encoded_newname
, symlink_target
;
2169 symlink_target
= encoded_file
= encoded_newname
= Qnil
;
2170 GCPRO5 (file
, newname
, encoded_file
, encoded_newname
, symlink_target
);
2171 CHECK_STRING (file
);
2172 CHECK_STRING (newname
);
2173 file
= Fexpand_file_name (file
, Qnil
);
2175 if ((!NILP (Ffile_directory_p (newname
)))
2177 /* If the file names are identical but for the case,
2178 don't attempt to move directory to itself. */
2179 && (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2183 Lisp_Object fname
= NILP (Ffile_directory_p (file
))
2184 ? file
: Fdirectory_file_name (file
);
2185 newname
= Fexpand_file_name (Ffile_name_nondirectory (fname
), newname
);
2188 newname
= Fexpand_file_name (newname
, Qnil
);
2190 /* If the file name has special constructs in it,
2191 call the corresponding file handler. */
2192 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2194 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2195 if (!NILP (handler
))
2196 RETURN_UNGCPRO (call4 (handler
, Qrename_file
,
2197 file
, newname
, ok_if_already_exists
));
2199 encoded_file
= ENCODE_FILE (file
);
2200 encoded_newname
= ENCODE_FILE (newname
);
2203 /* If the file names are identical but for the case, don't ask for
2204 confirmation: they simply want to change the letter-case of the
2206 if (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2208 if (NILP (ok_if_already_exists
)
2209 || INTEGERP (ok_if_already_exists
))
2210 barf_or_query_if_file_exists (newname
, "rename to it",
2211 INTEGERP (ok_if_already_exists
), 0, 0);
2212 if (0 > rename (SSDATA (encoded_file
), SSDATA (encoded_newname
)))
2217 symlink_target
= Ffile_symlink_p (file
);
2218 if (! NILP (symlink_target
))
2219 Fmake_symbolic_link (symlink_target
, newname
,
2220 NILP (ok_if_already_exists
) ? Qnil
: Qt
);
2221 else if (!NILP (Ffile_directory_p (file
)))
2222 call4 (Qcopy_directory
, file
, newname
, Qt
, Qnil
);
2224 /* We have already prompted if it was an integer, so don't
2225 have copy-file prompt again. */
2226 Fcopy_file (file
, newname
,
2227 NILP (ok_if_already_exists
) ? Qnil
: Qt
,
2230 count
= SPECPDL_INDEX ();
2231 specbind (Qdelete_by_moving_to_trash
, Qnil
);
2233 if (!NILP (Ffile_directory_p (file
)) && NILP (symlink_target
))
2234 call2 (Qdelete_directory
, file
, Qt
);
2236 Fdelete_file (file
, Qnil
);
2237 unbind_to (count
, Qnil
);
2240 report_file_error ("Renaming", list2 (file
, newname
));
2246 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2247 "fAdd name to file: \nGName to add to %s: \np",
2248 doc
: /* Give FILE additional name NEWNAME. Both args must be strings.
2249 Signals a `file-already-exists' error if a file NEWNAME already exists
2250 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2251 A number as third arg means request confirmation if NEWNAME already exists.
2252 This is what happens in interactive use with M-x. */)
2253 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2255 Lisp_Object handler
;
2256 Lisp_Object encoded_file
, encoded_newname
;
2257 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2259 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2260 encoded_file
= encoded_newname
= Qnil
;
2261 CHECK_STRING (file
);
2262 CHECK_STRING (newname
);
2263 file
= Fexpand_file_name (file
, Qnil
);
2265 if (!NILP (Ffile_directory_p (newname
)))
2266 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
2268 newname
= Fexpand_file_name (newname
, Qnil
);
2270 /* If the file name has special constructs in it,
2271 call the corresponding file handler. */
2272 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2273 if (!NILP (handler
))
2274 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2275 newname
, ok_if_already_exists
));
2277 /* If the new name has special constructs in it,
2278 call the corresponding file handler. */
2279 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2280 if (!NILP (handler
))
2281 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2282 newname
, ok_if_already_exists
));
2284 encoded_file
= ENCODE_FILE (file
);
2285 encoded_newname
= ENCODE_FILE (newname
);
2287 if (NILP (ok_if_already_exists
)
2288 || INTEGERP (ok_if_already_exists
))
2289 barf_or_query_if_file_exists (newname
, "make it a new name",
2290 INTEGERP (ok_if_already_exists
), 0, 0);
2292 unlink (SSDATA (newname
));
2293 if (0 > link (SSDATA (encoded_file
), SSDATA (encoded_newname
)))
2294 report_file_error ("Adding new name", list2 (file
, newname
));
2300 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2301 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2302 doc
: /* Make a symbolic link to FILENAME, named LINKNAME.
2303 Both args must be strings.
2304 Signals a `file-already-exists' error if a file LINKNAME already exists
2305 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2306 A number as third arg means request confirmation if LINKNAME already exists.
2307 This happens for interactive use with M-x. */)
2308 (Lisp_Object filename
, Lisp_Object linkname
, Lisp_Object ok_if_already_exists
)
2310 Lisp_Object handler
;
2311 Lisp_Object encoded_filename
, encoded_linkname
;
2312 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2314 GCPRO4 (filename
, linkname
, encoded_filename
, encoded_linkname
);
2315 encoded_filename
= encoded_linkname
= Qnil
;
2316 CHECK_STRING (filename
);
2317 CHECK_STRING (linkname
);
2318 /* If the link target has a ~, we must expand it to get
2319 a truly valid file name. Otherwise, do not expand;
2320 we want to permit links to relative file names. */
2321 if (SREF (filename
, 0) == '~')
2322 filename
= Fexpand_file_name (filename
, Qnil
);
2324 if (!NILP (Ffile_directory_p (linkname
)))
2325 linkname
= Fexpand_file_name (Ffile_name_nondirectory (filename
), linkname
);
2327 linkname
= Fexpand_file_name (linkname
, Qnil
);
2329 /* If the file name has special constructs in it,
2330 call the corresponding file handler. */
2331 handler
= Ffind_file_name_handler (filename
, Qmake_symbolic_link
);
2332 if (!NILP (handler
))
2333 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2334 linkname
, ok_if_already_exists
));
2336 /* If the new link name has special constructs in it,
2337 call the corresponding file handler. */
2338 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2339 if (!NILP (handler
))
2340 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2341 linkname
, ok_if_already_exists
));
2343 encoded_filename
= ENCODE_FILE (filename
);
2344 encoded_linkname
= ENCODE_FILE (linkname
);
2346 if (NILP (ok_if_already_exists
)
2347 || INTEGERP (ok_if_already_exists
))
2348 barf_or_query_if_file_exists (linkname
, "make it a link",
2349 INTEGERP (ok_if_already_exists
), 0, 0);
2350 if (0 > symlink (SSDATA (encoded_filename
),
2351 SSDATA (encoded_linkname
)))
2353 /* If we didn't complain already, silently delete existing file. */
2354 if (errno
== EEXIST
)
2356 unlink (SSDATA (encoded_linkname
));
2357 if (0 <= symlink (SSDATA (encoded_filename
),
2358 SSDATA (encoded_linkname
)))
2364 if (errno
== ENOSYS
)
2367 xsignal1 (Qfile_error
,
2368 build_string ("Symbolic links are not supported"));
2371 report_file_error ("Making symbolic link", list2 (filename
, linkname
));
2378 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2380 doc
: /* Return t if file FILENAME specifies an absolute file name.
2381 On Unix, this is a name starting with a `/' or a `~'. */)
2382 (Lisp_Object filename
)
2384 CHECK_STRING (filename
);
2385 return file_name_absolute_p (SSDATA (filename
)) ? Qt
: Qnil
;
2388 /* Return nonzero if file FILENAME exists and can be executed. */
2391 check_executable (char *filename
)
2395 if (stat (filename
, &st
) < 0)
2397 return ((st
.st_mode
& S_IEXEC
) != 0);
2398 #else /* not DOS_NT */
2399 #ifdef HAVE_EUIDACCESS
2400 return (euidaccess (filename
, 1) >= 0);
2402 /* Access isn't quite right because it uses the real uid
2403 and we really want to test with the effective uid.
2404 But Unix doesn't give us a right way to do it. */
2405 return (access (filename
, 1) >= 0);
2407 #endif /* not DOS_NT */
2410 /* Return nonzero if file FILENAME exists and can be written. */
2413 check_writable (const char *filename
)
2417 if (stat (filename
, &st
) < 0)
2419 return (st
.st_mode
& S_IWRITE
|| S_ISDIR (st
.st_mode
));
2420 #else /* not MSDOS */
2421 #ifdef HAVE_EUIDACCESS
2422 int res
= (euidaccess (filename
, 2) >= 0);
2424 /* euidaccess may have returned failure because Cygwin couldn't
2425 determine the file's UID or GID; if so, we return success. */
2429 if (stat (filename
, &st
) < 0)
2431 res
= (st
.st_uid
== -1 || st
.st_gid
== -1);
2435 #else /* not HAVE_EUIDACCESS */
2436 /* Access isn't quite right because it uses the real uid
2437 and we really want to test with the effective uid.
2438 But Unix doesn't give us a right way to do it.
2439 Opening with O_WRONLY could work for an ordinary file,
2440 but would lose for directories. */
2441 return (access (filename
, 2) >= 0);
2442 #endif /* not HAVE_EUIDACCESS */
2443 #endif /* not MSDOS */
2446 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2447 doc
: /* Return t if file FILENAME exists (whether or not you can read it.)
2448 See also `file-readable-p' and `file-attributes'.
2449 This returns nil for a symlink to a nonexistent file.
2450 Use `file-symlink-p' to test for such links. */)
2451 (Lisp_Object filename
)
2453 Lisp_Object absname
;
2454 Lisp_Object handler
;
2455 struct stat statbuf
;
2457 CHECK_STRING (filename
);
2458 absname
= Fexpand_file_name (filename
, Qnil
);
2460 /* If the file name has special constructs in it,
2461 call the corresponding file handler. */
2462 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2463 if (!NILP (handler
))
2464 return call2 (handler
, Qfile_exists_p
, absname
);
2466 absname
= ENCODE_FILE (absname
);
2468 return (stat (SSDATA (absname
), &statbuf
) >= 0) ? Qt
: Qnil
;
2471 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2472 doc
: /* Return t if FILENAME can be executed by you.
2473 For a directory, this means you can access files in that directory. */)
2474 (Lisp_Object filename
)
2476 Lisp_Object absname
;
2477 Lisp_Object handler
;
2479 CHECK_STRING (filename
);
2480 absname
= Fexpand_file_name (filename
, Qnil
);
2482 /* If the file name has special constructs in it,
2483 call the corresponding file handler. */
2484 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
2485 if (!NILP (handler
))
2486 return call2 (handler
, Qfile_executable_p
, absname
);
2488 absname
= ENCODE_FILE (absname
);
2490 return (check_executable (SSDATA (absname
)) ? Qt
: Qnil
);
2493 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
2494 doc
: /* Return t if file FILENAME exists and you can read it.
2495 See also `file-exists-p' and `file-attributes'. */)
2496 (Lisp_Object filename
)
2498 Lisp_Object absname
;
2499 Lisp_Object handler
;
2502 struct stat statbuf
;
2504 CHECK_STRING (filename
);
2505 absname
= Fexpand_file_name (filename
, Qnil
);
2507 /* If the file name has special constructs in it,
2508 call the corresponding file handler. */
2509 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
2510 if (!NILP (handler
))
2511 return call2 (handler
, Qfile_readable_p
, absname
);
2513 absname
= ENCODE_FILE (absname
);
2515 #if defined (DOS_NT) || defined (macintosh)
2516 /* Under MS-DOS, Windows, and Macintosh, open does not work for
2518 if (access (SDATA (absname
), 0) == 0)
2521 #else /* not DOS_NT and not macintosh */
2524 /* Opening a fifo without O_NONBLOCK can wait.
2525 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2526 except in the case of a fifo, on a system which handles it. */
2527 desc
= stat (SSDATA (absname
), &statbuf
);
2530 if (S_ISFIFO (statbuf
.st_mode
))
2531 flags
|= O_NONBLOCK
;
2533 desc
= emacs_open (SSDATA (absname
), flags
, 0);
2538 #endif /* not DOS_NT and not macintosh */
2541 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2543 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
2544 doc
: /* Return t if file FILENAME can be written or created by you. */)
2545 (Lisp_Object filename
)
2547 Lisp_Object absname
, dir
, encoded
;
2548 Lisp_Object handler
;
2549 struct stat statbuf
;
2551 CHECK_STRING (filename
);
2552 absname
= Fexpand_file_name (filename
, Qnil
);
2554 /* If the file name has special constructs in it,
2555 call the corresponding file handler. */
2556 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
2557 if (!NILP (handler
))
2558 return call2 (handler
, Qfile_writable_p
, absname
);
2560 encoded
= ENCODE_FILE (absname
);
2561 if (stat (SSDATA (encoded
), &statbuf
) >= 0)
2562 return (check_writable (SSDATA (encoded
))
2565 dir
= Ffile_name_directory (absname
);
2568 dir
= Fdirectory_file_name (dir
);
2571 dir
= ENCODE_FILE (dir
);
2573 /* The read-only attribute of the parent directory doesn't affect
2574 whether a file or directory can be created within it. Some day we
2575 should check ACLs though, which do affect this. */
2576 if (stat (SDATA (dir
), &statbuf
) < 0)
2578 return S_ISDIR (statbuf
.st_mode
) ? Qt
: Qnil
;
2580 return (check_writable (!NILP (dir
) ? SSDATA (dir
) : "")
2585 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
2586 doc
: /* Access file FILENAME, and get an error if that does not work.
2587 The second argument STRING is used in the error message.
2588 If there is no error, returns nil. */)
2589 (Lisp_Object filename
, Lisp_Object string
)
2591 Lisp_Object handler
, encoded_filename
, absname
;
2594 CHECK_STRING (filename
);
2595 absname
= Fexpand_file_name (filename
, Qnil
);
2597 CHECK_STRING (string
);
2599 /* If the file name has special constructs in it,
2600 call the corresponding file handler. */
2601 handler
= Ffind_file_name_handler (absname
, Qaccess_file
);
2602 if (!NILP (handler
))
2603 return call3 (handler
, Qaccess_file
, absname
, string
);
2605 encoded_filename
= ENCODE_FILE (absname
);
2607 fd
= emacs_open (SSDATA (encoded_filename
), O_RDONLY
, 0);
2609 report_file_error (SSDATA (string
), Fcons (filename
, Qnil
));
2615 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
2616 doc
: /* Return non-nil if file FILENAME is the name of a symbolic link.
2617 The value is the link target, as a string.
2618 Otherwise it returns nil.
2620 This function returns t when given the name of a symlink that
2621 points to a nonexistent file. */)
2622 (Lisp_Object filename
)
2624 Lisp_Object handler
;
2627 char readlink_buf
[READLINK_BUFSIZE
];
2629 CHECK_STRING (filename
);
2630 filename
= Fexpand_file_name (filename
, Qnil
);
2632 /* If the file name has special constructs in it,
2633 call the corresponding file handler. */
2634 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
2635 if (!NILP (handler
))
2636 return call2 (handler
, Qfile_symlink_p
, filename
);
2638 filename
= ENCODE_FILE (filename
);
2640 buf
= emacs_readlink (SSDATA (filename
), readlink_buf
);
2644 val
= build_string (buf
);
2645 if (buf
[0] == '/' && strchr (buf
, ':'))
2646 val
= concat2 (build_string ("/:"), val
);
2647 if (buf
!= readlink_buf
)
2649 val
= DECODE_FILE (val
);
2653 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
2654 doc
: /* Return t if FILENAME names an existing directory.
2655 Symbolic links to directories count as directories.
2656 See `file-symlink-p' to distinguish symlinks. */)
2657 (Lisp_Object filename
)
2659 register Lisp_Object absname
;
2661 Lisp_Object handler
;
2663 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2665 /* If the file name has special constructs in it,
2666 call the corresponding file handler. */
2667 handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
2668 if (!NILP (handler
))
2669 return call2 (handler
, Qfile_directory_p
, absname
);
2671 absname
= ENCODE_FILE (absname
);
2673 if (stat (SSDATA (absname
), &st
) < 0)
2675 return S_ISDIR (st
.st_mode
) ? Qt
: Qnil
;
2678 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
,
2679 Sfile_accessible_directory_p
, 1, 1, 0,
2680 doc
: /* Return t if file FILENAME names a directory you can open.
2681 For the value to be t, FILENAME must specify the name of a directory as a file,
2682 and the directory must allow you to open files in it. In order to use a
2683 directory as a buffer's current directory, this predicate must return true.
2684 A directory name spec may be given instead; then the value is t
2685 if the directory so specified exists and really is a readable and
2686 searchable directory. */)
2687 (Lisp_Object filename
)
2689 Lisp_Object handler
;
2691 struct gcpro gcpro1
;
2693 /* If the file name has special constructs in it,
2694 call the corresponding file handler. */
2695 handler
= Ffind_file_name_handler (filename
, Qfile_accessible_directory_p
);
2696 if (!NILP (handler
))
2697 return call2 (handler
, Qfile_accessible_directory_p
, filename
);
2700 tem
= (NILP (Ffile_directory_p (filename
))
2701 || NILP (Ffile_executable_p (filename
)));
2703 return tem
? Qnil
: Qt
;
2706 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
2707 doc
: /* Return t if FILENAME names a regular file.
2708 This is the sort of file that holds an ordinary stream of data bytes.
2709 Symbolic links to regular files count as regular files.
2710 See `file-symlink-p' to distinguish symlinks. */)
2711 (Lisp_Object filename
)
2713 register Lisp_Object absname
;
2715 Lisp_Object handler
;
2717 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2719 /* If the file name has special constructs in it,
2720 call the corresponding file handler. */
2721 handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
2722 if (!NILP (handler
))
2723 return call2 (handler
, Qfile_regular_p
, absname
);
2725 absname
= ENCODE_FILE (absname
);
2730 Lisp_Object tem
= Vw32_get_true_file_attributes
;
2732 /* Tell stat to use expensive method to get accurate info. */
2733 Vw32_get_true_file_attributes
= Qt
;
2734 result
= stat (SDATA (absname
), &st
);
2735 Vw32_get_true_file_attributes
= tem
;
2739 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2742 if (stat (SSDATA (absname
), &st
) < 0)
2744 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2748 DEFUN ("file-selinux-context", Ffile_selinux_context
,
2749 Sfile_selinux_context
, 1, 1, 0,
2750 doc
: /* Return SELinux context of file named FILENAME,
2751 as a list ("user", "role", "type", "range"). Return (nil, nil, nil, nil)
2752 if file does not exist, is not accessible, or SELinux is disabled */)
2753 (Lisp_Object filename
)
2755 Lisp_Object absname
;
2756 Lisp_Object values
[4];
2757 Lisp_Object handler
;
2759 security_context_t con
;
2764 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2766 /* If the file name has special constructs in it,
2767 call the corresponding file handler. */
2768 handler
= Ffind_file_name_handler (absname
, Qfile_selinux_context
);
2769 if (!NILP (handler
))
2770 return call2 (handler
, Qfile_selinux_context
, absname
);
2772 absname
= ENCODE_FILE (absname
);
2779 if (is_selinux_enabled ())
2781 conlength
= lgetfilecon (SSDATA (absname
), &con
);
2784 context
= context_new (con
);
2785 if (context_user_get (context
))
2786 values
[0] = build_string (context_user_get (context
));
2787 if (context_role_get (context
))
2788 values
[1] = build_string (context_role_get (context
));
2789 if (context_type_get (context
))
2790 values
[2] = build_string (context_type_get (context
));
2791 if (context_range_get (context
))
2792 values
[3] = build_string (context_range_get (context
));
2793 context_free (context
);
2800 return Flist (sizeof (values
) / sizeof (values
[0]), values
);
2803 DEFUN ("set-file-selinux-context", Fset_file_selinux_context
,
2804 Sset_file_selinux_context
, 2, 2, 0,
2805 doc
: /* Set SELinux context of file named FILENAME to CONTEXT
2806 as a list ("user", "role", "type", "range"). Has no effect if SELinux
2808 (Lisp_Object filename
, Lisp_Object context
)
2810 Lisp_Object absname
;
2811 Lisp_Object handler
;
2813 Lisp_Object encoded_absname
;
2814 Lisp_Object user
= CAR_SAFE (context
);
2815 Lisp_Object role
= CAR_SAFE (CDR_SAFE (context
));
2816 Lisp_Object type
= CAR_SAFE (CDR_SAFE (CDR_SAFE (context
)));
2817 Lisp_Object range
= CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context
))));
2818 security_context_t con
;
2819 int fail
, conlength
;
2820 context_t parsed_con
;
2823 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2825 /* If the file name has special constructs in it,
2826 call the corresponding file handler. */
2827 handler
= Ffind_file_name_handler (absname
, Qset_file_selinux_context
);
2828 if (!NILP (handler
))
2829 return call3 (handler
, Qset_file_selinux_context
, absname
, context
);
2832 if (is_selinux_enabled ())
2834 /* Get current file context. */
2835 encoded_absname
= ENCODE_FILE (absname
);
2836 conlength
= lgetfilecon (SSDATA (encoded_absname
), &con
);
2839 parsed_con
= context_new (con
);
2840 /* Change the parts defined in the parameter.*/
2843 if (context_user_set (parsed_con
, SSDATA (user
)))
2844 error ("Doing context_user_set");
2848 if (context_role_set (parsed_con
, SSDATA (role
)))
2849 error ("Doing context_role_set");
2853 if (context_type_set (parsed_con
, SSDATA (type
)))
2854 error ("Doing context_type_set");
2856 if (STRINGP (range
))
2858 if (context_range_set (parsed_con
, SSDATA (range
)))
2859 error ("Doing context_range_set");
2862 /* Set the modified context back to the file. */
2863 fail
= lsetfilecon (SSDATA (encoded_absname
),
2864 context_str (parsed_con
));
2866 report_file_error ("Doing lsetfilecon", Fcons (absname
, Qnil
));
2868 context_free (parsed_con
);
2871 report_file_error ("Doing lgetfilecon", Fcons (absname
, Qnil
));
2881 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
2882 doc
: /* Return mode bits of file named FILENAME, as an integer.
2883 Return nil, if file does not exist or is not accessible. */)
2884 (Lisp_Object filename
)
2886 Lisp_Object absname
;
2888 Lisp_Object handler
;
2890 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2892 /* If the file name has special constructs in it,
2893 call the corresponding file handler. */
2894 handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
2895 if (!NILP (handler
))
2896 return call2 (handler
, Qfile_modes
, absname
);
2898 absname
= ENCODE_FILE (absname
);
2900 if (stat (SSDATA (absname
), &st
) < 0)
2903 return make_number (st
.st_mode
& 07777);
2906 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2,
2907 "(let ((file (read-file-name \"File: \"))) \
2908 (list file (read-file-modes nil file)))",
2909 doc
: /* Set mode bits of file named FILENAME to MODE (an integer).
2910 Only the 12 low bits of MODE are used.
2912 Interactively, mode bits are read by `read-file-modes', which accepts
2913 symbolic notation, like the `chmod' command from GNU Coreutils. */)
2914 (Lisp_Object filename
, Lisp_Object mode
)
2916 Lisp_Object absname
, encoded_absname
;
2917 Lisp_Object handler
;
2919 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2920 CHECK_NUMBER (mode
);
2922 /* If the file name has special constructs in it,
2923 call the corresponding file handler. */
2924 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
2925 if (!NILP (handler
))
2926 return call3 (handler
, Qset_file_modes
, absname
, mode
);
2928 encoded_absname
= ENCODE_FILE (absname
);
2930 if (chmod (SSDATA (encoded_absname
), XINT (mode
) & 07777) < 0)
2931 report_file_error ("Doing chmod", Fcons (absname
, Qnil
));
2936 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
2937 doc
: /* Set the file permission bits for newly created files.
2938 The argument MODE should be an integer; only the low 9 bits are used.
2939 This setting is inherited by subprocesses. */)
2942 CHECK_NUMBER (mode
);
2944 umask ((~ XINT (mode
)) & 0777);
2949 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
2950 doc
: /* Return the default file protection for created files.
2951 The value is an integer. */)
2957 realmask
= umask (0);
2960 XSETINT (value
, (~ realmask
) & 0777);
2965 DEFUN ("set-file-times", Fset_file_times
, Sset_file_times
, 1, 2, 0,
2966 doc
: /* Set times of file FILENAME to TIMESTAMP.
2967 Set both access and modification times.
2968 Return t on success, else nil.
2969 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
2971 (Lisp_Object filename
, Lisp_Object timestamp
)
2973 Lisp_Object absname
, encoded_absname
;
2974 Lisp_Object handler
;
2978 if (! lisp_time_argument (timestamp
, &sec
, &usec
))
2979 error ("Invalid time specification");
2981 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2983 /* If the file name has special constructs in it,
2984 call the corresponding file handler. */
2985 handler
= Ffind_file_name_handler (absname
, Qset_file_times
);
2986 if (!NILP (handler
))
2987 return call3 (handler
, Qset_file_times
, absname
, timestamp
);
2989 encoded_absname
= ENCODE_FILE (absname
);
2994 EMACS_SET_SECS (t
, sec
);
2995 EMACS_SET_USECS (t
, usec
);
2997 if (set_file_times (SSDATA (encoded_absname
), t
, t
))
3002 /* Setting times on a directory always fails. */
3003 if (stat (SSDATA (encoded_absname
), &st
) == 0 && S_ISDIR (st
.st_mode
))
3006 report_file_error ("Setting file times", Fcons (absname
, Qnil
));
3015 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3016 doc
: /* Tell Unix to finish all pending disk updates. */)
3023 #endif /* HAVE_SYNC */
3025 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3026 doc
: /* Return t if file FILE1 is newer than file FILE2.
3027 If FILE1 does not exist, the answer is nil;
3028 otherwise, if FILE2 does not exist, the answer is t. */)
3029 (Lisp_Object file1
, Lisp_Object file2
)
3031 Lisp_Object absname1
, absname2
;
3034 Lisp_Object handler
;
3035 struct gcpro gcpro1
, gcpro2
;
3037 CHECK_STRING (file1
);
3038 CHECK_STRING (file2
);
3041 GCPRO2 (absname1
, file2
);
3042 absname1
= expand_and_dir_to_file (file1
, BVAR (current_buffer
, directory
));
3043 absname2
= expand_and_dir_to_file (file2
, BVAR (current_buffer
, directory
));
3046 /* If the file name has special constructs in it,
3047 call the corresponding file handler. */
3048 handler
= Ffind_file_name_handler (absname1
, Qfile_newer_than_file_p
);
3050 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3051 if (!NILP (handler
))
3052 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3054 GCPRO2 (absname1
, absname2
);
3055 absname1
= ENCODE_FILE (absname1
);
3056 absname2
= ENCODE_FILE (absname2
);
3059 if (stat (SSDATA (absname1
), &st
) < 0)
3062 mtime1
= st
.st_mtime
;
3064 if (stat (SSDATA (absname2
), &st
) < 0)
3067 return (mtime1
> st
.st_mtime
) ? Qt
: Qnil
;
3070 #ifndef READ_BUF_SIZE
3071 #define READ_BUF_SIZE (64 << 10)
3073 /* Some buffer offsets are stored in 'int' variables. */
3074 verify (READ_BUF_SIZE
<= INT_MAX
);
3076 /* This function is called after Lisp functions to decide a coding
3077 system are called, or when they cause an error. Before they are
3078 called, the current buffer is set unibyte and it contains only a
3079 newly inserted text (thus the buffer was empty before the
3082 The functions may set markers, overlays, text properties, or even
3083 alter the buffer contents, change the current buffer.
3085 Here, we reset all those changes by:
3086 o set back the current buffer.
3087 o move all markers and overlays to BEG.
3088 o remove all text properties.
3089 o set back the buffer multibyteness. */
3092 decide_coding_unwind (Lisp_Object unwind_data
)
3094 Lisp_Object multibyte
, undo_list
, buffer
;
3096 multibyte
= XCAR (unwind_data
);
3097 unwind_data
= XCDR (unwind_data
);
3098 undo_list
= XCAR (unwind_data
);
3099 buffer
= XCDR (unwind_data
);
3101 if (current_buffer
!= XBUFFER (buffer
))
3102 set_buffer_internal (XBUFFER (buffer
));
3103 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3104 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3105 BUF_INTERVALS (current_buffer
) = 0;
3106 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3108 /* Now we are safe to change the buffer's multibyteness directly. */
3109 BVAR (current_buffer
, enable_multibyte_characters
) = multibyte
;
3110 BVAR (current_buffer
, undo_list
) = undo_list
;
3116 /* Used to pass values from insert-file-contents to read_non_regular. */
3118 static int non_regular_fd
;
3119 static ptrdiff_t non_regular_inserted
;
3120 static int non_regular_nbytes
;
3123 /* Read from a non-regular file.
3124 Read non_regular_nbytes bytes max from non_regular_fd.
3125 Non_regular_inserted specifies where to put the read bytes.
3126 Value is the number of bytes read. */
3129 read_non_regular (Lisp_Object ignore
)
3135 nbytes
= emacs_read (non_regular_fd
,
3136 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
3137 + non_regular_inserted
),
3138 non_regular_nbytes
);
3140 return make_number (nbytes
);
3144 /* Condition-case handler used when reading from non-regular files
3145 in insert-file-contents. */
3148 read_non_regular_quit (Lisp_Object ignore
)
3153 /* Reposition FD to OFFSET, based on WHENCE. This acts like lseek
3154 except that it also tests for OFFSET being out of lseek's range. */
3156 emacs_lseek (int fd
, EMACS_INT offset
, int whence
)
3158 /* Use "&" rather than "&&" to suppress a bogus GCC warning; see
3159 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43772>. */
3160 if (! ((TYPE_MINIMUM (off_t
) <= offset
) & (offset
<= TYPE_MAXIMUM (off_t
))))
3165 return lseek (fd
, offset
, whence
);
3169 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3171 doc
: /* Insert contents of file FILENAME after point.
3172 Returns list of absolute file name and number of characters inserted.
3173 If second argument VISIT is non-nil, the buffer's visited filename and
3174 last save file modtime are set, and it is marked unmodified. If
3175 visiting and the file does not exist, visiting is completed before the
3178 The optional third and fourth arguments BEG and END specify what portion
3179 of the file to insert. These arguments count bytes in the file, not
3180 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3182 If optional fifth argument REPLACE is non-nil, replace the current
3183 buffer contents (in the accessible portion) with the file contents.
3184 This is better than simply deleting and inserting the whole thing
3185 because (1) it preserves some marker positions and (2) it puts less data
3186 in the undo list. When REPLACE is non-nil, the second return value is
3187 the number of characters that replace previous buffer contents.
3189 This function does code conversion according to the value of
3190 `coding-system-for-read' or `file-coding-system-alist', and sets the
3191 variable `last-coding-system-used' to the coding system actually used. */)
3192 (Lisp_Object filename
, Lisp_Object visit
, Lisp_Object beg
, Lisp_Object end
, Lisp_Object replace
)
3196 ptrdiff_t inserted
= 0;
3198 register ptrdiff_t how_much
;
3199 off_t beg_offset
, end_offset
;
3200 register int unprocessed
;
3201 ptrdiff_t count
= SPECPDL_INDEX ();
3202 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
3203 Lisp_Object handler
, val
, insval
, orig_filename
, old_undo
;
3205 ptrdiff_t total
= 0;
3206 int not_regular
= 0;
3208 char read_buf
[READ_BUF_SIZE
];
3209 struct coding_system coding
;
3210 char buffer
[1 << 14];
3211 int replace_handled
= 0;
3212 int set_coding_system
= 0;
3213 Lisp_Object coding_system
;
3215 Lisp_Object old_Vdeactivate_mark
= Vdeactivate_mark
;
3216 int we_locked_file
= 0;
3217 int deferred_remove_unwind_protect
= 0;
3219 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3220 error ("Cannot do file visiting in an indirect buffer");
3222 if (!NILP (BVAR (current_buffer
, read_only
)))
3223 Fbarf_if_buffer_read_only ();
3227 orig_filename
= Qnil
;
3230 GCPRO5 (filename
, val
, p
, orig_filename
, old_undo
);
3232 CHECK_STRING (filename
);
3233 filename
= Fexpand_file_name (filename
, Qnil
);
3235 /* The value Qnil means that the coding system is not yet
3237 coding_system
= Qnil
;
3239 /* If the file name has special constructs in it,
3240 call the corresponding file handler. */
3241 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3242 if (!NILP (handler
))
3244 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3245 visit
, beg
, end
, replace
);
3246 if (CONSP (val
) && CONSP (XCDR (val
))
3247 && RANGED_INTEGERP (0, XCAR (XCDR (val
)), ZV
- PT
))
3248 inserted
= XINT (XCAR (XCDR (val
)));
3252 orig_filename
= filename
;
3253 filename
= ENCODE_FILE (filename
);
3259 Lisp_Object tem
= Vw32_get_true_file_attributes
;
3261 /* Tell stat to use expensive method to get accurate info. */
3262 Vw32_get_true_file_attributes
= Qt
;
3263 total
= stat (SSDATA (filename
), &st
);
3264 Vw32_get_true_file_attributes
= tem
;
3268 if (stat (SSDATA (filename
), &st
) < 0)
3269 #endif /* WINDOWSNT */
3274 report_file_error ("Opening input file", Fcons (orig_filename
, Qnil
));
3278 if (!NILP (Vcoding_system_for_read
))
3279 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3283 /* This code will need to be changed in order to work on named
3284 pipes, and it's probably just not worth it. So we should at
3285 least signal an error. */
3286 if (!S_ISREG (st
.st_mode
))
3293 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3294 xsignal2 (Qfile_error
,
3295 build_string ("not a regular file"), orig_filename
);
3299 if ((fd
= emacs_open (SSDATA (filename
), O_RDONLY
, 0)) < 0)
3302 /* Replacement should preserve point as it preserves markers. */
3303 if (!NILP (replace
))
3304 record_unwind_protect (restore_point_unwind
, Fpoint_marker ());
3306 record_unwind_protect (close_file_unwind
, make_number (fd
));
3311 if (!NILP (beg
) || !NILP (end
))
3312 error ("Attempt to visit less than an entire file");
3313 if (BEG
< Z
&& NILP (replace
))
3314 error ("Cannot do file visiting in a non-empty buffer");
3319 if (! (RANGED_INTEGERP (0, beg
, TYPE_MAXIMUM (off_t
))))
3320 wrong_type_argument (intern ("file-offset"), beg
);
3321 beg_offset
= XFASTINT (beg
);
3328 if (! (RANGED_INTEGERP (0, end
, TYPE_MAXIMUM (off_t
))))
3329 wrong_type_argument (intern ("file-offset"), end
);
3330 end_offset
= XFASTINT (end
);
3335 end_offset
= TYPE_MAXIMUM (off_t
);
3338 end_offset
= st
.st_size
;
3340 /* A negative size can happen on a platform that allows file
3341 sizes greater than the maximum off_t value. */
3345 /* The file size returned from stat may be zero, but data
3346 may be readable nonetheless, for example when this is a
3347 file in the /proc filesystem. */
3348 if (end_offset
== 0)
3349 end_offset
= READ_BUF_SIZE
;
3353 /* Check now whether the buffer will become too large,
3354 in the likely case where the file's length is not changing.
3355 This saves a lot of needless work before a buffer overflow. */
3358 /* The likely offset where we will stop reading. We could read
3359 more (or less), if the file grows (or shrinks) as we read it. */
3360 off_t likely_end
= min (end_offset
, st
.st_size
);
3362 if (beg_offset
< likely_end
)
3364 ptrdiff_t buf_bytes
=
3365 Z_BYTE
- (!NILP (replace
) ? ZV_BYTE
- BEGV_BYTE
: 0);
3366 ptrdiff_t buf_growth_max
= BUF_BYTES_MAX
- buf_bytes
;
3367 off_t likely_growth
= likely_end
- beg_offset
;
3368 if (buf_growth_max
< likely_growth
)
3373 /* Prevent redisplay optimizations. */
3374 current_buffer
->clip_changed
= 1;
3376 if (EQ (Vcoding_system_for_read
, Qauto_save_coding
))
3378 coding_system
= coding_inherit_eol_type (Qutf_8_emacs
, Qunix
);
3379 setup_coding_system (coding_system
, &coding
);
3380 /* Ensure we set Vlast_coding_system_used. */
3381 set_coding_system
= 1;
3385 /* Decide the coding system to use for reading the file now
3386 because we can't use an optimized method for handling
3387 `coding:' tag if the current buffer is not empty. */
3388 if (!NILP (Vcoding_system_for_read
))
3389 coding_system
= Vcoding_system_for_read
;
3392 /* Don't try looking inside a file for a coding system
3393 specification if it is not seekable. */
3394 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3396 /* Find a coding system specified in the heading two
3397 lines or in the tailing several lines of the file.
3398 We assume that the 1K-byte and 3K-byte for heading
3399 and tailing respectively are sufficient for this
3403 if (st
.st_size
<= (1024 * 4))
3404 nread
= emacs_read (fd
, read_buf
, 1024 * 4);
3407 nread
= emacs_read (fd
, read_buf
, 1024);
3410 if (lseek (fd
, st
.st_size
- (1024 * 3), SEEK_SET
) < 0)
3411 report_file_error ("Setting file position",
3412 Fcons (orig_filename
, Qnil
));
3413 nread
+= emacs_read (fd
, read_buf
+ nread
, 1024 * 3);
3418 error ("IO error reading %s: %s",
3419 SDATA (orig_filename
), emacs_strerror (errno
));
3422 struct buffer
*prev
= current_buffer
;
3423 Lisp_Object workbuf
;
3426 record_unwind_protect (Fset_buffer
, Fcurrent_buffer ());
3428 workbuf
= Fget_buffer_create (build_string (" *code-converting-work*"));
3429 buf
= XBUFFER (workbuf
);
3431 delete_all_overlays (buf
);
3432 BVAR (buf
, directory
) = BVAR (current_buffer
, directory
);
3433 BVAR (buf
, read_only
) = Qnil
;
3434 BVAR (buf
, filename
) = Qnil
;
3435 BVAR (buf
, undo_list
) = Qt
;
3436 eassert (buf
->overlays_before
== NULL
);
3437 eassert (buf
->overlays_after
== NULL
);
3439 set_buffer_internal (buf
);
3441 BVAR (buf
, enable_multibyte_characters
) = Qnil
;
3443 insert_1_both ((char *) read_buf
, nread
, nread
, 0, 0, 0);
3444 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3445 coding_system
= call2 (Vset_auto_coding_function
,
3446 filename
, make_number (nread
));
3447 set_buffer_internal (prev
);
3449 /* Discard the unwind protect for recovering the
3453 /* Rewind the file for the actual read done later. */
3454 if (lseek (fd
, 0, SEEK_SET
) < 0)
3455 report_file_error ("Setting file position",
3456 Fcons (orig_filename
, Qnil
));
3460 if (NILP (coding_system
))
3462 /* If we have not yet decided a coding system, check
3463 file-coding-system-alist. */
3464 Lisp_Object args
[6];
3466 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
3467 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = replace
;
3468 coding_system
= Ffind_operation_coding_system (6, args
);
3469 if (CONSP (coding_system
))
3470 coding_system
= XCAR (coding_system
);
3474 if (NILP (coding_system
))
3475 coding_system
= Qundecided
;
3477 CHECK_CODING_SYSTEM (coding_system
);
3479 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3480 /* We must suppress all character code conversion except for
3481 end-of-line conversion. */
3482 coding_system
= raw_text_coding_system (coding_system
);
3484 setup_coding_system (coding_system
, &coding
);
3485 /* Ensure we set Vlast_coding_system_used. */
3486 set_coding_system
= 1;
3489 /* If requested, replace the accessible part of the buffer
3490 with the file contents. Avoid replacing text at the
3491 beginning or end of the buffer that matches the file contents;
3492 that preserves markers pointing to the unchanged parts.
3494 Here we implement this feature in an optimized way
3495 for the case where code conversion is NOT needed.
3496 The following if-statement handles the case of conversion
3497 in a less optimal way.
3499 If the code conversion is "automatic" then we try using this
3500 method and hope for the best.
3501 But if we discover the need for conversion, we give up on this method
3502 and let the following if-statement handle the replace job. */
3505 && (NILP (coding_system
)
3506 || ! CODING_REQUIRE_DECODING (&coding
)))
3508 /* same_at_start and same_at_end count bytes,
3509 because file access counts bytes
3510 and BEG and END count bytes. */
3511 ptrdiff_t same_at_start
= BEGV_BYTE
;
3512 ptrdiff_t same_at_end
= ZV_BYTE
;
3514 /* There is still a possibility we will find the need to do code
3515 conversion. If that happens, we set this variable to 1 to
3516 give up on handling REPLACE in the optimized way. */
3517 int giveup_match_end
= 0;
3519 if (beg_offset
!= 0)
3521 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3522 report_file_error ("Setting file position",
3523 Fcons (orig_filename
, Qnil
));
3528 /* Count how many chars at the start of the file
3529 match the text at the beginning of the buffer. */
3534 nread
= emacs_read (fd
, buffer
, sizeof buffer
);
3536 error ("IO error reading %s: %s",
3537 SSDATA (orig_filename
), emacs_strerror (errno
));
3538 else if (nread
== 0)
3541 if (CODING_REQUIRE_DETECTION (&coding
))
3543 coding_system
= detect_coding_system ((unsigned char *) buffer
,
3546 setup_coding_system (coding_system
, &coding
);
3549 if (CODING_REQUIRE_DECODING (&coding
))
3550 /* We found that the file should be decoded somehow.
3551 Let's give up here. */
3553 giveup_match_end
= 1;
3558 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3559 && FETCH_BYTE (same_at_start
) == buffer
[bufpos
])
3560 same_at_start
++, bufpos
++;
3561 /* If we found a discrepancy, stop the scan.
3562 Otherwise loop around and scan the next bufferful. */
3563 if (bufpos
!= nread
)
3567 /* If the file matches the buffer completely,
3568 there's no need to replace anything. */
3569 if (same_at_start
- BEGV_BYTE
== end_offset
- beg_offset
)
3573 /* Truncate the buffer to the size of the file. */
3574 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3579 /* Count how many chars at the end of the file
3580 match the text at the end of the buffer. But, if we have
3581 already found that decoding is necessary, don't waste time. */
3582 while (!giveup_match_end
)
3584 int total_read
, nread
, bufpos
, trial
;
3587 /* At what file position are we now scanning? */
3588 curpos
= end_offset
- (ZV_BYTE
- same_at_end
);
3589 /* If the entire file matches the buffer tail, stop the scan. */
3592 /* How much can we scan in the next step? */
3593 trial
= min (curpos
, sizeof buffer
);
3594 if (lseek (fd
, curpos
- trial
, SEEK_SET
) < 0)
3595 report_file_error ("Setting file position",
3596 Fcons (orig_filename
, Qnil
));
3598 total_read
= nread
= 0;
3599 while (total_read
< trial
)
3601 nread
= emacs_read (fd
, buffer
+ total_read
, trial
- total_read
);
3603 error ("IO error reading %s: %s",
3604 SDATA (orig_filename
), emacs_strerror (errno
));
3605 else if (nread
== 0)
3607 total_read
+= nread
;
3610 /* Scan this bufferful from the end, comparing with
3611 the Emacs buffer. */
3612 bufpos
= total_read
;
3614 /* Compare with same_at_start to avoid counting some buffer text
3615 as matching both at the file's beginning and at the end. */
3616 while (bufpos
> 0 && same_at_end
> same_at_start
3617 && FETCH_BYTE (same_at_end
- 1) == buffer
[bufpos
- 1])
3618 same_at_end
--, bufpos
--;
3620 /* If we found a discrepancy, stop the scan.
3621 Otherwise loop around and scan the preceding bufferful. */
3624 /* If this discrepancy is because of code conversion,
3625 we cannot use this method; giveup and try the other. */
3626 if (same_at_end
> same_at_start
3627 && FETCH_BYTE (same_at_end
- 1) >= 0200
3628 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
))
3629 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3630 giveup_match_end
= 1;
3639 if (! giveup_match_end
)
3643 /* We win! We can handle REPLACE the optimized way. */
3645 /* Extend the start of non-matching text area to multibyte
3646 character boundary. */
3647 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3648 while (same_at_start
> BEGV_BYTE
3649 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3652 /* Extend the end of non-matching text area to multibyte
3653 character boundary. */
3654 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3655 while (same_at_end
< ZV_BYTE
3656 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3659 /* Don't try to reuse the same piece of text twice. */
3660 overlap
= (same_at_start
- BEGV_BYTE
3662 + (! NILP (end
) ? end_offset
: st
.st_size
) - ZV_BYTE
));
3664 same_at_end
+= overlap
;
3666 /* Arrange to read only the nonmatching middle part of the file. */
3667 beg_offset
+= same_at_start
- BEGV_BYTE
;
3668 end_offset
-= ZV_BYTE
- same_at_end
;
3670 del_range_byte (same_at_start
, same_at_end
, 0);
3671 /* Insert from the file at the proper position. */
3672 temp
= BYTE_TO_CHAR (same_at_start
);
3673 SET_PT_BOTH (temp
, same_at_start
);
3675 /* If display currently starts at beginning of line,
3676 keep it that way. */
3677 if (XBUFFER (XWINDOW (selected_window
)->buffer
) == current_buffer
)
3678 XWINDOW (selected_window
)->start_at_line_beg
= Fbolp ();
3680 replace_handled
= 1;
3684 /* If requested, replace the accessible part of the buffer
3685 with the file contents. Avoid replacing text at the
3686 beginning or end of the buffer that matches the file contents;
3687 that preserves markers pointing to the unchanged parts.
3689 Here we implement this feature for the case where code conversion
3690 is needed, in a simple way that needs a lot of memory.
3691 The preceding if-statement handles the case of no conversion
3692 in a more optimized way. */
3693 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
3695 ptrdiff_t same_at_start
= BEGV_BYTE
;
3696 ptrdiff_t same_at_end
= ZV_BYTE
;
3697 ptrdiff_t same_at_start_charpos
;
3698 ptrdiff_t inserted_chars
;
3701 unsigned char *decoded
;
3704 ptrdiff_t this_count
= SPECPDL_INDEX ();
3705 int multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3706 Lisp_Object conversion_buffer
;
3707 struct gcpro gcpro1
;
3709 conversion_buffer
= code_conversion_save (1, multibyte
);
3711 /* First read the whole file, performing code conversion into
3712 CONVERSION_BUFFER. */
3714 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3715 report_file_error ("Setting file position",
3716 Fcons (orig_filename
, Qnil
));
3718 total
= st
.st_size
; /* Total bytes in the file. */
3719 how_much
= 0; /* Bytes read from file so far. */
3720 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
3721 unprocessed
= 0; /* Bytes not processed in previous loop. */
3723 GCPRO1 (conversion_buffer
);
3724 while (how_much
< total
)
3726 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
3727 quitting while reading a huge while. */
3728 /* `try'' is reserved in some compilers (Microsoft C). */
3729 int trytry
= min (total
- how_much
, READ_BUF_SIZE
- unprocessed
);
3731 /* Allow quitting out of the actual I/O. */
3734 this = emacs_read (fd
, read_buf
+ unprocessed
, trytry
);
3742 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer
),
3743 BUF_Z (XBUFFER (conversion_buffer
)));
3744 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3745 unprocessed
+ this, conversion_buffer
);
3746 unprocessed
= coding
.carryover_bytes
;
3747 if (coding
.carryover_bytes
> 0)
3748 memcpy (read_buf
, coding
.carryover
, unprocessed
);
3753 /* We should remove the unwind_protect calling
3754 close_file_unwind, but other stuff has been added the stack,
3755 so defer the removal till we reach the `handled' label. */
3756 deferred_remove_unwind_protect
= 1;
3758 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
3759 if we couldn't read the file. */
3762 error ("IO error reading %s: %s",
3763 SDATA (orig_filename
), emacs_strerror (errno
));
3765 if (unprocessed
> 0)
3767 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
3768 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3769 unprocessed
, conversion_buffer
);
3770 coding
.mode
&= ~CODING_MODE_LAST_BLOCK
;
3773 coding_system
= CODING_ID_NAME (coding
.id
);
3774 set_coding_system
= 1;
3775 decoded
= BUF_BEG_ADDR (XBUFFER (conversion_buffer
));
3776 inserted
= (BUF_Z_BYTE (XBUFFER (conversion_buffer
))
3777 - BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
3779 /* Compare the beginning of the converted string with the buffer
3783 while (bufpos
< inserted
&& same_at_start
< same_at_end
3784 && FETCH_BYTE (same_at_start
) == decoded
[bufpos
])
3785 same_at_start
++, bufpos
++;
3787 /* If the file matches the head of buffer completely,
3788 there's no need to replace anything. */
3790 if (bufpos
== inserted
)
3792 /* Truncate the buffer to the size of the file. */
3793 if (same_at_start
== same_at_end
)
3796 del_range_byte (same_at_start
, same_at_end
, 0);
3799 unbind_to (this_count
, Qnil
);
3803 /* Extend the start of non-matching text area to the previous
3804 multibyte character boundary. */
3805 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3806 while (same_at_start
> BEGV_BYTE
3807 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3810 /* Scan this bufferful from the end, comparing with
3811 the Emacs buffer. */
3814 /* Compare with same_at_start to avoid counting some buffer text
3815 as matching both at the file's beginning and at the end. */
3816 while (bufpos
> 0 && same_at_end
> same_at_start
3817 && FETCH_BYTE (same_at_end
- 1) == decoded
[bufpos
- 1])
3818 same_at_end
--, bufpos
--;
3820 /* Extend the end of non-matching text area to the next
3821 multibyte character boundary. */
3822 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3823 while (same_at_end
< ZV_BYTE
3824 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3827 /* Don't try to reuse the same piece of text twice. */
3828 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
3830 same_at_end
+= overlap
;
3832 /* If display currently starts at beginning of line,
3833 keep it that way. */
3834 if (XBUFFER (XWINDOW (selected_window
)->buffer
) == current_buffer
)
3835 XWINDOW (selected_window
)->start_at_line_beg
= Fbolp ();
3837 /* Replace the chars that we need to replace,
3838 and update INSERTED to equal the number of bytes
3839 we are taking from the decoded string. */
3840 inserted
-= (ZV_BYTE
- same_at_end
) + (same_at_start
- BEGV_BYTE
);
3842 if (same_at_end
!= same_at_start
)
3844 del_range_byte (same_at_start
, same_at_end
, 0);
3846 same_at_start
= GPT_BYTE
;
3850 temp
= BYTE_TO_CHAR (same_at_start
);
3852 /* Insert from the file at the proper position. */
3853 SET_PT_BOTH (temp
, same_at_start
);
3854 same_at_start_charpos
3855 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
3856 same_at_start
- BEGV_BYTE
3857 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
3859 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
3860 same_at_start
+ inserted
- BEGV_BYTE
3861 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)))
3862 - same_at_start_charpos
);
3863 /* This binding is to avoid ask-user-about-supersession-threat
3864 being called in insert_from_buffer (via in
3865 prepare_to_modify_buffer). */
3866 specbind (intern ("buffer-file-name"), Qnil
);
3867 insert_from_buffer (XBUFFER (conversion_buffer
),
3868 same_at_start_charpos
, inserted_chars
, 0);
3869 /* Set `inserted' to the number of inserted characters. */
3870 inserted
= PT
- temp
;
3871 /* Set point before the inserted characters. */
3872 SET_PT_BOTH (temp
, same_at_start
);
3874 unbind_to (this_count
, Qnil
);
3880 total
= end_offset
- beg_offset
;
3882 /* For a special file, all we can do is guess. */
3883 total
= READ_BUF_SIZE
;
3885 if (NILP (visit
) && total
> 0)
3887 #ifdef CLASH_DETECTION
3888 if (!NILP (BVAR (current_buffer
, file_truename
))
3889 /* Make binding buffer-file-name to nil effective. */
3890 && !NILP (BVAR (current_buffer
, filename
))
3891 && SAVE_MODIFF
>= MODIFF
)
3893 #endif /* CLASH_DETECTION */
3894 prepare_to_modify_buffer (GPT
, GPT
, NULL
);
3898 if (GAP_SIZE
< total
)
3899 make_gap (total
- GAP_SIZE
);
3901 if (beg_offset
!= 0 || !NILP (replace
))
3903 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3904 report_file_error ("Setting file position",
3905 Fcons (orig_filename
, Qnil
));
3908 /* In the following loop, HOW_MUCH contains the total bytes read so
3909 far for a regular file, and not changed for a special file. But,
3910 before exiting the loop, it is set to a negative value if I/O
3914 /* Total bytes inserted. */
3917 /* Here, we don't do code conversion in the loop. It is done by
3918 decode_coding_gap after all data are read into the buffer. */
3920 ptrdiff_t gap_size
= GAP_SIZE
;
3922 while (how_much
< total
)
3924 /* try is reserved in some compilers (Microsoft C) */
3925 int trytry
= min (total
- how_much
, READ_BUF_SIZE
);
3932 /* Maybe make more room. */
3933 if (gap_size
< trytry
)
3935 make_gap (total
- gap_size
);
3936 gap_size
= GAP_SIZE
;
3939 /* Read from the file, capturing `quit'. When an
3940 error occurs, end the loop, and arrange for a quit
3941 to be signaled after decoding the text we read. */
3942 non_regular_fd
= fd
;
3943 non_regular_inserted
= inserted
;
3944 non_regular_nbytes
= trytry
;
3945 nbytes
= internal_condition_case_1 (read_non_regular
,
3947 read_non_regular_quit
);
3954 this = XINT (nbytes
);
3958 /* Allow quitting out of the actual I/O. We don't make text
3959 part of the buffer until all the reading is done, so a C-g
3960 here doesn't do any harm. */
3963 this = emacs_read (fd
,
3964 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
3978 /* For a regular file, where TOTAL is the real size,
3979 count HOW_MUCH to compare with it.
3980 For a special file, where TOTAL is just a buffer size,
3981 so don't bother counting in HOW_MUCH.
3982 (INSERTED is where we count the number of characters inserted.) */
3989 /* Now we have read all the file data into the gap.
3990 If it was empty, undo marking the buffer modified. */
3994 #ifdef CLASH_DETECTION
3996 unlock_file (BVAR (current_buffer
, file_truename
));
3998 Vdeactivate_mark
= old_Vdeactivate_mark
;
4001 Vdeactivate_mark
= Qt
;
4003 /* Make the text read part of the buffer. */
4004 GAP_SIZE
-= inserted
;
4006 GPT_BYTE
+= inserted
;
4008 ZV_BYTE
+= inserted
;
4013 /* Put an anchor to ensure multi-byte form ends at gap. */
4018 /* Discard the unwind protect for closing the file. */
4022 error ("IO error reading %s: %s",
4023 SDATA (orig_filename
), emacs_strerror (errno
));
4027 if (NILP (coding_system
))
4029 /* The coding system is not yet decided. Decide it by an
4030 optimized method for handling `coding:' tag.
4032 Note that we can get here only if the buffer was empty
4033 before the insertion. */
4035 if (!NILP (Vcoding_system_for_read
))
4036 coding_system
= Vcoding_system_for_read
;
4039 /* Since we are sure that the current buffer was empty
4040 before the insertion, we can toggle
4041 enable-multibyte-characters directly here without taking
4042 care of marker adjustment. By this way, we can run Lisp
4043 program safely before decoding the inserted text. */
4044 Lisp_Object unwind_data
;
4045 ptrdiff_t count1
= SPECPDL_INDEX ();
4047 unwind_data
= Fcons (BVAR (current_buffer
, enable_multibyte_characters
),
4048 Fcons (BVAR (current_buffer
, undo_list
),
4049 Fcurrent_buffer ()));
4050 BVAR (current_buffer
, enable_multibyte_characters
) = Qnil
;
4051 BVAR (current_buffer
, undo_list
) = Qt
;
4052 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4054 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4056 coding_system
= call2 (Vset_auto_coding_function
,
4057 filename
, make_number (inserted
));
4060 if (NILP (coding_system
))
4062 /* If the coding system is not yet decided, check
4063 file-coding-system-alist. */
4064 Lisp_Object args
[6];
4066 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
4067 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = Qnil
;
4068 coding_system
= Ffind_operation_coding_system (6, args
);
4069 if (CONSP (coding_system
))
4070 coding_system
= XCAR (coding_system
);
4072 unbind_to (count1
, Qnil
);
4073 inserted
= Z_BYTE
- BEG_BYTE
;
4076 if (NILP (coding_system
))
4077 coding_system
= Qundecided
;
4079 CHECK_CODING_SYSTEM (coding_system
);
4081 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4082 /* We must suppress all character code conversion except for
4083 end-of-line conversion. */
4084 coding_system
= raw_text_coding_system (coding_system
);
4085 setup_coding_system (coding_system
, &coding
);
4086 /* Ensure we set Vlast_coding_system_used. */
4087 set_coding_system
= 1;
4092 /* When we visit a file by raw-text, we change the buffer to
4094 if (CODING_FOR_UNIBYTE (&coding
)
4095 /* Can't do this if part of the buffer might be preserved. */
4097 /* Visiting a file with these coding system makes the buffer
4099 BVAR (current_buffer
, enable_multibyte_characters
) = Qnil
;
4102 coding
.dst_multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
4103 if (CODING_MAY_REQUIRE_DECODING (&coding
)
4104 && (inserted
> 0 || CODING_REQUIRE_FLUSHING (&coding
)))
4106 move_gap_both (PT
, PT_BYTE
);
4107 GAP_SIZE
+= inserted
;
4108 ZV_BYTE
-= inserted
;
4112 decode_coding_gap (&coding
, inserted
, inserted
);
4113 inserted
= coding
.produced_char
;
4114 coding_system
= CODING_ID_NAME (coding
.id
);
4116 else if (inserted
> 0)
4117 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4120 /* Call after-change hooks for the inserted text, aside from the case
4121 of normal visiting (not with REPLACE), which is done in a new buffer
4122 "before" the buffer is changed. */
4123 if (inserted
> 0 && total
> 0
4124 && (NILP (visit
) || !NILP (replace
)))
4126 signal_after_change (PT
, 0, inserted
);
4127 update_compositions (PT
, PT
, CHECK_BORDER
);
4130 /* Now INSERTED is measured in characters. */
4134 if (deferred_remove_unwind_protect
)
4135 /* If requested above, discard the unwind protect for closing the
4141 if (!EQ (BVAR (current_buffer
, undo_list
), Qt
) && !nochange
)
4142 BVAR (current_buffer
, undo_list
) = Qnil
;
4146 current_buffer
->modtime
= st
.st_mtime
;
4147 current_buffer
->modtime_size
= st
.st_size
;
4148 BVAR (current_buffer
, filename
) = orig_filename
;
4151 SAVE_MODIFF
= MODIFF
;
4152 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
4153 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4154 #ifdef CLASH_DETECTION
4157 if (!NILP (BVAR (current_buffer
, file_truename
)))
4158 unlock_file (BVAR (current_buffer
, file_truename
));
4159 unlock_file (filename
);
4161 #endif /* CLASH_DETECTION */
4163 xsignal2 (Qfile_error
,
4164 build_string ("not a regular file"), orig_filename
);
4167 if (set_coding_system
)
4168 Vlast_coding_system_used
= coding_system
;
4170 if (! NILP (Ffboundp (Qafter_insert_file_set_coding
)))
4172 insval
= call2 (Qafter_insert_file_set_coding
, make_number (inserted
),
4174 if (! NILP (insval
))
4176 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4177 wrong_type_argument (intern ("inserted-chars"), insval
);
4178 inserted
= XFASTINT (insval
);
4182 /* Decode file format. */
4185 /* Don't run point motion or modification hooks when decoding. */
4186 ptrdiff_t count1
= SPECPDL_INDEX ();
4187 ptrdiff_t old_inserted
= inserted
;
4188 specbind (Qinhibit_point_motion_hooks
, Qt
);
4189 specbind (Qinhibit_modification_hooks
, Qt
);
4191 /* Save old undo list and don't record undo for decoding. */
4192 old_undo
= BVAR (current_buffer
, undo_list
);
4193 BVAR (current_buffer
, undo_list
) = Qt
;
4197 insval
= call3 (Qformat_decode
,
4198 Qnil
, make_number (inserted
), visit
);
4199 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4200 wrong_type_argument (intern ("inserted-chars"), insval
);
4201 inserted
= XFASTINT (insval
);
4205 /* If REPLACE is non-nil and we succeeded in not replacing the
4206 beginning or end of the buffer text with the file's contents,
4207 call format-decode with `point' positioned at the beginning
4208 of the buffer and `inserted' equaling the number of
4209 characters in the buffer. Otherwise, format-decode might
4210 fail to correctly analyze the beginning or end of the buffer.
4211 Hence we temporarily save `point' and `inserted' here and
4212 restore `point' iff format-decode did not insert or delete
4213 any text. Otherwise we leave `point' at point-min. */
4214 ptrdiff_t opoint
= PT
;
4215 ptrdiff_t opoint_byte
= PT_BYTE
;
4216 ptrdiff_t oinserted
= ZV
- BEGV
;
4217 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4219 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4220 insval
= call3 (Qformat_decode
,
4221 Qnil
, make_number (oinserted
), visit
);
4222 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4223 wrong_type_argument (intern ("inserted-chars"), insval
);
4224 if (ochars_modiff
== CHARS_MODIFF
)
4225 /* format_decode didn't modify buffer's characters => move
4226 point back to position before inserted text and leave
4227 value of inserted alone. */
4228 SET_PT_BOTH (opoint
, opoint_byte
);
4230 /* format_decode modified buffer's characters => consider
4231 entire buffer changed and leave point at point-min. */
4232 inserted
= XFASTINT (insval
);
4235 /* For consistency with format-decode call these now iff inserted > 0
4236 (martin 2007-06-28). */
4237 p
= Vafter_insert_file_functions
;
4242 insval
= call1 (XCAR (p
), make_number (inserted
));
4245 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4246 wrong_type_argument (intern ("inserted-chars"), insval
);
4247 inserted
= XFASTINT (insval
);
4252 /* For the rationale of this see the comment on
4253 format-decode above. */
4254 ptrdiff_t opoint
= PT
;
4255 ptrdiff_t opoint_byte
= PT_BYTE
;
4256 ptrdiff_t oinserted
= ZV
- BEGV
;
4257 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4259 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4260 insval
= call1 (XCAR (p
), make_number (oinserted
));
4263 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4264 wrong_type_argument (intern ("inserted-chars"), insval
);
4265 if (ochars_modiff
== CHARS_MODIFF
)
4266 /* after_insert_file_functions didn't modify
4267 buffer's characters => move point back to
4268 position before inserted text and leave value of
4270 SET_PT_BOTH (opoint
, opoint_byte
);
4272 /* after_insert_file_functions did modify buffer's
4273 characters => consider entire buffer changed and
4274 leave point at point-min. */
4275 inserted
= XFASTINT (insval
);
4285 BVAR (current_buffer
, undo_list
) = old_undo
;
4286 if (CONSP (old_undo
) && inserted
!= old_inserted
)
4288 /* Adjust the last undo record for the size change during
4289 the format conversion. */
4290 Lisp_Object tem
= XCAR (old_undo
);
4291 if (CONSP (tem
) && INTEGERP (XCAR (tem
))
4292 && INTEGERP (XCDR (tem
))
4293 && XFASTINT (XCDR (tem
)) == PT
+ old_inserted
)
4294 XSETCDR (tem
, make_number (PT
+ inserted
));
4298 /* If undo_list was Qt before, keep it that way.
4299 Otherwise start with an empty undo_list. */
4300 BVAR (current_buffer
, undo_list
) = EQ (old_undo
, Qt
) ? Qt
: Qnil
;
4302 unbind_to (count1
, Qnil
);
4306 && current_buffer
->modtime
== -1)
4308 /* If visiting nonexistent file, return nil. */
4310 report_file_error ("Opening input file", Fcons (orig_filename
, Qnil
));
4314 Fsignal (Qquit
, Qnil
);
4316 /* ??? Retval needs to be dealt with in all cases consistently. */
4318 val
= Fcons (orig_filename
,
4319 Fcons (make_number (inserted
),
4322 RETURN_UNGCPRO (unbind_to (count
, val
));
4325 static Lisp_Object
build_annotations (Lisp_Object
, Lisp_Object
);
4328 build_annotations_unwind (Lisp_Object arg
)
4330 Vwrite_region_annotation_buffers
= arg
;
4334 /* Decide the coding-system to encode the data with. */
4337 choose_write_coding_system (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4338 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4339 struct coding_system
*coding
)
4342 Lisp_Object eol_parent
= Qnil
;
4345 && NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4346 BVAR (current_buffer
, auto_save_file_name
))))
4351 else if (!NILP (Vcoding_system_for_write
))
4353 val
= Vcoding_system_for_write
;
4354 if (coding_system_require_warning
4355 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4356 /* Confirm that VAL can surely encode the current region. */
4357 val
= call5 (Vselect_safe_coding_system_function
,
4358 start
, end
, Fcons (Qt
, Fcons (val
, Qnil
)),
4363 /* If the variable `buffer-file-coding-system' is set locally,
4364 it means that the file was read with some kind of code
4365 conversion or the variable is explicitly set by users. We
4366 had better write it out with the same coding system even if
4367 `enable-multibyte-characters' is nil.
4369 If it is not set locally, we anyway have to convert EOL
4370 format if the default value of `buffer-file-coding-system'
4371 tells that it is not Unix-like (LF only) format. */
4372 int using_default_coding
= 0;
4373 int force_raw_text
= 0;
4375 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4377 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4380 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4386 /* Check file-coding-system-alist. */
4387 Lisp_Object args
[7], coding_systems
;
4389 args
[0] = Qwrite_region
; args
[1] = start
; args
[2] = end
;
4390 args
[3] = filename
; args
[4] = append
; args
[5] = visit
;
4392 coding_systems
= Ffind_operation_coding_system (7, args
);
4393 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4394 val
= XCDR (coding_systems
);
4399 /* If we still have not decided a coding system, use the
4400 default value of buffer-file-coding-system. */
4401 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4402 using_default_coding
= 1;
4405 if (! NILP (val
) && ! force_raw_text
)
4407 Lisp_Object spec
, attrs
;
4409 CHECK_CODING_SYSTEM_GET_SPEC (val
, spec
);
4410 attrs
= AREF (spec
, 0);
4411 if (EQ (CODING_ATTR_TYPE (attrs
), Qraw_text
))
4416 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4417 /* Confirm that VAL can surely encode the current region. */
4418 val
= call5 (Vselect_safe_coding_system_function
,
4419 start
, end
, val
, Qnil
, filename
);
4421 /* If the decided coding-system doesn't specify end-of-line
4422 format, we use that of
4423 `default-buffer-file-coding-system'. */
4424 if (! using_default_coding
4425 && ! NILP (BVAR (&buffer_defaults
, buffer_file_coding_system
)))
4426 val
= (coding_inherit_eol_type
4427 (val
, BVAR (&buffer_defaults
, buffer_file_coding_system
)));
4429 /* If we decide not to encode text, use `raw-text' or one of its
4432 val
= raw_text_coding_system (val
);
4435 val
= coding_inherit_eol_type (val
, eol_parent
);
4436 setup_coding_system (val
, coding
);
4438 if (!STRINGP (start
) && !NILP (BVAR (current_buffer
, selective_display
)))
4439 coding
->mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4443 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4444 "r\nFWrite region to file: \ni\ni\ni\np",
4445 doc
: /* Write current region into specified file.
4446 When called from a program, requires three arguments:
4447 START, END and FILENAME. START and END are normally buffer positions
4448 specifying the part of the buffer to write.
4449 If START is nil, that means to use the entire buffer contents.
4450 If START is a string, then output that string to the file
4451 instead of any buffer contents; END is ignored.
4453 Optional fourth argument APPEND if non-nil means
4454 append to existing file contents (if any). If it is an integer,
4455 seek to that offset in the file before writing.
4456 Optional fifth argument VISIT, if t or a string, means
4457 set the last-save-file-modtime of buffer to this file's modtime
4458 and mark buffer not modified.
4459 If VISIT is a string, it is a second file name;
4460 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4461 VISIT is also the file name to lock and unlock for clash detection.
4462 If VISIT is neither t nor nil nor a string,
4463 that means do not display the \"Wrote file\" message.
4464 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4465 use for locking and unlocking, overriding FILENAME and VISIT.
4466 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4467 for an existing file with the same name. If MUSTBENEW is `excl',
4468 that means to get an error if the file already exists; never overwrite.
4469 If MUSTBENEW is neither nil nor `excl', that means ask for
4470 confirmation before overwriting, but do go ahead and overwrite the file
4471 if the user confirms.
4473 This does code conversion according to the value of
4474 `coding-system-for-write', `buffer-file-coding-system', or
4475 `file-coding-system-alist', and sets the variable
4476 `last-coding-system-used' to the coding system actually used.
4478 This calls `write-region-annotate-functions' at the start, and
4479 `write-region-post-annotation-function' at the end. */)
4480 (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
, Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
, Lisp_Object mustbenew
)
4487 ptrdiff_t count
= SPECPDL_INDEX ();
4489 Lisp_Object handler
;
4490 Lisp_Object visit_file
;
4491 Lisp_Object annotations
;
4492 Lisp_Object encoded_filename
;
4493 int visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4494 int quietly
= !NILP (visit
);
4495 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
4496 struct buffer
*given_buffer
;
4497 struct coding_system coding
;
4499 if (current_buffer
->base_buffer
&& visiting
)
4500 error ("Cannot do file visiting in an indirect buffer");
4502 if (!NILP (start
) && !STRINGP (start
))
4503 validate_region (&start
, &end
);
4506 GCPRO5 (start
, filename
, visit
, visit_file
, lockname
);
4508 filename
= Fexpand_file_name (filename
, Qnil
);
4510 if (!NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4511 barf_or_query_if_file_exists (filename
, "overwrite", 1, 0, 1);
4513 if (STRINGP (visit
))
4514 visit_file
= Fexpand_file_name (visit
, Qnil
);
4516 visit_file
= filename
;
4518 if (NILP (lockname
))
4519 lockname
= visit_file
;
4523 /* If the file name has special constructs in it,
4524 call the corresponding file handler. */
4525 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4526 /* If FILENAME has no handler, see if VISIT has one. */
4527 if (NILP (handler
) && STRINGP (visit
))
4528 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4530 if (!NILP (handler
))
4533 val
= call6 (handler
, Qwrite_region
, start
, end
,
4534 filename
, append
, visit
);
4538 SAVE_MODIFF
= MODIFF
;
4539 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4540 BVAR (current_buffer
, filename
) = visit_file
;
4546 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
4548 /* Special kludge to simplify auto-saving. */
4551 /* Do it later, so write-region-annotate-function can work differently
4552 if we save "the buffer" vs "a region".
4553 This is useful in tar-mode. --Stef
4554 XSETFASTINT (start, BEG);
4555 XSETFASTINT (end, Z); */
4559 record_unwind_protect (build_annotations_unwind
,
4560 Vwrite_region_annotation_buffers
);
4561 Vwrite_region_annotation_buffers
= Fcons (Fcurrent_buffer (), Qnil
);
4562 count1
= SPECPDL_INDEX ();
4564 given_buffer
= current_buffer
;
4566 if (!STRINGP (start
))
4568 annotations
= build_annotations (start
, end
);
4570 if (current_buffer
!= given_buffer
)
4572 XSETFASTINT (start
, BEGV
);
4573 XSETFASTINT (end
, ZV
);
4579 XSETFASTINT (start
, BEGV
);
4580 XSETFASTINT (end
, ZV
);
4585 GCPRO5 (start
, filename
, annotations
, visit_file
, lockname
);
4587 /* Decide the coding-system to encode the data with.
4588 We used to make this choice before calling build_annotations, but that
4589 leads to problems when a write-annotate-function takes care of
4590 unsavable chars (as was the case with X-Symbol). */
4591 Vlast_coding_system_used
4592 = choose_write_coding_system (start
, end
, filename
,
4593 append
, visit
, lockname
, &coding
);
4595 #ifdef CLASH_DETECTION
4597 lock_file (lockname
);
4598 #endif /* CLASH_DETECTION */
4600 encoded_filename
= ENCODE_FILE (filename
);
4602 fn
= SSDATA (encoded_filename
);
4606 desc
= emacs_open (fn
, O_WRONLY
| O_BINARY
, 0);
4607 #else /* not DOS_NT */
4608 desc
= emacs_open (fn
, O_WRONLY
, 0);
4609 #endif /* not DOS_NT */
4611 if (desc
< 0 && (NILP (append
) || errno
== ENOENT
))
4613 desc
= emacs_open (fn
,
4614 O_WRONLY
| O_CREAT
| O_BINARY
4615 | (EQ (mustbenew
, Qexcl
) ? O_EXCL
: O_TRUNC
),
4616 S_IREAD
| S_IWRITE
);
4617 #else /* not DOS_NT */
4618 desc
= emacs_open (fn
, O_WRONLY
| O_TRUNC
| O_CREAT
4619 | (EQ (mustbenew
, Qexcl
) ? O_EXCL
: 0),
4620 auto_saving
? auto_save_mode_bits
: 0666);
4621 #endif /* not DOS_NT */
4625 #ifdef CLASH_DETECTION
4627 if (!auto_saving
) unlock_file (lockname
);
4629 #endif /* CLASH_DETECTION */
4631 report_file_error ("Opening output file", Fcons (filename
, Qnil
));
4634 record_unwind_protect (close_file_unwind
, make_number (desc
));
4636 if (!NILP (append
) && !NILP (Ffile_regular_p (filename
)))
4640 if (NUMBERP (append
))
4641 ret
= emacs_lseek (desc
, XINT (append
), SEEK_CUR
);
4643 ret
= lseek (desc
, 0, SEEK_END
);
4646 #ifdef CLASH_DETECTION
4648 if (!auto_saving
) unlock_file (lockname
);
4650 #endif /* CLASH_DETECTION */
4652 report_file_error ("Lseek error", Fcons (filename
, Qnil
));
4661 if (STRINGP (start
))
4663 failure
= 0 > a_write (desc
, start
, 0, SCHARS (start
),
4664 &annotations
, &coding
);
4667 else if (XINT (start
) != XINT (end
))
4669 failure
= 0 > a_write (desc
, Qnil
,
4670 XINT (start
), XINT (end
) - XINT (start
),
4671 &annotations
, &coding
);
4676 /* If file was empty, still need to write the annotations */
4677 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4678 failure
= 0 > a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4682 if (CODING_REQUIRE_FLUSHING (&coding
)
4683 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
)
4686 /* We have to flush out a data. */
4687 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4688 failure
= 0 > e_write (desc
, Qnil
, 1, 1, &coding
);
4695 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4696 Disk full in NFS may be reported here. */
4697 /* mib says that closing the file will try to write as fast as NFS can do
4698 it, and that means the fsync here is not crucial for autosave files. */
4699 if (!auto_saving
&& !write_region_inhibit_fsync
&& fsync (desc
) < 0)
4701 /* If fsync fails with EINTR, don't treat that as serious. Also
4702 ignore EINVAL which happens when fsync is not supported on this
4704 if (errno
!= EINTR
&& errno
!= EINVAL
)
4705 failure
= 1, save_errno
= errno
;
4709 /* NFS can report a write failure now. */
4710 if (emacs_close (desc
) < 0)
4711 failure
= 1, save_errno
= errno
;
4715 /* Discard the unwind protect for close_file_unwind. */
4716 specpdl_ptr
= specpdl
+ count1
;
4718 /* Call write-region-post-annotation-function. */
4719 while (CONSP (Vwrite_region_annotation_buffers
))
4721 Lisp_Object buf
= XCAR (Vwrite_region_annotation_buffers
);
4722 if (!NILP (Fbuffer_live_p (buf
)))
4725 if (FUNCTIONP (Vwrite_region_post_annotation_function
))
4726 call0 (Vwrite_region_post_annotation_function
);
4728 Vwrite_region_annotation_buffers
4729 = XCDR (Vwrite_region_annotation_buffers
);
4732 unbind_to (count
, Qnil
);
4734 #ifdef CLASH_DETECTION
4736 unlock_file (lockname
);
4737 #endif /* CLASH_DETECTION */
4739 /* Do this before reporting IO error
4740 to avoid a "file has changed on disk" warning on
4741 next attempt to save. */
4744 current_buffer
->modtime
= st
.st_mtime
;
4745 current_buffer
->modtime_size
= st
.st_size
;
4749 error ("IO error writing %s: %s", SDATA (filename
),
4750 emacs_strerror (save_errno
));
4754 SAVE_MODIFF
= MODIFF
;
4755 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4756 BVAR (current_buffer
, filename
) = visit_file
;
4757 update_mode_lines
++;
4762 && ! NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4763 BVAR (current_buffer
, auto_save_file_name
))))
4764 SAVE_MODIFF
= MODIFF
;
4770 message_with_string ((INTEGERP (append
)
4780 Lisp_Object
merge (Lisp_Object
, Lisp_Object
, Lisp_Object
);
4782 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
4783 doc
: /* Return t if (car A) is numerically less than (car B). */)
4784 (Lisp_Object a
, Lisp_Object b
)
4786 return Flss (Fcar (a
), Fcar (b
));
4789 /* Build the complete list of annotations appropriate for writing out
4790 the text between START and END, by calling all the functions in
4791 write-region-annotate-functions and merging the lists they return.
4792 If one of these functions switches to a different buffer, we assume
4793 that buffer contains altered text. Therefore, the caller must
4794 make sure to restore the current buffer in all cases,
4795 as save-excursion would do. */
4798 build_annotations (Lisp_Object start
, Lisp_Object end
)
4800 Lisp_Object annotations
;
4802 struct gcpro gcpro1
, gcpro2
;
4803 Lisp_Object original_buffer
;
4804 int i
, used_global
= 0;
4806 XSETBUFFER (original_buffer
, current_buffer
);
4809 p
= Vwrite_region_annotate_functions
;
4810 GCPRO2 (annotations
, p
);
4813 struct buffer
*given_buffer
= current_buffer
;
4814 if (EQ (Qt
, XCAR (p
)) && !used_global
)
4815 { /* Use the global value of the hook. */
4818 arg
[0] = Fdefault_value (Qwrite_region_annotate_functions
);
4820 p
= Fappend (2, arg
);
4823 Vwrite_region_annotations_so_far
= annotations
;
4824 res
= call2 (XCAR (p
), start
, end
);
4825 /* If the function makes a different buffer current,
4826 assume that means this buffer contains altered text to be output.
4827 Reset START and END from the buffer bounds
4828 and discard all previous annotations because they should have
4829 been dealt with by this function. */
4830 if (current_buffer
!= given_buffer
)
4832 Vwrite_region_annotation_buffers
4833 = Fcons (Fcurrent_buffer (),
4834 Vwrite_region_annotation_buffers
);
4835 XSETFASTINT (start
, BEGV
);
4836 XSETFASTINT (end
, ZV
);
4839 Flength (res
); /* Check basic validity of return value */
4840 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
4844 /* Now do the same for annotation functions implied by the file-format */
4845 if (auto_saving
&& (!EQ (BVAR (current_buffer
, auto_save_file_format
), Qt
)))
4846 p
= BVAR (current_buffer
, auto_save_file_format
);
4848 p
= BVAR (current_buffer
, file_format
);
4849 for (i
= 0; CONSP (p
); p
= XCDR (p
), ++i
)
4851 struct buffer
*given_buffer
= current_buffer
;
4853 Vwrite_region_annotations_so_far
= annotations
;
4855 /* Value is either a list of annotations or nil if the function
4856 has written annotations to a temporary buffer, which is now
4858 res
= call5 (Qformat_annotate_function
, XCAR (p
), start
, end
,
4859 original_buffer
, make_number (i
));
4860 if (current_buffer
!= given_buffer
)
4862 XSETFASTINT (start
, BEGV
);
4863 XSETFASTINT (end
, ZV
);
4868 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
4876 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
4877 If STRING is nil, POS is the character position in the current buffer.
4878 Intersperse with them the annotations from *ANNOT
4879 which fall within the range of POS to POS + NCHARS,
4880 each at its appropriate position.
4882 We modify *ANNOT by discarding elements as we use them up.
4884 The return value is negative in case of system call failure. */
4887 a_write (int desc
, Lisp_Object string
, ptrdiff_t pos
,
4888 register ptrdiff_t nchars
, Lisp_Object
*annot
,
4889 struct coding_system
*coding
)
4893 ptrdiff_t lastpos
= pos
+ nchars
;
4895 while (NILP (*annot
) || CONSP (*annot
))
4897 tem
= Fcar_safe (Fcar (*annot
));
4900 nextpos
= XFASTINT (tem
);
4902 /* If there are no more annotations in this range,
4903 output the rest of the range all at once. */
4904 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
4905 return e_write (desc
, string
, pos
, lastpos
, coding
);
4907 /* Output buffer text up to the next annotation's position. */
4910 if (0 > e_write (desc
, string
, pos
, nextpos
, coding
))
4914 /* Output the annotation. */
4915 tem
= Fcdr (Fcar (*annot
));
4918 if (0 > e_write (desc
, tem
, 0, SCHARS (tem
), coding
))
4921 *annot
= Fcdr (*annot
);
4927 /* Write text in the range START and END into descriptor DESC,
4928 encoding them with coding system CODING. If STRING is nil, START
4929 and END are character positions of the current buffer, else they
4930 are indexes to the string STRING. */
4933 e_write (int desc
, Lisp_Object string
, ptrdiff_t start
, ptrdiff_t end
,
4934 struct coding_system
*coding
)
4936 if (STRINGP (string
))
4939 end
= SCHARS (string
);
4942 /* We used to have a code for handling selective display here. But,
4943 now it is handled within encode_coding. */
4947 if (STRINGP (string
))
4949 coding
->src_multibyte
= SCHARS (string
) < SBYTES (string
);
4950 if (CODING_REQUIRE_ENCODING (coding
))
4952 encode_coding_object (coding
, string
,
4953 start
, string_char_to_byte (string
, start
),
4954 end
, string_char_to_byte (string
, end
), Qt
);
4958 coding
->dst_object
= string
;
4959 coding
->consumed_char
= SCHARS (string
);
4960 coding
->produced
= SBYTES (string
);
4965 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
4966 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
4968 coding
->src_multibyte
= (end
- start
) < (end_byte
- start_byte
);
4969 if (CODING_REQUIRE_ENCODING (coding
))
4971 encode_coding_object (coding
, Fcurrent_buffer (),
4972 start
, start_byte
, end
, end_byte
, Qt
);
4976 coding
->dst_object
= Qnil
;
4977 coding
->dst_pos_byte
= start_byte
;
4978 if (start
>= GPT
|| end
<= GPT
)
4980 coding
->consumed_char
= end
- start
;
4981 coding
->produced
= end_byte
- start_byte
;
4985 coding
->consumed_char
= GPT
- start
;
4986 coding
->produced
= GPT_BYTE
- start_byte
;
4991 if (coding
->produced
> 0)
4995 STRINGP (coding
->dst_object
)
4996 ? SSDATA (coding
->dst_object
)
4997 : (char *) BYTE_POS_ADDR (coding
->dst_pos_byte
),
5000 if (coding
->produced
)
5003 start
+= coding
->consumed_char
;
5009 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5010 Sverify_visited_file_modtime
, 0, 1, 0,
5011 doc
: /* Return t if last mod time of BUF's visited file matches what BUF records.
5012 This means that the file has not been changed since it was visited or saved.
5013 If BUF is omitted or nil, it defaults to the current buffer.
5014 See Info node `(elisp)Modification Time' for more details. */)
5019 Lisp_Object handler
;
5020 Lisp_Object filename
;
5030 if (!STRINGP (BVAR (b
, filename
))) return Qt
;
5031 if (b
->modtime
== 0) return Qt
;
5033 /* If the file name has special constructs in it,
5034 call the corresponding file handler. */
5035 handler
= Ffind_file_name_handler (BVAR (b
, filename
),
5036 Qverify_visited_file_modtime
);
5037 if (!NILP (handler
))
5038 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5040 filename
= ENCODE_FILE (BVAR (b
, filename
));
5042 if (stat (SSDATA (filename
), &st
) < 0)
5044 /* If the file doesn't exist now and didn't exist before,
5045 we say that it isn't modified, provided the error is a tame one. */
5046 if (errno
== ENOENT
|| errno
== EACCES
|| errno
== ENOTDIR
)
5051 if ((st
.st_mtime
== b
->modtime
5052 /* If both are positive, accept them if they are off by one second. */
5053 || (st
.st_mtime
> 0 && b
->modtime
> 0
5054 && (st
.st_mtime
- 1 == b
->modtime
5055 || st
.st_mtime
== b
->modtime
- 1)))
5056 && (st
.st_size
== b
->modtime_size
5057 || b
->modtime_size
< 0))
5062 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime
,
5063 Sclear_visited_file_modtime
, 0, 0, 0,
5064 doc
: /* Clear out records of last mod time of visited file.
5065 Next attempt to save will certainly not complain of a discrepancy. */)
5068 current_buffer
->modtime
= 0;
5069 current_buffer
->modtime_size
= -1;
5073 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5074 Svisited_file_modtime
, 0, 0, 0,
5075 doc
: /* Return the current buffer's recorded visited file modification time.
5076 The value is a list of the form (HIGH LOW), like the time values that
5077 `file-attributes' returns. If the current buffer has no recorded file
5078 modification time, this function returns 0. If the visited file
5079 doesn't exist, HIGH will be -1.
5080 See Info node `(elisp)Modification Time' for more details. */)
5083 if (! current_buffer
->modtime
)
5084 return make_number (0);
5085 return make_time (current_buffer
->modtime
);
5088 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5089 Sset_visited_file_modtime
, 0, 1, 0,
5090 doc
: /* Update buffer's recorded modification time from the visited file's time.
5091 Useful if the buffer was not read from the file normally
5092 or if the file itself has been changed for some known benign reason.
5093 An argument specifies the modification time value to use
5094 \(instead of that of the visited file), in the form of a list
5095 \(HIGH . LOW) or (HIGH LOW). */)
5096 (Lisp_Object time_list
)
5098 if (!NILP (time_list
))
5100 CONS_TO_INTEGER (time_list
, time_t, current_buffer
->modtime
);
5101 current_buffer
->modtime_size
= -1;
5105 register Lisp_Object filename
;
5107 Lisp_Object handler
;
5109 filename
= Fexpand_file_name (BVAR (current_buffer
, filename
), Qnil
);
5111 /* If the file name has special constructs in it,
5112 call the corresponding file handler. */
5113 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5114 if (!NILP (handler
))
5115 /* The handler can find the file name the same way we did. */
5116 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5118 filename
= ENCODE_FILE (filename
);
5120 if (stat (SSDATA (filename
), &st
) >= 0)
5122 current_buffer
->modtime
= st
.st_mtime
;
5123 current_buffer
->modtime_size
= st
.st_size
;
5131 auto_save_error (Lisp_Object error_val
)
5133 Lisp_Object args
[3], msg
;
5135 struct gcpro gcpro1
;
5139 auto_save_error_occurred
= 1;
5141 ring_bell (XFRAME (selected_frame
));
5143 args
[0] = build_string ("Auto-saving %s: %s");
5144 args
[1] = BVAR (current_buffer
, name
);
5145 args
[2] = Ferror_message_string (error_val
);
5146 msg
= Fformat (3, args
);
5148 nbytes
= SBYTES (msg
);
5149 SAFE_ALLOCA (msgbuf
, char *, nbytes
);
5150 memcpy (msgbuf
, SDATA (msg
), nbytes
);
5152 for (i
= 0; i
< 3; ++i
)
5155 message2 (msgbuf
, nbytes
, STRING_MULTIBYTE (msg
));
5157 message2_nolog (msgbuf
, nbytes
, STRING_MULTIBYTE (msg
));
5158 Fsleep_for (make_number (1), Qnil
);
5172 auto_save_mode_bits
= 0666;
5174 /* Get visited file's mode to become the auto save file's mode. */
5175 if (! NILP (BVAR (current_buffer
, filename
)))
5177 if (stat (SSDATA (BVAR (current_buffer
, filename
)), &st
) >= 0)
5178 /* But make sure we can overwrite it later! */
5179 auto_save_mode_bits
= (st
.st_mode
| 0600) & 0777;
5180 else if ((modes
= Ffile_modes (BVAR (current_buffer
, filename
)),
5182 /* Remote files don't cooperate with stat. */
5183 auto_save_mode_bits
= (XINT (modes
) | 0600) & 0777;
5187 Fwrite_region (Qnil
, Qnil
, BVAR (current_buffer
, auto_save_file_name
), Qnil
,
5188 NILP (Vauto_save_visited_file_name
) ? Qlambda
: Qt
,
5193 do_auto_save_unwind (Lisp_Object arg
) /* used as unwind-protect function */
5196 FILE *stream
= (FILE *) XSAVE_VALUE (arg
)->pointer
;
5208 do_auto_save_unwind_1 (Lisp_Object value
) /* used as unwind-protect function */
5211 minibuffer_auto_raise
= XINT (value
);
5216 do_auto_save_make_dir (Lisp_Object dir
)
5220 auto_saving_dir_umask
= 077;
5221 result
= call2 (Qmake_directory
, dir
, Qt
);
5222 auto_saving_dir_umask
= 0;
5227 do_auto_save_eh (Lisp_Object ignore
)
5229 auto_saving_dir_umask
= 0;
5233 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5234 doc
: /* Auto-save all buffers that need it.
5235 This is all buffers that have auto-saving enabled
5236 and are changed since last auto-saved.
5237 Auto-saving writes the buffer into a file
5238 so that your editing is not lost if the system crashes.
5239 This file is not the file you visited; that changes only when you save.
5240 Normally we run the normal hook `auto-save-hook' before saving.
5242 A non-nil NO-MESSAGE argument means do not print any message if successful.
5243 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5244 (Lisp_Object no_message
, Lisp_Object current_only
)
5246 struct buffer
*old
= current_buffer
, *b
;
5247 Lisp_Object tail
, buf
, hook
;
5249 int do_handled_files
;
5251 FILE *stream
= NULL
;
5252 ptrdiff_t count
= SPECPDL_INDEX ();
5253 int orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5254 int old_message_p
= 0;
5255 struct gcpro gcpro1
, gcpro2
;
5257 if (max_specpdl_size
< specpdl_size
+ 40)
5258 max_specpdl_size
= specpdl_size
+ 40;
5263 if (NILP (no_message
))
5265 old_message_p
= push_message ();
5266 record_unwind_protect (pop_message_unwind
, Qnil
);
5269 /* Ordinarily don't quit within this function,
5270 but don't make it impossible to quit (in case we get hung in I/O). */
5274 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5275 point to non-strings reached from Vbuffer_alist. */
5277 hook
= intern ("auto-save-hook");
5278 Frun_hooks (1, &hook
);
5280 if (STRINGP (Vauto_save_list_file_name
))
5282 Lisp_Object listfile
;
5284 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5286 /* Don't try to create the directory when shutting down Emacs,
5287 because creating the directory might signal an error, and
5288 that would leave Emacs in a strange state. */
5289 if (!NILP (Vrun_hooks
))
5293 GCPRO2 (dir
, listfile
);
5294 dir
= Ffile_name_directory (listfile
);
5295 if (NILP (Ffile_directory_p (dir
)))
5296 internal_condition_case_1 (do_auto_save_make_dir
,
5302 stream
= fopen (SSDATA (listfile
), "w");
5305 record_unwind_protect (do_auto_save_unwind
,
5306 make_save_value (stream
, 0));
5307 record_unwind_protect (do_auto_save_unwind_1
,
5308 make_number (minibuffer_auto_raise
));
5309 minibuffer_auto_raise
= 0;
5311 auto_save_error_occurred
= 0;
5313 /* On first pass, save all files that don't have handlers.
5314 On second pass, save all files that do have handlers.
5316 If Emacs is crashing, the handlers may tweak what is causing
5317 Emacs to crash in the first place, and it would be a shame if
5318 Emacs failed to autosave perfectly ordinary files because it
5319 couldn't handle some ange-ftp'd file. */
5321 for (do_handled_files
= 0; do_handled_files
< 2; do_handled_files
++)
5322 for (tail
= Vbuffer_alist
; CONSP (tail
); tail
= XCDR (tail
))
5324 buf
= XCDR (XCAR (tail
));
5327 /* Record all the buffers that have auto save mode
5328 in the special file that lists them. For each of these buffers,
5329 Record visited name (if any) and auto save name. */
5330 if (STRINGP (BVAR (b
, auto_save_file_name
))
5331 && stream
!= NULL
&& do_handled_files
== 0)
5334 if (!NILP (BVAR (b
, filename
)))
5336 fwrite (SDATA (BVAR (b
, filename
)), 1,
5337 SBYTES (BVAR (b
, filename
)), stream
);
5339 putc ('\n', stream
);
5340 fwrite (SDATA (BVAR (b
, auto_save_file_name
)), 1,
5341 SBYTES (BVAR (b
, auto_save_file_name
)), stream
);
5342 putc ('\n', stream
);
5346 if (!NILP (current_only
)
5347 && b
!= current_buffer
)
5350 /* Don't auto-save indirect buffers.
5351 The base buffer takes care of it. */
5355 /* Check for auto save enabled
5356 and file changed since last auto save
5357 and file changed since last real save. */
5358 if (STRINGP (BVAR (b
, auto_save_file_name
))
5359 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
)
5360 && BUF_AUTOSAVE_MODIFF (b
) < BUF_MODIFF (b
)
5361 /* -1 means we've turned off autosaving for a while--see below. */
5362 && XINT (BVAR (b
, save_length
)) >= 0
5363 && (do_handled_files
5364 || NILP (Ffind_file_name_handler (BVAR (b
, auto_save_file_name
),
5367 EMACS_TIME before_time
, after_time
;
5369 EMACS_GET_TIME (before_time
);
5371 /* If we had a failure, don't try again for 20 minutes. */
5372 if (b
->auto_save_failure_time
> 0
5373 && EMACS_SECS (before_time
) - b
->auto_save_failure_time
< 1200)
5376 set_buffer_internal (b
);
5377 if (NILP (Vauto_save_include_big_deletions
)
5378 && (XFASTINT (BVAR (b
, save_length
)) * 10
5379 > (BUF_Z (b
) - BUF_BEG (b
)) * 13)
5380 /* A short file is likely to change a large fraction;
5381 spare the user annoying messages. */
5382 && XFASTINT (BVAR (b
, save_length
)) > 5000
5383 /* These messages are frequent and annoying for `*mail*'. */
5384 && !EQ (BVAR (b
, filename
), Qnil
)
5385 && NILP (no_message
))
5387 /* It has shrunk too much; turn off auto-saving here. */
5388 minibuffer_auto_raise
= orig_minibuffer_auto_raise
;
5389 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5391 minibuffer_auto_raise
= 0;
5392 /* Turn off auto-saving until there's a real save,
5393 and prevent any more warnings. */
5394 XSETINT (BVAR (b
, save_length
), -1);
5395 Fsleep_for (make_number (1), Qnil
);
5398 if (!auto_saved
&& NILP (no_message
))
5399 message1 ("Auto-saving...");
5400 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
5402 BUF_AUTOSAVE_MODIFF (b
) = BUF_MODIFF (b
);
5403 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5404 set_buffer_internal (old
);
5406 EMACS_GET_TIME (after_time
);
5408 /* If auto-save took more than 60 seconds,
5409 assume it was an NFS failure that got a timeout. */
5410 if (EMACS_SECS (after_time
) - EMACS_SECS (before_time
) > 60)
5411 b
->auto_save_failure_time
= EMACS_SECS (after_time
);
5415 /* Prevent another auto save till enough input events come in. */
5416 record_auto_save ();
5418 if (auto_saved
&& NILP (no_message
))
5422 /* If we are going to restore an old message,
5423 give time to read ours. */
5424 sit_for (make_number (1), 0, 0);
5427 else if (!auto_save_error_occurred
)
5428 /* Don't overwrite the error message if an error occurred.
5429 If we displayed a message and then restored a state
5430 with no message, leave a "done" message on the screen. */
5431 message1 ("Auto-saving...done");
5436 /* This restores the message-stack status. */
5437 unbind_to (count
, Qnil
);
5441 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved
,
5442 Sset_buffer_auto_saved
, 0, 0, 0,
5443 doc
: /* Mark current buffer as auto-saved with its current text.
5444 No auto-save file will be written until the buffer changes again. */)
5447 /* FIXME: This should not be called in indirect buffers, since
5448 they're not autosaved. */
5449 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
5450 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5451 current_buffer
->auto_save_failure_time
= 0;
5455 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure
,
5456 Sclear_buffer_auto_save_failure
, 0, 0, 0,
5457 doc
: /* Clear any record of a recent auto-save failure in the current buffer. */)
5460 current_buffer
->auto_save_failure_time
= 0;
5464 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
5466 doc
: /* Return t if current buffer has been auto-saved recently.
5467 More precisely, if it has been auto-saved since last read from or saved
5468 in the visited file. If the buffer has no visited file,
5469 then any auto-save counts as "recent". */)
5472 /* FIXME: maybe we should return nil for indirect buffers since
5473 they're never autosaved. */
5474 return (SAVE_MODIFF
< BUF_AUTOSAVE_MODIFF (current_buffer
) ? Qt
: Qnil
);
5477 /* Reading and completing file names */
5479 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p
,
5480 Snext_read_file_uses_dialog_p
, 0, 0, 0,
5481 doc
: /* Return t if a call to `read-file-name' will use a dialog.
5482 The return value is only relevant for a call to `read-file-name' that happens
5483 before any other event (mouse or keypress) is handled. */)
5486 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK)
5487 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5497 Fread_file_name (Lisp_Object prompt
, Lisp_Object dir
, Lisp_Object default_filename
, Lisp_Object mustmatch
, Lisp_Object initial
, Lisp_Object predicate
)
5499 struct gcpro gcpro1
;
5500 Lisp_Object args
[7];
5502 GCPRO1 (default_filename
);
5503 args
[0] = intern ("read-file-name");
5506 args
[3] = default_filename
;
5507 args
[4] = mustmatch
;
5509 args
[6] = predicate
;
5510 RETURN_UNGCPRO (Ffuncall (7, args
));
5515 syms_of_fileio (void)
5517 DEFSYM (Qoperations
, "operations");
5518 DEFSYM (Qexpand_file_name
, "expand-file-name");
5519 DEFSYM (Qsubstitute_in_file_name
, "substitute-in-file-name");
5520 DEFSYM (Qdirectory_file_name
, "directory-file-name");
5521 DEFSYM (Qfile_name_directory
, "file-name-directory");
5522 DEFSYM (Qfile_name_nondirectory
, "file-name-nondirectory");
5523 DEFSYM (Qunhandled_file_name_directory
, "unhandled-file-name-directory");
5524 DEFSYM (Qfile_name_as_directory
, "file-name-as-directory");
5525 DEFSYM (Qcopy_file
, "copy-file");
5526 DEFSYM (Qmake_directory_internal
, "make-directory-internal");
5527 DEFSYM (Qmake_directory
, "make-directory");
5528 DEFSYM (Qdelete_directory_internal
, "delete-directory-internal");
5529 DEFSYM (Qdelete_file
, "delete-file");
5530 DEFSYM (Qrename_file
, "rename-file");
5531 DEFSYM (Qadd_name_to_file
, "add-name-to-file");
5532 DEFSYM (Qmake_symbolic_link
, "make-symbolic-link");
5533 DEFSYM (Qfile_exists_p
, "file-exists-p");
5534 DEFSYM (Qfile_executable_p
, "file-executable-p");
5535 DEFSYM (Qfile_readable_p
, "file-readable-p");
5536 DEFSYM (Qfile_writable_p
, "file-writable-p");
5537 DEFSYM (Qfile_symlink_p
, "file-symlink-p");
5538 DEFSYM (Qaccess_file
, "access-file");
5539 DEFSYM (Qfile_directory_p
, "file-directory-p");
5540 DEFSYM (Qfile_regular_p
, "file-regular-p");
5541 DEFSYM (Qfile_accessible_directory_p
, "file-accessible-directory-p");
5542 DEFSYM (Qfile_modes
, "file-modes");
5543 DEFSYM (Qset_file_modes
, "set-file-modes");
5544 DEFSYM (Qset_file_times
, "set-file-times");
5545 DEFSYM (Qfile_selinux_context
, "file-selinux-context");
5546 DEFSYM (Qset_file_selinux_context
, "set-file-selinux-context");
5547 DEFSYM (Qfile_newer_than_file_p
, "file-newer-than-file-p");
5548 DEFSYM (Qinsert_file_contents
, "insert-file-contents");
5549 DEFSYM (Qwrite_region
, "write-region");
5550 DEFSYM (Qverify_visited_file_modtime
, "verify-visited-file-modtime");
5551 DEFSYM (Qset_visited_file_modtime
, "set-visited-file-modtime");
5552 DEFSYM (Qauto_save_coding
, "auto-save-coding");
5554 DEFSYM (Qfile_name_history
, "file-name-history");
5555 Fset (Qfile_name_history
, Qnil
);
5557 DEFSYM (Qfile_error
, "file-error");
5558 DEFSYM (Qfile_already_exists
, "file-already-exists");
5559 DEFSYM (Qfile_date_error
, "file-date-error");
5560 DEFSYM (Qexcl
, "excl");
5562 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system
,
5563 doc
: /* *Coding system for encoding file names.
5564 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5565 Vfile_name_coding_system
= Qnil
;
5567 DEFVAR_LISP ("default-file-name-coding-system",
5568 Vdefault_file_name_coding_system
,
5569 doc
: /* Default coding system for encoding file names.
5570 This variable is used only when `file-name-coding-system' is nil.
5572 This variable is set/changed by the command `set-language-environment'.
5573 User should not set this variable manually,
5574 instead use `file-name-coding-system' to get a constant encoding
5575 of file names regardless of the current language environment. */);
5576 Vdefault_file_name_coding_system
= Qnil
;
5578 DEFSYM (Qformat_decode
, "format-decode");
5579 DEFSYM (Qformat_annotate_function
, "format-annotate-function");
5580 DEFSYM (Qafter_insert_file_set_coding
, "after-insert-file-set-coding");
5581 DEFSYM (Qcar_less_than_car
, "car-less-than-car");
5583 Fput (Qfile_error
, Qerror_conditions
,
5584 Fpurecopy (list2 (Qfile_error
, Qerror
)));
5585 Fput (Qfile_error
, Qerror_message
,
5586 make_pure_c_string ("File error"));
5588 Fput (Qfile_already_exists
, Qerror_conditions
,
5589 Fpurecopy (list3 (Qfile_already_exists
, Qfile_error
, Qerror
)));
5590 Fput (Qfile_already_exists
, Qerror_message
,
5591 make_pure_c_string ("File already exists"));
5593 Fput (Qfile_date_error
, Qerror_conditions
,
5594 Fpurecopy (list3 (Qfile_date_error
, Qfile_error
, Qerror
)));
5595 Fput (Qfile_date_error
, Qerror_message
,
5596 make_pure_c_string ("Cannot set file date"));
5598 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist
,
5599 doc
: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
5600 If a file name matches REGEXP, then all I/O on that file is done by calling
5603 The first argument given to HANDLER is the name of the I/O primitive
5604 to be handled; the remaining arguments are the arguments that were
5605 passed to that primitive. For example, if you do
5606 (file-exists-p FILENAME)
5607 and FILENAME is handled by HANDLER, then HANDLER is called like this:
5608 (funcall HANDLER 'file-exists-p FILENAME)
5609 The function `find-file-name-handler' checks this list for a handler
5610 for its argument. */);
5611 Vfile_name_handler_alist
= Qnil
;
5613 DEFVAR_LISP ("set-auto-coding-function",
5614 Vset_auto_coding_function
,
5615 doc
: /* If non-nil, a function to call to decide a coding system of file.
5616 Two arguments are passed to this function: the file name
5617 and the length of a file contents following the point.
5618 This function should return a coding system to decode the file contents.
5619 It should check the file name against `auto-coding-alist'.
5620 If no coding system is decided, it should check a coding system
5621 specified in the heading lines with the format:
5622 -*- ... coding: CODING-SYSTEM; ... -*-
5623 or local variable spec of the tailing lines with `coding:' tag. */);
5624 Vset_auto_coding_function
= Qnil
;
5626 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions
,
5627 doc
: /* A list of functions to be called at the end of `insert-file-contents'.
5628 Each is passed one argument, the number of characters inserted,
5629 with point at the start of the inserted text. Each function
5630 should leave point the same, and return the new character count.
5631 If `insert-file-contents' is intercepted by a handler from
5632 `file-name-handler-alist', that handler is responsible for calling the
5633 functions in `after-insert-file-functions' if appropriate. */);
5634 Vafter_insert_file_functions
= Qnil
;
5636 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions
,
5637 doc
: /* A list of functions to be called at the start of `write-region'.
5638 Each is passed two arguments, START and END as for `write-region'.
5639 These are usually two numbers but not always; see the documentation
5640 for `write-region'. The function should return a list of pairs
5641 of the form (POSITION . STRING), consisting of strings to be effectively
5642 inserted at the specified positions of the file being written (1 means to
5643 insert before the first byte written). The POSITIONs must be sorted into
5646 If there are several annotation functions, the lists returned by these
5647 functions are merged destructively. As each annotation function runs,
5648 the variable `write-region-annotations-so-far' contains a list of all
5649 annotations returned by previous annotation functions.
5651 An annotation function can return with a different buffer current.
5652 Doing so removes the annotations returned by previous functions, and
5653 resets START and END to `point-min' and `point-max' of the new buffer.
5655 After `write-region' completes, Emacs calls the function stored in
5656 `write-region-post-annotation-function', once for each buffer that was
5657 current when building the annotations (i.e., at least once), with that
5658 buffer current. */);
5659 Vwrite_region_annotate_functions
= Qnil
;
5660 DEFSYM (Qwrite_region_annotate_functions
, "write-region-annotate-functions");
5662 DEFVAR_LISP ("write-region-post-annotation-function",
5663 Vwrite_region_post_annotation_function
,
5664 doc
: /* Function to call after `write-region' completes.
5665 The function is called with no arguments. If one or more of the
5666 annotation functions in `write-region-annotate-functions' changed the
5667 current buffer, the function stored in this variable is called for
5668 each of those additional buffers as well, in addition to the original
5669 buffer. The relevant buffer is current during each function call. */);
5670 Vwrite_region_post_annotation_function
= Qnil
;
5671 staticpro (&Vwrite_region_annotation_buffers
);
5673 DEFVAR_LISP ("write-region-annotations-so-far",
5674 Vwrite_region_annotations_so_far
,
5675 doc
: /* When an annotation function is called, this holds the previous annotations.
5676 These are the annotations made by other annotation functions
5677 that were already called. See also `write-region-annotate-functions'. */);
5678 Vwrite_region_annotations_so_far
= Qnil
;
5680 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers
,
5681 doc
: /* A list of file name handlers that temporarily should not be used.
5682 This applies only to the operation `inhibit-file-name-operation'. */);
5683 Vinhibit_file_name_handlers
= Qnil
;
5685 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation
,
5686 doc
: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5687 Vinhibit_file_name_operation
= Qnil
;
5689 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name
,
5690 doc
: /* File name in which we write a list of all auto save file names.
5691 This variable is initialized automatically from `auto-save-list-file-prefix'
5692 shortly after Emacs reads your `.emacs' file, if you have not yet given it
5693 a non-nil value. */);
5694 Vauto_save_list_file_name
= Qnil
;
5696 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name
,
5697 doc
: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5698 Normally auto-save files are written under other names. */);
5699 Vauto_save_visited_file_name
= Qnil
;
5701 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions
,
5702 doc
: /* If non-nil, auto-save even if a large part of the text is deleted.
5703 If nil, deleting a substantial portion of the text disables auto-save
5704 in the buffer; this is the default behavior, because the auto-save
5705 file is usually more useful if it contains the deleted text. */);
5706 Vauto_save_include_big_deletions
= Qnil
;
5709 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync
,
5710 doc
: /* *Non-nil means don't call fsync in `write-region'.
5711 This variable affects calls to `write-region' as well as save commands.
5712 A non-nil value may result in data loss! */);
5713 write_region_inhibit_fsync
= 0;
5716 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash
,
5717 doc
: /* Specifies whether to use the system's trash can.
5718 When non-nil, certain file deletion commands use the function
5719 `move-file-to-trash' instead of deleting files outright.
5720 This includes interactive calls to `delete-file' and
5721 `delete-directory' and the Dired deletion commands. */);
5722 delete_by_moving_to_trash
= 0;
5723 Qdelete_by_moving_to_trash
= intern_c_string ("delete-by-moving-to-trash");
5725 DEFSYM (Qmove_file_to_trash
, "move-file-to-trash");
5726 DEFSYM (Qcopy_directory
, "copy-directory");
5727 DEFSYM (Qdelete_directory
, "delete-directory");
5729 defsubr (&Sfind_file_name_handler
);
5730 defsubr (&Sfile_name_directory
);
5731 defsubr (&Sfile_name_nondirectory
);
5732 defsubr (&Sunhandled_file_name_directory
);
5733 defsubr (&Sfile_name_as_directory
);
5734 defsubr (&Sdirectory_file_name
);
5735 defsubr (&Smake_temp_name
);
5736 defsubr (&Sexpand_file_name
);
5737 defsubr (&Ssubstitute_in_file_name
);
5738 defsubr (&Scopy_file
);
5739 defsubr (&Smake_directory_internal
);
5740 defsubr (&Sdelete_directory_internal
);
5741 defsubr (&Sdelete_file
);
5742 defsubr (&Srename_file
);
5743 defsubr (&Sadd_name_to_file
);
5744 defsubr (&Smake_symbolic_link
);
5745 defsubr (&Sfile_name_absolute_p
);
5746 defsubr (&Sfile_exists_p
);
5747 defsubr (&Sfile_executable_p
);
5748 defsubr (&Sfile_readable_p
);
5749 defsubr (&Sfile_writable_p
);
5750 defsubr (&Saccess_file
);
5751 defsubr (&Sfile_symlink_p
);
5752 defsubr (&Sfile_directory_p
);
5753 defsubr (&Sfile_accessible_directory_p
);
5754 defsubr (&Sfile_regular_p
);
5755 defsubr (&Sfile_modes
);
5756 defsubr (&Sset_file_modes
);
5757 defsubr (&Sset_file_times
);
5758 defsubr (&Sfile_selinux_context
);
5759 defsubr (&Sset_file_selinux_context
);
5760 defsubr (&Sset_default_file_modes
);
5761 defsubr (&Sdefault_file_modes
);
5762 defsubr (&Sfile_newer_than_file_p
);
5763 defsubr (&Sinsert_file_contents
);
5764 defsubr (&Swrite_region
);
5765 defsubr (&Scar_less_than_car
);
5766 defsubr (&Sverify_visited_file_modtime
);
5767 defsubr (&Sclear_visited_file_modtime
);
5768 defsubr (&Svisited_file_modtime
);
5769 defsubr (&Sset_visited_file_modtime
);
5770 defsubr (&Sdo_auto_save
);
5771 defsubr (&Sset_buffer_auto_saved
);
5772 defsubr (&Sclear_buffer_auto_save_failure
);
5773 defsubr (&Srecent_auto_save_p
);
5775 defsubr (&Snext_read_file_uses_dialog_p
);
5778 defsubr (&Sunix_sync
);