1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2013 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>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
39 #ifdef HAVE_ACL_SET_FILE
46 #include "intervals.h"
47 #include "character.h"
51 #include "blockinput.h"
53 #include "dispextern.h"
60 #endif /* not WINDOWSNT */
64 #include <sys/param.h>
68 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
69 redirector allows the six letters between 'Z' and 'a' as well. */
71 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
74 #define IS_DRIVE(x) c_isalpha (x)
76 /* Need to lower-case the drive letter, or else expanded
77 filenames will sometimes compare unequal, because
78 `expand-file-name' doesn't always down-case the drive letter. */
79 #define DRIVE_LETTER(x) c_tolower (x)
84 #include <allocator.h>
85 #include <careadlinkat.h>
86 #include <stat-time.h>
94 /* True during writing of auto-save files. */
95 static bool auto_saving
;
97 /* Nonzero umask during creation of auto-save directories. */
98 static mode_t auto_saving_dir_umask
;
100 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
101 a new file with the same mode as the original. */
102 static mode_t auto_save_mode_bits
;
104 /* Set by auto_save_1 if an error occurred during the last auto-save. */
105 static bool auto_save_error_occurred
;
107 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
108 number of a file system where time stamps were observed to to work. */
109 static bool valid_timestamp_file_system
;
110 static dev_t timestamp_file_system
;
112 /* The symbol bound to coding-system-for-read when
113 insert-file-contents is called for recovering a file. This is not
114 an actual coding system name, but just an indicator to tell
115 insert-file-contents to use `emacs-mule' with a special flag for
116 auto saving and recovering a file. */
117 static Lisp_Object Qauto_save_coding
;
119 /* Property name of a file name handler,
120 which gives a list of operations it handles.. */
121 static Lisp_Object Qoperations
;
123 /* Lisp functions for translating file formats. */
124 static Lisp_Object Qformat_decode
, Qformat_annotate_function
;
126 /* Lisp function for setting buffer-file-coding-system and the
127 multibyteness of the current buffer after inserting a file. */
128 static Lisp_Object Qafter_insert_file_set_coding
;
130 static Lisp_Object Qwrite_region_annotate_functions
;
131 /* Each time an annotation function changes the buffer, the new buffer
133 static Lisp_Object Vwrite_region_annotation_buffers
;
135 static Lisp_Object Qdelete_by_moving_to_trash
;
137 /* Lisp function for moving files to trash. */
138 static Lisp_Object Qmove_file_to_trash
;
140 /* Lisp function for recursively copying directories. */
141 static Lisp_Object Qcopy_directory
;
143 /* Lisp function for recursively deleting directories. */
144 static Lisp_Object Qdelete_directory
;
149 Lisp_Object Qfile_error
, Qfile_notify_error
;
150 static Lisp_Object Qfile_already_exists
, Qfile_date_error
;
151 static Lisp_Object Qexcl
;
152 Lisp_Object Qfile_name_history
;
154 static Lisp_Object Qcar_less_than_car
;
156 static bool a_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
157 Lisp_Object
*, struct coding_system
*);
158 static bool e_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
159 struct coding_system
*);
162 /* Signal a file-access failure. STRING describes the failure,
163 NAME the file involved, and ERRORNO the errno value.
165 If NAME is neither null nor a pair, package it up as a singleton
166 list before reporting it; this saves report_file_errno's caller the
167 trouble of preserving errno before calling list1. */
170 report_file_errno (char const *string
, Lisp_Object name
, int errorno
)
172 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
173 Lisp_Object errstring
;
176 synchronize_system_messages_locale ();
177 str
= strerror (errorno
);
178 errstring
= code_convert_string_norecord (build_unibyte_string (str
),
179 Vlocale_coding_system
, 0);
185 xsignal (Qfile_already_exists
, Fcons (errstring
, data
));
188 /* System error messages are capitalized. Downcase the initial
189 unless it is followed by a slash. (The slash case caters to
190 error messages that begin with "I/O" or, in German, "E/A".) */
191 if (STRING_MULTIBYTE (errstring
)
192 && ! EQ (Faref (errstring
, make_number (1)), make_number ('/')))
196 str
= SSDATA (errstring
);
197 c
= STRING_CHAR ((unsigned char *) str
);
198 Faset (errstring
, make_number (0), make_number (downcase (c
)));
201 xsignal (Qfile_error
,
202 Fcons (build_string (string
), Fcons (errstring
, data
)));
206 /* Signal a file-access failure that set errno. STRING describes the
207 failure, NAME the file involved. */
210 report_file_error (char const *string
, Lisp_Object name
)
212 report_file_errno (string
, name
, errno
);
216 close_file_unwind (int fd
)
222 /* Restore point, having saved it as a marker. */
225 restore_point_unwind (Lisp_Object location
)
227 Fgoto_char (location
);
228 Fset_marker (location
, Qnil
, Qnil
);
232 static Lisp_Object Qexpand_file_name
;
233 static Lisp_Object Qsubstitute_in_file_name
;
234 static Lisp_Object Qdirectory_file_name
;
235 static Lisp_Object Qfile_name_directory
;
236 static Lisp_Object Qfile_name_nondirectory
;
237 static Lisp_Object Qunhandled_file_name_directory
;
238 static Lisp_Object Qfile_name_as_directory
;
239 static Lisp_Object Qcopy_file
;
240 static Lisp_Object Qmake_directory_internal
;
241 static Lisp_Object Qmake_directory
;
242 static Lisp_Object Qdelete_directory_internal
;
243 Lisp_Object Qdelete_file
;
244 static Lisp_Object Qrename_file
;
245 static Lisp_Object Qadd_name_to_file
;
246 static Lisp_Object Qmake_symbolic_link
;
247 Lisp_Object Qfile_exists_p
;
248 static Lisp_Object Qfile_executable_p
;
249 static Lisp_Object Qfile_readable_p
;
250 static Lisp_Object Qfile_writable_p
;
251 static Lisp_Object Qfile_symlink_p
;
252 static Lisp_Object Qaccess_file
;
253 Lisp_Object Qfile_directory_p
;
254 static Lisp_Object Qfile_regular_p
;
255 static Lisp_Object Qfile_accessible_directory_p
;
256 static Lisp_Object Qfile_modes
;
257 static Lisp_Object Qset_file_modes
;
258 static Lisp_Object Qset_file_times
;
259 static Lisp_Object Qfile_selinux_context
;
260 static Lisp_Object Qset_file_selinux_context
;
261 static Lisp_Object Qfile_acl
;
262 static Lisp_Object Qset_file_acl
;
263 static Lisp_Object Qfile_newer_than_file_p
;
264 Lisp_Object Qinsert_file_contents
;
265 static Lisp_Object Qchoose_write_coding_system
;
266 Lisp_Object Qwrite_region
;
267 static Lisp_Object Qverify_visited_file_modtime
;
268 static Lisp_Object Qset_visited_file_modtime
;
270 DEFUN ("find-file-name-handler", Ffind_file_name_handler
,
271 Sfind_file_name_handler
, 2, 2, 0,
272 doc
: /* Return FILENAME's handler function for OPERATION, if it has one.
273 Otherwise, return nil.
274 A file name is handled if one of the regular expressions in
275 `file-name-handler-alist' matches it.
277 If OPERATION equals `inhibit-file-name-operation', then we ignore
278 any handlers that are members of `inhibit-file-name-handlers',
279 but we still do run any other handlers. This lets handlers
280 use the standard functions without calling themselves recursively. */)
281 (Lisp_Object filename
, Lisp_Object operation
)
283 /* This function must not munge the match data. */
284 Lisp_Object chain
, inhibited_handlers
, result
;
288 CHECK_STRING (filename
);
290 if (EQ (operation
, Vinhibit_file_name_operation
))
291 inhibited_handlers
= Vinhibit_file_name_handlers
;
293 inhibited_handlers
= Qnil
;
295 for (chain
= Vfile_name_handler_alist
; CONSP (chain
);
296 chain
= XCDR (chain
))
302 Lisp_Object string
= XCAR (elt
);
304 Lisp_Object handler
= XCDR (elt
);
305 Lisp_Object operations
= Qnil
;
307 if (SYMBOLP (handler
))
308 operations
= Fget (handler
, Qoperations
);
311 && (match_pos
= fast_string_match (string
, filename
)) > pos
312 && (NILP (operations
) || ! NILP (Fmemq (operation
, operations
))))
316 handler
= XCDR (elt
);
317 tem
= Fmemq (handler
, inhibited_handlers
);
331 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
333 doc
: /* Return the directory component in file name FILENAME.
334 Return nil if FILENAME does not include a directory.
335 Otherwise return a directory name.
336 Given a Unix syntax file name, returns a string ending in slash. */)
337 (Lisp_Object filename
)
340 register const char *beg
;
345 register const char *p
;
348 CHECK_STRING (filename
);
350 /* If the file name has special constructs in it,
351 call the corresponding file handler. */
352 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
355 Lisp_Object handled_name
= call2 (handler
, Qfile_name_directory
,
357 return STRINGP (handled_name
) ? handled_name
: Qnil
;
361 beg
= alloca (SBYTES (filename
) + 1);
362 memcpy (beg
, SSDATA (filename
), SBYTES (filename
) + 1);
364 beg
= SSDATA (filename
);
366 p
= beg
+ SBYTES (filename
);
368 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
370 /* only recognize drive specifier at the beginning */
372 /* handle the "/:d:foo" and "/:foo" cases correctly */
373 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
374 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
381 /* Expansion of "c:" to drive and default directory. */
384 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
385 char *res
= alloca (MAXPATHLEN
+ 1);
388 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
390 memcpy (res
, beg
, 2);
395 if (getdefdir (c_toupper (*beg
) - 'A' + 1, r
))
397 size_t l
= strlen (res
);
399 if (l
> 3 || !IS_DIRECTORY_SEP (res
[l
- 1]))
402 p
= beg
+ strlen (beg
);
403 dostounix_filename (beg
, 0);
404 tem_fn
= make_specified_string (beg
, -1, p
- beg
,
405 STRING_MULTIBYTE (filename
));
408 tem_fn
= make_specified_string (beg
- 2, -1, p
- beg
+ 2,
409 STRING_MULTIBYTE (filename
));
411 else if (STRING_MULTIBYTE (filename
))
413 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 1);
414 dostounix_filename (SSDATA (tem_fn
), 1);
416 if (!NILP (Vw32_downcase_file_names
))
417 tem_fn
= Fdowncase (tem_fn
);
422 dostounix_filename (beg
, 0);
423 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 0);
427 return make_specified_string (beg
, -1, p
- beg
, STRING_MULTIBYTE (filename
));
431 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
432 Sfile_name_nondirectory
, 1, 1, 0,
433 doc
: /* Return file name FILENAME sans its directory.
434 For example, in a Unix-syntax file name,
435 this is everything after the last slash,
436 or the entire name if it contains no slash. */)
437 (Lisp_Object filename
)
439 register const char *beg
, *p
, *end
;
442 CHECK_STRING (filename
);
444 /* If the file name has special constructs in it,
445 call the corresponding file handler. */
446 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
449 Lisp_Object handled_name
= call2 (handler
, Qfile_name_nondirectory
,
451 if (STRINGP (handled_name
))
453 error ("Invalid handler in `file-name-handler-alist'");
456 beg
= SSDATA (filename
);
457 end
= p
= beg
+ SBYTES (filename
);
459 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
461 /* only recognize drive specifier at beginning */
463 /* handle the "/:d:foo" case correctly */
464 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
469 return make_specified_string (p
, -1, end
- p
, STRING_MULTIBYTE (filename
));
472 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
473 Sunhandled_file_name_directory
, 1, 1, 0,
474 doc
: /* Return a directly usable directory name somehow associated with FILENAME.
475 A `directly usable' directory name is one that may be used without the
476 intervention of any file handler.
477 If FILENAME is a directly usable file itself, return
478 \(file-name-directory FILENAME).
479 If FILENAME refers to a file which is not accessible from a local process,
480 then this should return nil.
481 The `call-process' and `start-process' functions use this function to
482 get a current directory to run processes in. */)
483 (Lisp_Object filename
)
487 /* If the file name has special constructs in it,
488 call the corresponding file handler. */
489 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
492 Lisp_Object handled_name
= call2 (handler
, Qunhandled_file_name_directory
,
494 return STRINGP (handled_name
) ? handled_name
: Qnil
;
497 return Ffile_name_directory (filename
);
500 /* Convert from file name SRC of length SRCLEN to directory name in
501 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
502 string. On UNIX, just make sure there is a terminating /. Return
503 the length of DST in bytes. */
506 file_name_as_directory (char *dst
, const char *src
, ptrdiff_t srclen
,
519 if (!IS_DIRECTORY_SEP (dst
[srclen
- 1]))
521 dst
[srclen
] = DIRECTORY_SEP
;
522 dst
[srclen
+ 1] = '\0';
526 dostounix_filename (dst
, multibyte
);
531 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
532 Sfile_name_as_directory
, 1, 1, 0,
533 doc
: /* Return a string representing the file name FILE interpreted as a directory.
534 This operation exists because a directory is also a file, but its name as
535 a directory is different from its name as a file.
536 The result can be used as the value of `default-directory'
537 or passed as second argument to `expand-file-name'.
538 For a Unix-syntax file name, just appends a slash. */)
549 /* If the file name has special constructs in it,
550 call the corresponding file handler. */
551 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
554 Lisp_Object handled_name
= call2 (handler
, Qfile_name_as_directory
,
556 if (STRINGP (handled_name
))
558 error ("Invalid handler in `file-name-handler-alist'");
562 if (!NILP (Vw32_downcase_file_names
))
563 file
= Fdowncase (file
);
565 buf
= alloca (SBYTES (file
) + 10);
566 length
= file_name_as_directory (buf
, SSDATA (file
), SBYTES (file
),
567 STRING_MULTIBYTE (file
));
568 return make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (file
));
571 /* Convert from directory name SRC of length SRCLEN to file name in
572 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
573 string. On UNIX, just make sure there isn't a terminating /.
574 Return the length of DST in bytes. */
577 directory_file_name (char *dst
, char *src
, ptrdiff_t srclen
, bool multibyte
)
579 /* Process as Unix format: just remove any final slash.
580 But leave "/" unchanged; do not change it to "". */
583 && IS_DIRECTORY_SEP (dst
[srclen
- 1])
585 && !IS_ANY_SEP (dst
[srclen
- 2])
593 dostounix_filename (dst
, multibyte
);
598 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
600 doc
: /* Returns the file name of the directory named DIRECTORY.
601 This is the name of the file that holds the data for the directory DIRECTORY.
602 This operation exists because a directory is also a file, but its name as
603 a directory is different from its name as a file.
604 In Unix-syntax, this function just removes the final slash. */)
605 (Lisp_Object directory
)
611 CHECK_STRING (directory
);
613 if (NILP (directory
))
616 /* If the file name has special constructs in it,
617 call the corresponding file handler. */
618 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
621 Lisp_Object handled_name
= call2 (handler
, Qdirectory_file_name
,
623 if (STRINGP (handled_name
))
625 error ("Invalid handler in `file-name-handler-alist'");
629 if (!NILP (Vw32_downcase_file_names
))
630 directory
= Fdowncase (directory
);
632 buf
= alloca (SBYTES (directory
) + 20);
633 length
= directory_file_name (buf
, SSDATA (directory
), SBYTES (directory
),
634 STRING_MULTIBYTE (directory
));
635 return make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (directory
));
638 static const char make_temp_name_tbl
[64] =
640 'A','B','C','D','E','F','G','H',
641 'I','J','K','L','M','N','O','P',
642 'Q','R','S','T','U','V','W','X',
643 'Y','Z','a','b','c','d','e','f',
644 'g','h','i','j','k','l','m','n',
645 'o','p','q','r','s','t','u','v',
646 'w','x','y','z','0','1','2','3',
647 '4','5','6','7','8','9','-','_'
650 static unsigned make_temp_name_count
, make_temp_name_count_initialized_p
;
652 /* Value is a temporary file name starting with PREFIX, a string.
654 The Emacs process number forms part of the result, so there is
655 no danger of generating a name being used by another process.
656 In addition, this function makes an attempt to choose a name
657 which has no existing file. To make this work, PREFIX should be
658 an absolute file name.
660 BASE64_P means add the pid as 3 characters in base64
661 encoding. In this case, 6 characters will be added to PREFIX to
662 form the file name. Otherwise, if Emacs is running on a system
663 with long file names, add the pid as a decimal number.
665 This function signals an error if no unique file name could be
669 make_temp_name (Lisp_Object prefix
, bool base64_p
)
675 char pidbuf
[INT_BUFSIZE_BOUND (printmax_t
)];
678 CHECK_STRING (prefix
);
680 /* VAL is created by adding 6 characters to PREFIX. The first
681 three are the PID of this process, in base 64, and the second
682 three are incremented if the file already exists. This ensures
683 262144 unique file names per PID per PREFIX. */
689 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
690 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
691 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
696 #ifdef HAVE_LONG_FILE_NAMES
697 pidlen
= sprintf (pidbuf
, "%"pMd
, pid
);
699 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
700 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
701 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
706 len
= SBYTES (prefix
); clen
= SCHARS (prefix
);
707 val
= make_uninit_multibyte_string (clen
+ 3 + pidlen
, len
+ 3 + pidlen
);
708 if (!STRING_MULTIBYTE (prefix
))
709 STRING_SET_UNIBYTE (val
);
711 memcpy (data
, SSDATA (prefix
), len
);
714 memcpy (p
, pidbuf
, pidlen
);
717 /* Here we try to minimize useless stat'ing when this function is
718 invoked many times successively with the same PREFIX. We achieve
719 this by initializing count to a random value, and incrementing it
722 We don't want make-temp-name to be called while dumping,
723 because then make_temp_name_count_initialized_p would get set
724 and then make_temp_name_count would not be set when Emacs starts. */
726 if (!make_temp_name_count_initialized_p
)
728 make_temp_name_count
= time (NULL
);
729 make_temp_name_count_initialized_p
= 1;
734 unsigned num
= make_temp_name_count
;
736 p
[0] = make_temp_name_tbl
[num
& 63], num
>>= 6;
737 p
[1] = make_temp_name_tbl
[num
& 63], num
>>= 6;
738 p
[2] = make_temp_name_tbl
[num
& 63], num
>>= 6;
740 /* Poor man's congruential RN generator. Replace with
741 ++make_temp_name_count for debugging. */
742 make_temp_name_count
+= 25229;
743 make_temp_name_count
%= 225307;
745 if (!check_existing (data
))
747 /* We want to return only if errno is ENOENT. */
751 /* The error here is dubious, but there is little else we
752 can do. The alternatives are to return nil, which is
753 as bad as (and in many cases worse than) throwing the
754 error, or to ignore the error, which will likely result
755 in looping through 225307 stat's, which is not only
756 dog-slow, but also useless since eventually nil would
757 have to be returned anyway. */
758 report_file_error ("Cannot create temporary name for prefix",
766 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
767 doc
: /* Generate temporary file name (string) starting with PREFIX (a string).
768 The Emacs process number forms part of the result,
769 so there is no danger of generating a name being used by another process.
771 In addition, this function makes an attempt to choose a name
772 which has no existing file. To make this work,
773 PREFIX should be an absolute file name.
775 There is a race condition between calling `make-temp-name' and creating the
776 file which opens all kinds of security holes. For that reason, you should
777 probably use `make-temp-file' instead, except in three circumstances:
779 * If you are creating the file in the user's home directory.
780 * If you are creating a directory rather than an ordinary file.
781 * If you are taking special precautions as `make-temp-file' does. */)
784 return make_temp_name (prefix
, 0);
789 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
790 doc
: /* Convert filename NAME to absolute, and canonicalize it.
791 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
792 \(does not start with slash or tilde); both the directory name and
793 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
794 missing, the current buffer's value of `default-directory' is used.
795 NAME should be a string that is a valid file name for the underlying
797 File name components that are `.' are removed, and
798 so are file name components followed by `..', along with the `..' itself;
799 note that these simplifications are done without checking the resulting
800 file names in the file system.
801 Multiple consecutive slashes are collapsed into a single slash,
802 except at the beginning of the file name when they are significant (e.g.,
803 UNC file names on MS-Windows.)
804 An initial `~/' expands to your home directory.
805 An initial `~USER/' expands to USER's home directory.
806 See also the function `substitute-in-file-name'.
808 For technical reasons, this function can return correct but
809 non-intuitive results for the root directory; for instance,
810 \(expand-file-name ".." "/") returns "/..". For this reason, use
811 \(directory-file-name (file-name-directory dirname)) to traverse a
812 filesystem tree, not (expand-file-name ".." dirname). */)
813 (Lisp_Object name
, Lisp_Object default_directory
)
815 /* These point to SDATA and need to be careful with string-relocation
816 during GC (via DECODE_FILE). */
819 /* This should only point to alloca'd data. */
826 bool collapse_newdir
= 1;
830 Lisp_Object handler
, result
, handled_name
;
836 /* If the file name has special constructs in it,
837 call the corresponding file handler. */
838 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
841 handled_name
= call3 (handler
, Qexpand_file_name
,
842 name
, default_directory
);
843 if (STRINGP (handled_name
))
845 error ("Invalid handler in `file-name-handler-alist'");
849 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
850 if (NILP (default_directory
))
851 default_directory
= BVAR (current_buffer
, directory
);
852 if (! STRINGP (default_directory
))
855 /* "/" is not considered a root directory on DOS_NT, so using "/"
856 here causes an infinite recursion in, e.g., the following:
858 (let (default-directory)
859 (expand-file-name "a"))
861 To avoid this, we set default_directory to the root of the
863 default_directory
= build_string (emacs_root_dir ());
865 default_directory
= build_string ("/");
869 if (!NILP (default_directory
))
871 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
874 handled_name
= call3 (handler
, Qexpand_file_name
,
875 name
, default_directory
);
876 if (STRINGP (handled_name
))
878 error ("Invalid handler in `file-name-handler-alist'");
883 char *o
= SSDATA (default_directory
);
885 /* Make sure DEFAULT_DIRECTORY is properly expanded.
886 It would be better to do this down below where we actually use
887 default_directory. Unfortunately, calling Fexpand_file_name recursively
888 could invoke GC, and the strings might be relocated. This would
889 be annoying because we have pointers into strings lying around
890 that would need adjusting, and people would add new pointers to
891 the code and forget to adjust them, resulting in intermittent bugs.
892 Putting this call here avoids all that crud.
894 The EQ test avoids infinite recursion. */
895 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
896 /* Save time in some common cases - as long as default_directory
897 is not relative, it can be canonicalized with name below (if it
898 is needed at all) without requiring it to be expanded now. */
900 /* Detect MSDOS file names with drive specifiers. */
901 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1])
902 && IS_DIRECTORY_SEP (o
[2]))
904 /* Detect Windows file names in UNC format. */
905 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
907 #else /* not DOS_NT */
908 /* Detect Unix absolute file names (/... alone is not absolute on
910 && ! (IS_DIRECTORY_SEP (o
[0]))
911 #endif /* not DOS_NT */
917 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
921 multibyte
= STRING_MULTIBYTE (name
);
922 if (multibyte
!= STRING_MULTIBYTE (default_directory
))
925 default_directory
= string_to_multibyte (default_directory
);
928 name
= string_to_multibyte (name
);
934 if (!NILP (Vw32_downcase_file_names
))
935 default_directory
= Fdowncase (default_directory
);
938 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
939 nm
= alloca (SBYTES (name
) + 1);
940 memcpy (nm
, SSDATA (name
), SBYTES (name
) + 1);
943 /* Note if special escape prefix is present, but remove for now. */
944 if (nm
[0] == '/' && nm
[1] == ':')
950 /* Find and remove drive specifier if present; this makes nm absolute
951 even if the rest of the name appears to be relative. Only look for
952 drive specifier at the beginning. */
953 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
955 drive
= (unsigned char) nm
[0];
960 /* If we see "c://somedir", we want to strip the first slash after the
961 colon when stripping the drive letter. Otherwise, this expands to
963 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
966 /* Discard any previous drive specifier if nm is now in UNC format. */
967 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
971 #endif /* WINDOWSNT */
974 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
975 none are found, we can probably return right away. We will avoid
976 allocating a new string if name is already fully expanded. */
978 IS_DIRECTORY_SEP (nm
[0])
980 && drive
&& !is_escaped
983 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
987 /* If it turns out that the filename we want to return is just a
988 suffix of FILENAME, we don't need to go through and edit
989 things; we just need to construct a new string using data
990 starting at the middle of FILENAME. If we set LOSE, that
991 means we've discovered that we can't do that cool trick. */
997 /* Since we know the name is absolute, we can assume that each
998 element starts with a "/". */
1000 /* "." and ".." are hairy. */
1001 if (IS_DIRECTORY_SEP (p
[0])
1003 && (IS_DIRECTORY_SEP (p
[2])
1005 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
1008 /* We want to replace multiple `/' in a row with a single
1011 && IS_DIRECTORY_SEP (p
[0])
1012 && IS_DIRECTORY_SEP (p
[1]))
1019 /* Make sure directories are all separated with /, but
1020 avoid allocation of a new string when not required. */
1021 dostounix_filename (nm
, multibyte
);
1023 if (IS_DIRECTORY_SEP (nm
[1]))
1025 if (strcmp (nm
, SSDATA (name
)) != 0)
1026 name
= make_specified_string (nm
, -1, strlen (nm
), multibyte
);
1030 /* Drive must be set, so this is okay. */
1031 if (strcmp (nm
- 2, SSDATA (name
)) != 0)
1035 name
= make_specified_string (nm
, -1, p
- nm
, multibyte
);
1036 temp
[0] = DRIVE_LETTER (drive
);
1037 name
= concat2 (build_string (temp
), name
);
1040 if (!NILP (Vw32_downcase_file_names
))
1041 name
= Fdowncase (name
);
1044 #else /* not DOS_NT */
1045 if (strcmp (nm
, SSDATA (name
)) == 0)
1047 return make_specified_string (nm
, -1, strlen (nm
), multibyte
);
1048 #endif /* not DOS_NT */
1052 /* At this point, nm might or might not be an absolute file name. We
1053 need to expand ~ or ~user if present, otherwise prefix nm with
1054 default_directory if nm is not absolute, and finally collapse /./
1055 and /foo/../ sequences.
1057 We set newdir to be the appropriate prefix if one is needed:
1058 - the relevant user directory if nm starts with ~ or ~user
1059 - the specified drive's working dir (DOS/NT only) if nm does not
1061 - the value of default_directory.
1063 Note that these prefixes are not guaranteed to be absolute (except
1064 for the working dir of a drive). Therefore, to ensure we always
1065 return an absolute name, if the final prefix is not absolute we
1066 append it to the current working directory. */
1070 if (nm
[0] == '~') /* prefix ~ */
1072 if (IS_DIRECTORY_SEP (nm
[1])
1073 || nm
[1] == 0) /* ~ by itself */
1077 if (!(newdir
= egetenv ("HOME")))
1080 /* `egetenv' may return a unibyte string, which will bite us since
1081 we expect the directory to be multibyte. */
1082 tem
= build_string (newdir
);
1083 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1085 hdir
= DECODE_FILE (tem
);
1086 newdir
= SSDATA (hdir
);
1089 collapse_newdir
= 0;
1092 else /* ~user/filename */
1095 for (p
= nm
; *p
&& (!IS_DIRECTORY_SEP (*p
)); p
++);
1096 o
= alloca (p
- nm
+ 1);
1097 memcpy (o
, nm
, p
- nm
);
1101 pw
= getpwnam (o
+ 1);
1107 newdir
= pw
->pw_dir
;
1108 /* `getpwnam' may return a unibyte string, which will
1109 bite us since we expect the directory to be
1111 tem
= build_string (newdir
);
1112 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1114 hdir
= DECODE_FILE (tem
);
1115 newdir
= SSDATA (hdir
);
1119 collapse_newdir
= 0;
1123 /* If we don't find a user of that name, leave the name
1124 unchanged; don't move nm forward to p. */
1129 /* On DOS and Windows, nm is absolute if a drive name was specified;
1130 use the drive's current directory as the prefix if needed. */
1131 if (!newdir
&& drive
)
1133 /* Get default directory if needed to make nm absolute. */
1135 if (!IS_DIRECTORY_SEP (nm
[0]))
1137 adir
= alloca (MAXPATHLEN
+ 1);
1138 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1142 Lisp_Object tem
= build_string (adir
);
1144 tem
= DECODE_FILE (tem
);
1145 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1150 /* Either nm starts with /, or drive isn't mounted. */
1152 adir
[0] = DRIVE_LETTER (drive
);
1161 /* Finally, if no prefix has been specified and nm is not absolute,
1162 then it must be expanded relative to default_directory. */
1166 /* /... alone is not absolute on DOS and Windows. */
1167 && !IS_DIRECTORY_SEP (nm
[0])
1170 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
1174 newdir
= SSDATA (default_directory
);
1176 /* Note if special escape prefix is present, but remove for now. */
1177 if (newdir
[0] == '/' && newdir
[1] == ':')
1188 /* First ensure newdir is an absolute name. */
1190 /* Detect MSDOS file names with drive specifiers. */
1191 ! (IS_DRIVE (newdir
[0])
1192 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1194 /* Detect Windows file names in UNC format. */
1195 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1199 /* Effectively, let newdir be (expand-file-name newdir cwd).
1200 Because of the admonition against calling expand-file-name
1201 when we have pointers into lisp strings, we accomplish this
1202 indirectly by prepending newdir to nm if necessary, and using
1203 cwd (or the wd of newdir's drive) as the new newdir. */
1206 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1208 drive
= (unsigned char) newdir
[0];
1211 if (!IS_DIRECTORY_SEP (nm
[0]))
1213 ptrdiff_t newlen
= strlen (newdir
);
1214 char *tmp
= alloca (newlen
+ strlen (nm
) + 2);
1215 file_name_as_directory (tmp
, newdir
, newlen
, multibyte
);
1219 adir
= alloca (MAXPATHLEN
+ 1);
1222 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1226 getcwd (adir
, MAXPATHLEN
+ 1);
1229 Lisp_Object tem
= build_string (adir
);
1231 tem
= DECODE_FILE (tem
);
1232 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1237 /* Strip off drive name from prefix, if present. */
1238 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1244 /* Keep only a prefix from newdir if nm starts with slash
1245 (//server/share for UNC, nothing otherwise). */
1246 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1249 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1]))
1251 char *adir
= strcpy (alloca (strlen (newdir
) + 1), newdir
);
1253 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1255 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1268 /* Get rid of any slash at the end of newdir, unless newdir is
1269 just / or // (an incomplete UNC name). */
1270 length
= strlen (newdir
);
1272 if (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1274 && !(length
== 2 && IS_DIRECTORY_SEP (newdir
[0]))
1278 char *temp
= alloca (length
);
1279 memcpy (temp
, newdir
, length
- 1);
1280 temp
[length
- 1] = 0;
1291 /* Now concatenate the directory and name to new space in the stack frame. */
1292 tlen
+= strlen (nm
) + 1;
1294 /* Reserve space for drive specifier and escape prefix, since either
1295 or both may need to be inserted. (The Microsoft x86 compiler
1296 produces incorrect code if the following two lines are combined.) */
1297 target
= alloca (tlen
+ 4);
1299 #else /* not DOS_NT */
1300 target
= alloca (tlen
);
1301 #endif /* not DOS_NT */
1306 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1309 /* If newdir is effectively "C:/", then the drive letter will have
1310 been stripped and newdir will be "/". Concatenating with an
1311 absolute directory in nm produces "//", which will then be
1312 incorrectly treated as a network share. Ignore newdir in
1313 this case (keeping the drive letter). */
1314 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1315 && newdir
[1] == '\0'))
1317 strcpy (target
, newdir
);
1320 file_name_as_directory (target
, newdir
, length
, multibyte
);
1323 strcat (target
, nm
);
1325 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1333 if (!IS_DIRECTORY_SEP (*p
))
1337 else if (p
[1] == '.'
1338 && (IS_DIRECTORY_SEP (p
[2])
1341 /* If "/." is the entire filename, keep the "/". Otherwise,
1342 just delete the whole "/.". */
1343 if (o
== target
&& p
[2] == '\0')
1347 else if (p
[1] == '.' && p
[2] == '.'
1348 /* `/../' is the "superroot" on certain file systems.
1349 Turned off on DOS_NT systems because they have no
1350 "superroot" and because this causes us to produce
1351 file names like "d:/../foo" which fail file-related
1352 functions of the underlying OS. (To reproduce, try a
1353 long series of "../../" in default_directory, longer
1354 than the number of levels from the root.) */
1358 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1363 while (o
!= target
&& (--o
, !IS_DIRECTORY_SEP (*o
)))
1366 /* Don't go below server level in UNC filenames. */
1367 if (o
== target
+ 1 && IS_DIRECTORY_SEP (*o
)
1368 && IS_DIRECTORY_SEP (*target
))
1372 /* Keep initial / only if this is the whole name. */
1373 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1377 else if (p
> target
&& IS_DIRECTORY_SEP (p
[1]))
1378 /* Collapse multiple `/' in a row. */
1387 /* At last, set drive name. */
1389 /* Except for network file name. */
1390 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1391 #endif /* WINDOWSNT */
1393 if (!drive
) emacs_abort ();
1395 target
[0] = DRIVE_LETTER (drive
);
1398 /* Reinsert the escape prefix if required. */
1405 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1406 dostounix_filename (SSDATA (result
), multibyte
);
1408 if (!NILP (Vw32_downcase_file_names
))
1409 result
= Fdowncase (result
);
1412 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1413 #endif /* !DOS_NT */
1416 /* Again look to see if the file name has special constructs in it
1417 and perhaps call the corresponding file handler. This is needed
1418 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1419 the ".." component gives us "/user@host:/bar/../baz" which needs
1420 to be expanded again. */
1421 handler
= Ffind_file_name_handler (result
, Qexpand_file_name
);
1422 if (!NILP (handler
))
1424 handled_name
= call3 (handler
, Qexpand_file_name
,
1425 result
, default_directory
);
1426 if (STRINGP (handled_name
))
1427 return handled_name
;
1428 error ("Invalid handler in `file-name-handler-alist'");
1435 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1436 This is the old version of expand-file-name, before it was thoroughly
1437 rewritten for Emacs 10.31. We leave this version here commented-out,
1438 because the code is very complex and likely to have subtle bugs. If
1439 bugs _are_ found, it might be of interest to look at the old code and
1440 see what did it do in the relevant situation.
1442 Don't remove this code: it's true that it will be accessible
1443 from the repository, but a few years from deletion, people will
1444 forget it is there. */
1446 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1447 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1448 "Convert FILENAME to absolute, and canonicalize it.\n\
1449 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1450 \(does not start with slash); if DEFAULT is nil or missing,\n\
1451 the current buffer's value of default-directory is used.\n\
1452 Filenames containing `.' or `..' as components are simplified;\n\
1453 initial `~/' expands to your home directory.\n\
1454 See also the function `substitute-in-file-name'.")
1456 Lisp_Object name
, defalt
;
1460 register unsigned char *newdir
, *p
, *o
;
1462 unsigned char *target
;
1465 CHECK_STRING (name
);
1468 /* If nm is absolute, flush ...// and detect /./ and /../.
1469 If no /./ or /../ we can return right away. */
1476 if (p
[0] == '/' && p
[1] == '/')
1478 if (p
[0] == '/' && p
[1] == '~')
1479 nm
= p
+ 1, lose
= 1;
1480 if (p
[0] == '/' && p
[1] == '.'
1481 && (p
[2] == '/' || p
[2] == 0
1482 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1488 if (nm
== SDATA (name
))
1490 return build_string (nm
);
1494 /* Now determine directory to start with and put it in NEWDIR. */
1498 if (nm
[0] == '~') /* prefix ~ */
1499 if (nm
[1] == '/' || nm
[1] == 0)/* ~/filename */
1501 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1502 newdir
= (unsigned char *) "";
1505 else /* ~user/filename */
1507 /* Get past ~ to user. */
1508 unsigned char *user
= nm
+ 1;
1509 /* Find end of name. */
1510 unsigned char *ptr
= (unsigned char *) strchr (user
, '/');
1511 ptrdiff_t len
= ptr
? ptr
- user
: strlen (user
);
1512 /* Copy the user name into temp storage. */
1513 o
= alloca (len
+ 1);
1514 memcpy (o
, user
, len
);
1517 /* Look up the user name. */
1519 pw
= (struct passwd
*) getpwnam (o
+ 1);
1522 error ("\"%s\" isn't a registered user", o
+ 1);
1524 newdir
= (unsigned char *) pw
->pw_dir
;
1526 /* Discard the user name from NM. */
1530 if (nm
[0] != '/' && !newdir
)
1533 defalt
= current_buffer
->directory
;
1534 CHECK_STRING (defalt
);
1535 newdir
= SDATA (defalt
);
1538 /* Now concatenate the directory and name to new space in the stack frame. */
1540 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1541 target
= alloca (tlen
);
1546 if (nm
[0] == 0 || nm
[0] == '/')
1547 strcpy (target
, newdir
);
1549 file_name_as_directory (target
, newdir
);
1552 strcat (target
, nm
);
1554 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1565 else if (!strncmp (p
, "//", 2)
1571 else if (p
[0] == '/' && p
[1] == '.'
1572 && (p
[2] == '/' || p
[2] == 0))
1574 else if (!strncmp (p
, "/..", 3)
1575 /* `/../' is the "superroot" on certain file systems. */
1577 && (p
[3] == '/' || p
[3] == 0))
1579 while (o
!= target
&& *--o
!= '/')
1581 if (o
== target
&& *o
== '/')
1591 return make_string (target
, o
- target
);
1595 /* If /~ or // appears, discard everything through first slash. */
1597 file_name_absolute_p (const char *filename
)
1600 (IS_DIRECTORY_SEP (*filename
) || *filename
== '~'
1602 || (IS_DRIVE (*filename
) && IS_DEVICE_SEP (filename
[1])
1603 && IS_DIRECTORY_SEP (filename
[2]))
1609 search_embedded_absfilename (char *nm
, char *endp
)
1613 for (p
= nm
+ 1; p
< endp
; p
++)
1615 if (IS_DIRECTORY_SEP (p
[-1])
1616 && file_name_absolute_p (p
)
1617 #if defined (WINDOWSNT) || defined (CYGWIN)
1618 /* // at start of file name is meaningful in Apollo,
1619 WindowsNT and Cygwin systems. */
1620 && !(IS_DIRECTORY_SEP (p
[0]) && p
- 1 == nm
)
1621 #endif /* not (WINDOWSNT || CYGWIN) */
1624 for (s
= p
; *s
&& !IS_DIRECTORY_SEP (*s
); s
++);
1625 if (p
[0] == '~' && s
> p
+ 1) /* We've got "/~something/". */
1627 char *o
= alloca (s
- p
+ 1);
1629 memcpy (o
, p
, s
- p
);
1632 /* If we have ~user and `user' exists, discard
1633 everything up to ~. But if `user' does not exist, leave
1634 ~user alone, it might be a literal file name. */
1636 pw
= getpwnam (o
+ 1);
1648 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
1649 Ssubstitute_in_file_name
, 1, 1, 0,
1650 doc
: /* Substitute environment variables referred to in FILENAME.
1651 `$FOO' where FOO is an environment variable name means to substitute
1652 the value of that variable. The variable name should be terminated
1653 with a character not a letter, digit or underscore; otherwise, enclose
1654 the entire variable name in braces.
1656 If `/~' appears, all of FILENAME through that `/' is discarded.
1657 If `//' appears, everything up to and including the first of
1658 those `/' is discarded. */)
1659 (Lisp_Object filename
)
1661 char *nm
, *s
, *p
, *o
, *x
, *endp
;
1662 char *target
= NULL
;
1663 ptrdiff_t total
= 0;
1664 bool substituted
= 0;
1667 Lisp_Object handler
;
1669 CHECK_STRING (filename
);
1671 multibyte
= STRING_MULTIBYTE (filename
);
1673 /* If the file name has special constructs in it,
1674 call the corresponding file handler. */
1675 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
1676 if (!NILP (handler
))
1678 Lisp_Object handled_name
= call2 (handler
, Qsubstitute_in_file_name
,
1680 if (STRINGP (handled_name
))
1681 return handled_name
;
1682 error ("Invalid handler in `file-name-handler-alist'");
1685 /* Always work on a copy of the string, in case GC happens during
1686 decode of environment variables, causing the original Lisp_String
1687 data to be relocated. */
1688 nm
= alloca (SBYTES (filename
) + 1);
1689 memcpy (nm
, SDATA (filename
), SBYTES (filename
) + 1);
1692 dostounix_filename (nm
, multibyte
);
1693 substituted
= (memcmp (nm
, SDATA (filename
), SBYTES (filename
)) != 0);
1695 endp
= nm
+ SBYTES (filename
);
1697 /* If /~ or // appears, discard everything through first slash. */
1698 p
= search_embedded_absfilename (nm
, endp
);
1700 /* Start over with the new string, so we check the file-name-handler
1701 again. Important with filenames like "/home/foo//:/hello///there"
1702 which would substitute to "/:/hello///there" rather than "/there". */
1703 return Fsubstitute_in_file_name
1704 (make_specified_string (p
, -1, endp
- p
, multibyte
));
1706 /* See if any variables are substituted into the string
1707 and find the total length of their values in `total'. */
1709 for (p
= nm
; p
!= endp
;)
1719 /* "$$" means a single "$". */
1728 p
= memchr (p
, '}', endp
- p
);
1736 while (p
!= endp
&& (c_isalnum (*p
) || *p
== '_')) p
++;
1740 /* Copy out the variable name. */
1741 target
= alloca (s
- o
+ 1);
1742 memcpy (target
, o
, s
- o
);
1745 strupr (target
); /* $home == $HOME etc. */
1748 /* Get variable value. */
1749 o
= egetenv (target
);
1752 /* Don't try to guess a maximum length - UTF8 can use up to
1753 four bytes per character. This code is unlikely to run
1754 in a situation that requires performance, so decoding the
1755 env variables twice should be acceptable. Note that
1756 decoding may cause a garbage collect. */
1757 Lisp_Object orig
, decoded
;
1758 orig
= build_unibyte_string (o
);
1759 decoded
= DECODE_FILE (orig
);
1760 total
+= SBYTES (decoded
);
1770 if (!NILP (Vw32_downcase_file_names
))
1771 filename
= Fdowncase (filename
);
1776 /* If substitution required, recopy the string and do it. */
1777 /* Make space in stack frame for the new copy. */
1778 xnm
= alloca (SBYTES (filename
) + total
+ 1);
1781 /* Copy the rest of the name through, replacing $ constructs with values. */
1798 p
= memchr (p
, '}', endp
- p
);
1806 while (p
!= endp
&& (c_isalnum (*p
) || *p
== '_')) p
++;
1810 /* Copy out the variable name. */
1811 target
= alloca (s
- o
+ 1);
1812 memcpy (target
, o
, s
- o
);
1815 /* Get variable value. */
1816 o
= egetenv (target
);
1820 strcpy (x
, target
); x
+= strlen (target
);
1824 Lisp_Object orig
, decoded
;
1825 ptrdiff_t orig_length
, decoded_length
;
1826 orig_length
= strlen (o
);
1827 orig
= make_unibyte_string (o
, orig_length
);
1828 decoded
= DECODE_FILE (orig
);
1829 decoded_length
= SBYTES (decoded
);
1830 memcpy (x
, SDATA (decoded
), decoded_length
);
1831 x
+= decoded_length
;
1833 /* If environment variable needed decoding, return value
1834 needs to be multibyte. */
1835 if (decoded_length
!= orig_length
1836 || memcmp (SDATA (decoded
), o
, orig_length
))
1843 /* If /~ or // appears, discard everything through first slash. */
1844 while ((p
= search_embedded_absfilename (xnm
, x
)) != NULL
)
1845 /* This time we do not start over because we've already expanded envvars
1846 and replaced $$ with $. Maybe we should start over as well, but we'd
1847 need to quote some $ to $$ first. */
1851 if (!NILP (Vw32_downcase_file_names
))
1853 Lisp_Object xname
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1855 xname
= Fdowncase (xname
);
1860 return make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1863 error ("Bad format environment-variable substitution");
1865 error ("Missing \"}\" in environment-variable substitution");
1867 error ("Substituting nonexistent environment variable \"%s\"", target
);
1870 /* A slightly faster and more convenient way to get
1871 (directory-file-name (expand-file-name FOO)). */
1874 expand_and_dir_to_file (Lisp_Object filename
, Lisp_Object defdir
)
1876 register Lisp_Object absname
;
1878 absname
= Fexpand_file_name (filename
, defdir
);
1880 /* Remove final slash, if any (unless this is the root dir).
1881 stat behaves differently depending! */
1882 if (SCHARS (absname
) > 1
1883 && IS_DIRECTORY_SEP (SREF (absname
, SBYTES (absname
) - 1))
1884 && !IS_DEVICE_SEP (SREF (absname
, SBYTES (absname
) - 2)))
1885 /* We cannot take shortcuts; they might be wrong for magic file names. */
1886 absname
= Fdirectory_file_name (absname
);
1890 /* Signal an error if the file ABSNAME already exists.
1891 If INTERACTIVE, ask the user whether to proceed,
1892 and bypass the error if the user says to go ahead.
1893 QUERYSTRING is a name for the action that is being considered
1896 *STATPTR is used to store the stat information if the file exists.
1897 If the file does not exist, STATPTR->st_mode is set to 0.
1898 If STATPTR is null, we don't store into it.
1900 If QUICK, ask for y or n, not yes or no. */
1903 barf_or_query_if_file_exists (Lisp_Object absname
, const char *querystring
,
1904 bool interactive
, struct stat
*statptr
,
1907 Lisp_Object tem
, encoded_filename
;
1908 struct stat statbuf
;
1909 struct gcpro gcpro1
;
1911 encoded_filename
= ENCODE_FILE (absname
);
1913 /* `stat' is a good way to tell whether the file exists,
1914 regardless of what access permissions it has. */
1915 if (lstat (SSDATA (encoded_filename
), &statbuf
) >= 0)
1917 if (S_ISDIR (statbuf
.st_mode
))
1918 xsignal2 (Qfile_error
,
1919 build_string ("File is a directory"), absname
);
1922 xsignal2 (Qfile_already_exists
,
1923 build_string ("File already exists"), absname
);
1925 tem
= format2 ("File %s already exists; %s anyway? ",
1926 absname
, build_string (querystring
));
1928 tem
= call1 (intern ("y-or-n-p"), tem
);
1930 tem
= do_yes_or_no_p (tem
);
1933 xsignal2 (Qfile_already_exists
,
1934 build_string ("File already exists"), absname
);
1941 statptr
->st_mode
= 0;
1946 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 6,
1947 "fCopy file: \nGCopy %s to file: \np\nP",
1948 doc
: /* Copy FILE to NEWNAME. Both args must be strings.
1949 If NEWNAME names a directory, copy FILE there.
1951 This function always sets the file modes of the output file to match
1954 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1955 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1956 signal a `file-already-exists' error without overwriting. If
1957 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1958 about overwriting; this is what happens in interactive use with M-x.
1959 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1962 Fourth arg KEEP-TIME non-nil means give the output file the same
1963 last-modified time as the old one. (This works on only some systems.)
1965 A prefix arg makes KEEP-TIME non-nil.
1967 If PRESERVE-UID-GID is non-nil, we try to transfer the
1968 uid and gid of FILE to NEWNAME.
1970 If PRESERVE-EXTENDED-ATTRIBUTES is non-nil, we try to copy additional
1971 attributes of FILE to NEWNAME, such as its SELinux context and ACL
1972 entries (depending on how Emacs was built). */)
1973 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
, Lisp_Object keep_time
, Lisp_Object preserve_uid_gid
, Lisp_Object preserve_extended_attributes
)
1977 char buf
[16 * 1024];
1978 struct stat st
, out_st
;
1979 Lisp_Object handler
;
1980 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
1981 ptrdiff_t count
= SPECPDL_INDEX ();
1982 Lisp_Object encoded_file
, encoded_newname
;
1984 security_context_t con
;
1991 encoded_file
= encoded_newname
= Qnil
;
1992 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
1993 CHECK_STRING (file
);
1994 CHECK_STRING (newname
);
1996 if (!NILP (Ffile_directory_p (newname
)))
1997 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
1999 newname
= Fexpand_file_name (newname
, Qnil
);
2001 file
= Fexpand_file_name (file
, Qnil
);
2003 /* If the input file name has special constructs in it,
2004 call the corresponding file handler. */
2005 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
2006 /* Likewise for output file name. */
2008 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
2009 if (!NILP (handler
))
2010 RETURN_UNGCPRO (call7 (handler
, Qcopy_file
, file
, newname
,
2011 ok_if_already_exists
, keep_time
, preserve_uid_gid
,
2012 preserve_extended_attributes
));
2014 encoded_file
= ENCODE_FILE (file
);
2015 encoded_newname
= ENCODE_FILE (newname
);
2017 if (NILP (ok_if_already_exists
)
2018 || INTEGERP (ok_if_already_exists
))
2019 barf_or_query_if_file_exists (newname
, "copy to it",
2020 INTEGERP (ok_if_already_exists
), &out_st
, 0);
2021 else if (stat (SSDATA (encoded_newname
), &out_st
) < 0)
2025 if (!NILP (preserve_extended_attributes
))
2027 acl
= acl_get_file (SDATA (encoded_file
), ACL_TYPE_ACCESS
);
2028 if (acl
== NULL
&& acl_errno_valid (errno
))
2029 report_file_error ("Getting ACL", file
);
2031 if (!CopyFile (SDATA (encoded_file
),
2032 SDATA (encoded_newname
),
2035 /* CopyFile doesn't set errno when it fails. By far the most
2036 "popular" reason is that the target is read-only. */
2037 report_file_errno ("Copying file", list2 (file
, newname
),
2038 GetLastError () == 5 ? EACCES
: EPERM
);
2040 /* CopyFile retains the timestamp by default. */
2041 else if (NILP (keep_time
))
2047 filename
= SDATA (encoded_newname
);
2049 /* Ensure file is writable while its modified time is set. */
2050 attributes
= GetFileAttributes (filename
);
2051 SetFileAttributes (filename
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
2052 now
= current_emacs_time ();
2053 if (set_file_times (-1, filename
, now
, now
))
2055 /* Restore original attributes. */
2056 SetFileAttributes (filename
, attributes
);
2057 xsignal2 (Qfile_date_error
,
2058 build_string ("Cannot set file date"), newname
);
2060 /* Restore original attributes. */
2061 SetFileAttributes (filename
, attributes
);
2066 acl_set_file (SDATA (encoded_newname
), ACL_TYPE_ACCESS
, acl
) != 0;
2067 if (fail
&& acl_errno_valid (errno
))
2068 report_file_error ("Setting ACL", newname
);
2072 #else /* not WINDOWSNT */
2074 ifd
= emacs_open (SSDATA (encoded_file
), O_RDONLY
, 0);
2078 report_file_error ("Opening input file", file
);
2080 record_unwind_protect_int (close_file_unwind
, ifd
);
2082 if (fstat (ifd
, &st
) != 0)
2083 report_file_error ("Input file status", file
);
2085 if (!NILP (preserve_extended_attributes
))
2088 if (is_selinux_enabled ())
2090 conlength
= fgetfilecon (ifd
, &con
);
2091 if (conlength
== -1)
2092 report_file_error ("Doing fgetfilecon", file
);
2097 if (out_st
.st_mode
!= 0
2098 && st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
2099 report_file_errno ("Input and output files are the same",
2100 list2 (file
, newname
), 0);
2102 /* We can copy only regular files. */
2103 if (!S_ISREG (st
.st_mode
))
2104 report_file_errno ("Non-regular file", file
,
2105 S_ISDIR (st
.st_mode
) ? EISDIR
: EINVAL
);
2109 int new_mask
= st
.st_mode
& (!NILP (preserve_uid_gid
) ? 0600 : 0666);
2111 int new_mask
= S_IREAD
| S_IWRITE
;
2113 ofd
= emacs_open (SSDATA (encoded_newname
),
2114 (O_WRONLY
| O_TRUNC
| O_CREAT
2115 | (NILP (ok_if_already_exists
) ? O_EXCL
: 0)),
2119 report_file_error ("Opening output file", newname
);
2121 record_unwind_protect_int (close_file_unwind
, ofd
);
2125 while ((n
= emacs_read (ifd
, buf
, sizeof buf
)) > 0)
2126 if (emacs_write_sig (ofd
, buf
, n
) != n
)
2127 report_file_error ("Write error", newname
);
2131 /* Preserve the original file permissions, and if requested, also its
2134 mode_t mode_mask
= 07777;
2135 if (!NILP (preserve_uid_gid
))
2137 /* Attempt to change owner and group. If that doesn't work
2138 attempt to change just the group, as that is sometimes allowed.
2139 Adjust the mode mask to eliminate setuid or setgid bits
2140 that are inappropriate if the owner and group are wrong. */
2141 if (fchown (ofd
, st
.st_uid
, st
.st_gid
) != 0)
2143 mode_mask
&= ~06000;
2144 if (fchown (ofd
, -1, st
.st_gid
) == 0)
2149 switch (!NILP (preserve_extended_attributes
)
2150 ? qcopy_acl (SSDATA (encoded_file
), ifd
,
2151 SSDATA (encoded_newname
), ofd
,
2152 st
.st_mode
& mode_mask
)
2153 : fchmod (ofd
, st
.st_mode
& mode_mask
))
2155 case -2: report_file_error ("Copying permissions from", file
);
2156 case -1: report_file_error ("Copying permissions to", newname
);
2159 #endif /* not MSDOS */
2164 /* Set the modified context back to the file. */
2165 bool fail
= fsetfilecon (ofd
, con
) != 0;
2166 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2167 if (fail
&& errno
!= ENOTSUP
)
2168 report_file_error ("Doing fsetfilecon", newname
);
2174 if (!NILP (keep_time
))
2176 EMACS_TIME atime
= get_stat_atime (&st
);
2177 EMACS_TIME mtime
= get_stat_mtime (&st
);
2178 if (set_file_times (ofd
, SSDATA (encoded_newname
), atime
, mtime
))
2179 xsignal2 (Qfile_date_error
,
2180 build_string ("Cannot set file date"), newname
);
2183 if (emacs_close (ofd
) < 0)
2184 report_file_error ("Write error", newname
);
2189 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2190 and if it can't, it tells so. Otherwise, under MSDOS we usually
2191 get only the READ bit, which will make the copied file read-only,
2192 so it's better not to chmod at all. */
2193 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2194 chmod (SDATA (encoded_newname
), st
.st_mode
& 07777);
2196 #endif /* not WINDOWSNT */
2198 /* Discard the unwind protects. */
2199 specpdl_ptr
= specpdl
+ count
;
2205 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2206 Smake_directory_internal
, 1, 1, 0,
2207 doc
: /* Create a new directory named DIRECTORY. */)
2208 (Lisp_Object directory
)
2211 Lisp_Object handler
;
2212 Lisp_Object encoded_dir
;
2214 CHECK_STRING (directory
);
2215 directory
= Fexpand_file_name (directory
, Qnil
);
2217 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2218 if (!NILP (handler
))
2219 return call2 (handler
, Qmake_directory_internal
, directory
);
2221 encoded_dir
= ENCODE_FILE (directory
);
2223 dir
= SSDATA (encoded_dir
);
2226 if (mkdir (dir
) != 0)
2228 if (mkdir (dir
, 0777 & ~auto_saving_dir_umask
) != 0)
2230 report_file_error ("Creating directory", directory
);
2235 DEFUN ("delete-directory-internal", Fdelete_directory_internal
,
2236 Sdelete_directory_internal
, 1, 1, 0,
2237 doc
: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2238 (Lisp_Object directory
)
2241 Lisp_Object encoded_dir
;
2243 CHECK_STRING (directory
);
2244 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2245 encoded_dir
= ENCODE_FILE (directory
);
2246 dir
= SSDATA (encoded_dir
);
2248 if (rmdir (dir
) != 0)
2249 report_file_error ("Removing directory", directory
);
2254 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 2,
2255 "(list (read-file-name \
2256 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2257 \"Move file to trash: \" \"Delete file: \") \
2258 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2259 (null current-prefix-arg))",
2260 doc
: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2261 If file has multiple names, it continues to exist with the other names.
2262 TRASH non-nil means to trash the file instead of deleting, provided
2263 `delete-by-moving-to-trash' is non-nil.
2265 When called interactively, TRASH is t if no prefix argument is given.
2266 With a prefix argument, TRASH is nil. */)
2267 (Lisp_Object filename
, Lisp_Object trash
)
2269 Lisp_Object handler
;
2270 Lisp_Object encoded_file
;
2271 struct gcpro gcpro1
;
2274 if (!NILP (Ffile_directory_p (filename
))
2275 && NILP (Ffile_symlink_p (filename
)))
2276 xsignal2 (Qfile_error
,
2277 build_string ("Removing old name: is a directory"),
2280 filename
= Fexpand_file_name (filename
, Qnil
);
2282 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2283 if (!NILP (handler
))
2284 return call3 (handler
, Qdelete_file
, filename
, trash
);
2286 if (delete_by_moving_to_trash
&& !NILP (trash
))
2287 return call1 (Qmove_file_to_trash
, filename
);
2289 encoded_file
= ENCODE_FILE (filename
);
2291 if (unlink (SSDATA (encoded_file
)) < 0)
2292 report_file_error ("Removing old name", filename
);
2297 internal_delete_file_1 (Lisp_Object ignore
)
2302 /* Delete file FILENAME, returning true if successful.
2303 This ignores `delete-by-moving-to-trash'. */
2306 internal_delete_file (Lisp_Object filename
)
2310 tem
= internal_condition_case_2 (Fdelete_file
, filename
, Qnil
,
2311 Qt
, internal_delete_file_1
);
2315 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2316 "fRename file: \nGRename %s to file: \np",
2317 doc
: /* Rename FILE as NEWNAME. Both args must be strings.
2318 If file has names other than FILE, it continues to have those names.
2319 Signals a `file-already-exists' error if a file NEWNAME already exists
2320 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2321 A number as third arg means request confirmation if NEWNAME already exists.
2322 This is what happens in interactive use with M-x. */)
2323 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2325 Lisp_Object handler
;
2326 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
2327 Lisp_Object encoded_file
, encoded_newname
, symlink_target
;
2329 symlink_target
= encoded_file
= encoded_newname
= Qnil
;
2330 GCPRO5 (file
, newname
, encoded_file
, encoded_newname
, symlink_target
);
2331 CHECK_STRING (file
);
2332 CHECK_STRING (newname
);
2333 file
= Fexpand_file_name (file
, Qnil
);
2335 if ((!NILP (Ffile_directory_p (newname
)))
2337 /* If the file names are identical but for the case,
2338 don't attempt to move directory to itself. */
2339 && (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2343 Lisp_Object fname
= (NILP (Ffile_directory_p (file
))
2344 ? file
: Fdirectory_file_name (file
));
2345 newname
= Fexpand_file_name (Ffile_name_nondirectory (fname
), newname
);
2348 newname
= Fexpand_file_name (newname
, Qnil
);
2350 /* If the file name has special constructs in it,
2351 call the corresponding file handler. */
2352 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2354 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2355 if (!NILP (handler
))
2356 RETURN_UNGCPRO (call4 (handler
, Qrename_file
,
2357 file
, newname
, ok_if_already_exists
));
2359 encoded_file
= ENCODE_FILE (file
);
2360 encoded_newname
= ENCODE_FILE (newname
);
2363 /* If the file names are identical but for the case, don't ask for
2364 confirmation: they simply want to change the letter-case of the
2366 if (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2368 if (NILP (ok_if_already_exists
)
2369 || INTEGERP (ok_if_already_exists
))
2370 barf_or_query_if_file_exists (newname
, "rename to it",
2371 INTEGERP (ok_if_already_exists
), 0, 0);
2372 if (rename (SSDATA (encoded_file
), SSDATA (encoded_newname
)) < 0)
2377 symlink_target
= Ffile_symlink_p (file
);
2378 if (! NILP (symlink_target
))
2379 Fmake_symbolic_link (symlink_target
, newname
,
2380 NILP (ok_if_already_exists
) ? Qnil
: Qt
);
2381 else if (!NILP (Ffile_directory_p (file
)))
2382 call4 (Qcopy_directory
, file
, newname
, Qt
, Qnil
);
2384 /* We have already prompted if it was an integer, so don't
2385 have copy-file prompt again. */
2386 Fcopy_file (file
, newname
,
2387 NILP (ok_if_already_exists
) ? Qnil
: Qt
,
2390 count
= SPECPDL_INDEX ();
2391 specbind (Qdelete_by_moving_to_trash
, Qnil
);
2393 if (!NILP (Ffile_directory_p (file
)) && NILP (symlink_target
))
2394 call2 (Qdelete_directory
, file
, Qt
);
2396 Fdelete_file (file
, Qnil
);
2397 unbind_to (count
, Qnil
);
2400 report_file_error ("Renaming", list2 (file
, newname
));
2406 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2407 "fAdd name to file: \nGName to add to %s: \np",
2408 doc
: /* Give FILE additional name NEWNAME. Both args must be strings.
2409 Signals a `file-already-exists' error if a file NEWNAME already exists
2410 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2411 A number as third arg means request confirmation if NEWNAME already exists.
2412 This is what happens in interactive use with M-x. */)
2413 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2415 Lisp_Object handler
;
2416 Lisp_Object encoded_file
, encoded_newname
;
2417 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2419 GCPRO4 (file
, newname
, encoded_file
, encoded_newname
);
2420 encoded_file
= encoded_newname
= Qnil
;
2421 CHECK_STRING (file
);
2422 CHECK_STRING (newname
);
2423 file
= Fexpand_file_name (file
, Qnil
);
2425 if (!NILP (Ffile_directory_p (newname
)))
2426 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
2428 newname
= Fexpand_file_name (newname
, Qnil
);
2430 /* If the file name has special constructs in it,
2431 call the corresponding file handler. */
2432 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2433 if (!NILP (handler
))
2434 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2435 newname
, ok_if_already_exists
));
2437 /* If the new name has special constructs in it,
2438 call the corresponding file handler. */
2439 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2440 if (!NILP (handler
))
2441 RETURN_UNGCPRO (call4 (handler
, Qadd_name_to_file
, file
,
2442 newname
, ok_if_already_exists
));
2444 encoded_file
= ENCODE_FILE (file
);
2445 encoded_newname
= ENCODE_FILE (newname
);
2447 if (NILP (ok_if_already_exists
)
2448 || INTEGERP (ok_if_already_exists
))
2449 barf_or_query_if_file_exists (newname
, "make it a new name",
2450 INTEGERP (ok_if_already_exists
), 0, 0);
2452 unlink (SSDATA (newname
));
2453 if (link (SSDATA (encoded_file
), SSDATA (encoded_newname
)) < 0)
2454 report_file_error ("Adding new name", list2 (file
, newname
));
2460 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2461 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2462 doc
: /* Make a symbolic link to FILENAME, named LINKNAME.
2463 Both args must be strings.
2464 Signals a `file-already-exists' error if a file LINKNAME already exists
2465 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2466 A number as third arg means request confirmation if LINKNAME already exists.
2467 This happens for interactive use with M-x. */)
2468 (Lisp_Object filename
, Lisp_Object linkname
, Lisp_Object ok_if_already_exists
)
2470 Lisp_Object handler
;
2471 Lisp_Object encoded_filename
, encoded_linkname
;
2472 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
;
2474 GCPRO4 (filename
, linkname
, encoded_filename
, encoded_linkname
);
2475 encoded_filename
= encoded_linkname
= Qnil
;
2476 CHECK_STRING (filename
);
2477 CHECK_STRING (linkname
);
2478 /* If the link target has a ~, we must expand it to get
2479 a truly valid file name. Otherwise, do not expand;
2480 we want to permit links to relative file names. */
2481 if (SREF (filename
, 0) == '~')
2482 filename
= Fexpand_file_name (filename
, Qnil
);
2484 if (!NILP (Ffile_directory_p (linkname
)))
2485 linkname
= Fexpand_file_name (Ffile_name_nondirectory (filename
), linkname
);
2487 linkname
= Fexpand_file_name (linkname
, Qnil
);
2489 /* If the file name has special constructs in it,
2490 call the corresponding file handler. */
2491 handler
= Ffind_file_name_handler (filename
, Qmake_symbolic_link
);
2492 if (!NILP (handler
))
2493 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2494 linkname
, ok_if_already_exists
));
2496 /* If the new link name has special constructs in it,
2497 call the corresponding file handler. */
2498 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2499 if (!NILP (handler
))
2500 RETURN_UNGCPRO (call4 (handler
, Qmake_symbolic_link
, filename
,
2501 linkname
, ok_if_already_exists
));
2503 encoded_filename
= ENCODE_FILE (filename
);
2504 encoded_linkname
= ENCODE_FILE (linkname
);
2506 if (NILP (ok_if_already_exists
)
2507 || INTEGERP (ok_if_already_exists
))
2508 barf_or_query_if_file_exists (linkname
, "make it a link",
2509 INTEGERP (ok_if_already_exists
), 0, 0);
2510 if (symlink (SSDATA (encoded_filename
), SSDATA (encoded_linkname
)) < 0)
2512 /* If we didn't complain already, silently delete existing file. */
2513 if (errno
== EEXIST
)
2515 unlink (SSDATA (encoded_linkname
));
2516 if (symlink (SSDATA (encoded_filename
), SSDATA (encoded_linkname
))
2523 if (errno
== ENOSYS
)
2526 xsignal1 (Qfile_error
,
2527 build_string ("Symbolic links are not supported"));
2530 report_file_error ("Making symbolic link", list2 (filename
, linkname
));
2537 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2539 doc
: /* Return t if file FILENAME specifies an absolute file name.
2540 On Unix, this is a name starting with a `/' or a `~'. */)
2541 (Lisp_Object filename
)
2543 CHECK_STRING (filename
);
2544 return file_name_absolute_p (SSDATA (filename
)) ? Qt
: Qnil
;
2547 /* Return true if FILENAME exists. */
2549 check_existing (const char *filename
)
2551 return faccessat (AT_FDCWD
, filename
, F_OK
, AT_EACCESS
) == 0;
2554 /* Return true if file FILENAME exists and can be executed. */
2557 check_executable (char *filename
)
2559 return faccessat (AT_FDCWD
, filename
, X_OK
, AT_EACCESS
) == 0;
2562 /* Return true if file FILENAME exists and can be accessed
2563 according to AMODE, which should include W_OK.
2564 On failure, return false and set errno. */
2567 check_writable (const char *filename
, int amode
)
2570 /* FIXME: an faccessat implementation should be added to the
2571 DOS/Windows ports and this #ifdef branch should be removed. */
2573 if (stat (filename
, &st
) < 0)
2576 return (st
.st_mode
& S_IWRITE
|| S_ISDIR (st
.st_mode
));
2577 #else /* not MSDOS */
2578 bool res
= faccessat (AT_FDCWD
, filename
, amode
, AT_EACCESS
) == 0;
2580 /* faccessat may have returned failure because Cygwin couldn't
2581 determine the file's UID or GID; if so, we return success. */
2584 int faccessat_errno
= errno
;
2586 if (stat (filename
, &st
) < 0)
2588 res
= (st
.st_uid
== -1 || st
.st_gid
== -1);
2589 errno
= faccessat_errno
;
2593 #endif /* not MSDOS */
2596 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2597 doc
: /* Return t if file FILENAME exists (whether or not you can read it.)
2598 See also `file-readable-p' and `file-attributes'.
2599 This returns nil for a symlink to a nonexistent file.
2600 Use `file-symlink-p' to test for such links. */)
2601 (Lisp_Object filename
)
2603 Lisp_Object absname
;
2604 Lisp_Object handler
;
2606 CHECK_STRING (filename
);
2607 absname
= Fexpand_file_name (filename
, Qnil
);
2609 /* If the file name has special constructs in it,
2610 call the corresponding file handler. */
2611 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2612 if (!NILP (handler
))
2614 Lisp_Object result
= call2 (handler
, Qfile_exists_p
, absname
);
2619 absname
= ENCODE_FILE (absname
);
2621 return (check_existing (SSDATA (absname
))) ? Qt
: Qnil
;
2624 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2625 doc
: /* Return t if FILENAME can be executed by you.
2626 For a directory, this means you can access files in that directory. */)
2627 (Lisp_Object filename
)
2629 Lisp_Object absname
;
2630 Lisp_Object handler
;
2632 CHECK_STRING (filename
);
2633 absname
= Fexpand_file_name (filename
, Qnil
);
2635 /* If the file name has special constructs in it,
2636 call the corresponding file handler. */
2637 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
2638 if (!NILP (handler
))
2639 return call2 (handler
, Qfile_executable_p
, absname
);
2641 absname
= ENCODE_FILE (absname
);
2643 return (check_executable (SSDATA (absname
)) ? Qt
: Qnil
);
2646 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
2647 doc
: /* Return t if file FILENAME exists and you can read it.
2648 See also `file-exists-p' and `file-attributes'. */)
2649 (Lisp_Object filename
)
2651 Lisp_Object absname
;
2652 Lisp_Object handler
;
2654 CHECK_STRING (filename
);
2655 absname
= Fexpand_file_name (filename
, Qnil
);
2657 /* If the file name has special constructs in it,
2658 call the corresponding file handler. */
2659 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
2660 if (!NILP (handler
))
2661 return call2 (handler
, Qfile_readable_p
, absname
);
2663 absname
= ENCODE_FILE (absname
);
2664 return (faccessat (AT_FDCWD
, SSDATA (absname
), R_OK
, AT_EACCESS
) == 0
2668 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
2669 doc
: /* Return t if file FILENAME can be written or created by you. */)
2670 (Lisp_Object filename
)
2672 Lisp_Object absname
, dir
, encoded
;
2673 Lisp_Object handler
;
2675 CHECK_STRING (filename
);
2676 absname
= Fexpand_file_name (filename
, Qnil
);
2678 /* If the file name has special constructs in it,
2679 call the corresponding file handler. */
2680 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
2681 if (!NILP (handler
))
2682 return call2 (handler
, Qfile_writable_p
, absname
);
2684 encoded
= ENCODE_FILE (absname
);
2685 if (check_writable (SSDATA (encoded
), W_OK
))
2687 if (errno
!= ENOENT
)
2690 dir
= Ffile_name_directory (absname
);
2691 eassert (!NILP (dir
));
2693 dir
= Fdirectory_file_name (dir
);
2696 dir
= ENCODE_FILE (dir
);
2698 /* The read-only attribute of the parent directory doesn't affect
2699 whether a file or directory can be created within it. Some day we
2700 should check ACLs though, which do affect this. */
2701 return file_directory_p (SDATA (dir
)) ? Qt
: Qnil
;
2703 return check_writable (SSDATA (dir
), W_OK
| X_OK
) ? Qt
: Qnil
;
2707 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
2708 doc
: /* Access file FILENAME, and get an error if that does not work.
2709 The second argument STRING is used in the error message.
2710 If there is no error, returns nil. */)
2711 (Lisp_Object filename
, Lisp_Object string
)
2713 Lisp_Object handler
, encoded_filename
, absname
;
2715 CHECK_STRING (filename
);
2716 absname
= Fexpand_file_name (filename
, Qnil
);
2718 CHECK_STRING (string
);
2720 /* If the file name has special constructs in it,
2721 call the corresponding file handler. */
2722 handler
= Ffind_file_name_handler (absname
, Qaccess_file
);
2723 if (!NILP (handler
))
2724 return call3 (handler
, Qaccess_file
, absname
, string
);
2726 encoded_filename
= ENCODE_FILE (absname
);
2728 if (faccessat (AT_FDCWD
, SSDATA (encoded_filename
), R_OK
, AT_EACCESS
) != 0)
2729 report_file_error (SSDATA (string
), filename
);
2734 /* Relative to directory FD, return the symbolic link value of FILENAME.
2735 On failure, return nil. */
2737 emacs_readlinkat (int fd
, char const *filename
)
2739 static struct allocator
const emacs_norealloc_allocator
=
2740 { xmalloc
, NULL
, xfree
, memory_full
};
2742 char readlink_buf
[1024];
2743 char *buf
= careadlinkat (fd
, filename
, readlink_buf
, sizeof readlink_buf
,
2744 &emacs_norealloc_allocator
, readlinkat
);
2748 val
= build_string (buf
);
2749 if (buf
[0] == '/' && strchr (buf
, ':'))
2750 val
= concat2 (build_string ("/:"), val
);
2751 if (buf
!= readlink_buf
)
2753 val
= DECODE_FILE (val
);
2757 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
2758 doc
: /* Return non-nil if file FILENAME is the name of a symbolic link.
2759 The value is the link target, as a string.
2760 Otherwise it returns nil.
2762 This function returns t when given the name of a symlink that
2763 points to a nonexistent file. */)
2764 (Lisp_Object filename
)
2766 Lisp_Object handler
;
2768 CHECK_STRING (filename
);
2769 filename
= Fexpand_file_name (filename
, Qnil
);
2771 /* If the file name has special constructs in it,
2772 call the corresponding file handler. */
2773 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
2774 if (!NILP (handler
))
2775 return call2 (handler
, Qfile_symlink_p
, filename
);
2777 filename
= ENCODE_FILE (filename
);
2779 return emacs_readlinkat (AT_FDCWD
, SSDATA (filename
));
2782 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
2783 doc
: /* Return t if FILENAME names an existing directory.
2784 Symbolic links to directories count as directories.
2785 See `file-symlink-p' to distinguish symlinks. */)
2786 (Lisp_Object filename
)
2788 Lisp_Object absname
;
2789 Lisp_Object handler
;
2791 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2793 /* If the file name has special constructs in it,
2794 call the corresponding file handler. */
2795 handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
2796 if (!NILP (handler
))
2797 return call2 (handler
, Qfile_directory_p
, absname
);
2799 absname
= ENCODE_FILE (absname
);
2801 return file_directory_p (SSDATA (absname
)) ? Qt
: Qnil
;
2804 /* Return true if FILE is a directory or a symlink to a directory. */
2806 file_directory_p (char const *file
)
2809 /* This is cheaper than 'stat'. */
2810 return faccessat (AT_FDCWD
, file
, D_OK
, AT_EACCESS
) == 0;
2813 return stat (file
, &st
) == 0 && S_ISDIR (st
.st_mode
);
2817 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
,
2818 Sfile_accessible_directory_p
, 1, 1, 0,
2819 doc
: /* Return t if file FILENAME names a directory you can open.
2820 For the value to be t, FILENAME must specify the name of a directory as a file,
2821 and the directory must allow you to open files in it. In order to use a
2822 directory as a buffer's current directory, this predicate must return true.
2823 A directory name spec may be given instead; then the value is t
2824 if the directory so specified exists and really is a readable and
2825 searchable directory. */)
2826 (Lisp_Object filename
)
2828 Lisp_Object absname
;
2829 Lisp_Object handler
;
2831 CHECK_STRING (filename
);
2832 absname
= Fexpand_file_name (filename
, Qnil
);
2834 /* If the file name has special constructs in it,
2835 call the corresponding file handler. */
2836 handler
= Ffind_file_name_handler (absname
, Qfile_accessible_directory_p
);
2837 if (!NILP (handler
))
2839 Lisp_Object r
= call2 (handler
, Qfile_accessible_directory_p
, absname
);
2844 absname
= ENCODE_FILE (absname
);
2845 return file_accessible_directory_p (SSDATA (absname
)) ? Qt
: Qnil
;
2848 /* If FILE is a searchable directory or a symlink to a
2849 searchable directory, return true. Otherwise return
2850 false and set errno to an error number. */
2852 file_accessible_directory_p (char const *file
)
2855 /* There's no need to test whether FILE is searchable, as the
2856 searchable/executable bit is invented on DOS_NT platforms. */
2857 return file_directory_p (file
);
2859 /* On POSIXish platforms, use just one system call; this avoids a
2860 race and is typically faster. */
2861 ptrdiff_t len
= strlen (file
);
2867 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2868 There are three exceptions: "", "/", and "//". Leave "" alone,
2869 as it's invalid. Append only "." to the other two exceptions as
2870 "/" and "//" are distinct on some platforms, whereas "/", "///",
2871 "////", etc. are all equivalent. */
2876 /* Just check for trailing '/' when deciding whether to append '/'.
2877 That's simpler than testing the two special cases "/" and "//",
2878 and it's a safe optimization here. */
2879 char *buf
= SAFE_ALLOCA (len
+ 3);
2880 memcpy (buf
, file
, len
);
2881 strcpy (buf
+ len
, &"/."[file
[len
- 1] == '/']);
2885 ok
= check_existing (dir
);
2886 saved_errno
= errno
;
2888 errno
= saved_errno
;
2893 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
2894 doc
: /* Return t if FILENAME names a regular file.
2895 This is the sort of file that holds an ordinary stream of data bytes.
2896 Symbolic links to regular files count as regular files.
2897 See `file-symlink-p' to distinguish symlinks. */)
2898 (Lisp_Object filename
)
2900 register Lisp_Object absname
;
2902 Lisp_Object handler
;
2904 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2906 /* If the file name has special constructs in it,
2907 call the corresponding file handler. */
2908 handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
2909 if (!NILP (handler
))
2910 return call2 (handler
, Qfile_regular_p
, absname
);
2912 absname
= ENCODE_FILE (absname
);
2917 Lisp_Object tem
= Vw32_get_true_file_attributes
;
2919 /* Tell stat to use expensive method to get accurate info. */
2920 Vw32_get_true_file_attributes
= Qt
;
2921 result
= stat (SDATA (absname
), &st
);
2922 Vw32_get_true_file_attributes
= tem
;
2926 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2929 if (stat (SSDATA (absname
), &st
) < 0)
2931 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2935 DEFUN ("file-selinux-context", Ffile_selinux_context
,
2936 Sfile_selinux_context
, 1, 1, 0,
2937 doc
: /* Return SELinux context of file named FILENAME.
2938 The return value is a list (USER ROLE TYPE RANGE), where the list
2939 elements are strings naming the user, role, type, and range of the
2940 file's SELinux security context.
2942 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2943 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2944 (Lisp_Object filename
)
2946 Lisp_Object absname
;
2947 Lisp_Object values
[4];
2948 Lisp_Object handler
;
2950 security_context_t con
;
2955 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2957 /* If the file name has special constructs in it,
2958 call the corresponding file handler. */
2959 handler
= Ffind_file_name_handler (absname
, Qfile_selinux_context
);
2960 if (!NILP (handler
))
2961 return call2 (handler
, Qfile_selinux_context
, absname
);
2963 absname
= ENCODE_FILE (absname
);
2970 if (is_selinux_enabled ())
2972 conlength
= lgetfilecon (SSDATA (absname
), &con
);
2975 context
= context_new (con
);
2976 if (context_user_get (context
))
2977 values
[0] = build_string (context_user_get (context
));
2978 if (context_role_get (context
))
2979 values
[1] = build_string (context_role_get (context
));
2980 if (context_type_get (context
))
2981 values
[2] = build_string (context_type_get (context
));
2982 if (context_range_get (context
))
2983 values
[3] = build_string (context_range_get (context
));
2984 context_free (context
);
2990 return Flist (sizeof (values
) / sizeof (values
[0]), values
);
2993 DEFUN ("set-file-selinux-context", Fset_file_selinux_context
,
2994 Sset_file_selinux_context
, 2, 2, 0,
2995 doc
: /* Set SELinux context of file named FILENAME to CONTEXT.
2996 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2997 elements are strings naming the components of a SELinux context.
2999 Value is t if setting of SELinux context was successful, nil otherwise.
3001 This function does nothing and returns nil if SELinux is disabled,
3002 or if Emacs was not compiled with SELinux support. */)
3003 (Lisp_Object filename
, Lisp_Object context
)
3005 Lisp_Object absname
;
3006 Lisp_Object handler
;
3008 Lisp_Object encoded_absname
;
3009 Lisp_Object user
= CAR_SAFE (context
);
3010 Lisp_Object role
= CAR_SAFE (CDR_SAFE (context
));
3011 Lisp_Object type
= CAR_SAFE (CDR_SAFE (CDR_SAFE (context
)));
3012 Lisp_Object range
= CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context
))));
3013 security_context_t con
;
3016 context_t parsed_con
;
3019 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3021 /* If the file name has special constructs in it,
3022 call the corresponding file handler. */
3023 handler
= Ffind_file_name_handler (absname
, Qset_file_selinux_context
);
3024 if (!NILP (handler
))
3025 return call3 (handler
, Qset_file_selinux_context
, absname
, context
);
3028 if (is_selinux_enabled ())
3030 /* Get current file context. */
3031 encoded_absname
= ENCODE_FILE (absname
);
3032 conlength
= lgetfilecon (SSDATA (encoded_absname
), &con
);
3035 parsed_con
= context_new (con
);
3036 /* Change the parts defined in the parameter.*/
3039 if (context_user_set (parsed_con
, SSDATA (user
)))
3040 error ("Doing context_user_set");
3044 if (context_role_set (parsed_con
, SSDATA (role
)))
3045 error ("Doing context_role_set");
3049 if (context_type_set (parsed_con
, SSDATA (type
)))
3050 error ("Doing context_type_set");
3052 if (STRINGP (range
))
3054 if (context_range_set (parsed_con
, SSDATA (range
)))
3055 error ("Doing context_range_set");
3058 /* Set the modified context back to the file. */
3059 fail
= (lsetfilecon (SSDATA (encoded_absname
),
3060 context_str (parsed_con
))
3062 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
3063 if (fail
&& errno
!= ENOTSUP
)
3064 report_file_error ("Doing lsetfilecon", absname
);
3066 context_free (parsed_con
);
3068 return fail
? Qnil
: Qt
;
3071 report_file_error ("Doing lgetfilecon", absname
);
3078 DEFUN ("file-acl", Ffile_acl
, Sfile_acl
, 1, 1, 0,
3079 doc
: /* Return ACL entries of file named FILENAME.
3080 The entries are returned in a format suitable for use in `set-file-acl'
3081 but is otherwise undocumented and subject to change.
3082 Return nil if file does not exist or is not accessible, or if Emacs
3083 was unable to determine the ACL entries. */)
3084 (Lisp_Object filename
)
3086 Lisp_Object absname
;
3087 Lisp_Object handler
;
3088 #ifdef HAVE_ACL_SET_FILE
3090 Lisp_Object acl_string
;
3094 absname
= expand_and_dir_to_file (filename
,
3095 BVAR (current_buffer
, directory
));
3097 /* If the file name has special constructs in it,
3098 call the corresponding file handler. */
3099 handler
= Ffind_file_name_handler (absname
, Qfile_acl
);
3100 if (!NILP (handler
))
3101 return call2 (handler
, Qfile_acl
, absname
);
3103 #ifdef HAVE_ACL_SET_FILE
3104 absname
= ENCODE_FILE (absname
);
3106 acl
= acl_get_file (SSDATA (absname
), ACL_TYPE_ACCESS
);
3110 str
= acl_to_text (acl
, NULL
);
3117 acl_string
= build_string (str
);
3127 DEFUN ("set-file-acl", Fset_file_acl
, Sset_file_acl
,
3129 doc
: /* Set ACL of file named FILENAME to ACL-STRING.
3130 ACL-STRING should contain the textual representation of the ACL
3131 entries in a format suitable for the platform.
3133 Value is t if setting of ACL was successful, nil otherwise.
3135 Setting ACL for local files requires Emacs to be built with ACL
3137 (Lisp_Object filename
, Lisp_Object acl_string
)
3139 Lisp_Object absname
;
3140 Lisp_Object handler
;
3141 #ifdef HAVE_ACL_SET_FILE
3142 Lisp_Object encoded_absname
;
3147 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3149 /* If the file name has special constructs in it,
3150 call the corresponding file handler. */
3151 handler
= Ffind_file_name_handler (absname
, Qset_file_acl
);
3152 if (!NILP (handler
))
3153 return call3 (handler
, Qset_file_acl
, absname
, acl_string
);
3155 #ifdef HAVE_ACL_SET_FILE
3156 if (STRINGP (acl_string
))
3158 acl
= acl_from_text (SSDATA (acl_string
));
3161 report_file_error ("Converting ACL", absname
);
3165 encoded_absname
= ENCODE_FILE (absname
);
3167 fail
= (acl_set_file (SSDATA (encoded_absname
), ACL_TYPE_ACCESS
,
3170 if (fail
&& acl_errno_valid (errno
))
3171 report_file_error ("Setting ACL", absname
);
3174 return fail
? Qnil
: Qt
;
3181 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
3182 doc
: /* Return mode bits of file named FILENAME, as an integer.
3183 Return nil, if file does not exist or is not accessible. */)
3184 (Lisp_Object filename
)
3186 Lisp_Object absname
;
3188 Lisp_Object handler
;
3190 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
3192 /* If the file name has special constructs in it,
3193 call the corresponding file handler. */
3194 handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
3195 if (!NILP (handler
))
3196 return call2 (handler
, Qfile_modes
, absname
);
3198 absname
= ENCODE_FILE (absname
);
3200 if (stat (SSDATA (absname
), &st
) < 0)
3203 return make_number (st
.st_mode
& 07777);
3206 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2,
3207 "(let ((file (read-file-name \"File: \"))) \
3208 (list file (read-file-modes nil file)))",
3209 doc
: /* Set mode bits of file named FILENAME to MODE (an integer).
3210 Only the 12 low bits of MODE are used.
3212 Interactively, mode bits are read by `read-file-modes', which accepts
3213 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3214 (Lisp_Object filename
, Lisp_Object mode
)
3216 Lisp_Object absname
, encoded_absname
;
3217 Lisp_Object handler
;
3219 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3220 CHECK_NUMBER (mode
);
3222 /* If the file name has special constructs in it,
3223 call the corresponding file handler. */
3224 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
3225 if (!NILP (handler
))
3226 return call3 (handler
, Qset_file_modes
, absname
, mode
);
3228 encoded_absname
= ENCODE_FILE (absname
);
3230 if (chmod (SSDATA (encoded_absname
), XINT (mode
) & 07777) < 0)
3231 report_file_error ("Doing chmod", absname
);
3236 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
3237 doc
: /* Set the file permission bits for newly created files.
3238 The argument MODE should be an integer; only the low 9 bits are used.
3239 This setting is inherited by subprocesses. */)
3242 CHECK_NUMBER (mode
);
3244 umask ((~ XINT (mode
)) & 0777);
3249 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
3250 doc
: /* Return the default file protection for created files.
3251 The value is an integer. */)
3258 realmask
= umask (0);
3262 XSETINT (value
, (~ realmask
) & 0777);
3267 DEFUN ("set-file-times", Fset_file_times
, Sset_file_times
, 1, 2, 0,
3268 doc
: /* Set times of file FILENAME to TIMESTAMP.
3269 Set both access and modification times.
3270 Return t on success, else nil.
3271 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3273 (Lisp_Object filename
, Lisp_Object timestamp
)
3275 Lisp_Object absname
, encoded_absname
;
3276 Lisp_Object handler
;
3277 EMACS_TIME t
= lisp_time_argument (timestamp
);
3279 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3281 /* If the file name has special constructs in it,
3282 call the corresponding file handler. */
3283 handler
= Ffind_file_name_handler (absname
, Qset_file_times
);
3284 if (!NILP (handler
))
3285 return call3 (handler
, Qset_file_times
, absname
, timestamp
);
3287 encoded_absname
= ENCODE_FILE (absname
);
3290 if (set_file_times (-1, SSDATA (encoded_absname
), t
, t
))
3293 /* Setting times on a directory always fails. */
3294 if (file_directory_p (SSDATA (encoded_absname
)))
3297 report_file_error ("Setting file times", absname
);
3305 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3306 doc
: /* Tell Unix to finish all pending disk updates. */)
3313 #endif /* HAVE_SYNC */
3315 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3316 doc
: /* Return t if file FILE1 is newer than file FILE2.
3317 If FILE1 does not exist, the answer is nil;
3318 otherwise, if FILE2 does not exist, the answer is t. */)
3319 (Lisp_Object file1
, Lisp_Object file2
)
3321 Lisp_Object absname1
, absname2
;
3322 struct stat st1
, st2
;
3323 Lisp_Object handler
;
3324 struct gcpro gcpro1
, gcpro2
;
3326 CHECK_STRING (file1
);
3327 CHECK_STRING (file2
);
3330 GCPRO2 (absname1
, file2
);
3331 absname1
= expand_and_dir_to_file (file1
, BVAR (current_buffer
, directory
));
3332 absname2
= expand_and_dir_to_file (file2
, BVAR (current_buffer
, directory
));
3335 /* If the file name has special constructs in it,
3336 call the corresponding file handler. */
3337 handler
= Ffind_file_name_handler (absname1
, Qfile_newer_than_file_p
);
3339 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3340 if (!NILP (handler
))
3341 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3343 GCPRO2 (absname1
, absname2
);
3344 absname1
= ENCODE_FILE (absname1
);
3345 absname2
= ENCODE_FILE (absname2
);
3348 if (stat (SSDATA (absname1
), &st1
) < 0)
3351 if (stat (SSDATA (absname2
), &st2
) < 0)
3354 return (EMACS_TIME_LT (get_stat_mtime (&st2
), get_stat_mtime (&st1
))
3358 #ifndef READ_BUF_SIZE
3359 #define READ_BUF_SIZE (64 << 10)
3361 /* Some buffer offsets are stored in 'int' variables. */
3362 verify (READ_BUF_SIZE
<= INT_MAX
);
3364 /* This function is called after Lisp functions to decide a coding
3365 system are called, or when they cause an error. Before they are
3366 called, the current buffer is set unibyte and it contains only a
3367 newly inserted text (thus the buffer was empty before the
3370 The functions may set markers, overlays, text properties, or even
3371 alter the buffer contents, change the current buffer.
3373 Here, we reset all those changes by:
3374 o set back the current buffer.
3375 o move all markers and overlays to BEG.
3376 o remove all text properties.
3377 o set back the buffer multibyteness. */
3380 decide_coding_unwind (Lisp_Object unwind_data
)
3382 Lisp_Object multibyte
, undo_list
, buffer
;
3384 multibyte
= XCAR (unwind_data
);
3385 unwind_data
= XCDR (unwind_data
);
3386 undo_list
= XCAR (unwind_data
);
3387 buffer
= XCDR (unwind_data
);
3389 set_buffer_internal (XBUFFER (buffer
));
3390 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3391 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3392 set_buffer_intervals (current_buffer
, NULL
);
3393 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3395 /* Now we are safe to change the buffer's multibyteness directly. */
3396 bset_enable_multibyte_characters (current_buffer
, multibyte
);
3397 bset_undo_list (current_buffer
, undo_list
);
3400 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3401 object where slot 0 is the file descriptor, slot 1 specifies
3402 an offset to put the read bytes, and slot 2 is the maximum
3403 amount of bytes to read. Value is the number of bytes read. */
3406 read_non_regular (Lisp_Object state
)
3412 nbytes
= emacs_read (XSAVE_INTEGER (state
, 0),
3413 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
3414 + XSAVE_INTEGER (state
, 1)),
3415 XSAVE_INTEGER (state
, 2));
3417 /* Fast recycle this object for the likely next call. */
3419 return make_number (nbytes
);
3423 /* Condition-case handler used when reading from non-regular files
3424 in insert-file-contents. */
3427 read_non_regular_quit (Lisp_Object ignore
)
3432 /* Return the file offset that VAL represents, checking for type
3433 errors and overflow. */
3435 file_offset (Lisp_Object val
)
3437 if (RANGED_INTEGERP (0, val
, TYPE_MAXIMUM (off_t
)))
3442 double v
= XFLOAT_DATA (val
);
3444 && (sizeof (off_t
) < sizeof v
3445 ? v
<= TYPE_MAXIMUM (off_t
)
3446 : v
< TYPE_MAXIMUM (off_t
)))
3450 wrong_type_argument (intern ("file-offset"), val
);
3453 /* Return a special time value indicating the error number ERRNUM. */
3455 time_error_value (int errnum
)
3457 int ns
= (errnum
== ENOENT
|| errnum
== EACCES
|| errnum
== ENOTDIR
3458 ? NONEXISTENT_MODTIME_NSECS
3459 : UNKNOWN_MODTIME_NSECS
);
3460 return make_emacs_time (0, ns
);
3463 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3465 doc
: /* Insert contents of file FILENAME after point.
3466 Returns list of absolute file name and number of characters inserted.
3467 If second argument VISIT is non-nil, the buffer's visited filename and
3468 last save file modtime are set, and it is marked unmodified. If
3469 visiting and the file does not exist, visiting is completed before the
3472 The optional third and fourth arguments BEG and END specify what portion
3473 of the file to insert. These arguments count bytes in the file, not
3474 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3476 If optional fifth argument REPLACE is non-nil, replace the current
3477 buffer contents (in the accessible portion) with the file contents.
3478 This is better than simply deleting and inserting the whole thing
3479 because (1) it preserves some marker positions and (2) it puts less data
3480 in the undo list. When REPLACE is non-nil, the second return value is
3481 the number of characters that replace previous buffer contents.
3483 This function does code conversion according to the value of
3484 `coding-system-for-read' or `file-coding-system-alist', and sets the
3485 variable `last-coding-system-used' to the coding system actually used.
3487 In addition, this function decodes the inserted text from known formats
3488 by calling `format-decode', which see. */)
3489 (Lisp_Object filename
, Lisp_Object visit
, Lisp_Object beg
, Lisp_Object end
, Lisp_Object replace
)
3494 ptrdiff_t inserted
= 0;
3496 off_t beg_offset
, end_offset
;
3498 ptrdiff_t count
= SPECPDL_INDEX ();
3499 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
3500 Lisp_Object handler
, val
, insval
, orig_filename
, old_undo
;
3502 ptrdiff_t total
= 0;
3503 bool not_regular
= 0;
3505 char read_buf
[READ_BUF_SIZE
];
3506 struct coding_system coding
;
3507 bool replace_handled
= 0;
3508 bool set_coding_system
= 0;
3509 Lisp_Object coding_system
;
3511 /* If the undo log only contains the insertion, there's no point
3512 keeping it. It's typically when we first fill a file-buffer. */
3513 bool empty_undo_list_p
3514 = (!NILP (visit
) && NILP (BVAR (current_buffer
, undo_list
))
3516 Lisp_Object old_Vdeactivate_mark
= Vdeactivate_mark
;
3517 bool we_locked_file
= 0;
3520 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3521 error ("Cannot do file visiting in an indirect buffer");
3523 if (!NILP (BVAR (current_buffer
, read_only
)))
3524 Fbarf_if_buffer_read_only ();
3528 orig_filename
= Qnil
;
3531 GCPRO5 (filename
, val
, p
, orig_filename
, old_undo
);
3533 CHECK_STRING (filename
);
3534 filename
= Fexpand_file_name (filename
, Qnil
);
3536 /* The value Qnil means that the coding system is not yet
3538 coding_system
= Qnil
;
3540 /* If the file name has special constructs in it,
3541 call the corresponding file handler. */
3542 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3543 if (!NILP (handler
))
3545 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3546 visit
, beg
, end
, replace
);
3547 if (CONSP (val
) && CONSP (XCDR (val
))
3548 && RANGED_INTEGERP (0, XCAR (XCDR (val
)), ZV
- PT
))
3549 inserted
= XINT (XCAR (XCDR (val
)));
3553 orig_filename
= filename
;
3554 filename
= ENCODE_FILE (filename
);
3556 fd
= emacs_open (SSDATA (filename
), O_RDONLY
, 0);
3561 report_file_error ("Opening input file", orig_filename
);
3562 mtime
= time_error_value (save_errno
);
3564 if (!NILP (Vcoding_system_for_read
))
3565 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3569 fd_index
= SPECPDL_INDEX ();
3570 record_unwind_protect_int (close_file_unwind
, fd
);
3572 /* Replacement should preserve point as it preserves markers. */
3573 if (!NILP (replace
))
3574 record_unwind_protect (restore_point_unwind
, Fpoint_marker ());
3576 if (fstat (fd
, &st
) != 0)
3577 report_file_error ("Input file status", orig_filename
);
3578 mtime
= get_stat_mtime (&st
);
3580 /* This code will need to be changed in order to work on named
3581 pipes, and it's probably just not worth it. So we should at
3582 least signal an error. */
3583 if (!S_ISREG (st
.st_mode
))
3590 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3591 xsignal2 (Qfile_error
,
3592 build_string ("not a regular file"), orig_filename
);
3597 if (!NILP (beg
) || !NILP (end
))
3598 error ("Attempt to visit less than an entire file");
3599 if (BEG
< Z
&& NILP (replace
))
3600 error ("Cannot do file visiting in a non-empty buffer");
3604 beg_offset
= file_offset (beg
);
3609 end_offset
= file_offset (end
);
3613 end_offset
= TYPE_MAXIMUM (off_t
);
3616 end_offset
= st
.st_size
;
3618 /* A negative size can happen on a platform that allows file
3619 sizes greater than the maximum off_t value. */
3623 /* The file size returned from stat may be zero, but data
3624 may be readable nonetheless, for example when this is a
3625 file in the /proc filesystem. */
3626 if (end_offset
== 0)
3627 end_offset
= READ_BUF_SIZE
;
3631 /* Check now whether the buffer will become too large,
3632 in the likely case where the file's length is not changing.
3633 This saves a lot of needless work before a buffer overflow. */
3636 /* The likely offset where we will stop reading. We could read
3637 more (or less), if the file grows (or shrinks) as we read it. */
3638 off_t likely_end
= min (end_offset
, st
.st_size
);
3640 if (beg_offset
< likely_end
)
3643 = Z_BYTE
- (!NILP (replace
) ? ZV_BYTE
- BEGV_BYTE
: 0);
3644 ptrdiff_t buf_growth_max
= BUF_BYTES_MAX
- buf_bytes
;
3645 off_t likely_growth
= likely_end
- beg_offset
;
3646 if (buf_growth_max
< likely_growth
)
3651 /* Prevent redisplay optimizations. */
3652 current_buffer
->clip_changed
= 1;
3654 if (EQ (Vcoding_system_for_read
, Qauto_save_coding
))
3656 coding_system
= coding_inherit_eol_type (Qutf_8_emacs
, Qunix
);
3657 setup_coding_system (coding_system
, &coding
);
3658 /* Ensure we set Vlast_coding_system_used. */
3659 set_coding_system
= 1;
3663 /* Decide the coding system to use for reading the file now
3664 because we can't use an optimized method for handling
3665 `coding:' tag if the current buffer is not empty. */
3666 if (!NILP (Vcoding_system_for_read
))
3667 coding_system
= Vcoding_system_for_read
;
3670 /* Don't try looking inside a file for a coding system
3671 specification if it is not seekable. */
3672 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3674 /* Find a coding system specified in the heading two
3675 lines or in the tailing several lines of the file.
3676 We assume that the 1K-byte and 3K-byte for heading
3677 and tailing respectively are sufficient for this
3681 if (st
.st_size
<= (1024 * 4))
3682 nread
= emacs_read (fd
, read_buf
, 1024 * 4);
3685 nread
= emacs_read (fd
, read_buf
, 1024);
3689 if (lseek (fd
, - (1024 * 3), SEEK_END
) < 0)
3690 report_file_error ("Setting file position",
3692 ntail
= emacs_read (fd
, read_buf
+ nread
, 1024 * 3);
3693 nread
= ntail
< 0 ? ntail
: nread
+ ntail
;
3698 report_file_error ("Read error", orig_filename
);
3701 struct buffer
*prev
= current_buffer
;
3702 Lisp_Object workbuf
;
3705 record_unwind_current_buffer ();
3707 workbuf
= Fget_buffer_create (build_string (" *code-converting-work*"));
3708 buf
= XBUFFER (workbuf
);
3710 delete_all_overlays (buf
);
3711 bset_directory (buf
, BVAR (current_buffer
, directory
));
3712 bset_read_only (buf
, Qnil
);
3713 bset_filename (buf
, Qnil
);
3714 bset_undo_list (buf
, Qt
);
3715 eassert (buf
->overlays_before
== NULL
);
3716 eassert (buf
->overlays_after
== NULL
);
3718 set_buffer_internal (buf
);
3720 bset_enable_multibyte_characters (buf
, Qnil
);
3722 insert_1_both ((char *) read_buf
, nread
, nread
, 0, 0, 0);
3723 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3724 coding_system
= call2 (Vset_auto_coding_function
,
3725 filename
, make_number (nread
));
3726 set_buffer_internal (prev
);
3728 /* Discard the unwind protect for recovering the
3732 /* Rewind the file for the actual read done later. */
3733 if (lseek (fd
, 0, SEEK_SET
) < 0)
3734 report_file_error ("Setting file position", orig_filename
);
3738 if (NILP (coding_system
))
3740 /* If we have not yet decided a coding system, check
3741 file-coding-system-alist. */
3742 Lisp_Object args
[6];
3744 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
3745 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = replace
;
3746 coding_system
= Ffind_operation_coding_system (6, args
);
3747 if (CONSP (coding_system
))
3748 coding_system
= XCAR (coding_system
);
3752 if (NILP (coding_system
))
3753 coding_system
= Qundecided
;
3755 CHECK_CODING_SYSTEM (coding_system
);
3757 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3758 /* We must suppress all character code conversion except for
3759 end-of-line conversion. */
3760 coding_system
= raw_text_coding_system (coding_system
);
3762 setup_coding_system (coding_system
, &coding
);
3763 /* Ensure we set Vlast_coding_system_used. */
3764 set_coding_system
= 1;
3767 /* If requested, replace the accessible part of the buffer
3768 with the file contents. Avoid replacing text at the
3769 beginning or end of the buffer that matches the file contents;
3770 that preserves markers pointing to the unchanged parts.
3772 Here we implement this feature in an optimized way
3773 for the case where code conversion is NOT needed.
3774 The following if-statement handles the case of conversion
3775 in a less optimal way.
3777 If the code conversion is "automatic" then we try using this
3778 method and hope for the best.
3779 But if we discover the need for conversion, we give up on this method
3780 and let the following if-statement handle the replace job. */
3783 && (NILP (coding_system
)
3784 || ! CODING_REQUIRE_DECODING (&coding
)))
3786 /* same_at_start and same_at_end count bytes,
3787 because file access counts bytes
3788 and BEG and END count bytes. */
3789 ptrdiff_t same_at_start
= BEGV_BYTE
;
3790 ptrdiff_t same_at_end
= ZV_BYTE
;
3792 /* There is still a possibility we will find the need to do code
3793 conversion. If that happens, set this variable to
3794 give up on handling REPLACE in the optimized way. */
3795 bool giveup_match_end
= 0;
3797 if (beg_offset
!= 0)
3799 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3800 report_file_error ("Setting file position", orig_filename
);
3805 /* Count how many chars at the start of the file
3806 match the text at the beginning of the buffer. */
3811 nread
= emacs_read (fd
, read_buf
, sizeof read_buf
);
3813 report_file_error ("Read error", orig_filename
);
3814 else if (nread
== 0)
3817 if (CODING_REQUIRE_DETECTION (&coding
))
3819 coding_system
= detect_coding_system ((unsigned char *) read_buf
,
3822 setup_coding_system (coding_system
, &coding
);
3825 if (CODING_REQUIRE_DECODING (&coding
))
3826 /* We found that the file should be decoded somehow.
3827 Let's give up here. */
3829 giveup_match_end
= 1;
3834 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3835 && FETCH_BYTE (same_at_start
) == read_buf
[bufpos
])
3836 same_at_start
++, bufpos
++;
3837 /* If we found a discrepancy, stop the scan.
3838 Otherwise loop around and scan the next bufferful. */
3839 if (bufpos
!= nread
)
3843 /* If the file matches the buffer completely,
3844 there's no need to replace anything. */
3845 if (same_at_start
- BEGV_BYTE
== end_offset
- beg_offset
)
3849 /* Truncate the buffer to the size of the file. */
3850 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3855 /* Count how many chars at the end of the file
3856 match the text at the end of the buffer. But, if we have
3857 already found that decoding is necessary, don't waste time. */
3858 while (!giveup_match_end
)
3860 int total_read
, nread
, bufpos
, trial
;
3863 /* At what file position are we now scanning? */
3864 curpos
= end_offset
- (ZV_BYTE
- same_at_end
);
3865 /* If the entire file matches the buffer tail, stop the scan. */
3868 /* How much can we scan in the next step? */
3869 trial
= min (curpos
, sizeof read_buf
);
3870 if (lseek (fd
, curpos
- trial
, SEEK_SET
) < 0)
3871 report_file_error ("Setting file position", orig_filename
);
3873 total_read
= nread
= 0;
3874 while (total_read
< trial
)
3876 nread
= emacs_read (fd
, read_buf
+ total_read
, trial
- total_read
);
3878 report_file_error ("Read error", orig_filename
);
3879 else if (nread
== 0)
3881 total_read
+= nread
;
3884 /* Scan this bufferful from the end, comparing with
3885 the Emacs buffer. */
3886 bufpos
= total_read
;
3888 /* Compare with same_at_start to avoid counting some buffer text
3889 as matching both at the file's beginning and at the end. */
3890 while (bufpos
> 0 && same_at_end
> same_at_start
3891 && FETCH_BYTE (same_at_end
- 1) == read_buf
[bufpos
- 1])
3892 same_at_end
--, bufpos
--;
3894 /* If we found a discrepancy, stop the scan.
3895 Otherwise loop around and scan the preceding bufferful. */
3898 /* If this discrepancy is because of code conversion,
3899 we cannot use this method; giveup and try the other. */
3900 if (same_at_end
> same_at_start
3901 && FETCH_BYTE (same_at_end
- 1) >= 0200
3902 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
))
3903 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3904 giveup_match_end
= 1;
3913 if (! giveup_match_end
)
3917 /* We win! We can handle REPLACE the optimized way. */
3919 /* Extend the start of non-matching text area to multibyte
3920 character boundary. */
3921 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3922 while (same_at_start
> BEGV_BYTE
3923 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3926 /* Extend the end of non-matching text area to multibyte
3927 character boundary. */
3928 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3929 while (same_at_end
< ZV_BYTE
3930 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3933 /* Don't try to reuse the same piece of text twice. */
3934 overlap
= (same_at_start
- BEGV_BYTE
3936 + (! NILP (end
) ? end_offset
: st
.st_size
) - ZV_BYTE
));
3938 same_at_end
+= overlap
;
3940 /* Arrange to read only the nonmatching middle part of the file. */
3941 beg_offset
+= same_at_start
- BEGV_BYTE
;
3942 end_offset
-= ZV_BYTE
- same_at_end
;
3944 del_range_byte (same_at_start
, same_at_end
, 0);
3945 /* Insert from the file at the proper position. */
3946 temp
= BYTE_TO_CHAR (same_at_start
);
3947 SET_PT_BOTH (temp
, same_at_start
);
3949 /* If display currently starts at beginning of line,
3950 keep it that way. */
3951 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
3952 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
3954 replace_handled
= 1;
3958 /* If requested, replace the accessible part of the buffer
3959 with the file contents. Avoid replacing text at the
3960 beginning or end of the buffer that matches the file contents;
3961 that preserves markers pointing to the unchanged parts.
3963 Here we implement this feature for the case where code conversion
3964 is needed, in a simple way that needs a lot of memory.
3965 The preceding if-statement handles the case of no conversion
3966 in a more optimized way. */
3967 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
3969 ptrdiff_t same_at_start
= BEGV_BYTE
;
3970 ptrdiff_t same_at_end
= ZV_BYTE
;
3971 ptrdiff_t same_at_start_charpos
;
3972 ptrdiff_t inserted_chars
;
3975 unsigned char *decoded
;
3978 ptrdiff_t this_count
= SPECPDL_INDEX ();
3980 = ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3981 Lisp_Object conversion_buffer
;
3982 struct gcpro gcpro1
;
3984 conversion_buffer
= code_conversion_save (1, multibyte
);
3986 /* First read the whole file, performing code conversion into
3987 CONVERSION_BUFFER. */
3989 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3990 report_file_error ("Setting file position", orig_filename
);
3992 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
3993 unprocessed
= 0; /* Bytes not processed in previous loop. */
3995 GCPRO1 (conversion_buffer
);
3998 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3999 quitting while reading a huge file. */
4001 /* Allow quitting out of the actual I/O. */
4004 this = emacs_read (fd
, read_buf
+ unprocessed
,
4005 READ_BUF_SIZE
- unprocessed
);
4011 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer
),
4012 BUF_Z (XBUFFER (conversion_buffer
)));
4013 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
4014 unprocessed
+ this, conversion_buffer
);
4015 unprocessed
= coding
.carryover_bytes
;
4016 if (coding
.carryover_bytes
> 0)
4017 memcpy (read_buf
, coding
.carryover
, unprocessed
);
4021 report_file_error ("Read error", orig_filename
);
4023 set_unwind_protect_int (fd_index
, -1);
4025 if (unprocessed
> 0)
4027 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4028 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
4029 unprocessed
, conversion_buffer
);
4030 coding
.mode
&= ~CODING_MODE_LAST_BLOCK
;
4033 coding_system
= CODING_ID_NAME (coding
.id
);
4034 set_coding_system
= 1;
4035 decoded
= BUF_BEG_ADDR (XBUFFER (conversion_buffer
));
4036 inserted
= (BUF_Z_BYTE (XBUFFER (conversion_buffer
))
4037 - BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4039 /* Compare the beginning of the converted string with the buffer
4043 while (bufpos
< inserted
&& same_at_start
< same_at_end
4044 && FETCH_BYTE (same_at_start
) == decoded
[bufpos
])
4045 same_at_start
++, bufpos
++;
4047 /* If the file matches the head of buffer completely,
4048 there's no need to replace anything. */
4050 if (bufpos
== inserted
)
4052 /* Truncate the buffer to the size of the file. */
4053 if (same_at_start
!= same_at_end
)
4054 del_range_byte (same_at_start
, same_at_end
, 0);
4057 unbind_to (this_count
, Qnil
);
4061 /* Extend the start of non-matching text area to the previous
4062 multibyte character boundary. */
4063 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4064 while (same_at_start
> BEGV_BYTE
4065 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
4068 /* Scan this bufferful from the end, comparing with
4069 the Emacs buffer. */
4072 /* Compare with same_at_start to avoid counting some buffer text
4073 as matching both at the file's beginning and at the end. */
4074 while (bufpos
> 0 && same_at_end
> same_at_start
4075 && FETCH_BYTE (same_at_end
- 1) == decoded
[bufpos
- 1])
4076 same_at_end
--, bufpos
--;
4078 /* Extend the end of non-matching text area to the next
4079 multibyte character boundary. */
4080 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4081 while (same_at_end
< ZV_BYTE
4082 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
4085 /* Don't try to reuse the same piece of text twice. */
4086 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
4088 same_at_end
+= overlap
;
4090 /* If display currently starts at beginning of line,
4091 keep it that way. */
4092 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
4093 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
4095 /* Replace the chars that we need to replace,
4096 and update INSERTED to equal the number of bytes
4097 we are taking from the decoded string. */
4098 inserted
-= (ZV_BYTE
- same_at_end
) + (same_at_start
- BEGV_BYTE
);
4100 if (same_at_end
!= same_at_start
)
4102 del_range_byte (same_at_start
, same_at_end
, 0);
4104 eassert (same_at_start
== GPT_BYTE
);
4105 same_at_start
= GPT_BYTE
;
4109 temp
= BYTE_TO_CHAR (same_at_start
);
4111 /* Insert from the file at the proper position. */
4112 SET_PT_BOTH (temp
, same_at_start
);
4113 same_at_start_charpos
4114 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4115 same_at_start
- BEGV_BYTE
4116 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4117 eassert (same_at_start_charpos
== temp
- (BEGV
- BEG
));
4119 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4120 same_at_start
+ inserted
- BEGV_BYTE
4121 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)))
4122 - same_at_start_charpos
);
4123 /* This binding is to avoid ask-user-about-supersession-threat
4124 being called in insert_from_buffer (via in
4125 prepare_to_modify_buffer). */
4126 specbind (intern ("buffer-file-name"), Qnil
);
4127 insert_from_buffer (XBUFFER (conversion_buffer
),
4128 same_at_start_charpos
, inserted_chars
, 0);
4129 /* Set `inserted' to the number of inserted characters. */
4130 inserted
= PT
- temp
;
4131 /* Set point before the inserted characters. */
4132 SET_PT_BOTH (temp
, same_at_start
);
4134 unbind_to (this_count
, Qnil
);
4140 total
= end_offset
- beg_offset
;
4142 /* For a special file, all we can do is guess. */
4143 total
= READ_BUF_SIZE
;
4145 if (NILP (visit
) && total
> 0)
4147 #ifdef CLASH_DETECTION
4148 if (!NILP (BVAR (current_buffer
, file_truename
))
4149 /* Make binding buffer-file-name to nil effective. */
4150 && !NILP (BVAR (current_buffer
, filename
))
4151 && SAVE_MODIFF
>= MODIFF
)
4153 #endif /* CLASH_DETECTION */
4154 prepare_to_modify_buffer (GPT
, GPT
, NULL
);
4157 move_gap_both (PT
, PT_BYTE
);
4158 if (GAP_SIZE
< total
)
4159 make_gap (total
- GAP_SIZE
);
4161 if (beg_offset
!= 0 || !NILP (replace
))
4163 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
4164 report_file_error ("Setting file position", orig_filename
);
4167 /* In the following loop, HOW_MUCH contains the total bytes read so
4168 far for a regular file, and not changed for a special file. But,
4169 before exiting the loop, it is set to a negative value if I/O
4173 /* Total bytes inserted. */
4176 /* Here, we don't do code conversion in the loop. It is done by
4177 decode_coding_gap after all data are read into the buffer. */
4179 ptrdiff_t gap_size
= GAP_SIZE
;
4181 while (how_much
< total
)
4183 /* try is reserved in some compilers (Microsoft C) */
4184 ptrdiff_t trytry
= min (total
- how_much
, READ_BUF_SIZE
);
4191 /* Maybe make more room. */
4192 if (gap_size
< trytry
)
4194 make_gap (trytry
- gap_size
);
4195 gap_size
= GAP_SIZE
- inserted
;
4198 /* Read from the file, capturing `quit'. When an
4199 error occurs, end the loop, and arrange for a quit
4200 to be signaled after decoding the text we read. */
4201 nbytes
= internal_condition_case_1
4203 make_save_value (SAVE_TYPE_INT_INT_INT
, (ptrdiff_t) fd
,
4205 Qerror
, read_non_regular_quit
);
4213 this = XINT (nbytes
);
4217 /* Allow quitting out of the actual I/O. We don't make text
4218 part of the buffer until all the reading is done, so a C-g
4219 here doesn't do any harm. */
4222 this = emacs_read (fd
,
4223 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
4237 /* For a regular file, where TOTAL is the real size,
4238 count HOW_MUCH to compare with it.
4239 For a special file, where TOTAL is just a buffer size,
4240 so don't bother counting in HOW_MUCH.
4241 (INSERTED is where we count the number of characters inserted.) */
4248 /* Now we have either read all the file data into the gap,
4249 or stop reading on I/O error or quit. If nothing was
4250 read, undo marking the buffer modified. */
4254 #ifdef CLASH_DETECTION
4256 unlock_file (BVAR (current_buffer
, file_truename
));
4258 Vdeactivate_mark
= old_Vdeactivate_mark
;
4261 Vdeactivate_mark
= Qt
;
4264 set_unwind_protect_int (fd_index
, -1);
4267 report_file_error ("Read error", orig_filename
);
4269 /* Make the text read part of the buffer. */
4270 GAP_SIZE
-= inserted
;
4272 GPT_BYTE
+= inserted
;
4274 ZV_BYTE
+= inserted
;
4279 /* Put an anchor to ensure multi-byte form ends at gap. */
4284 if (NILP (coding_system
))
4286 /* The coding system is not yet decided. Decide it by an
4287 optimized method for handling `coding:' tag.
4289 Note that we can get here only if the buffer was empty
4290 before the insertion. */
4292 if (!NILP (Vcoding_system_for_read
))
4293 coding_system
= Vcoding_system_for_read
;
4296 /* Since we are sure that the current buffer was empty
4297 before the insertion, we can toggle
4298 enable-multibyte-characters directly here without taking
4299 care of marker adjustment. By this way, we can run Lisp
4300 program safely before decoding the inserted text. */
4301 Lisp_Object unwind_data
;
4302 ptrdiff_t count1
= SPECPDL_INDEX ();
4304 unwind_data
= Fcons (BVAR (current_buffer
, enable_multibyte_characters
),
4305 Fcons (BVAR (current_buffer
, undo_list
),
4306 Fcurrent_buffer ()));
4307 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4308 bset_undo_list (current_buffer
, Qt
);
4309 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4311 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4313 coding_system
= call2 (Vset_auto_coding_function
,
4314 filename
, make_number (inserted
));
4317 if (NILP (coding_system
))
4319 /* If the coding system is not yet decided, check
4320 file-coding-system-alist. */
4321 Lisp_Object args
[6];
4323 args
[0] = Qinsert_file_contents
, args
[1] = orig_filename
;
4324 args
[2] = visit
, args
[3] = beg
, args
[4] = end
, args
[5] = Qnil
;
4325 coding_system
= Ffind_operation_coding_system (6, args
);
4326 if (CONSP (coding_system
))
4327 coding_system
= XCAR (coding_system
);
4329 unbind_to (count1
, Qnil
);
4330 inserted
= Z_BYTE
- BEG_BYTE
;
4333 if (NILP (coding_system
))
4334 coding_system
= Qundecided
;
4336 CHECK_CODING_SYSTEM (coding_system
);
4338 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4339 /* We must suppress all character code conversion except for
4340 end-of-line conversion. */
4341 coding_system
= raw_text_coding_system (coding_system
);
4342 setup_coding_system (coding_system
, &coding
);
4343 /* Ensure we set Vlast_coding_system_used. */
4344 set_coding_system
= 1;
4349 /* When we visit a file by raw-text, we change the buffer to
4351 if (CODING_FOR_UNIBYTE (&coding
)
4352 /* Can't do this if part of the buffer might be preserved. */
4354 /* Visiting a file with these coding system makes the buffer
4356 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4359 coding
.dst_multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
4360 if (CODING_MAY_REQUIRE_DECODING (&coding
)
4361 && (inserted
> 0 || CODING_REQUIRE_FLUSHING (&coding
)))
4363 move_gap_both (PT
, PT_BYTE
);
4364 GAP_SIZE
+= inserted
;
4365 ZV_BYTE
-= inserted
;
4369 decode_coding_gap (&coding
, inserted
, inserted
);
4370 inserted
= coding
.produced_char
;
4371 coding_system
= CODING_ID_NAME (coding
.id
);
4373 else if (inserted
> 0)
4374 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4377 /* Call after-change hooks for the inserted text, aside from the case
4378 of normal visiting (not with REPLACE), which is done in a new buffer
4379 "before" the buffer is changed. */
4380 if (inserted
> 0 && total
> 0
4381 && (NILP (visit
) || !NILP (replace
)))
4383 signal_after_change (PT
, 0, inserted
);
4384 update_compositions (PT
, PT
, CHECK_BORDER
);
4387 /* Now INSERTED is measured in characters. */
4393 if (empty_undo_list_p
)
4394 bset_undo_list (current_buffer
, Qnil
);
4398 current_buffer
->modtime
= mtime
;
4399 current_buffer
->modtime_size
= st
.st_size
;
4400 bset_filename (current_buffer
, orig_filename
);
4403 SAVE_MODIFF
= MODIFF
;
4404 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
4405 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4406 #ifdef CLASH_DETECTION
4409 if (!NILP (BVAR (current_buffer
, file_truename
)))
4410 unlock_file (BVAR (current_buffer
, file_truename
));
4411 unlock_file (filename
);
4413 #endif /* CLASH_DETECTION */
4415 xsignal2 (Qfile_error
,
4416 build_string ("not a regular file"), orig_filename
);
4419 if (set_coding_system
)
4420 Vlast_coding_system_used
= coding_system
;
4422 if (! NILP (Ffboundp (Qafter_insert_file_set_coding
)))
4424 insval
= call2 (Qafter_insert_file_set_coding
, make_number (inserted
),
4426 if (! NILP (insval
))
4428 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4429 wrong_type_argument (intern ("inserted-chars"), insval
);
4430 inserted
= XFASTINT (insval
);
4434 /* Decode file format. */
4437 /* Don't run point motion or modification hooks when decoding. */
4438 ptrdiff_t count1
= SPECPDL_INDEX ();
4439 ptrdiff_t old_inserted
= inserted
;
4440 specbind (Qinhibit_point_motion_hooks
, Qt
);
4441 specbind (Qinhibit_modification_hooks
, Qt
);
4443 /* Save old undo list and don't record undo for decoding. */
4444 old_undo
= BVAR (current_buffer
, undo_list
);
4445 bset_undo_list (current_buffer
, Qt
);
4449 insval
= call3 (Qformat_decode
,
4450 Qnil
, make_number (inserted
), visit
);
4451 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4452 wrong_type_argument (intern ("inserted-chars"), insval
);
4453 inserted
= XFASTINT (insval
);
4457 /* If REPLACE is non-nil and we succeeded in not replacing the
4458 beginning or end of the buffer text with the file's contents,
4459 call format-decode with `point' positioned at the beginning
4460 of the buffer and `inserted' equaling the number of
4461 characters in the buffer. Otherwise, format-decode might
4462 fail to correctly analyze the beginning or end of the buffer.
4463 Hence we temporarily save `point' and `inserted' here and
4464 restore `point' iff format-decode did not insert or delete
4465 any text. Otherwise we leave `point' at point-min. */
4466 ptrdiff_t opoint
= PT
;
4467 ptrdiff_t opoint_byte
= PT_BYTE
;
4468 ptrdiff_t oinserted
= ZV
- BEGV
;
4469 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4471 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4472 insval
= call3 (Qformat_decode
,
4473 Qnil
, make_number (oinserted
), visit
);
4474 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4475 wrong_type_argument (intern ("inserted-chars"), insval
);
4476 if (ochars_modiff
== CHARS_MODIFF
)
4477 /* format_decode didn't modify buffer's characters => move
4478 point back to position before inserted text and leave
4479 value of inserted alone. */
4480 SET_PT_BOTH (opoint
, opoint_byte
);
4482 /* format_decode modified buffer's characters => consider
4483 entire buffer changed and leave point at point-min. */
4484 inserted
= XFASTINT (insval
);
4487 /* For consistency with format-decode call these now iff inserted > 0
4488 (martin 2007-06-28). */
4489 p
= Vafter_insert_file_functions
;
4494 insval
= call1 (XCAR (p
), make_number (inserted
));
4497 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4498 wrong_type_argument (intern ("inserted-chars"), insval
);
4499 inserted
= XFASTINT (insval
);
4504 /* For the rationale of this see the comment on
4505 format-decode above. */
4506 ptrdiff_t opoint
= PT
;
4507 ptrdiff_t opoint_byte
= PT_BYTE
;
4508 ptrdiff_t oinserted
= ZV
- BEGV
;
4509 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4511 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4512 insval
= call1 (XCAR (p
), make_number (oinserted
));
4515 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4516 wrong_type_argument (intern ("inserted-chars"), insval
);
4517 if (ochars_modiff
== CHARS_MODIFF
)
4518 /* after_insert_file_functions didn't modify
4519 buffer's characters => move point back to
4520 position before inserted text and leave value of
4522 SET_PT_BOTH (opoint
, opoint_byte
);
4524 /* after_insert_file_functions did modify buffer's
4525 characters => consider entire buffer changed and
4526 leave point at point-min. */
4527 inserted
= XFASTINT (insval
);
4535 if (!empty_undo_list_p
)
4537 bset_undo_list (current_buffer
, old_undo
);
4538 if (CONSP (old_undo
) && inserted
!= old_inserted
)
4540 /* Adjust the last undo record for the size change during
4541 the format conversion. */
4542 Lisp_Object tem
= XCAR (old_undo
);
4543 if (CONSP (tem
) && INTEGERP (XCAR (tem
))
4544 && INTEGERP (XCDR (tem
))
4545 && XFASTINT (XCDR (tem
)) == PT
+ old_inserted
)
4546 XSETCDR (tem
, make_number (PT
+ inserted
));
4550 /* If undo_list was Qt before, keep it that way.
4551 Otherwise start with an empty undo_list. */
4552 bset_undo_list (current_buffer
, EQ (old_undo
, Qt
) ? Qt
: Qnil
);
4554 unbind_to (count1
, Qnil
);
4558 && EMACS_NSECS (current_buffer
->modtime
) == NONEXISTENT_MODTIME_NSECS
)
4560 /* If visiting nonexistent file, return nil. */
4561 report_file_errno ("Opening input file", orig_filename
, save_errno
);
4565 Fsignal (Qquit
, Qnil
);
4567 /* Retval needs to be dealt with in all cases consistently. */
4569 val
= list2 (orig_filename
, make_number (inserted
));
4571 RETURN_UNGCPRO (unbind_to (count
, val
));
4574 static Lisp_Object
build_annotations (Lisp_Object
, Lisp_Object
);
4577 build_annotations_unwind (Lisp_Object arg
)
4579 Vwrite_region_annotation_buffers
= arg
;
4582 /* Decide the coding-system to encode the data with. */
4584 DEFUN ("choose-write-coding-system", Fchoose_write_coding_system
,
4585 Schoose_write_coding_system
, 3, 6, 0,
4586 doc
: /* Choose the coding system for writing a file.
4587 Arguments are as for `write-region'.
4588 This function is for internal use only. It may prompt the user. */ )
4589 (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4590 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
)
4593 Lisp_Object eol_parent
= Qnil
;
4595 /* Mimic write-region behavior. */
4598 XSETFASTINT (start
, BEGV
);
4599 XSETFASTINT (end
, ZV
);
4603 && NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4604 BVAR (current_buffer
, auto_save_file_name
))))
4609 else if (!NILP (Vcoding_system_for_write
))
4611 val
= Vcoding_system_for_write
;
4612 if (coding_system_require_warning
4613 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4614 /* Confirm that VAL can surely encode the current region. */
4615 val
= call5 (Vselect_safe_coding_system_function
,
4616 start
, end
, list2 (Qt
, val
),
4621 /* If the variable `buffer-file-coding-system' is set locally,
4622 it means that the file was read with some kind of code
4623 conversion or the variable is explicitly set by users. We
4624 had better write it out with the same coding system even if
4625 `enable-multibyte-characters' is nil.
4627 If it is not set locally, we anyway have to convert EOL
4628 format if the default value of `buffer-file-coding-system'
4629 tells that it is not Unix-like (LF only) format. */
4630 bool using_default_coding
= 0;
4631 bool force_raw_text
= 0;
4633 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4635 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4638 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4644 /* Check file-coding-system-alist. */
4645 Lisp_Object args
[7], coding_systems
;
4647 args
[0] = Qwrite_region
; args
[1] = start
; args
[2] = end
;
4648 args
[3] = filename
; args
[4] = append
; args
[5] = visit
;
4650 coding_systems
= Ffind_operation_coding_system (7, args
);
4651 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4652 val
= XCDR (coding_systems
);
4657 /* If we still have not decided a coding system, use the
4658 default value of buffer-file-coding-system. */
4659 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4660 using_default_coding
= 1;
4663 if (! NILP (val
) && ! force_raw_text
)
4665 Lisp_Object spec
, attrs
;
4667 CHECK_CODING_SYSTEM_GET_SPEC (val
, spec
);
4668 attrs
= AREF (spec
, 0);
4669 if (EQ (CODING_ATTR_TYPE (attrs
), Qraw_text
))
4674 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4675 /* Confirm that VAL can surely encode the current region. */
4676 val
= call5 (Vselect_safe_coding_system_function
,
4677 start
, end
, val
, Qnil
, filename
);
4679 /* If the decided coding-system doesn't specify end-of-line
4680 format, we use that of
4681 `default-buffer-file-coding-system'. */
4682 if (! using_default_coding
4683 && ! NILP (BVAR (&buffer_defaults
, buffer_file_coding_system
)))
4684 val
= (coding_inherit_eol_type
4685 (val
, BVAR (&buffer_defaults
, buffer_file_coding_system
)));
4687 /* If we decide not to encode text, use `raw-text' or one of its
4690 val
= raw_text_coding_system (val
);
4693 val
= coding_inherit_eol_type (val
, eol_parent
);
4697 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4698 "r\nFWrite region to file: \ni\ni\ni\np",
4699 doc
: /* Write current region into specified file.
4700 When called from a program, requires three arguments:
4701 START, END and FILENAME. START and END are normally buffer positions
4702 specifying the part of the buffer to write.
4703 If START is nil, that means to use the entire buffer contents.
4704 If START is a string, then output that string to the file
4705 instead of any buffer contents; END is ignored.
4707 Optional fourth argument APPEND if non-nil means
4708 append to existing file contents (if any). If it is a number,
4709 seek to that offset in the file before writing.
4710 Optional fifth argument VISIT, if t or a string, means
4711 set the last-save-file-modtime of buffer to this file's modtime
4712 and mark buffer not modified.
4713 If VISIT is a string, it is a second file name;
4714 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4715 VISIT is also the file name to lock and unlock for clash detection.
4716 If VISIT is neither t nor nil nor a string,
4717 that means do not display the \"Wrote file\" message.
4718 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4719 use for locking and unlocking, overriding FILENAME and VISIT.
4720 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4721 for an existing file with the same name. If MUSTBENEW is `excl',
4722 that means to get an error if the file already exists; never overwrite.
4723 If MUSTBENEW is neither nil nor `excl', that means ask for
4724 confirmation before overwriting, but do go ahead and overwrite the file
4725 if the user confirms.
4727 This does code conversion according to the value of
4728 `coding-system-for-write', `buffer-file-coding-system', or
4729 `file-coding-system-alist', and sets the variable
4730 `last-coding-system-used' to the coding system actually used.
4732 This calls `write-region-annotate-functions' at the start, and
4733 `write-region-post-annotation-function' at the end. */)
4734 (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
, Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
, Lisp_Object mustbenew
)
4739 off_t offset
IF_LINT (= 0);
4745 ptrdiff_t count
= SPECPDL_INDEX ();
4747 Lisp_Object handler
;
4748 Lisp_Object visit_file
;
4749 Lisp_Object annotations
;
4750 Lisp_Object encoded_filename
;
4751 bool visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4752 bool quietly
= !NILP (visit
);
4753 struct gcpro gcpro1
, gcpro2
, gcpro3
, gcpro4
, gcpro5
;
4754 struct buffer
*given_buffer
;
4755 struct coding_system coding
;
4757 if (current_buffer
->base_buffer
&& visiting
)
4758 error ("Cannot do file visiting in an indirect buffer");
4760 if (!NILP (start
) && !STRINGP (start
))
4761 validate_region (&start
, &end
);
4764 GCPRO5 (start
, filename
, visit
, visit_file
, lockname
);
4766 filename
= Fexpand_file_name (filename
, Qnil
);
4768 if (!NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4769 barf_or_query_if_file_exists (filename
, "overwrite", 1, 0, 1);
4771 if (STRINGP (visit
))
4772 visit_file
= Fexpand_file_name (visit
, Qnil
);
4774 visit_file
= filename
;
4776 if (NILP (lockname
))
4777 lockname
= visit_file
;
4781 /* If the file name has special constructs in it,
4782 call the corresponding file handler. */
4783 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4784 /* If FILENAME has no handler, see if VISIT has one. */
4785 if (NILP (handler
) && STRINGP (visit
))
4786 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4788 if (!NILP (handler
))
4791 val
= call6 (handler
, Qwrite_region
, start
, end
,
4792 filename
, append
, visit
);
4796 SAVE_MODIFF
= MODIFF
;
4797 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4798 bset_filename (current_buffer
, visit_file
);
4804 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
4806 /* Special kludge to simplify auto-saving. */
4809 /* Do it later, so write-region-annotate-function can work differently
4810 if we save "the buffer" vs "a region".
4811 This is useful in tar-mode. --Stef
4812 XSETFASTINT (start, BEG);
4813 XSETFASTINT (end, Z); */
4817 record_unwind_protect (build_annotations_unwind
,
4818 Vwrite_region_annotation_buffers
);
4819 Vwrite_region_annotation_buffers
= list1 (Fcurrent_buffer ());
4820 count1
= SPECPDL_INDEX ();
4822 given_buffer
= current_buffer
;
4824 if (!STRINGP (start
))
4826 annotations
= build_annotations (start
, end
);
4828 if (current_buffer
!= given_buffer
)
4830 XSETFASTINT (start
, BEGV
);
4831 XSETFASTINT (end
, ZV
);
4837 XSETFASTINT (start
, BEGV
);
4838 XSETFASTINT (end
, ZV
);
4843 GCPRO5 (start
, filename
, annotations
, visit_file
, lockname
);
4845 /* Decide the coding-system to encode the data with.
4846 We used to make this choice before calling build_annotations, but that
4847 leads to problems when a write-annotate-function takes care of
4848 unsavable chars (as was the case with X-Symbol). */
4849 Vlast_coding_system_used
=
4850 Fchoose_write_coding_system (start
, end
, filename
,
4851 append
, visit
, lockname
);
4853 setup_coding_system (Vlast_coding_system_used
, &coding
);
4855 if (!STRINGP (start
) && !NILP (BVAR (current_buffer
, selective_display
)))
4856 coding
.mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4858 #ifdef CLASH_DETECTION
4860 lock_file (lockname
);
4861 #endif /* CLASH_DETECTION */
4863 encoded_filename
= ENCODE_FILE (filename
);
4864 fn
= SSDATA (encoded_filename
);
4865 open_flags
= O_WRONLY
| O_BINARY
| O_CREAT
;
4866 open_flags
|= EQ (mustbenew
, Qexcl
) ? O_EXCL
: !NILP (append
) ? 0 : O_TRUNC
;
4867 if (NUMBERP (append
))
4868 offset
= file_offset (append
);
4869 else if (!NILP (append
))
4870 open_flags
|= O_APPEND
;
4872 mode
= S_IREAD
| S_IWRITE
;
4874 mode
= auto_saving
? auto_save_mode_bits
: 0666;
4877 desc
= emacs_open (fn
, open_flags
, mode
);
4881 int open_errno
= errno
;
4882 #ifdef CLASH_DETECTION
4883 if (!auto_saving
) unlock_file (lockname
);
4884 #endif /* CLASH_DETECTION */
4886 report_file_errno ("Opening output file", filename
, open_errno
);
4889 record_unwind_protect_int (close_file_unwind
, desc
);
4891 if (NUMBERP (append
))
4893 off_t ret
= lseek (desc
, offset
, SEEK_SET
);
4896 int lseek_errno
= errno
;
4897 #ifdef CLASH_DETECTION
4898 if (!auto_saving
) unlock_file (lockname
);
4899 #endif /* CLASH_DETECTION */
4901 report_file_errno ("Lseek error", filename
, lseek_errno
);
4909 if (STRINGP (start
))
4910 ok
= a_write (desc
, start
, 0, SCHARS (start
), &annotations
, &coding
);
4911 else if (XINT (start
) != XINT (end
))
4912 ok
= a_write (desc
, Qnil
, XINT (start
), XINT (end
) - XINT (start
),
4913 &annotations
, &coding
);
4916 /* If file was empty, still need to write the annotations. */
4917 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4918 ok
= a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4922 if (ok
&& CODING_REQUIRE_FLUSHING (&coding
)
4923 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
))
4925 /* We have to flush out a data. */
4926 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4927 ok
= e_write (desc
, Qnil
, 1, 1, &coding
);
4933 /* fsync is not crucial for auto-save files, since they might lose
4934 some work anyway. */
4935 if (!auto_saving
&& !write_region_inhibit_fsync
)
4937 /* Transfer data and metadata to disk, retrying if interrupted.
4938 fsync can report a write failure here, e.g., due to disk full
4939 under NFS. But ignore EINVAL, which means fsync is not
4940 supported on this file. */
4941 while (fsync (desc
) != 0)
4944 if (errno
!= EINVAL
)
4945 ok
= 0, save_errno
= errno
;
4950 modtime
= invalid_emacs_time ();
4953 if (fstat (desc
, &st
) == 0)
4954 modtime
= get_stat_mtime (&st
);
4956 ok
= 0, save_errno
= errno
;
4959 /* NFS can report a write failure now. */
4960 if (emacs_close (desc
) < 0)
4961 ok
= 0, save_errno
= errno
;
4963 /* Discard the unwind protect for close_file_unwind. */
4964 specpdl_ptr
= specpdl
+ count1
;
4966 /* Some file systems have a bug where st_mtime is not updated
4967 properly after a write. For example, CIFS might not see the
4968 st_mtime change until after the file is opened again.
4970 Attempt to detect this file system bug, and update MODTIME to the
4971 newer st_mtime if the bug appears to be present. This introduces
4972 a race condition, so to avoid most instances of the race condition
4973 on non-buggy file systems, skip this check if the most recently
4974 encountered non-buggy file system was the current file system.
4976 A race condition can occur if some other process modifies the
4977 file between the fstat above and the fstat below, but the race is
4978 unlikely and a similar race between the last write and the fstat
4979 above cannot possibly be closed anyway. */
4981 if (EMACS_TIME_VALID_P (modtime
)
4982 && ! (valid_timestamp_file_system
&& st
.st_dev
== timestamp_file_system
))
4984 int desc1
= emacs_open (fn
, O_WRONLY
| O_BINARY
, 0);
4988 if (fstat (desc1
, &st1
) == 0
4989 && st
.st_dev
== st1
.st_dev
&& st
.st_ino
== st1
.st_ino
)
4991 /* Use the heuristic if it appears to be valid. With neither
4992 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4993 file, the time stamp won't change. Also, some non-POSIX
4994 systems don't update an empty file's time stamp when
4995 truncating it. Finally, file systems with 100 ns or worse
4996 resolution sometimes seem to have bugs: on a system with ns
4997 resolution, checking ns % 100 incorrectly avoids the heuristic
4998 1% of the time, but the problem should be temporary as we will
4999 try again on the next time stamp. */
5001 = ((open_flags
& (O_EXCL
| O_TRUNC
)) != 0
5003 && EMACS_NSECS (modtime
) % 100 != 0);
5005 EMACS_TIME modtime1
= get_stat_mtime (&st1
);
5007 && EMACS_TIME_EQ (modtime
, modtime1
)
5008 && st
.st_size
== st1
.st_size
)
5010 timestamp_file_system
= st
.st_dev
;
5011 valid_timestamp_file_system
= 1;
5015 st
.st_size
= st1
.st_size
;
5019 emacs_close (desc1
);
5023 /* Call write-region-post-annotation-function. */
5024 while (CONSP (Vwrite_region_annotation_buffers
))
5026 Lisp_Object buf
= XCAR (Vwrite_region_annotation_buffers
);
5027 if (!NILP (Fbuffer_live_p (buf
)))
5030 if (FUNCTIONP (Vwrite_region_post_annotation_function
))
5031 call0 (Vwrite_region_post_annotation_function
);
5033 Vwrite_region_annotation_buffers
5034 = XCDR (Vwrite_region_annotation_buffers
);
5037 unbind_to (count
, Qnil
);
5039 #ifdef CLASH_DETECTION
5041 unlock_file (lockname
);
5042 #endif /* CLASH_DETECTION */
5044 /* Do this before reporting IO error
5045 to avoid a "file has changed on disk" warning on
5046 next attempt to save. */
5047 if (EMACS_TIME_VALID_P (modtime
))
5049 current_buffer
->modtime
= modtime
;
5050 current_buffer
->modtime_size
= st
.st_size
;
5054 report_file_errno ("Write error", filename
, save_errno
);
5058 SAVE_MODIFF
= MODIFF
;
5059 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5060 bset_filename (current_buffer
, visit_file
);
5061 update_mode_lines
++;
5066 && ! NILP (Fstring_equal (BVAR (current_buffer
, filename
),
5067 BVAR (current_buffer
, auto_save_file_name
))))
5068 SAVE_MODIFF
= MODIFF
;
5074 message_with_string ((NUMBERP (append
)
5084 Lisp_Object
merge (Lisp_Object
, Lisp_Object
, Lisp_Object
);
5086 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
5087 doc
: /* Return t if (car A) is numerically less than (car B). */)
5088 (Lisp_Object a
, Lisp_Object b
)
5090 return Flss (Fcar (a
), Fcar (b
));
5093 /* Build the complete list of annotations appropriate for writing out
5094 the text between START and END, by calling all the functions in
5095 write-region-annotate-functions and merging the lists they return.
5096 If one of these functions switches to a different buffer, we assume
5097 that buffer contains altered text. Therefore, the caller must
5098 make sure to restore the current buffer in all cases,
5099 as save-excursion would do. */
5102 build_annotations (Lisp_Object start
, Lisp_Object end
)
5104 Lisp_Object annotations
;
5106 struct gcpro gcpro1
, gcpro2
;
5107 Lisp_Object original_buffer
;
5109 bool used_global
= 0;
5111 XSETBUFFER (original_buffer
, current_buffer
);
5114 p
= Vwrite_region_annotate_functions
;
5115 GCPRO2 (annotations
, p
);
5118 struct buffer
*given_buffer
= current_buffer
;
5119 if (EQ (Qt
, XCAR (p
)) && !used_global
)
5120 { /* Use the global value of the hook. */
5123 arg
[0] = Fdefault_value (Qwrite_region_annotate_functions
);
5125 p
= Fappend (2, arg
);
5128 Vwrite_region_annotations_so_far
= annotations
;
5129 res
= call2 (XCAR (p
), start
, end
);
5130 /* If the function makes a different buffer current,
5131 assume that means this buffer contains altered text to be output.
5132 Reset START and END from the buffer bounds
5133 and discard all previous annotations because they should have
5134 been dealt with by this function. */
5135 if (current_buffer
!= given_buffer
)
5137 Vwrite_region_annotation_buffers
5138 = Fcons (Fcurrent_buffer (),
5139 Vwrite_region_annotation_buffers
);
5140 XSETFASTINT (start
, BEGV
);
5141 XSETFASTINT (end
, ZV
);
5144 Flength (res
); /* Check basic validity of return value */
5145 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5149 /* Now do the same for annotation functions implied by the file-format */
5150 if (auto_saving
&& (!EQ (BVAR (current_buffer
, auto_save_file_format
), Qt
)))
5151 p
= BVAR (current_buffer
, auto_save_file_format
);
5153 p
= BVAR (current_buffer
, file_format
);
5154 for (i
= 0; CONSP (p
); p
= XCDR (p
), ++i
)
5156 struct buffer
*given_buffer
= current_buffer
;
5158 Vwrite_region_annotations_so_far
= annotations
;
5160 /* Value is either a list of annotations or nil if the function
5161 has written annotations to a temporary buffer, which is now
5163 res
= call5 (Qformat_annotate_function
, XCAR (p
), start
, end
,
5164 original_buffer
, make_number (i
));
5165 if (current_buffer
!= given_buffer
)
5167 XSETFASTINT (start
, BEGV
);
5168 XSETFASTINT (end
, ZV
);
5173 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5181 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5182 If STRING is nil, POS is the character position in the current buffer.
5183 Intersperse with them the annotations from *ANNOT
5184 which fall within the range of POS to POS + NCHARS,
5185 each at its appropriate position.
5187 We modify *ANNOT by discarding elements as we use them up.
5189 Return true if successful. */
5192 a_write (int desc
, Lisp_Object string
, ptrdiff_t pos
,
5193 ptrdiff_t nchars
, Lisp_Object
*annot
,
5194 struct coding_system
*coding
)
5198 ptrdiff_t lastpos
= pos
+ nchars
;
5200 while (NILP (*annot
) || CONSP (*annot
))
5202 tem
= Fcar_safe (Fcar (*annot
));
5205 nextpos
= XFASTINT (tem
);
5207 /* If there are no more annotations in this range,
5208 output the rest of the range all at once. */
5209 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
5210 return e_write (desc
, string
, pos
, lastpos
, coding
);
5212 /* Output buffer text up to the next annotation's position. */
5215 if (!e_write (desc
, string
, pos
, nextpos
, coding
))
5219 /* Output the annotation. */
5220 tem
= Fcdr (Fcar (*annot
));
5223 if (!e_write (desc
, tem
, 0, SCHARS (tem
), coding
))
5226 *annot
= Fcdr (*annot
);
5232 /* Write text in the range START and END into descriptor DESC,
5233 encoding them with coding system CODING. If STRING is nil, START
5234 and END are character positions of the current buffer, else they
5235 are indexes to the string STRING. Return true if successful. */
5238 e_write (int desc
, Lisp_Object string
, ptrdiff_t start
, ptrdiff_t end
,
5239 struct coding_system
*coding
)
5241 if (STRINGP (string
))
5244 end
= SCHARS (string
);
5247 /* We used to have a code for handling selective display here. But,
5248 now it is handled within encode_coding. */
5252 if (STRINGP (string
))
5254 coding
->src_multibyte
= SCHARS (string
) < SBYTES (string
);
5255 if (CODING_REQUIRE_ENCODING (coding
))
5257 encode_coding_object (coding
, string
,
5258 start
, string_char_to_byte (string
, start
),
5259 end
, string_char_to_byte (string
, end
), Qt
);
5263 coding
->dst_object
= string
;
5264 coding
->consumed_char
= SCHARS (string
);
5265 coding
->produced
= SBYTES (string
);
5270 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
5271 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
5273 coding
->src_multibyte
= (end
- start
) < (end_byte
- start_byte
);
5274 if (CODING_REQUIRE_ENCODING (coding
))
5276 encode_coding_object (coding
, Fcurrent_buffer (),
5277 start
, start_byte
, end
, end_byte
, Qt
);
5281 coding
->dst_object
= Qnil
;
5282 coding
->dst_pos_byte
= start_byte
;
5283 if (start
>= GPT
|| end
<= GPT
)
5285 coding
->consumed_char
= end
- start
;
5286 coding
->produced
= end_byte
- start_byte
;
5290 coding
->consumed_char
= GPT
- start
;
5291 coding
->produced
= GPT_BYTE
- start_byte
;
5296 if (coding
->produced
> 0)
5298 char *buf
= (STRINGP (coding
->dst_object
)
5299 ? SSDATA (coding
->dst_object
)
5300 : (char *) BYTE_POS_ADDR (coding
->dst_pos_byte
));
5301 coding
->produced
-= emacs_write_sig (desc
, buf
, coding
->produced
);
5303 if (coding
->produced
)
5306 start
+= coding
->consumed_char
;
5312 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5313 Sverify_visited_file_modtime
, 0, 1, 0,
5314 doc
: /* Return t if last mod time of BUF's visited file matches what BUF records.
5315 This means that the file has not been changed since it was visited or saved.
5316 If BUF is omitted or nil, it defaults to the current buffer.
5317 See Info node `(elisp)Modification Time' for more details. */)
5322 Lisp_Object handler
;
5323 Lisp_Object filename
;
5334 if (!STRINGP (BVAR (b
, filename
))) return Qt
;
5335 if (EMACS_NSECS (b
->modtime
) == UNKNOWN_MODTIME_NSECS
) return Qt
;
5337 /* If the file name has special constructs in it,
5338 call the corresponding file handler. */
5339 handler
= Ffind_file_name_handler (BVAR (b
, filename
),
5340 Qverify_visited_file_modtime
);
5341 if (!NILP (handler
))
5342 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5344 filename
= ENCODE_FILE (BVAR (b
, filename
));
5346 mtime
= (stat (SSDATA (filename
), &st
) == 0
5347 ? get_stat_mtime (&st
)
5348 : time_error_value (errno
));
5349 if (EMACS_TIME_EQ (mtime
, b
->modtime
)
5350 && (b
->modtime_size
< 0
5351 || st
.st_size
== b
->modtime_size
))
5356 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5357 Svisited_file_modtime
, 0, 0, 0,
5358 doc
: /* Return the current buffer's recorded visited file modification time.
5359 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5360 `file-attributes' returns. If the current buffer has no recorded file
5361 modification time, this function returns 0. If the visited file
5362 doesn't exist, return -1.
5363 See Info node `(elisp)Modification Time' for more details. */)
5366 int ns
= EMACS_NSECS (current_buffer
->modtime
);
5368 return make_number (UNKNOWN_MODTIME_NSECS
- ns
);
5369 return make_lisp_time (current_buffer
->modtime
);
5372 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5373 Sset_visited_file_modtime
, 0, 1, 0,
5374 doc
: /* Update buffer's recorded modification time from the visited file's time.
5375 Useful if the buffer was not read from the file normally
5376 or if the file itself has been changed for some known benign reason.
5377 An argument specifies the modification time value to use
5378 \(instead of that of the visited file), in the form of a list
5379 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5380 `visited-file-modtime'. */)
5381 (Lisp_Object time_flag
)
5383 if (!NILP (time_flag
))
5386 if (INTEGERP (time_flag
))
5388 CHECK_RANGED_INTEGER (time_flag
, -1, 0);
5389 mtime
= make_emacs_time (0, UNKNOWN_MODTIME_NSECS
- XINT (time_flag
));
5392 mtime
= lisp_time_argument (time_flag
);
5394 current_buffer
->modtime
= mtime
;
5395 current_buffer
->modtime_size
= -1;
5399 register Lisp_Object filename
;
5401 Lisp_Object handler
;
5403 filename
= Fexpand_file_name (BVAR (current_buffer
, filename
), Qnil
);
5405 /* If the file name has special constructs in it,
5406 call the corresponding file handler. */
5407 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5408 if (!NILP (handler
))
5409 /* The handler can find the file name the same way we did. */
5410 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5412 filename
= ENCODE_FILE (filename
);
5414 if (stat (SSDATA (filename
), &st
) >= 0)
5416 current_buffer
->modtime
= get_stat_mtime (&st
);
5417 current_buffer
->modtime_size
= st
.st_size
;
5425 auto_save_error (Lisp_Object error_val
)
5427 Lisp_Object args
[3], msg
;
5429 struct gcpro gcpro1
;
5431 auto_save_error_occurred
= 1;
5433 ring_bell (XFRAME (selected_frame
));
5435 args
[0] = build_string ("Auto-saving %s: %s");
5436 args
[1] = BVAR (current_buffer
, name
);
5437 args
[2] = Ferror_message_string (error_val
);
5438 msg
= Fformat (3, args
);
5441 for (i
= 0; i
< 3; ++i
)
5446 message3_nolog (msg
);
5447 Fsleep_for (make_number (1), Qnil
);
5460 auto_save_mode_bits
= 0666;
5462 /* Get visited file's mode to become the auto save file's mode. */
5463 if (! NILP (BVAR (current_buffer
, filename
)))
5465 if (stat (SSDATA (BVAR (current_buffer
, filename
)), &st
) >= 0)
5466 /* But make sure we can overwrite it later! */
5467 auto_save_mode_bits
= (st
.st_mode
| 0600) & 0777;
5468 else if (modes
= Ffile_modes (BVAR (current_buffer
, filename
)),
5470 /* Remote files don't cooperate with stat. */
5471 auto_save_mode_bits
= (XINT (modes
) | 0600) & 0777;
5475 Fwrite_region (Qnil
, Qnil
, BVAR (current_buffer
, auto_save_file_name
), Qnil
,
5476 NILP (Vauto_save_visited_file_name
) ? Qlambda
: Qt
,
5480 struct auto_save_unwind
5487 do_auto_save_unwind (void *arg
)
5489 struct auto_save_unwind
*p
= arg
;
5490 FILE *stream
= p
->stream
;
5491 minibuffer_auto_raise
= p
->auto_raise
;
5502 do_auto_save_make_dir (Lisp_Object dir
)
5506 auto_saving_dir_umask
= 077;
5507 result
= call2 (Qmake_directory
, dir
, Qt
);
5508 auto_saving_dir_umask
= 0;
5513 do_auto_save_eh (Lisp_Object ignore
)
5515 auto_saving_dir_umask
= 0;
5519 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5520 doc
: /* Auto-save all buffers that need it.
5521 This is all buffers that have auto-saving enabled
5522 and are changed since last auto-saved.
5523 Auto-saving writes the buffer into a file
5524 so that your editing is not lost if the system crashes.
5525 This file is not the file you visited; that changes only when you save.
5526 Normally we run the normal hook `auto-save-hook' before saving.
5528 A non-nil NO-MESSAGE argument means do not print any message if successful.
5529 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5530 (Lisp_Object no_message
, Lisp_Object current_only
)
5532 struct buffer
*old
= current_buffer
, *b
;
5533 Lisp_Object tail
, buf
, hook
;
5534 bool auto_saved
= 0;
5535 int do_handled_files
;
5537 FILE *stream
= NULL
;
5538 ptrdiff_t count
= SPECPDL_INDEX ();
5539 bool orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5540 bool old_message_p
= 0;
5541 struct auto_save_unwind auto_save_unwind
;
5542 struct gcpro gcpro1
, gcpro2
;
5544 if (max_specpdl_size
< specpdl_size
+ 40)
5545 max_specpdl_size
= specpdl_size
+ 40;
5550 if (NILP (no_message
))
5552 old_message_p
= push_message ();
5553 record_unwind_protect_void (pop_message_unwind
);
5556 /* Ordinarily don't quit within this function,
5557 but don't make it impossible to quit (in case we get hung in I/O). */
5561 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5562 point to non-strings reached from Vbuffer_alist. */
5564 hook
= intern ("auto-save-hook");
5565 safe_run_hooks (hook
);
5567 if (STRINGP (Vauto_save_list_file_name
))
5569 Lisp_Object listfile
;
5571 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5573 /* Don't try to create the directory when shutting down Emacs,
5574 because creating the directory might signal an error, and
5575 that would leave Emacs in a strange state. */
5576 if (!NILP (Vrun_hooks
))
5580 GCPRO2 (dir
, listfile
);
5581 dir
= Ffile_name_directory (listfile
);
5582 if (NILP (Ffile_directory_p (dir
)))
5583 internal_condition_case_1 (do_auto_save_make_dir
,
5589 stream
= emacs_fopen (SSDATA (listfile
), "w");
5592 auto_save_unwind
.stream
= stream
;
5593 auto_save_unwind
.auto_raise
= minibuffer_auto_raise
;
5594 record_unwind_protect_ptr (do_auto_save_unwind
, &auto_save_unwind
);
5595 minibuffer_auto_raise
= 0;
5597 auto_save_error_occurred
= 0;
5599 /* On first pass, save all files that don't have handlers.
5600 On second pass, save all files that do have handlers.
5602 If Emacs is crashing, the handlers may tweak what is causing
5603 Emacs to crash in the first place, and it would be a shame if
5604 Emacs failed to autosave perfectly ordinary files because it
5605 couldn't handle some ange-ftp'd file. */
5607 for (do_handled_files
= 0; do_handled_files
< 2; do_handled_files
++)
5608 for (tail
= Vbuffer_alist
; CONSP (tail
); tail
= XCDR (tail
))
5610 buf
= XCDR (XCAR (tail
));
5613 /* Record all the buffers that have auto save mode
5614 in the special file that lists them. For each of these buffers,
5615 Record visited name (if any) and auto save name. */
5616 if (STRINGP (BVAR (b
, auto_save_file_name
))
5617 && stream
!= NULL
&& do_handled_files
== 0)
5620 if (!NILP (BVAR (b
, filename
)))
5622 fwrite (SDATA (BVAR (b
, filename
)), 1,
5623 SBYTES (BVAR (b
, filename
)), stream
);
5625 putc ('\n', stream
);
5626 fwrite (SDATA (BVAR (b
, auto_save_file_name
)), 1,
5627 SBYTES (BVAR (b
, auto_save_file_name
)), stream
);
5628 putc ('\n', stream
);
5632 if (!NILP (current_only
)
5633 && b
!= current_buffer
)
5636 /* Don't auto-save indirect buffers.
5637 The base buffer takes care of it. */
5641 /* Check for auto save enabled
5642 and file changed since last auto save
5643 and file changed since last real save. */
5644 if (STRINGP (BVAR (b
, auto_save_file_name
))
5645 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
)
5646 && BUF_AUTOSAVE_MODIFF (b
) < BUF_MODIFF (b
)
5647 /* -1 means we've turned off autosaving for a while--see below. */
5648 && XINT (BVAR (b
, save_length
)) >= 0
5649 && (do_handled_files
5650 || NILP (Ffind_file_name_handler (BVAR (b
, auto_save_file_name
),
5653 EMACS_TIME before_time
= current_emacs_time ();
5654 EMACS_TIME after_time
;
5656 /* If we had a failure, don't try again for 20 minutes. */
5657 if (b
->auto_save_failure_time
> 0
5658 && EMACS_SECS (before_time
) - b
->auto_save_failure_time
< 1200)
5661 set_buffer_internal (b
);
5662 if (NILP (Vauto_save_include_big_deletions
)
5663 && (XFASTINT (BVAR (b
, save_length
)) * 10
5664 > (BUF_Z (b
) - BUF_BEG (b
)) * 13)
5665 /* A short file is likely to change a large fraction;
5666 spare the user annoying messages. */
5667 && XFASTINT (BVAR (b
, save_length
)) > 5000
5668 /* These messages are frequent and annoying for `*mail*'. */
5669 && !EQ (BVAR (b
, filename
), Qnil
)
5670 && NILP (no_message
))
5672 /* It has shrunk too much; turn off auto-saving here. */
5673 minibuffer_auto_raise
= orig_minibuffer_auto_raise
;
5674 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5676 minibuffer_auto_raise
= 0;
5677 /* Turn off auto-saving until there's a real save,
5678 and prevent any more warnings. */
5679 XSETINT (BVAR (b
, save_length
), -1);
5680 Fsleep_for (make_number (1), Qnil
);
5683 if (!auto_saved
&& NILP (no_message
))
5684 message1 ("Auto-saving...");
5685 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
5687 BUF_AUTOSAVE_MODIFF (b
) = BUF_MODIFF (b
);
5688 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5689 set_buffer_internal (old
);
5691 after_time
= current_emacs_time ();
5693 /* If auto-save took more than 60 seconds,
5694 assume it was an NFS failure that got a timeout. */
5695 if (EMACS_SECS (after_time
) - EMACS_SECS (before_time
) > 60)
5696 b
->auto_save_failure_time
= EMACS_SECS (after_time
);
5700 /* Prevent another auto save till enough input events come in. */
5701 record_auto_save ();
5703 if (auto_saved
&& NILP (no_message
))
5707 /* If we are going to restore an old message,
5708 give time to read ours. */
5709 sit_for (make_number (1), 0, 0);
5712 else if (!auto_save_error_occurred
)
5713 /* Don't overwrite the error message if an error occurred.
5714 If we displayed a message and then restored a state
5715 with no message, leave a "done" message on the screen. */
5716 message1 ("Auto-saving...done");
5721 /* This restores the message-stack status. */
5722 unbind_to (count
, Qnil
);
5726 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved
,
5727 Sset_buffer_auto_saved
, 0, 0, 0,
5728 doc
: /* Mark current buffer as auto-saved with its current text.
5729 No auto-save file will be written until the buffer changes again. */)
5732 /* FIXME: This should not be called in indirect buffers, since
5733 they're not autosaved. */
5734 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
5735 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5736 current_buffer
->auto_save_failure_time
= 0;
5740 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure
,
5741 Sclear_buffer_auto_save_failure
, 0, 0, 0,
5742 doc
: /* Clear any record of a recent auto-save failure in the current buffer. */)
5745 current_buffer
->auto_save_failure_time
= 0;
5749 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
5751 doc
: /* Return t if current buffer has been auto-saved recently.
5752 More precisely, if it has been auto-saved since last read from or saved
5753 in the visited file. If the buffer has no visited file,
5754 then any auto-save counts as "recent". */)
5757 /* FIXME: maybe we should return nil for indirect buffers since
5758 they're never autosaved. */
5759 return (SAVE_MODIFF
< BUF_AUTOSAVE_MODIFF (current_buffer
) ? Qt
: Qnil
);
5762 /* Reading and completing file names */
5764 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p
,
5765 Snext_read_file_uses_dialog_p
, 0, 0, 0,
5766 doc
: /* Return t if a call to `read-file-name' will use a dialog.
5767 The return value is only relevant for a call to `read-file-name' that happens
5768 before any other event (mouse or keypress) is handled. */)
5771 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) \
5772 || defined (HAVE_NS)
5773 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5776 && window_system_available (SELECTED_FRAME ()))
5783 Fread_file_name (Lisp_Object prompt
, Lisp_Object dir
, Lisp_Object default_filename
, Lisp_Object mustmatch
, Lisp_Object initial
, Lisp_Object predicate
)
5785 struct gcpro gcpro1
;
5786 Lisp_Object args
[7];
5788 GCPRO1 (default_filename
);
5789 args
[0] = intern ("read-file-name");
5792 args
[3] = default_filename
;
5793 args
[4] = mustmatch
;
5795 args
[6] = predicate
;
5796 RETURN_UNGCPRO (Ffuncall (7, args
));
5803 valid_timestamp_file_system
= 0;
5807 syms_of_fileio (void)
5809 DEFSYM (Qoperations
, "operations");
5810 DEFSYM (Qexpand_file_name
, "expand-file-name");
5811 DEFSYM (Qsubstitute_in_file_name
, "substitute-in-file-name");
5812 DEFSYM (Qdirectory_file_name
, "directory-file-name");
5813 DEFSYM (Qfile_name_directory
, "file-name-directory");
5814 DEFSYM (Qfile_name_nondirectory
, "file-name-nondirectory");
5815 DEFSYM (Qunhandled_file_name_directory
, "unhandled-file-name-directory");
5816 DEFSYM (Qfile_name_as_directory
, "file-name-as-directory");
5817 DEFSYM (Qcopy_file
, "copy-file");
5818 DEFSYM (Qmake_directory_internal
, "make-directory-internal");
5819 DEFSYM (Qmake_directory
, "make-directory");
5820 DEFSYM (Qdelete_directory_internal
, "delete-directory-internal");
5821 DEFSYM (Qdelete_file
, "delete-file");
5822 DEFSYM (Qrename_file
, "rename-file");
5823 DEFSYM (Qadd_name_to_file
, "add-name-to-file");
5824 DEFSYM (Qmake_symbolic_link
, "make-symbolic-link");
5825 DEFSYM (Qfile_exists_p
, "file-exists-p");
5826 DEFSYM (Qfile_executable_p
, "file-executable-p");
5827 DEFSYM (Qfile_readable_p
, "file-readable-p");
5828 DEFSYM (Qfile_writable_p
, "file-writable-p");
5829 DEFSYM (Qfile_symlink_p
, "file-symlink-p");
5830 DEFSYM (Qaccess_file
, "access-file");
5831 DEFSYM (Qfile_directory_p
, "file-directory-p");
5832 DEFSYM (Qfile_regular_p
, "file-regular-p");
5833 DEFSYM (Qfile_accessible_directory_p
, "file-accessible-directory-p");
5834 DEFSYM (Qfile_modes
, "file-modes");
5835 DEFSYM (Qset_file_modes
, "set-file-modes");
5836 DEFSYM (Qset_file_times
, "set-file-times");
5837 DEFSYM (Qfile_selinux_context
, "file-selinux-context");
5838 DEFSYM (Qset_file_selinux_context
, "set-file-selinux-context");
5839 DEFSYM (Qfile_acl
, "file-acl");
5840 DEFSYM (Qset_file_acl
, "set-file-acl");
5841 DEFSYM (Qfile_newer_than_file_p
, "file-newer-than-file-p");
5842 DEFSYM (Qinsert_file_contents
, "insert-file-contents");
5843 DEFSYM (Qchoose_write_coding_system
, "choose-write-coding-system");
5844 DEFSYM (Qwrite_region
, "write-region");
5845 DEFSYM (Qverify_visited_file_modtime
, "verify-visited-file-modtime");
5846 DEFSYM (Qset_visited_file_modtime
, "set-visited-file-modtime");
5847 DEFSYM (Qauto_save_coding
, "auto-save-coding");
5849 DEFSYM (Qfile_name_history
, "file-name-history");
5850 Fset (Qfile_name_history
, Qnil
);
5852 DEFSYM (Qfile_error
, "file-error");
5853 DEFSYM (Qfile_already_exists
, "file-already-exists");
5854 DEFSYM (Qfile_date_error
, "file-date-error");
5855 DEFSYM (Qfile_notify_error
, "file-notify-error");
5856 DEFSYM (Qexcl
, "excl");
5858 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system
,
5859 doc
: /* Coding system for encoding file names.
5860 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5861 Vfile_name_coding_system
= Qnil
;
5863 DEFVAR_LISP ("default-file-name-coding-system",
5864 Vdefault_file_name_coding_system
,
5865 doc
: /* Default coding system for encoding file names.
5866 This variable is used only when `file-name-coding-system' is nil.
5868 This variable is set/changed by the command `set-language-environment'.
5869 User should not set this variable manually,
5870 instead use `file-name-coding-system' to get a constant encoding
5871 of file names regardless of the current language environment. */);
5872 Vdefault_file_name_coding_system
= Qnil
;
5874 DEFSYM (Qformat_decode
, "format-decode");
5875 DEFSYM (Qformat_annotate_function
, "format-annotate-function");
5876 DEFSYM (Qafter_insert_file_set_coding
, "after-insert-file-set-coding");
5877 DEFSYM (Qcar_less_than_car
, "car-less-than-car");
5879 Fput (Qfile_error
, Qerror_conditions
,
5880 Fpurecopy (list2 (Qfile_error
, Qerror
)));
5881 Fput (Qfile_error
, Qerror_message
,
5882 build_pure_c_string ("File error"));
5884 Fput (Qfile_already_exists
, Qerror_conditions
,
5885 Fpurecopy (list3 (Qfile_already_exists
, Qfile_error
, Qerror
)));
5886 Fput (Qfile_already_exists
, Qerror_message
,
5887 build_pure_c_string ("File already exists"));
5889 Fput (Qfile_date_error
, Qerror_conditions
,
5890 Fpurecopy (list3 (Qfile_date_error
, Qfile_error
, Qerror
)));
5891 Fput (Qfile_date_error
, Qerror_message
,
5892 build_pure_c_string ("Cannot set file date"));
5894 Fput (Qfile_notify_error
, Qerror_conditions
,
5895 Fpurecopy (list3 (Qfile_notify_error
, Qfile_error
, Qerror
)));
5896 Fput (Qfile_notify_error
, Qerror_message
,
5897 build_pure_c_string ("File notification error"));
5899 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist
,
5900 doc
: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5901 If a file name matches REGEXP, all I/O on that file is done by calling
5902 HANDLER. If a file name matches more than one handler, the handler
5903 whose match starts last in the file name gets precedence. The
5904 function `find-file-name-handler' checks this list for a handler for
5907 HANDLER should be a function. The first argument given to it is the
5908 name of the I/O primitive to be handled; the remaining arguments are
5909 the arguments that were passed to that primitive. For example, if you
5910 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5911 HANDLER is called like this:
5913 (funcall HANDLER 'file-exists-p FILENAME)
5915 Note that HANDLER must be able to handle all I/O primitives; if it has
5916 nothing special to do for a primitive, it should reinvoke the
5917 primitive to handle the operation \"the usual way\".
5918 See Info node `(elisp)Magic File Names' for more details. */);
5919 Vfile_name_handler_alist
= Qnil
;
5921 DEFVAR_LISP ("set-auto-coding-function",
5922 Vset_auto_coding_function
,
5923 doc
: /* If non-nil, a function to call to decide a coding system of file.
5924 Two arguments are passed to this function: the file name
5925 and the length of a file contents following the point.
5926 This function should return a coding system to decode the file contents.
5927 It should check the file name against `auto-coding-alist'.
5928 If no coding system is decided, it should check a coding system
5929 specified in the heading lines with the format:
5930 -*- ... coding: CODING-SYSTEM; ... -*-
5931 or local variable spec of the tailing lines with `coding:' tag. */);
5932 Vset_auto_coding_function
= Qnil
;
5934 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions
,
5935 doc
: /* A list of functions to be called at the end of `insert-file-contents'.
5936 Each is passed one argument, the number of characters inserted,
5937 with point at the start of the inserted text. Each function
5938 should leave point the same, and return the new character count.
5939 If `insert-file-contents' is intercepted by a handler from
5940 `file-name-handler-alist', that handler is responsible for calling the
5941 functions in `after-insert-file-functions' if appropriate. */);
5942 Vafter_insert_file_functions
= Qnil
;
5944 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions
,
5945 doc
: /* A list of functions to be called at the start of `write-region'.
5946 Each is passed two arguments, START and END as for `write-region'.
5947 These are usually two numbers but not always; see the documentation
5948 for `write-region'. The function should return a list of pairs
5949 of the form (POSITION . STRING), consisting of strings to be effectively
5950 inserted at the specified positions of the file being written (1 means to
5951 insert before the first byte written). The POSITIONs must be sorted into
5954 If there are several annotation functions, the lists returned by these
5955 functions are merged destructively. As each annotation function runs,
5956 the variable `write-region-annotations-so-far' contains a list of all
5957 annotations returned by previous annotation functions.
5959 An annotation function can return with a different buffer current.
5960 Doing so removes the annotations returned by previous functions, and
5961 resets START and END to `point-min' and `point-max' of the new buffer.
5963 After `write-region' completes, Emacs calls the function stored in
5964 `write-region-post-annotation-function', once for each buffer that was
5965 current when building the annotations (i.e., at least once), with that
5966 buffer current. */);
5967 Vwrite_region_annotate_functions
= Qnil
;
5968 DEFSYM (Qwrite_region_annotate_functions
, "write-region-annotate-functions");
5970 DEFVAR_LISP ("write-region-post-annotation-function",
5971 Vwrite_region_post_annotation_function
,
5972 doc
: /* Function to call after `write-region' completes.
5973 The function is called with no arguments. If one or more of the
5974 annotation functions in `write-region-annotate-functions' changed the
5975 current buffer, the function stored in this variable is called for
5976 each of those additional buffers as well, in addition to the original
5977 buffer. The relevant buffer is current during each function call. */);
5978 Vwrite_region_post_annotation_function
= Qnil
;
5979 staticpro (&Vwrite_region_annotation_buffers
);
5981 DEFVAR_LISP ("write-region-annotations-so-far",
5982 Vwrite_region_annotations_so_far
,
5983 doc
: /* When an annotation function is called, this holds the previous annotations.
5984 These are the annotations made by other annotation functions
5985 that were already called. See also `write-region-annotate-functions'. */);
5986 Vwrite_region_annotations_so_far
= Qnil
;
5988 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers
,
5989 doc
: /* A list of file name handlers that temporarily should not be used.
5990 This applies only to the operation `inhibit-file-name-operation'. */);
5991 Vinhibit_file_name_handlers
= Qnil
;
5993 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation
,
5994 doc
: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5995 Vinhibit_file_name_operation
= Qnil
;
5997 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name
,
5998 doc
: /* File name in which we write a list of all auto save file names.
5999 This variable is initialized automatically from `auto-save-list-file-prefix'
6000 shortly after Emacs reads your init file, if you have not yet given it
6001 a non-nil value. */);
6002 Vauto_save_list_file_name
= Qnil
;
6004 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name
,
6005 doc
: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6006 Normally auto-save files are written under other names. */);
6007 Vauto_save_visited_file_name
= Qnil
;
6009 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions
,
6010 doc
: /* If non-nil, auto-save even if a large part of the text is deleted.
6011 If nil, deleting a substantial portion of the text disables auto-save
6012 in the buffer; this is the default behavior, because the auto-save
6013 file is usually more useful if it contains the deleted text. */);
6014 Vauto_save_include_big_deletions
= Qnil
;
6016 /* fsync can be a significant performance hit. Often it doesn't
6017 suffice to make the file-save operation survive a crash. For
6018 batch scripts, which are typically part of larger shell commands
6019 that don't fsync other files, its effect on performance can be
6020 significant so its utility is particularly questionable.
6021 Hence, for now by default fsync is used only when interactive.
6023 For more on why fsync often fails to work on today's hardware, see:
6024 Zheng M et al. Understanding the robustness of SSDs under power fault.
6025 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
6026 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
6028 For more on why fsync does not suffice even if it works properly, see:
6029 Roche X. Necessary step(s) to synchronize filename operations on disk.
6030 Austin Group Defect 672, 2013-03-19
6031 http://austingroupbugs.net/view.php?id=672 */
6032 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync
,
6033 doc
: /* Non-nil means don't call fsync in `write-region'.
6034 This variable affects calls to `write-region' as well as save commands.
6035 Setting this to nil may avoid data loss if the system loses power or
6036 the operating system crashes. */);
6037 write_region_inhibit_fsync
= noninteractive
;
6039 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash
,
6040 doc
: /* Specifies whether to use the system's trash can.
6041 When non-nil, certain file deletion commands use the function
6042 `move-file-to-trash' instead of deleting files outright.
6043 This includes interactive calls to `delete-file' and
6044 `delete-directory' and the Dired deletion commands. */);
6045 delete_by_moving_to_trash
= 0;
6046 Qdelete_by_moving_to_trash
= intern_c_string ("delete-by-moving-to-trash");
6048 DEFSYM (Qmove_file_to_trash
, "move-file-to-trash");
6049 DEFSYM (Qcopy_directory
, "copy-directory");
6050 DEFSYM (Qdelete_directory
, "delete-directory");
6052 defsubr (&Sfind_file_name_handler
);
6053 defsubr (&Sfile_name_directory
);
6054 defsubr (&Sfile_name_nondirectory
);
6055 defsubr (&Sunhandled_file_name_directory
);
6056 defsubr (&Sfile_name_as_directory
);
6057 defsubr (&Sdirectory_file_name
);
6058 defsubr (&Smake_temp_name
);
6059 defsubr (&Sexpand_file_name
);
6060 defsubr (&Ssubstitute_in_file_name
);
6061 defsubr (&Scopy_file
);
6062 defsubr (&Smake_directory_internal
);
6063 defsubr (&Sdelete_directory_internal
);
6064 defsubr (&Sdelete_file
);
6065 defsubr (&Srename_file
);
6066 defsubr (&Sadd_name_to_file
);
6067 defsubr (&Smake_symbolic_link
);
6068 defsubr (&Sfile_name_absolute_p
);
6069 defsubr (&Sfile_exists_p
);
6070 defsubr (&Sfile_executable_p
);
6071 defsubr (&Sfile_readable_p
);
6072 defsubr (&Sfile_writable_p
);
6073 defsubr (&Saccess_file
);
6074 defsubr (&Sfile_symlink_p
);
6075 defsubr (&Sfile_directory_p
);
6076 defsubr (&Sfile_accessible_directory_p
);
6077 defsubr (&Sfile_regular_p
);
6078 defsubr (&Sfile_modes
);
6079 defsubr (&Sset_file_modes
);
6080 defsubr (&Sset_file_times
);
6081 defsubr (&Sfile_selinux_context
);
6082 defsubr (&Sfile_acl
);
6083 defsubr (&Sset_file_acl
);
6084 defsubr (&Sset_file_selinux_context
);
6085 defsubr (&Sset_default_file_modes
);
6086 defsubr (&Sdefault_file_modes
);
6087 defsubr (&Sfile_newer_than_file_p
);
6088 defsubr (&Sinsert_file_contents
);
6089 defsubr (&Schoose_write_coding_system
);
6090 defsubr (&Swrite_region
);
6091 defsubr (&Scar_less_than_car
);
6092 defsubr (&Sverify_visited_file_modtime
);
6093 defsubr (&Svisited_file_modtime
);
6094 defsubr (&Sset_visited_file_modtime
);
6095 defsubr (&Sdo_auto_save
);
6096 defsubr (&Sset_buffer_auto_saved
);
6097 defsubr (&Sclear_buffer_auto_save_failure
);
6098 defsubr (&Srecent_auto_save_p
);
6100 defsubr (&Snext_read_file_uses_dialog_p
);
6103 defsubr (&Sunix_sync
);