* lisp.h (lispstpcpy): Rename from lispstrcpy, and act like stpcpy.
[emacs.git] / src / fileio.c
blob13e2c889020144b7ec70c2982bd25e6ab8594bc9
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2014 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/>. */
20 #include <config.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include "sysstdio.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #include <errno.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
37 #endif
39 #ifdef HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "intervals.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "coding.h"
50 #include "window.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
53 #include "frame.h"
54 #include "dispextern.h"
56 #ifdef WINDOWSNT
57 #define NOMINMAX 1
58 #include <windows.h>
59 #include <sys/file.h>
60 #include "w32.h"
61 #endif /* not WINDOWSNT */
63 #ifdef MSDOS
64 #include "msdos.h"
65 #include <sys/param.h>
66 #endif
68 #ifdef DOS_NT
69 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
70 redirector allows the six letters between 'Z' and 'a' as well. */
71 #ifdef MSDOS
72 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
73 #endif
74 #ifdef WINDOWSNT
75 #define IS_DRIVE(x) c_isalpha (x)
76 #endif
77 /* Need to lower-case the drive letter, or else expanded
78 filenames will sometimes compare unequal, because
79 `expand-file-name' doesn't always down-case the drive letter. */
80 #define DRIVE_LETTER(x) c_tolower (x)
81 #endif
83 #include "systime.h"
84 #include <acl.h>
85 #include <allocator.h>
86 #include <careadlinkat.h>
87 #include <stat-time.h>
89 #ifdef HPUX
90 #include <netio.h>
91 #endif
93 #include "commands.h"
95 /* True during writing of auto-save files. */
96 static bool auto_saving;
98 /* Emacs's real umask. */
99 static mode_t realmask;
101 /* Nonzero umask during creation of auto-save directories. */
102 static mode_t auto_saving_dir_umask;
104 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
105 a new file with the same mode as the original. */
106 static mode_t auto_save_mode_bits;
108 /* Set by auto_save_1 if an error occurred during the last auto-save. */
109 static bool auto_save_error_occurred;
111 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
112 number of a file system where time stamps were observed to to work. */
113 static bool valid_timestamp_file_system;
114 static dev_t timestamp_file_system;
116 /* The symbol bound to coding-system-for-read when
117 insert-file-contents is called for recovering a file. This is not
118 an actual coding system name, but just an indicator to tell
119 insert-file-contents to use `emacs-mule' with a special flag for
120 auto saving and recovering a file. */
121 static Lisp_Object Qauto_save_coding;
123 /* Property name of a file name handler,
124 which gives a list of operations it handles.. */
125 static Lisp_Object Qoperations;
127 /* Lisp functions for translating file formats. */
128 static Lisp_Object Qformat_decode, Qformat_annotate_function;
130 /* Lisp function for setting buffer-file-coding-system and the
131 multibyteness of the current buffer after inserting a file. */
132 static Lisp_Object Qafter_insert_file_set_coding;
134 static Lisp_Object Qwrite_region_annotate_functions;
135 /* Each time an annotation function changes the buffer, the new buffer
136 is added here. */
137 static Lisp_Object Vwrite_region_annotation_buffers;
139 static Lisp_Object Qdelete_by_moving_to_trash;
141 /* Lisp function for moving files to trash. */
142 static Lisp_Object Qmove_file_to_trash;
144 /* Lisp function for recursively copying directories. */
145 static Lisp_Object Qcopy_directory;
147 /* Lisp function for recursively deleting directories. */
148 static Lisp_Object Qdelete_directory;
150 static Lisp_Object Qsubstitute_env_in_file_name;
152 Lisp_Object Qfile_error, Qfile_notify_error;
153 static Lisp_Object Qfile_already_exists, Qfile_date_error;
154 static Lisp_Object Qexcl;
155 Lisp_Object Qfile_name_history;
157 static Lisp_Object Qcar_less_than_car;
159 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
160 Lisp_Object *, struct coding_system *);
161 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
162 struct coding_system *);
165 /* Return true if FILENAME exists. */
167 static bool
168 check_existing (const char *filename)
170 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
173 /* Return true if file FILENAME exists and can be executed. */
175 static bool
176 check_executable (char *filename)
178 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
181 /* Return true if file FILENAME exists and can be accessed
182 according to AMODE, which should include W_OK.
183 On failure, return false and set errno. */
185 static bool
186 check_writable (const char *filename, int amode)
188 #ifdef MSDOS
189 /* FIXME: an faccessat implementation should be added to the
190 DOS/Windows ports and this #ifdef branch should be removed. */
191 struct stat st;
192 if (stat (filename, &st) < 0)
193 return 0;
194 errno = EPERM;
195 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
196 #else /* not MSDOS */
197 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
198 #ifdef CYGWIN
199 /* faccessat may have returned failure because Cygwin couldn't
200 determine the file's UID or GID; if so, we return success. */
201 if (!res)
203 int faccessat_errno = errno;
204 struct stat st;
205 if (stat (filename, &st) < 0)
206 return 0;
207 res = (st.st_uid == -1 || st.st_gid == -1);
208 errno = faccessat_errno;
210 #endif /* CYGWIN */
211 return res;
212 #endif /* not MSDOS */
215 /* Signal a file-access failure. STRING describes the failure,
216 NAME the file involved, and ERRORNO the errno value.
218 If NAME is neither null nor a pair, package it up as a singleton
219 list before reporting it; this saves report_file_errno's caller the
220 trouble of preserving errno before calling list1. */
222 void
223 report_file_errno (char const *string, Lisp_Object name, int errorno)
225 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
226 Lisp_Object errstring;
227 char *str;
229 synchronize_system_messages_locale ();
230 str = strerror (errorno);
231 errstring = code_convert_string_norecord (build_unibyte_string (str),
232 Vlocale_coding_system, 0);
234 while (1)
235 switch (errorno)
237 case EEXIST:
238 xsignal (Qfile_already_exists, Fcons (errstring, data));
239 break;
240 default:
241 /* System error messages are capitalized. Downcase the initial
242 unless it is followed by a slash. (The slash case caters to
243 error messages that begin with "I/O" or, in German, "E/A".) */
244 if (STRING_MULTIBYTE (errstring)
245 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
247 int c;
249 str = SSDATA (errstring);
250 c = STRING_CHAR ((unsigned char *) str);
251 Faset (errstring, make_number (0), make_number (downcase (c)));
254 xsignal (Qfile_error,
255 Fcons (build_string (string), Fcons (errstring, data)));
259 /* Signal a file-access failure that set errno. STRING describes the
260 failure, NAME the file involved. When invoking this function, take
261 care to not use arguments such as build_string ("foo") that involve
262 side effects that may set errno. */
264 void
265 report_file_error (char const *string, Lisp_Object name)
267 report_file_errno (string, name, errno);
270 void
271 close_file_unwind (int fd)
273 emacs_close (fd);
276 void
277 fclose_unwind (void *arg)
279 FILE *stream = arg;
280 fclose (stream);
283 /* Restore point, having saved it as a marker. */
285 void
286 restore_point_unwind (Lisp_Object location)
288 Fgoto_char (location);
289 unchain_marker (XMARKER (location));
293 static Lisp_Object Qexpand_file_name;
294 static Lisp_Object Qsubstitute_in_file_name;
295 static Lisp_Object Qdirectory_file_name;
296 static Lisp_Object Qfile_name_directory;
297 static Lisp_Object Qfile_name_nondirectory;
298 static Lisp_Object Qunhandled_file_name_directory;
299 static Lisp_Object Qfile_name_as_directory;
300 static Lisp_Object Qcopy_file;
301 static Lisp_Object Qmake_directory_internal;
302 static Lisp_Object Qmake_directory;
303 static Lisp_Object Qdelete_directory_internal;
304 Lisp_Object Qdelete_file;
305 static Lisp_Object Qrename_file;
306 static Lisp_Object Qadd_name_to_file;
307 static Lisp_Object Qmake_symbolic_link;
308 Lisp_Object Qfile_exists_p;
309 static Lisp_Object Qfile_executable_p;
310 static Lisp_Object Qfile_readable_p;
311 static Lisp_Object Qfile_writable_p;
312 static Lisp_Object Qfile_symlink_p;
313 static Lisp_Object Qaccess_file;
314 Lisp_Object Qfile_directory_p;
315 static Lisp_Object Qfile_regular_p;
316 static Lisp_Object Qfile_accessible_directory_p;
317 static Lisp_Object Qfile_modes;
318 static Lisp_Object Qset_file_modes;
319 static Lisp_Object Qset_file_times;
320 static Lisp_Object Qfile_selinux_context;
321 static Lisp_Object Qset_file_selinux_context;
322 static Lisp_Object Qfile_acl;
323 static Lisp_Object Qset_file_acl;
324 static Lisp_Object Qfile_newer_than_file_p;
325 Lisp_Object Qinsert_file_contents;
326 Lisp_Object Qwrite_region;
327 static Lisp_Object Qverify_visited_file_modtime;
328 static Lisp_Object Qset_visited_file_modtime;
330 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
331 Sfind_file_name_handler, 2, 2, 0,
332 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
333 Otherwise, return nil.
334 A file name is handled if one of the regular expressions in
335 `file-name-handler-alist' matches it.
337 If OPERATION equals `inhibit-file-name-operation', then we ignore
338 any handlers that are members of `inhibit-file-name-handlers',
339 but we still do run any other handlers. This lets handlers
340 use the standard functions without calling themselves recursively. */)
341 (Lisp_Object filename, Lisp_Object operation)
343 /* This function must not munge the match data. */
344 Lisp_Object chain, inhibited_handlers, result;
345 ptrdiff_t pos = -1;
347 result = Qnil;
348 CHECK_STRING (filename);
350 if (EQ (operation, Vinhibit_file_name_operation))
351 inhibited_handlers = Vinhibit_file_name_handlers;
352 else
353 inhibited_handlers = Qnil;
355 for (chain = Vfile_name_handler_alist; CONSP (chain);
356 chain = XCDR (chain))
358 Lisp_Object elt;
359 elt = XCAR (chain);
360 if (CONSP (elt))
362 Lisp_Object string = XCAR (elt);
363 ptrdiff_t match_pos;
364 Lisp_Object handler = XCDR (elt);
365 Lisp_Object operations = Qnil;
367 if (SYMBOLP (handler))
368 operations = Fget (handler, Qoperations);
370 if (STRINGP (string)
371 && (match_pos = fast_string_match (string, filename)) > pos
372 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
374 Lisp_Object tem;
376 handler = XCDR (elt);
377 tem = Fmemq (handler, inhibited_handlers);
378 if (NILP (tem))
380 result = handler;
381 pos = match_pos;
386 QUIT;
388 return result;
391 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
392 1, 1, 0,
393 doc: /* Return the directory component in file name FILENAME.
394 Return nil if FILENAME does not include a directory.
395 Otherwise return a directory name.
396 Given a Unix syntax file name, returns a string ending in slash. */)
397 (Lisp_Object filename)
399 Lisp_Object handler;
401 CHECK_STRING (filename);
403 /* If the file name has special constructs in it,
404 call the corresponding file handler. */
405 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
406 if (!NILP (handler))
408 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
409 filename);
410 return STRINGP (handled_name) ? handled_name : Qnil;
413 char *beg = SSDATA (filename);
414 char const *p = beg + SBYTES (filename);
416 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
417 #ifdef DOS_NT
418 /* only recognize drive specifier at the beginning */
419 && !(p[-1] == ':'
420 /* handle the "/:d:foo" and "/:foo" cases correctly */
421 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
422 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
423 #endif
424 ) p--;
426 if (p == beg)
427 return Qnil;
428 #ifdef DOS_NT
429 /* Expansion of "c:" to drive and default directory. */
430 Lisp_Object tem_fn;
431 USE_SAFE_ALLOCA;
432 SAFE_ALLOCA_STRING (beg, filename);
433 p = beg + (p - SSDATA (filename));
435 if (p[-1] == ':')
437 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
438 char *res = alloca (MAXPATHLEN + 1);
439 char *r = res;
441 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
443 memcpy (res, beg, 2);
444 beg += 2;
445 r += 2;
448 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
450 size_t l = strlen (res);
452 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
453 strcat (res, "/");
454 beg = res;
455 p = beg + strlen (beg);
456 dostounix_filename (beg);
457 tem_fn = make_specified_string (beg, -1, p - beg,
458 STRING_MULTIBYTE (filename));
460 else
461 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
462 STRING_MULTIBYTE (filename));
464 else if (STRING_MULTIBYTE (filename))
466 tem_fn = make_specified_string (beg, -1, p - beg, 1);
467 dostounix_filename (SSDATA (tem_fn));
468 #ifdef WINDOWSNT
469 if (!NILP (Vw32_downcase_file_names))
470 tem_fn = Fdowncase (tem_fn);
471 #endif
473 else
475 dostounix_filename (beg);
476 tem_fn = make_specified_string (beg, -1, p - beg, 0);
478 SAFE_FREE ();
479 return tem_fn;
480 #else /* DOS_NT */
481 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
482 #endif /* DOS_NT */
485 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
486 Sfile_name_nondirectory, 1, 1, 0,
487 doc: /* Return file name FILENAME sans its directory.
488 For example, in a Unix-syntax file name,
489 this is everything after the last slash,
490 or the entire name if it contains no slash. */)
491 (Lisp_Object filename)
493 register const char *beg, *p, *end;
494 Lisp_Object handler;
496 CHECK_STRING (filename);
498 /* If the file name has special constructs in it,
499 call the corresponding file handler. */
500 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
501 if (!NILP (handler))
503 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
504 filename);
505 if (STRINGP (handled_name))
506 return handled_name;
507 error ("Invalid handler in `file-name-handler-alist'");
510 beg = SSDATA (filename);
511 end = p = beg + SBYTES (filename);
513 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
514 #ifdef DOS_NT
515 /* only recognize drive specifier at beginning */
516 && !(p[-1] == ':'
517 /* handle the "/:d:foo" case correctly */
518 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
519 #endif
521 p--;
523 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
526 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
527 Sunhandled_file_name_directory, 1, 1, 0,
528 doc: /* Return a directly usable directory name somehow associated with FILENAME.
529 A `directly usable' directory name is one that may be used without the
530 intervention of any file handler.
531 If FILENAME is a directly usable file itself, return
532 \(file-name-directory FILENAME).
533 If FILENAME refers to a file which is not accessible from a local process,
534 then this should return nil.
535 The `call-process' and `start-process' functions use this function to
536 get a current directory to run processes in. */)
537 (Lisp_Object filename)
539 Lisp_Object handler;
541 /* If the file name has special constructs in it,
542 call the corresponding file handler. */
543 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
544 if (!NILP (handler))
546 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
547 filename);
548 return STRINGP (handled_name) ? handled_name : Qnil;
551 return Ffile_name_directory (filename);
554 /* Maximum number of bytes that DST will be longer than SRC
555 in file_name_as_directory. This occurs when SRCLEN == 0. */
556 enum { file_name_as_directory_slop = 2 };
558 /* Convert from file name SRC of length SRCLEN to directory name in
559 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
560 string. On UNIX, just make sure there is a terminating /. Return
561 the length of DST in bytes. */
563 static ptrdiff_t
564 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
565 bool multibyte)
567 if (srclen == 0)
569 dst[0] = '.';
570 dst[1] = '/';
571 dst[2] = '\0';
572 return 2;
575 memcpy (dst, src, srclen);
576 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
577 dst[srclen++] = DIRECTORY_SEP;
578 dst[srclen] = 0;
579 #ifdef DOS_NT
580 dostounix_filename (dst);
581 #endif
582 return srclen;
585 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
586 Sfile_name_as_directory, 1, 1, 0,
587 doc: /* Return a string representing the file name FILE interpreted as a directory.
588 This operation exists because a directory is also a file, but its name as
589 a directory is different from its name as a file.
590 The result can be used as the value of `default-directory'
591 or passed as second argument to `expand-file-name'.
592 For a Unix-syntax file name, just appends a slash. */)
593 (Lisp_Object file)
595 char *buf;
596 ptrdiff_t length;
597 Lisp_Object handler, val;
598 USE_SAFE_ALLOCA;
600 CHECK_STRING (file);
601 if (NILP (file))
602 return Qnil;
604 /* If the file name has special constructs in it,
605 call the corresponding file handler. */
606 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
607 if (!NILP (handler))
609 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
610 file);
611 if (STRINGP (handled_name))
612 return handled_name;
613 error ("Invalid handler in `file-name-handler-alist'");
616 #ifdef WINDOWSNT
617 if (!NILP (Vw32_downcase_file_names))
618 file = Fdowncase (file);
619 #endif
620 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
621 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
622 STRING_MULTIBYTE (file));
623 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
624 SAFE_FREE ();
625 return val;
628 /* Convert from directory name SRC of length SRCLEN to file name in
629 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
630 string. On UNIX, just make sure there isn't a terminating /.
631 Return the length of DST in bytes. */
633 static ptrdiff_t
634 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
636 /* Process as Unix format: just remove any final slash.
637 But leave "/" and "//" unchanged. */
638 while (srclen > 1
639 #ifdef DOS_NT
640 && !IS_ANY_SEP (src[srclen - 2])
641 #endif
642 && IS_DIRECTORY_SEP (src[srclen - 1])
643 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
644 srclen--;
646 memcpy (dst, src, srclen);
647 dst[srclen] = 0;
648 #ifdef DOS_NT
649 dostounix_filename (dst);
650 #endif
651 return srclen;
654 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
655 1, 1, 0,
656 doc: /* Returns the file name of the directory named DIRECTORY.
657 This is the name of the file that holds the data for the directory DIRECTORY.
658 This operation exists because a directory is also a file, but its name as
659 a directory is different from its name as a file.
660 In Unix-syntax, this function just removes the final slash. */)
661 (Lisp_Object directory)
663 char *buf;
664 ptrdiff_t length;
665 Lisp_Object handler, val;
666 USE_SAFE_ALLOCA;
668 CHECK_STRING (directory);
670 if (NILP (directory))
671 return Qnil;
673 /* If the file name has special constructs in it,
674 call the corresponding file handler. */
675 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
676 if (!NILP (handler))
678 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
679 directory);
680 if (STRINGP (handled_name))
681 return handled_name;
682 error ("Invalid handler in `file-name-handler-alist'");
685 #ifdef WINDOWSNT
686 if (!NILP (Vw32_downcase_file_names))
687 directory = Fdowncase (directory);
688 #endif
689 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
690 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
691 STRING_MULTIBYTE (directory));
692 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
693 SAFE_FREE ();
694 return val;
697 static const char make_temp_name_tbl[64] =
699 'A','B','C','D','E','F','G','H',
700 'I','J','K','L','M','N','O','P',
701 'Q','R','S','T','U','V','W','X',
702 'Y','Z','a','b','c','d','e','f',
703 'g','h','i','j','k','l','m','n',
704 'o','p','q','r','s','t','u','v',
705 'w','x','y','z','0','1','2','3',
706 '4','5','6','7','8','9','-','_'
709 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
711 /* Value is a temporary file name starting with PREFIX, a string.
713 The Emacs process number forms part of the result, so there is
714 no danger of generating a name being used by another process.
715 In addition, this function makes an attempt to choose a name
716 which has no existing file. To make this work, PREFIX should be
717 an absolute file name.
719 BASE64_P means add the pid as 3 characters in base64
720 encoding. In this case, 6 characters will be added to PREFIX to
721 form the file name. Otherwise, if Emacs is running on a system
722 with long file names, add the pid as a decimal number.
724 This function signals an error if no unique file name could be
725 generated. */
727 Lisp_Object
728 make_temp_name (Lisp_Object prefix, bool base64_p)
730 Lisp_Object val, encoded_prefix;
731 ptrdiff_t len;
732 printmax_t pid;
733 char *p, *data;
734 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
735 int pidlen;
737 CHECK_STRING (prefix);
739 /* VAL is created by adding 6 characters to PREFIX. The first
740 three are the PID of this process, in base 64, and the second
741 three are incremented if the file already exists. This ensures
742 262144 unique file names per PID per PREFIX. */
744 pid = getpid ();
746 if (base64_p)
748 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
749 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
750 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
751 pidlen = 3;
753 else
755 #ifdef HAVE_LONG_FILE_NAMES
756 pidlen = sprintf (pidbuf, "%"pMd, pid);
757 #else
758 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
759 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
760 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
761 pidlen = 3;
762 #endif
765 encoded_prefix = ENCODE_FILE (prefix);
766 len = SBYTES (encoded_prefix);
767 val = make_uninit_string (len + 3 + pidlen);
768 data = SSDATA (val);
769 memcpy (data, SSDATA (encoded_prefix), len);
770 p = data + len;
772 memcpy (p, pidbuf, pidlen);
773 p += pidlen;
775 /* Here we try to minimize useless stat'ing when this function is
776 invoked many times successively with the same PREFIX. We achieve
777 this by initializing count to a random value, and incrementing it
778 afterwards.
780 We don't want make-temp-name to be called while dumping,
781 because then make_temp_name_count_initialized_p would get set
782 and then make_temp_name_count would not be set when Emacs starts. */
784 if (!make_temp_name_count_initialized_p)
786 make_temp_name_count = time (NULL);
787 make_temp_name_count_initialized_p = 1;
790 while (1)
792 unsigned num = make_temp_name_count;
794 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
795 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
796 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
798 /* Poor man's congruential RN generator. Replace with
799 ++make_temp_name_count for debugging. */
800 make_temp_name_count += 25229;
801 make_temp_name_count %= 225307;
803 if (!check_existing (data))
805 /* We want to return only if errno is ENOENT. */
806 if (errno == ENOENT)
807 return DECODE_FILE (val);
808 else
809 /* The error here is dubious, but there is little else we
810 can do. The alternatives are to return nil, which is
811 as bad as (and in many cases worse than) throwing the
812 error, or to ignore the error, which will likely result
813 in looping through 225307 stat's, which is not only
814 dog-slow, but also useless since eventually nil would
815 have to be returned anyway. */
816 report_file_error ("Cannot create temporary name for prefix",
817 prefix);
818 /* not reached */
824 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
825 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
826 The Emacs process number forms part of the result,
827 so there is no danger of generating a name being used by another process.
829 In addition, this function makes an attempt to choose a name
830 which has no existing file. To make this work,
831 PREFIX should be an absolute file name.
833 There is a race condition between calling `make-temp-name' and creating the
834 file which opens all kinds of security holes. For that reason, you should
835 probably use `make-temp-file' instead, except in three circumstances:
837 * If you are creating the file in the user's home directory.
838 * If you are creating a directory rather than an ordinary file.
839 * If you are taking special precautions as `make-temp-file' does. */)
840 (Lisp_Object prefix)
842 return make_temp_name (prefix, 0);
845 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
846 doc: /* Convert filename NAME to absolute, and canonicalize it.
847 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
848 \(does not start with slash or tilde); both the directory name and
849 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
850 missing, the current buffer's value of `default-directory' is used.
851 NAME should be a string that is a valid file name for the underlying
852 filesystem.
853 File name components that are `.' are removed, and
854 so are file name components followed by `..', along with the `..' itself;
855 note that these simplifications are done without checking the resulting
856 file names in the file system.
857 Multiple consecutive slashes are collapsed into a single slash,
858 except at the beginning of the file name when they are significant (e.g.,
859 UNC file names on MS-Windows.)
860 An initial `~/' expands to your home directory.
861 An initial `~USER/' expands to USER's home directory.
862 See also the function `substitute-in-file-name'.
864 For technical reasons, this function can return correct but
865 non-intuitive results for the root directory; for instance,
866 \(expand-file-name ".." "/") returns "/..". For this reason, use
867 \(directory-file-name (file-name-directory dirname)) to traverse a
868 filesystem tree, not (expand-file-name ".." dirname). */)
869 (Lisp_Object name, Lisp_Object default_directory)
871 /* These point to SDATA and need to be careful with string-relocation
872 during GC (via DECODE_FILE). */
873 char *nm;
874 char *nmlim;
875 const char *newdir;
876 const char *newdirlim;
877 /* This should only point to alloca'd data. */
878 char *target;
880 ptrdiff_t tlen;
881 struct passwd *pw;
882 #ifdef DOS_NT
883 int drive = 0;
884 bool collapse_newdir = true;
885 bool is_escaped = 0;
886 #endif /* DOS_NT */
887 ptrdiff_t length, nbytes;
888 Lisp_Object handler, result, handled_name;
889 bool multibyte;
890 Lisp_Object hdir;
891 USE_SAFE_ALLOCA;
893 CHECK_STRING (name);
895 /* If the file name has special constructs in it,
896 call the corresponding file handler. */
897 handler = Ffind_file_name_handler (name, Qexpand_file_name);
898 if (!NILP (handler))
900 handled_name = call3 (handler, Qexpand_file_name,
901 name, default_directory);
902 if (STRINGP (handled_name))
903 return handled_name;
904 error ("Invalid handler in `file-name-handler-alist'");
908 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
909 if (NILP (default_directory))
910 default_directory = BVAR (current_buffer, directory);
911 if (! STRINGP (default_directory))
913 #ifdef DOS_NT
914 /* "/" is not considered a root directory on DOS_NT, so using "/"
915 here causes an infinite recursion in, e.g., the following:
917 (let (default-directory)
918 (expand-file-name "a"))
920 To avoid this, we set default_directory to the root of the
921 current drive. */
922 default_directory = build_string (emacs_root_dir ());
923 #else
924 default_directory = build_string ("/");
925 #endif
928 if (!NILP (default_directory))
930 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
931 if (!NILP (handler))
933 handled_name = call3 (handler, Qexpand_file_name,
934 name, default_directory);
935 if (STRINGP (handled_name))
936 return handled_name;
937 error ("Invalid handler in `file-name-handler-alist'");
942 char *o = SSDATA (default_directory);
944 /* Make sure DEFAULT_DIRECTORY is properly expanded.
945 It would be better to do this down below where we actually use
946 default_directory. Unfortunately, calling Fexpand_file_name recursively
947 could invoke GC, and the strings might be relocated. This would
948 be annoying because we have pointers into strings lying around
949 that would need adjusting, and people would add new pointers to
950 the code and forget to adjust them, resulting in intermittent bugs.
951 Putting this call here avoids all that crud.
953 The EQ test avoids infinite recursion. */
954 if (! NILP (default_directory) && !EQ (default_directory, name)
955 /* Save time in some common cases - as long as default_directory
956 is not relative, it can be canonicalized with name below (if it
957 is needed at all) without requiring it to be expanded now. */
958 #ifdef DOS_NT
959 /* Detect MSDOS file names with drive specifiers. */
960 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
961 && IS_DIRECTORY_SEP (o[2]))
962 #ifdef WINDOWSNT
963 /* Detect Windows file names in UNC format. */
964 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
965 #endif
966 #else /* not DOS_NT */
967 /* Detect Unix absolute file names (/... alone is not absolute on
968 DOS or Windows). */
969 && ! (IS_DIRECTORY_SEP (o[0]))
970 #endif /* not DOS_NT */
973 struct gcpro gcpro1;
975 GCPRO1 (name);
976 default_directory = Fexpand_file_name (default_directory, Qnil);
977 UNGCPRO;
980 multibyte = STRING_MULTIBYTE (name);
981 if (multibyte != STRING_MULTIBYTE (default_directory))
983 if (multibyte)
985 unsigned char *p = SDATA (name);
987 while (*p && ASCII_CHAR_P (*p))
988 p++;
989 if (*p == '\0')
991 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
992 unibyte. Do not convert DEFAULT_DIRECTORY to
993 multibyte; instead, convert NAME to a unibyte string,
994 so that the result of this function is also a unibyte
995 string. This is needed during bootstrapping and
996 dumping, when Emacs cannot decode file names, because
997 the locale environment is not set up. */
998 name = make_unibyte_string (SSDATA (name), SBYTES (name));
999 multibyte = 0;
1001 else
1002 default_directory = string_to_multibyte (default_directory);
1004 else
1006 name = string_to_multibyte (name);
1007 multibyte = 1;
1011 #ifdef WINDOWSNT
1012 if (!NILP (Vw32_downcase_file_names))
1013 default_directory = Fdowncase (default_directory);
1014 #endif
1016 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
1017 SAFE_ALLOCA_STRING (nm, name);
1018 nmlim = nm + SBYTES (name);
1020 #ifdef DOS_NT
1021 /* Note if special escape prefix is present, but remove for now. */
1022 if (nm[0] == '/' && nm[1] == ':')
1024 is_escaped = 1;
1025 nm += 2;
1028 /* Find and remove drive specifier if present; this makes nm absolute
1029 even if the rest of the name appears to be relative. Only look for
1030 drive specifier at the beginning. */
1031 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
1033 drive = (unsigned char) nm[0];
1034 nm += 2;
1037 #ifdef WINDOWSNT
1038 /* If we see "c://somedir", we want to strip the first slash after the
1039 colon when stripping the drive letter. Otherwise, this expands to
1040 "//somedir". */
1041 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1042 nm++;
1044 /* Discard any previous drive specifier if nm is now in UNC format. */
1045 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1046 && !IS_DIRECTORY_SEP (nm[2]))
1047 drive = 0;
1048 #endif /* WINDOWSNT */
1049 #endif /* DOS_NT */
1051 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
1052 none are found, we can probably return right away. We will avoid
1053 allocating a new string if name is already fully expanded. */
1054 if (
1055 IS_DIRECTORY_SEP (nm[0])
1056 #ifdef MSDOS
1057 && drive && !is_escaped
1058 #endif
1059 #ifdef WINDOWSNT
1060 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
1061 #endif
1064 /* If it turns out that the filename we want to return is just a
1065 suffix of FILENAME, we don't need to go through and edit
1066 things; we just need to construct a new string using data
1067 starting at the middle of FILENAME. If we set LOSE, that
1068 means we've discovered that we can't do that cool trick. */
1069 bool lose = 0;
1070 char *p = nm;
1072 while (*p)
1074 /* Since we know the name is absolute, we can assume that each
1075 element starts with a "/". */
1077 /* "." and ".." are hairy. */
1078 if (IS_DIRECTORY_SEP (p[0])
1079 && p[1] == '.'
1080 && (IS_DIRECTORY_SEP (p[2])
1081 || p[2] == 0
1082 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1083 || p[3] == 0))))
1084 lose = 1;
1085 /* Replace multiple slashes with a single one, except
1086 leave leading "//" alone. */
1087 else if (IS_DIRECTORY_SEP (p[0])
1088 && IS_DIRECTORY_SEP (p[1])
1089 && (p != nm || IS_DIRECTORY_SEP (p[2])))
1090 lose = 1;
1091 p++;
1093 if (!lose)
1095 #ifdef DOS_NT
1096 /* Make sure directories are all separated with /, but
1097 avoid allocation of a new string when not required. */
1098 dostounix_filename (nm);
1099 #ifdef WINDOWSNT
1100 if (IS_DIRECTORY_SEP (nm[1]))
1102 if (strcmp (nm, SSDATA (name)) != 0)
1103 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1105 else
1106 #endif
1107 /* Drive must be set, so this is okay. */
1108 if (strcmp (nm - 2, SSDATA (name)) != 0)
1110 char temp[] = " :";
1112 name = make_specified_string (nm, -1, p - nm, multibyte);
1113 temp[0] = DRIVE_LETTER (drive);
1114 name = concat2 (build_local_string (temp), name);
1116 #ifdef WINDOWSNT
1117 if (!NILP (Vw32_downcase_file_names))
1118 name = Fdowncase (name);
1119 #endif
1120 #else /* not DOS_NT */
1121 if (strcmp (nm, SSDATA (name)) != 0)
1122 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1123 #endif /* not DOS_NT */
1124 SAFE_FREE ();
1125 return name;
1129 /* At this point, nm might or might not be an absolute file name. We
1130 need to expand ~ or ~user if present, otherwise prefix nm with
1131 default_directory if nm is not absolute, and finally collapse /./
1132 and /foo/../ sequences.
1134 We set newdir to be the appropriate prefix if one is needed:
1135 - the relevant user directory if nm starts with ~ or ~user
1136 - the specified drive's working dir (DOS/NT only) if nm does not
1137 start with /
1138 - the value of default_directory.
1140 Note that these prefixes are not guaranteed to be absolute (except
1141 for the working dir of a drive). Therefore, to ensure we always
1142 return an absolute name, if the final prefix is not absolute we
1143 append it to the current working directory. */
1145 newdir = newdirlim = 0;
1147 if (nm[0] == '~') /* prefix ~ */
1149 if (IS_DIRECTORY_SEP (nm[1])
1150 || nm[1] == 0) /* ~ by itself */
1152 Lisp_Object tem;
1154 if (!(newdir = egetenv ("HOME")))
1155 newdir = newdirlim = "";
1156 nm++;
1157 /* `egetenv' may return a unibyte string, which will bite us since
1158 we expect the directory to be multibyte. */
1159 #ifdef WINDOWSNT
1160 if (newdir[0])
1162 char newdir_utf8[MAX_UTF8_PATH];
1164 filename_from_ansi (newdir, newdir_utf8);
1165 tem = build_local_string (newdir_utf8);
1167 else
1168 #endif
1169 tem = build_local_string (newdir);
1170 newdirlim = newdir + SBYTES (tem);
1171 if (multibyte && !STRING_MULTIBYTE (tem))
1173 hdir = DECODE_FILE (tem);
1174 newdir = SSDATA (hdir);
1175 newdirlim = newdir + SBYTES (hdir);
1177 #ifdef DOS_NT
1178 collapse_newdir = false;
1179 #endif
1181 else /* ~user/filename */
1183 char *o, *p;
1184 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1185 continue;
1186 o = SAFE_ALLOCA (p - nm + 1);
1187 memcpy (o, nm, p - nm);
1188 o[p - nm] = 0;
1190 block_input ();
1191 pw = getpwnam (o + 1);
1192 unblock_input ();
1193 if (pw)
1195 Lisp_Object tem;
1197 newdir = pw->pw_dir;
1198 /* `getpwnam' may return a unibyte string, which will
1199 bite us since we expect the directory to be
1200 multibyte. */
1201 tem = build_local_string (newdir);
1202 newdirlim = newdir + SBYTES (tem);
1203 if (multibyte && !STRING_MULTIBYTE (tem))
1205 hdir = DECODE_FILE (tem);
1206 newdir = SSDATA (hdir);
1207 newdirlim = newdir + SBYTES (hdir);
1209 nm = p;
1210 #ifdef DOS_NT
1211 collapse_newdir = false;
1212 #endif
1215 /* If we don't find a user of that name, leave the name
1216 unchanged; don't move nm forward to p. */
1220 #ifdef DOS_NT
1221 /* On DOS and Windows, nm is absolute if a drive name was specified;
1222 use the drive's current directory as the prefix if needed. */
1223 if (!newdir && drive)
1225 /* Get default directory if needed to make nm absolute. */
1226 char *adir = NULL;
1227 if (!IS_DIRECTORY_SEP (nm[0]))
1229 adir = alloca (MAXPATHLEN + 1);
1230 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1231 adir = NULL;
1232 else if (multibyte)
1234 Lisp_Object tem = build_local_string (adir);
1236 tem = DECODE_FILE (tem);
1237 newdirlim = adir + SBYTES (tem);
1238 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1240 else
1241 newdirlim = adir + strlen (adir);
1243 if (!adir)
1245 /* Either nm starts with /, or drive isn't mounted. */
1246 adir = alloca (4);
1247 adir[0] = DRIVE_LETTER (drive);
1248 adir[1] = ':';
1249 adir[2] = '/';
1250 adir[3] = 0;
1251 newdirlim = adir + 3;
1253 newdir = adir;
1255 #endif /* DOS_NT */
1257 /* Finally, if no prefix has been specified and nm is not absolute,
1258 then it must be expanded relative to default_directory. */
1260 if (1
1261 #ifndef DOS_NT
1262 /* /... alone is not absolute on DOS and Windows. */
1263 && !IS_DIRECTORY_SEP (nm[0])
1264 #endif
1265 #ifdef WINDOWSNT
1266 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1267 && !IS_DIRECTORY_SEP (nm[2]))
1268 #endif
1269 && !newdir)
1271 newdir = SSDATA (default_directory);
1272 newdirlim = newdir + SBYTES (default_directory);
1273 #ifdef DOS_NT
1274 /* Note if special escape prefix is present, but remove for now. */
1275 if (newdir[0] == '/' && newdir[1] == ':')
1277 is_escaped = 1;
1278 newdir += 2;
1280 #endif
1283 #ifdef DOS_NT
1284 if (newdir)
1286 /* First ensure newdir is an absolute name. */
1287 if (
1288 /* Detect MSDOS file names with drive specifiers. */
1289 ! (IS_DRIVE (newdir[0])
1290 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1291 #ifdef WINDOWSNT
1292 /* Detect Windows file names in UNC format. */
1293 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1294 && !IS_DIRECTORY_SEP (newdir[2]))
1295 #endif
1298 /* Effectively, let newdir be (expand-file-name newdir cwd).
1299 Because of the admonition against calling expand-file-name
1300 when we have pointers into lisp strings, we accomplish this
1301 indirectly by prepending newdir to nm if necessary, and using
1302 cwd (or the wd of newdir's drive) as the new newdir. */
1303 char *adir;
1304 #ifdef WINDOWSNT
1305 const int adir_size = MAX_UTF8_PATH;
1306 #else
1307 const int adir_size = MAXPATHLEN + 1;
1308 #endif
1310 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1312 drive = (unsigned char) newdir[0];
1313 newdir += 2;
1315 if (!IS_DIRECTORY_SEP (nm[0]))
1317 ptrdiff_t nmlen = nmlim - nm;
1318 ptrdiff_t newdirlen = newdirlim - newdir;
1319 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1320 + nmlen + 1);
1321 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1322 multibyte);
1323 memcpy (tmp + dlen, nm, nmlen + 1);
1324 nm = tmp;
1325 nmlim = nm + dlen + nmlen;
1327 adir = alloca (adir_size);
1328 if (drive)
1330 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1331 strcpy (adir, "/");
1333 else
1334 getcwd (adir, adir_size);
1335 if (multibyte)
1337 Lisp_Object tem = build_local_string (adir);
1339 tem = DECODE_FILE (tem);
1340 newdirlim = adir + SBYTES (tem);
1341 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1343 else
1344 newdirlim = adir + strlen (adir);
1345 newdir = adir;
1348 /* Strip off drive name from prefix, if present. */
1349 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1351 drive = newdir[0];
1352 newdir += 2;
1355 /* Keep only a prefix from newdir if nm starts with slash
1356 (//server/share for UNC, nothing otherwise). */
1357 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1359 #ifdef WINDOWSNT
1360 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1361 && !IS_DIRECTORY_SEP (newdir[2]))
1363 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1364 char *p = adir + 2;
1365 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1366 p++;
1367 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1368 *p = 0;
1369 newdir = adir;
1370 newdirlim = newdir + strlen (adir);
1372 else
1373 #endif
1374 newdir = newdirlim = "";
1377 #endif /* DOS_NT */
1379 /* Ignore any slash at the end of newdir, unless newdir is
1380 just "/" or "//". */
1381 length = newdirlim - newdir;
1382 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1383 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1384 length--;
1386 /* Now concatenate the directory and name to new space in the stack frame. */
1387 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1388 eassert (tlen > file_name_as_directory_slop + 1);
1389 #ifdef DOS_NT
1390 /* Reserve space for drive specifier and escape prefix, since either
1391 or both may need to be inserted. (The Microsoft x86 compiler
1392 produces incorrect code if the following two lines are combined.) */
1393 target = alloca (tlen + 4);
1394 target += 4;
1395 #else /* not DOS_NT */
1396 target = SAFE_ALLOCA (tlen);
1397 #endif /* not DOS_NT */
1398 *target = 0;
1399 nbytes = 0;
1401 if (newdir)
1403 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1405 #ifdef DOS_NT
1406 /* If newdir is effectively "C:/", then the drive letter will have
1407 been stripped and newdir will be "/". Concatenating with an
1408 absolute directory in nm produces "//", which will then be
1409 incorrectly treated as a network share. Ignore newdir in
1410 this case (keeping the drive letter). */
1411 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1412 && newdir[1] == '\0'))
1413 #endif
1415 memcpy (target, newdir, length);
1416 target[length] = 0;
1417 nbytes = length;
1420 else
1421 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1424 memcpy (target + nbytes, nm, nmlim - nm + 1);
1426 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1427 appear. */
1429 char *p = target;
1430 char *o = target;
1432 while (*p)
1434 if (!IS_DIRECTORY_SEP (*p))
1436 *o++ = *p++;
1438 else if (p[1] == '.'
1439 && (IS_DIRECTORY_SEP (p[2])
1440 || p[2] == 0))
1442 /* If "/." is the entire filename, keep the "/". Otherwise,
1443 just delete the whole "/.". */
1444 if (o == target && p[2] == '\0')
1445 *o++ = *p;
1446 p += 2;
1448 else if (p[1] == '.' && p[2] == '.'
1449 /* `/../' is the "superroot" on certain file systems.
1450 Turned off on DOS_NT systems because they have no
1451 "superroot" and because this causes us to produce
1452 file names like "d:/../foo" which fail file-related
1453 functions of the underlying OS. (To reproduce, try a
1454 long series of "../../" in default_directory, longer
1455 than the number of levels from the root.) */
1456 #ifndef DOS_NT
1457 && o != target
1458 #endif
1459 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1461 #ifdef WINDOWSNT
1462 char *prev_o = o;
1463 #endif
1464 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1465 continue;
1466 #ifdef WINDOWSNT
1467 /* Don't go below server level in UNC filenames. */
1468 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1469 && IS_DIRECTORY_SEP (*target))
1470 o = prev_o;
1471 else
1472 #endif
1473 /* Keep initial / only if this is the whole name. */
1474 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1475 ++o;
1476 p += 3;
1478 else if (IS_DIRECTORY_SEP (p[1])
1479 && (p != target || IS_DIRECTORY_SEP (p[2])))
1480 /* Collapse multiple "/", except leave leading "//" alone. */
1481 p++;
1482 else
1484 *o++ = *p++;
1488 #ifdef DOS_NT
1489 /* At last, set drive name. */
1490 #ifdef WINDOWSNT
1491 /* Except for network file name. */
1492 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1493 #endif /* WINDOWSNT */
1495 if (!drive) emacs_abort ();
1496 target -= 2;
1497 target[0] = DRIVE_LETTER (drive);
1498 target[1] = ':';
1500 /* Reinsert the escape prefix if required. */
1501 if (is_escaped)
1503 target -= 2;
1504 target[0] = '/';
1505 target[1] = ':';
1507 result = make_specified_string (target, -1, o - target, multibyte);
1508 dostounix_filename (SSDATA (result));
1509 #ifdef WINDOWSNT
1510 if (!NILP (Vw32_downcase_file_names))
1511 result = Fdowncase (result);
1512 #endif
1513 #else /* !DOS_NT */
1514 result = make_specified_string (target, -1, o - target, multibyte);
1515 #endif /* !DOS_NT */
1518 /* Again look to see if the file name has special constructs in it
1519 and perhaps call the corresponding file handler. This is needed
1520 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1521 the ".." component gives us "/user@host:/bar/../baz" which needs
1522 to be expanded again. */
1523 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1524 if (!NILP (handler))
1526 handled_name = call3 (handler, Qexpand_file_name,
1527 result, default_directory);
1528 if (! STRINGP (handled_name))
1529 error ("Invalid handler in `file-name-handler-alist'");
1530 result = handled_name;
1533 SAFE_FREE ();
1534 return result;
1537 #if 0
1538 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1539 This is the old version of expand-file-name, before it was thoroughly
1540 rewritten for Emacs 10.31. We leave this version here commented-out,
1541 because the code is very complex and likely to have subtle bugs. If
1542 bugs _are_ found, it might be of interest to look at the old code and
1543 see what did it do in the relevant situation.
1545 Don't remove this code: it's true that it will be accessible
1546 from the repository, but a few years from deletion, people will
1547 forget it is there. */
1549 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1550 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1551 "Convert FILENAME to absolute, and canonicalize it.\n\
1552 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1553 \(does not start with slash); if DEFAULT is nil or missing,\n\
1554 the current buffer's value of default-directory is used.\n\
1555 Filenames containing `.' or `..' as components are simplified;\n\
1556 initial `~/' expands to your home directory.\n\
1557 See also the function `substitute-in-file-name'.")
1558 (name, defalt)
1559 Lisp_Object name, defalt;
1561 unsigned char *nm;
1563 register unsigned char *newdir, *p, *o;
1564 ptrdiff_t tlen;
1565 unsigned char *target;
1566 struct passwd *pw;
1568 CHECK_STRING (name);
1569 nm = SDATA (name);
1571 /* If nm is absolute, flush ...// and detect /./ and /../.
1572 If no /./ or /../ we can return right away. */
1573 if (nm[0] == '/')
1575 bool lose = 0;
1576 p = nm;
1577 while (*p)
1579 if (p[0] == '/' && p[1] == '/')
1580 nm = p + 1;
1581 if (p[0] == '/' && p[1] == '~')
1582 nm = p + 1, lose = 1;
1583 if (p[0] == '/' && p[1] == '.'
1584 && (p[2] == '/' || p[2] == 0
1585 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1586 lose = 1;
1587 p++;
1589 if (!lose)
1591 if (nm == SDATA (name))
1592 return name;
1593 return build_string (nm);
1597 /* Now determine directory to start with and put it in NEWDIR. */
1599 newdir = 0;
1601 if (nm[0] == '~') /* prefix ~ */
1602 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1604 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1605 newdir = (unsigned char *) "";
1606 nm++;
1608 else /* ~user/filename */
1610 /* Get past ~ to user. */
1611 unsigned char *user = nm + 1;
1612 /* Find end of name. */
1613 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1614 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1615 /* Copy the user name into temp storage. */
1616 o = alloca (len + 1);
1617 memcpy (o, user, len);
1618 o[len] = 0;
1620 /* Look up the user name. */
1621 block_input ();
1622 pw = (struct passwd *) getpwnam (o + 1);
1623 unblock_input ();
1624 if (!pw)
1625 error ("\"%s\" isn't a registered user", o + 1);
1627 newdir = (unsigned char *) pw->pw_dir;
1629 /* Discard the user name from NM. */
1630 nm += len;
1633 if (nm[0] != '/' && !newdir)
1635 if (NILP (defalt))
1636 defalt = current_buffer->directory;
1637 CHECK_STRING (defalt);
1638 newdir = SDATA (defalt);
1641 /* Now concatenate the directory and name to new space in the stack frame. */
1643 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1644 target = alloca (tlen);
1645 *target = 0;
1647 if (newdir)
1649 if (nm[0] == 0 || nm[0] == '/')
1650 strcpy (target, newdir);
1651 else
1652 file_name_as_directory (target, newdir);
1655 strcat (target, nm);
1657 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1659 p = target;
1660 o = target;
1662 while (*p)
1664 if (*p != '/')
1666 *o++ = *p++;
1668 else if (!strncmp (p, "//", 2)
1671 o = target;
1672 p++;
1674 else if (p[0] == '/' && p[1] == '.'
1675 && (p[2] == '/' || p[2] == 0))
1676 p += 2;
1677 else if (!strncmp (p, "/..", 3)
1678 /* `/../' is the "superroot" on certain file systems. */
1679 && o != target
1680 && (p[3] == '/' || p[3] == 0))
1682 while (o != target && *--o != '/')
1684 if (o == target && *o == '/')
1685 ++o;
1686 p += 3;
1688 else
1690 *o++ = *p++;
1694 return make_string (target, o - target);
1696 #endif
1698 /* If /~ or // appears, discard everything through first slash. */
1699 static bool
1700 file_name_absolute_p (const char *filename)
1702 return
1703 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1704 #ifdef DOS_NT
1705 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1706 && IS_DIRECTORY_SEP (filename[2]))
1707 #endif
1711 static char *
1712 search_embedded_absfilename (char *nm, char *endp)
1714 char *p, *s;
1716 for (p = nm + 1; p < endp; p++)
1718 if (IS_DIRECTORY_SEP (p[-1])
1719 && file_name_absolute_p (p)
1720 #if defined (WINDOWSNT) || defined (CYGWIN)
1721 /* // at start of file name is meaningful in Apollo,
1722 WindowsNT and Cygwin systems. */
1723 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1724 #endif /* not (WINDOWSNT || CYGWIN) */
1727 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1728 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1730 USE_SAFE_ALLOCA;
1731 char *o = SAFE_ALLOCA (s - p + 1);
1732 struct passwd *pw;
1733 memcpy (o, p, s - p);
1734 o [s - p] = 0;
1736 /* If we have ~user and `user' exists, discard
1737 everything up to ~. But if `user' does not exist, leave
1738 ~user alone, it might be a literal file name. */
1739 block_input ();
1740 pw = getpwnam (o + 1);
1741 unblock_input ();
1742 SAFE_FREE ();
1743 if (pw)
1744 return p;
1746 else
1747 return p;
1750 return NULL;
1753 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1754 Ssubstitute_in_file_name, 1, 1, 0,
1755 doc: /* Substitute environment variables referred to in FILENAME.
1756 `$FOO' where FOO is an environment variable name means to substitute
1757 the value of that variable. The variable name should be terminated
1758 with a character not a letter, digit or underscore; otherwise, enclose
1759 the entire variable name in braces.
1761 If `/~' appears, all of FILENAME through that `/' is discarded.
1762 If `//' appears, everything up to and including the first of
1763 those `/' is discarded. */)
1764 (Lisp_Object filename)
1766 char *nm, *p, *x, *endp;
1767 bool substituted = false;
1768 bool multibyte;
1769 char *xnm;
1770 Lisp_Object handler;
1772 CHECK_STRING (filename);
1774 multibyte = STRING_MULTIBYTE (filename);
1776 /* If the file name has special constructs in it,
1777 call the corresponding file handler. */
1778 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1779 if (!NILP (handler))
1781 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1782 filename);
1783 if (STRINGP (handled_name))
1784 return handled_name;
1785 error ("Invalid handler in `file-name-handler-alist'");
1788 /* Always work on a copy of the string, in case GC happens during
1789 decode of environment variables, causing the original Lisp_String
1790 data to be relocated. */
1791 USE_SAFE_ALLOCA;
1792 SAFE_ALLOCA_STRING (nm, filename);
1794 #ifdef DOS_NT
1795 dostounix_filename (nm);
1796 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1797 #endif
1798 endp = nm + SBYTES (filename);
1800 /* If /~ or // appears, discard everything through first slash. */
1801 p = search_embedded_absfilename (nm, endp);
1802 if (p)
1803 /* Start over with the new string, so we check the file-name-handler
1804 again. Important with filenames like "/home/foo//:/hello///there"
1805 which would substitute to "/:/hello///there" rather than "/there". */
1807 Lisp_Object result
1808 = (Fsubstitute_in_file_name
1809 (make_specified_string (p, -1, endp - p, multibyte)));
1810 SAFE_FREE ();
1811 return result;
1814 /* See if any variables are substituted into the string. */
1816 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1818 Lisp_Object name
1819 = (!substituted ? filename
1820 : make_specified_string (nm, -1, endp - nm, multibyte));
1821 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1822 CHECK_STRING (tmp);
1823 if (!EQ (tmp, name))
1824 substituted = true;
1825 filename = tmp;
1828 if (!substituted)
1830 #ifdef WINDOWSNT
1831 if (!NILP (Vw32_downcase_file_names))
1832 filename = Fdowncase (filename);
1833 #endif
1834 SAFE_FREE ();
1835 return filename;
1838 xnm = SSDATA (filename);
1839 x = xnm + SBYTES (filename);
1841 /* If /~ or // appears, discard everything through first slash. */
1842 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1843 /* This time we do not start over because we've already expanded envvars
1844 and replaced $$ with $. Maybe we should start over as well, but we'd
1845 need to quote some $ to $$ first. */
1846 xnm = p;
1848 #ifdef WINDOWSNT
1849 if (!NILP (Vw32_downcase_file_names))
1851 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1853 filename = Fdowncase (xname);
1855 else
1856 #endif
1857 if (xnm != SSDATA (filename))
1858 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1859 SAFE_FREE ();
1860 return filename;
1863 /* A slightly faster and more convenient way to get
1864 (directory-file-name (expand-file-name FOO)). */
1866 Lisp_Object
1867 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1869 register Lisp_Object absname;
1871 absname = Fexpand_file_name (filename, defdir);
1873 /* Remove final slash, if any (unless this is the root dir).
1874 stat behaves differently depending! */
1875 if (SCHARS (absname) > 1
1876 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1877 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1878 /* We cannot take shortcuts; they might be wrong for magic file names. */
1879 absname = Fdirectory_file_name (absname);
1880 return absname;
1883 /* Signal an error if the file ABSNAME already exists.
1884 If KNOWN_TO_EXIST, the file is known to exist.
1885 QUERYSTRING is a name for the action that is being considered
1886 to alter the file.
1887 If INTERACTIVE, ask the user whether to proceed,
1888 and bypass the error if the user says to go ahead.
1889 If QUICK, ask for y or n, not yes or no. */
1891 static void
1892 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1893 const char *querystring, bool interactive,
1894 bool quick)
1896 Lisp_Object tem, encoded_filename;
1897 struct stat statbuf;
1898 struct gcpro gcpro1;
1900 encoded_filename = ENCODE_FILE (absname);
1902 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1904 if (S_ISDIR (statbuf.st_mode))
1905 xsignal2 (Qfile_error,
1906 build_string ("File is a directory"), absname);
1907 known_to_exist = true;
1910 if (known_to_exist)
1912 if (! interactive)
1913 xsignal2 (Qfile_already_exists,
1914 build_string ("File already exists"), absname);
1915 GCPRO1 (absname);
1916 tem = format2 ("File %s already exists; %s anyway? ",
1917 absname, build_string (querystring));
1918 if (quick)
1919 tem = call1 (intern ("y-or-n-p"), tem);
1920 else
1921 tem = do_yes_or_no_p (tem);
1922 UNGCPRO;
1923 if (NILP (tem))
1924 xsignal2 (Qfile_already_exists,
1925 build_string ("File already exists"), absname);
1929 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1930 "fCopy file: \nGCopy %s to file: \np\nP",
1931 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1932 If NEWNAME names a directory, copy FILE there.
1934 This function always sets the file modes of the output file to match
1935 the input file.
1937 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1938 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1939 signal a `file-already-exists' error without overwriting. If
1940 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1941 about overwriting; this is what happens in interactive use with M-x.
1942 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1943 existing file.
1945 Fourth arg KEEP-TIME non-nil means give the output file the same
1946 last-modified time as the old one. (This works on only some systems.)
1948 A prefix arg makes KEEP-TIME non-nil.
1950 If PRESERVE-UID-GID is non-nil, we try to transfer the
1951 uid and gid of FILE to NEWNAME.
1953 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1954 this includes the file modes, along with ACL entries and SELinux
1955 context if present. Otherwise, if NEWNAME is created its file
1956 permission bits are those of FILE, masked by the default file
1957 permissions. */)
1958 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1959 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1960 Lisp_Object preserve_permissions)
1962 Lisp_Object handler;
1963 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1964 ptrdiff_t count = SPECPDL_INDEX ();
1965 Lisp_Object encoded_file, encoded_newname;
1966 #if HAVE_LIBSELINUX
1967 security_context_t con;
1968 int conlength = 0;
1969 #endif
1970 #ifdef WINDOWSNT
1971 int result;
1972 #else
1973 bool already_exists = false;
1974 mode_t new_mask;
1975 int ifd, ofd;
1976 int n;
1977 char buf[16 * 1024];
1978 struct stat st;
1979 #endif
1981 encoded_file = encoded_newname = Qnil;
1982 GCPRO4 (file, newname, encoded_file, encoded_newname);
1983 CHECK_STRING (file);
1984 CHECK_STRING (newname);
1986 if (!NILP (Ffile_directory_p (newname)))
1987 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1988 else
1989 newname = Fexpand_file_name (newname, Qnil);
1991 file = Fexpand_file_name (file, Qnil);
1993 /* If the input file name has special constructs in it,
1994 call the corresponding file handler. */
1995 handler = Ffind_file_name_handler (file, Qcopy_file);
1996 /* Likewise for output file name. */
1997 if (NILP (handler))
1998 handler = Ffind_file_name_handler (newname, Qcopy_file);
1999 if (!NILP (handler))
2000 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
2001 ok_if_already_exists, keep_time, preserve_uid_gid,
2002 preserve_permissions));
2004 encoded_file = ENCODE_FILE (file);
2005 encoded_newname = ENCODE_FILE (newname);
2007 #ifdef WINDOWSNT
2008 if (NILP (ok_if_already_exists)
2009 || INTEGERP (ok_if_already_exists))
2010 barf_or_query_if_file_exists (newname, false, "copy to it",
2011 INTEGERP (ok_if_already_exists), false);
2013 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
2014 !NILP (keep_time), !NILP (preserve_uid_gid),
2015 !NILP (preserve_permissions));
2016 switch (result)
2018 case -1:
2019 report_file_error ("Copying file", list2 (file, newname));
2020 case -2:
2021 report_file_error ("Copying permissions from", file);
2022 case -3:
2023 xsignal2 (Qfile_date_error,
2024 build_string ("Resetting file times"), newname);
2025 case -4:
2026 report_file_error ("Copying permissions to", newname);
2028 #else /* not WINDOWSNT */
2029 immediate_quit = 1;
2030 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
2031 immediate_quit = 0;
2033 if (ifd < 0)
2034 report_file_error ("Opening input file", file);
2036 record_unwind_protect_int (close_file_unwind, ifd);
2038 if (fstat (ifd, &st) != 0)
2039 report_file_error ("Input file status", file);
2041 if (!NILP (preserve_permissions))
2043 #if HAVE_LIBSELINUX
2044 if (is_selinux_enabled ())
2046 conlength = fgetfilecon (ifd, &con);
2047 if (conlength == -1)
2048 report_file_error ("Doing fgetfilecon", file);
2050 #endif
2053 /* We can copy only regular files. */
2054 if (!S_ISREG (st.st_mode))
2055 report_file_errno ("Non-regular file", file,
2056 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
2058 #ifndef MSDOS
2059 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
2060 #else
2061 new_mask = S_IREAD | S_IWRITE;
2062 #endif
2064 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
2065 new_mask);
2066 if (ofd < 0 && errno == EEXIST)
2068 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
2069 barf_or_query_if_file_exists (newname, true, "copy to it",
2070 INTEGERP (ok_if_already_exists), false);
2071 already_exists = true;
2072 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
2074 if (ofd < 0)
2075 report_file_error ("Opening output file", newname);
2077 record_unwind_protect_int (close_file_unwind, ofd);
2079 if (already_exists)
2081 struct stat out_st;
2082 if (fstat (ofd, &out_st) != 0)
2083 report_file_error ("Output file status", newname);
2084 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2085 report_file_errno ("Input and output files are the same",
2086 list2 (file, newname), 0);
2087 if (ftruncate (ofd, 0) != 0)
2088 report_file_error ("Truncating output file", newname);
2091 immediate_quit = 1;
2092 QUIT;
2093 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2094 if (emacs_write_sig (ofd, buf, n) != n)
2095 report_file_error ("Write error", newname);
2096 immediate_quit = 0;
2098 #ifndef MSDOS
2099 /* Preserve the original file permissions, and if requested, also its
2100 owner and group. */
2102 mode_t preserved_permissions = st.st_mode & 07777;
2103 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2104 if (!NILP (preserve_uid_gid))
2106 /* Attempt to change owner and group. If that doesn't work
2107 attempt to change just the group, as that is sometimes allowed.
2108 Adjust the mode mask to eliminate setuid or setgid bits
2109 or group permissions bits that are inappropriate if the
2110 owner or group are wrong. */
2111 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2113 if (fchown (ofd, -1, st.st_gid) == 0)
2114 preserved_permissions &= ~04000;
2115 else
2117 preserved_permissions &= ~06000;
2119 /* Copy the other bits to the group bits, since the
2120 group is wrong. */
2121 preserved_permissions &= ~070;
2122 preserved_permissions |= (preserved_permissions & 7) << 3;
2123 default_permissions &= ~070;
2124 default_permissions |= (default_permissions & 7) << 3;
2129 switch (!NILP (preserve_permissions)
2130 ? qcopy_acl (SSDATA (encoded_file), ifd,
2131 SSDATA (encoded_newname), ofd,
2132 preserved_permissions)
2133 : (already_exists
2134 || (new_mask & ~realmask) == default_permissions)
2136 : fchmod (ofd, default_permissions))
2138 case -2: report_file_error ("Copying permissions from", file);
2139 case -1: report_file_error ("Copying permissions to", newname);
2142 #endif /* not MSDOS */
2144 #if HAVE_LIBSELINUX
2145 if (conlength > 0)
2147 /* Set the modified context back to the file. */
2148 bool fail = fsetfilecon (ofd, con) != 0;
2149 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2150 if (fail && errno != ENOTSUP)
2151 report_file_error ("Doing fsetfilecon", newname);
2153 freecon (con);
2155 #endif
2157 if (!NILP (keep_time))
2159 struct timespec atime = get_stat_atime (&st);
2160 struct timespec mtime = get_stat_mtime (&st);
2161 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2162 xsignal2 (Qfile_date_error,
2163 build_string ("Cannot set file date"), newname);
2166 if (emacs_close (ofd) < 0)
2167 report_file_error ("Write error", newname);
2169 emacs_close (ifd);
2171 #ifdef MSDOS
2172 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2173 and if it can't, it tells so. Otherwise, under MSDOS we usually
2174 get only the READ bit, which will make the copied file read-only,
2175 so it's better not to chmod at all. */
2176 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2177 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2178 #endif /* MSDOS */
2179 #endif /* not WINDOWSNT */
2181 /* Discard the unwind protects. */
2182 specpdl_ptr = specpdl + count;
2184 UNGCPRO;
2185 return Qnil;
2188 DEFUN ("make-directory-internal", Fmake_directory_internal,
2189 Smake_directory_internal, 1, 1, 0,
2190 doc: /* Create a new directory named DIRECTORY. */)
2191 (Lisp_Object directory)
2193 const char *dir;
2194 Lisp_Object handler;
2195 Lisp_Object encoded_dir;
2197 CHECK_STRING (directory);
2198 directory = Fexpand_file_name (directory, Qnil);
2200 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2201 if (!NILP (handler))
2202 return call2 (handler, Qmake_directory_internal, directory);
2204 encoded_dir = ENCODE_FILE (directory);
2206 dir = SSDATA (encoded_dir);
2208 #ifdef WINDOWSNT
2209 if (mkdir (dir) != 0)
2210 #else
2211 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2212 #endif
2213 report_file_error ("Creating directory", directory);
2215 return Qnil;
2218 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2219 Sdelete_directory_internal, 1, 1, 0,
2220 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2221 (Lisp_Object directory)
2223 const char *dir;
2224 Lisp_Object encoded_dir;
2226 CHECK_STRING (directory);
2227 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2228 encoded_dir = ENCODE_FILE (directory);
2229 dir = SSDATA (encoded_dir);
2231 if (rmdir (dir) != 0)
2232 report_file_error ("Removing directory", directory);
2234 return Qnil;
2237 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2238 "(list (read-file-name \
2239 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2240 \"Move file to trash: \" \"Delete file: \") \
2241 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2242 (null current-prefix-arg))",
2243 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2244 If file has multiple names, it continues to exist with the other names.
2245 TRASH non-nil means to trash the file instead of deleting, provided
2246 `delete-by-moving-to-trash' is non-nil.
2248 When called interactively, TRASH is t if no prefix argument is given.
2249 With a prefix argument, TRASH is nil. */)
2250 (Lisp_Object filename, Lisp_Object trash)
2252 Lisp_Object handler;
2253 Lisp_Object encoded_file;
2254 struct gcpro gcpro1;
2256 GCPRO1 (filename);
2257 if (!NILP (Ffile_directory_p (filename))
2258 && NILP (Ffile_symlink_p (filename)))
2259 xsignal2 (Qfile_error,
2260 build_string ("Removing old name: is a directory"),
2261 filename);
2262 UNGCPRO;
2263 filename = Fexpand_file_name (filename, Qnil);
2265 handler = Ffind_file_name_handler (filename, Qdelete_file);
2266 if (!NILP (handler))
2267 return call3 (handler, Qdelete_file, filename, trash);
2269 if (delete_by_moving_to_trash && !NILP (trash))
2270 return call1 (Qmove_file_to_trash, filename);
2272 encoded_file = ENCODE_FILE (filename);
2274 if (unlink (SSDATA (encoded_file)) < 0)
2275 report_file_error ("Removing old name", filename);
2276 return Qnil;
2279 static Lisp_Object
2280 internal_delete_file_1 (Lisp_Object ignore)
2282 return Qt;
2285 /* Delete file FILENAME, returning true if successful.
2286 This ignores `delete-by-moving-to-trash'. */
2288 bool
2289 internal_delete_file (Lisp_Object filename)
2291 Lisp_Object tem;
2293 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2294 Qt, internal_delete_file_1);
2295 return NILP (tem);
2298 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2299 "fRename file: \nGRename %s to file: \np",
2300 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2301 If file has names other than FILE, it continues to have those names.
2302 Signals a `file-already-exists' error if a file NEWNAME already exists
2303 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2304 A number as third arg means request confirmation if NEWNAME already exists.
2305 This is what happens in interactive use with M-x. */)
2306 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2308 Lisp_Object handler;
2309 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2310 Lisp_Object encoded_file, encoded_newname, symlink_target;
2312 symlink_target = encoded_file = encoded_newname = Qnil;
2313 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2314 CHECK_STRING (file);
2315 CHECK_STRING (newname);
2316 file = Fexpand_file_name (file, Qnil);
2318 if ((!NILP (Ffile_directory_p (newname)))
2319 #ifdef DOS_NT
2320 /* If the file names are identical but for the case,
2321 don't attempt to move directory to itself. */
2322 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2323 #endif
2326 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2327 ? file : Fdirectory_file_name (file));
2328 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2330 else
2331 newname = Fexpand_file_name (newname, Qnil);
2333 /* If the file name has special constructs in it,
2334 call the corresponding file handler. */
2335 handler = Ffind_file_name_handler (file, Qrename_file);
2336 if (NILP (handler))
2337 handler = Ffind_file_name_handler (newname, Qrename_file);
2338 if (!NILP (handler))
2339 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2340 file, newname, ok_if_already_exists));
2342 encoded_file = ENCODE_FILE (file);
2343 encoded_newname = ENCODE_FILE (newname);
2345 #ifdef DOS_NT
2346 /* If the file names are identical but for the case, don't ask for
2347 confirmation: they simply want to change the letter-case of the
2348 file name. */
2349 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2350 #endif
2351 if (NILP (ok_if_already_exists)
2352 || INTEGERP (ok_if_already_exists))
2353 barf_or_query_if_file_exists (newname, false, "rename to it",
2354 INTEGERP (ok_if_already_exists), false);
2355 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2357 int rename_errno = errno;
2358 if (rename_errno == EXDEV)
2360 ptrdiff_t count;
2361 symlink_target = Ffile_symlink_p (file);
2362 if (! NILP (symlink_target))
2363 Fmake_symbolic_link (symlink_target, newname,
2364 NILP (ok_if_already_exists) ? Qnil : Qt);
2365 else if (!NILP (Ffile_directory_p (file)))
2366 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2367 else
2368 /* We have already prompted if it was an integer, so don't
2369 have copy-file prompt again. */
2370 Fcopy_file (file, newname,
2371 NILP (ok_if_already_exists) ? Qnil : Qt,
2372 Qt, Qt, Qt);
2374 count = SPECPDL_INDEX ();
2375 specbind (Qdelete_by_moving_to_trash, Qnil);
2377 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2378 call2 (Qdelete_directory, file, Qt);
2379 else
2380 Fdelete_file (file, Qnil);
2381 unbind_to (count, Qnil);
2383 else
2384 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2386 UNGCPRO;
2387 return Qnil;
2390 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2391 "fAdd name to file: \nGName to add to %s: \np",
2392 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2393 Signals a `file-already-exists' error if a file NEWNAME already exists
2394 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2395 A number as third arg means request confirmation if NEWNAME already exists.
2396 This is what happens in interactive use with M-x. */)
2397 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2399 Lisp_Object handler;
2400 Lisp_Object encoded_file, encoded_newname;
2401 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2403 GCPRO4 (file, newname, encoded_file, encoded_newname);
2404 encoded_file = encoded_newname = Qnil;
2405 CHECK_STRING (file);
2406 CHECK_STRING (newname);
2407 file = Fexpand_file_name (file, Qnil);
2409 if (!NILP (Ffile_directory_p (newname)))
2410 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2411 else
2412 newname = Fexpand_file_name (newname, Qnil);
2414 /* If the file name has special constructs in it,
2415 call the corresponding file handler. */
2416 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2417 if (!NILP (handler))
2418 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2419 newname, ok_if_already_exists));
2421 /* If the new name has special constructs in it,
2422 call the corresponding file handler. */
2423 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2424 if (!NILP (handler))
2425 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2426 newname, ok_if_already_exists));
2428 encoded_file = ENCODE_FILE (file);
2429 encoded_newname = ENCODE_FILE (newname);
2431 if (NILP (ok_if_already_exists)
2432 || INTEGERP (ok_if_already_exists))
2433 barf_or_query_if_file_exists (newname, false, "make it a new name",
2434 INTEGERP (ok_if_already_exists), false);
2436 unlink (SSDATA (newname));
2437 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2439 int link_errno = errno;
2440 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2443 UNGCPRO;
2444 return Qnil;
2447 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2448 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2449 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2450 Both args must be strings.
2451 Signals a `file-already-exists' error if a file LINKNAME already exists
2452 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2453 A number as third arg means request confirmation if LINKNAME already exists.
2454 This happens for interactive use with M-x. */)
2455 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2457 Lisp_Object handler;
2458 Lisp_Object encoded_filename, encoded_linkname;
2459 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2461 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2462 encoded_filename = encoded_linkname = Qnil;
2463 CHECK_STRING (filename);
2464 CHECK_STRING (linkname);
2465 /* If the link target has a ~, we must expand it to get
2466 a truly valid file name. Otherwise, do not expand;
2467 we want to permit links to relative file names. */
2468 if (SREF (filename, 0) == '~')
2469 filename = Fexpand_file_name (filename, Qnil);
2471 if (!NILP (Ffile_directory_p (linkname)))
2472 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2473 else
2474 linkname = Fexpand_file_name (linkname, Qnil);
2476 /* If the file name has special constructs in it,
2477 call the corresponding file handler. */
2478 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2479 if (!NILP (handler))
2480 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2481 linkname, ok_if_already_exists));
2483 /* If the new link name has special constructs in it,
2484 call the corresponding file handler. */
2485 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2486 if (!NILP (handler))
2487 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2488 linkname, ok_if_already_exists));
2490 encoded_filename = ENCODE_FILE (filename);
2491 encoded_linkname = ENCODE_FILE (linkname);
2493 if (NILP (ok_if_already_exists)
2494 || INTEGERP (ok_if_already_exists))
2495 barf_or_query_if_file_exists (linkname, false, "make it a link",
2496 INTEGERP (ok_if_already_exists), false);
2497 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname)) < 0)
2499 /* If we didn't complain already, silently delete existing file. */
2500 int symlink_errno;
2501 if (errno == EEXIST)
2503 unlink (SSDATA (encoded_linkname));
2504 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname))
2505 >= 0)
2507 UNGCPRO;
2508 return Qnil;
2511 if (errno == ENOSYS)
2513 UNGCPRO;
2514 xsignal1 (Qfile_error,
2515 build_string ("Symbolic links are not supported"));
2518 symlink_errno = errno;
2519 report_file_errno ("Making symbolic link", list2 (filename, linkname),
2520 symlink_errno);
2522 UNGCPRO;
2523 return Qnil;
2527 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2528 1, 1, 0,
2529 doc: /* Return t if file FILENAME specifies an absolute file name.
2530 On Unix, this is a name starting with a `/' or a `~'. */)
2531 (Lisp_Object filename)
2533 CHECK_STRING (filename);
2534 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2537 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2538 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2539 See also `file-readable-p' and `file-attributes'.
2540 This returns nil for a symlink to a nonexistent file.
2541 Use `file-symlink-p' to test for such links. */)
2542 (Lisp_Object filename)
2544 Lisp_Object absname;
2545 Lisp_Object handler;
2547 CHECK_STRING (filename);
2548 absname = Fexpand_file_name (filename, Qnil);
2550 /* If the file name has special constructs in it,
2551 call the corresponding file handler. */
2552 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2553 if (!NILP (handler))
2555 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2556 errno = 0;
2557 return result;
2560 absname = ENCODE_FILE (absname);
2562 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2565 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2566 doc: /* Return t if FILENAME can be executed by you.
2567 For a directory, this means you can access files in that directory.
2568 \(It is generally better to use `file-accessible-directory-p' for that
2569 purpose, though.) */)
2570 (Lisp_Object filename)
2572 Lisp_Object absname;
2573 Lisp_Object handler;
2575 CHECK_STRING (filename);
2576 absname = Fexpand_file_name (filename, Qnil);
2578 /* If the file name has special constructs in it,
2579 call the corresponding file handler. */
2580 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2581 if (!NILP (handler))
2582 return call2 (handler, Qfile_executable_p, absname);
2584 absname = ENCODE_FILE (absname);
2586 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2589 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2590 doc: /* Return t if file FILENAME exists and you can read it.
2591 See also `file-exists-p' and `file-attributes'. */)
2592 (Lisp_Object filename)
2594 Lisp_Object absname;
2595 Lisp_Object handler;
2597 CHECK_STRING (filename);
2598 absname = Fexpand_file_name (filename, Qnil);
2600 /* If the file name has special constructs in it,
2601 call the corresponding file handler. */
2602 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2603 if (!NILP (handler))
2604 return call2 (handler, Qfile_readable_p, absname);
2606 absname = ENCODE_FILE (absname);
2607 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2608 ? Qt : Qnil);
2611 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2612 doc: /* Return t if file FILENAME can be written or created by you. */)
2613 (Lisp_Object filename)
2615 Lisp_Object absname, dir, encoded;
2616 Lisp_Object handler;
2618 CHECK_STRING (filename);
2619 absname = Fexpand_file_name (filename, Qnil);
2621 /* If the file name has special constructs in it,
2622 call the corresponding file handler. */
2623 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2624 if (!NILP (handler))
2625 return call2 (handler, Qfile_writable_p, absname);
2627 encoded = ENCODE_FILE (absname);
2628 if (check_writable (SSDATA (encoded), W_OK))
2629 return Qt;
2630 if (errno != ENOENT)
2631 return Qnil;
2633 dir = Ffile_name_directory (absname);
2634 eassert (!NILP (dir));
2635 #ifdef MSDOS
2636 dir = Fdirectory_file_name (dir);
2637 #endif /* MSDOS */
2639 dir = ENCODE_FILE (dir);
2640 #ifdef WINDOWSNT
2641 /* The read-only attribute of the parent directory doesn't affect
2642 whether a file or directory can be created within it. Some day we
2643 should check ACLs though, which do affect this. */
2644 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2645 #else
2646 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2647 #endif
2650 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2651 doc: /* Access file FILENAME, and get an error if that does not work.
2652 The second argument STRING is used in the error message.
2653 If there is no error, returns nil. */)
2654 (Lisp_Object filename, Lisp_Object string)
2656 Lisp_Object handler, encoded_filename, absname;
2658 CHECK_STRING (filename);
2659 absname = Fexpand_file_name (filename, Qnil);
2661 CHECK_STRING (string);
2663 /* If the file name has special constructs in it,
2664 call the corresponding file handler. */
2665 handler = Ffind_file_name_handler (absname, Qaccess_file);
2666 if (!NILP (handler))
2667 return call3 (handler, Qaccess_file, absname, string);
2669 encoded_filename = ENCODE_FILE (absname);
2671 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2672 report_file_error (SSDATA (string), filename);
2674 return Qnil;
2677 /* Relative to directory FD, return the symbolic link value of FILENAME.
2678 On failure, return nil. */
2679 Lisp_Object
2680 emacs_readlinkat (int fd, char const *filename)
2682 static struct allocator const emacs_norealloc_allocator =
2683 { xmalloc, NULL, xfree, memory_full };
2684 Lisp_Object val;
2685 char readlink_buf[1024];
2686 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2687 &emacs_norealloc_allocator, readlinkat);
2688 if (!buf)
2689 return Qnil;
2691 val = build_unibyte_string (buf);
2692 if (buf[0] == '/' && strchr (buf, ':'))
2693 val = concat2 (build_unibyte_string ("/:"), val);
2694 if (buf != readlink_buf)
2695 xfree (buf);
2696 val = DECODE_FILE (val);
2697 return val;
2700 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2701 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2702 The value is the link target, as a string.
2703 Otherwise it returns nil.
2705 This function does not check whether the link target exists. */)
2706 (Lisp_Object filename)
2708 Lisp_Object handler;
2710 CHECK_STRING (filename);
2711 filename = Fexpand_file_name (filename, Qnil);
2713 /* If the file name has special constructs in it,
2714 call the corresponding file handler. */
2715 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2716 if (!NILP (handler))
2717 return call2 (handler, Qfile_symlink_p, filename);
2719 filename = ENCODE_FILE (filename);
2721 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2724 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2725 doc: /* Return t if FILENAME names an existing directory.
2726 Symbolic links to directories count as directories.
2727 See `file-symlink-p' to distinguish symlinks. */)
2728 (Lisp_Object filename)
2730 Lisp_Object absname;
2731 Lisp_Object handler;
2733 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2735 /* If the file name has special constructs in it,
2736 call the corresponding file handler. */
2737 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2738 if (!NILP (handler))
2739 return call2 (handler, Qfile_directory_p, absname);
2741 absname = ENCODE_FILE (absname);
2743 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2746 /* Return true if FILE is a directory or a symlink to a directory. */
2747 bool
2748 file_directory_p (char const *file)
2750 #ifdef WINDOWSNT
2751 /* This is cheaper than 'stat'. */
2752 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2753 #else
2754 struct stat st;
2755 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2756 #endif
2759 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2760 Sfile_accessible_directory_p, 1, 1, 0,
2761 doc: /* Return t if file FILENAME names a directory you can open.
2762 For the value to be t, FILENAME must specify the name of a directory as a file,
2763 and the directory must allow you to open files in it. In order to use a
2764 directory as a buffer's current directory, this predicate must return true.
2765 A directory name spec may be given instead; then the value is t
2766 if the directory so specified exists and really is a readable and
2767 searchable directory. */)
2768 (Lisp_Object filename)
2770 Lisp_Object absname;
2771 Lisp_Object handler;
2773 CHECK_STRING (filename);
2774 absname = Fexpand_file_name (filename, Qnil);
2776 /* If the file name has special constructs in it,
2777 call the corresponding file handler. */
2778 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2779 if (!NILP (handler))
2781 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2782 errno = 0;
2783 return r;
2786 absname = ENCODE_FILE (absname);
2787 return file_accessible_directory_p (absname) ? Qt : Qnil;
2790 /* If FILE is a searchable directory or a symlink to a
2791 searchable directory, return true. Otherwise return
2792 false and set errno to an error number. */
2793 bool
2794 file_accessible_directory_p (Lisp_Object file)
2796 #ifdef DOS_NT
2797 /* There's no need to test whether FILE is searchable, as the
2798 searchable/executable bit is invented on DOS_NT platforms. */
2799 return file_directory_p (SSDATA (file));
2800 #else
2801 /* On POSIXish platforms, use just one system call; this avoids a
2802 race and is typically faster. */
2803 const char *data = SSDATA (file);
2804 ptrdiff_t len = SBYTES (file);
2805 char const *dir;
2806 bool ok;
2807 int saved_errno;
2808 USE_SAFE_ALLOCA;
2810 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2811 There are three exceptions: "", "/", and "//". Leave "" alone,
2812 as it's invalid. Append only "." to the other two exceptions as
2813 "/" and "//" are distinct on some platforms, whereas "/", "///",
2814 "////", etc. are all equivalent. */
2815 if (! len)
2816 dir = data;
2817 else
2819 /* Just check for trailing '/' when deciding whether to append '/'.
2820 That's simpler than testing the two special cases "/" and "//",
2821 and it's a safe optimization here. */
2822 char *buf = SAFE_ALLOCA (len + 3);
2823 memcpy (buf, data, len);
2824 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2825 dir = buf;
2828 ok = check_existing (dir);
2829 saved_errno = errno;
2830 SAFE_FREE ();
2831 errno = saved_errno;
2832 return ok;
2833 #endif
2836 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2837 doc: /* Return t if FILENAME names a regular file.
2838 This is the sort of file that holds an ordinary stream of data bytes.
2839 Symbolic links to regular files count as regular files.
2840 See `file-symlink-p' to distinguish symlinks. */)
2841 (Lisp_Object filename)
2843 register Lisp_Object absname;
2844 struct stat st;
2845 Lisp_Object handler;
2847 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2849 /* If the file name has special constructs in it,
2850 call the corresponding file handler. */
2851 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2852 if (!NILP (handler))
2853 return call2 (handler, Qfile_regular_p, absname);
2855 absname = ENCODE_FILE (absname);
2857 #ifdef WINDOWSNT
2859 int result;
2860 Lisp_Object tem = Vw32_get_true_file_attributes;
2862 /* Tell stat to use expensive method to get accurate info. */
2863 Vw32_get_true_file_attributes = Qt;
2864 result = stat (SDATA (absname), &st);
2865 Vw32_get_true_file_attributes = tem;
2867 if (result < 0)
2868 return Qnil;
2869 return S_ISREG (st.st_mode) ? Qt : Qnil;
2871 #else
2872 if (stat (SSDATA (absname), &st) < 0)
2873 return Qnil;
2874 return S_ISREG (st.st_mode) ? Qt : Qnil;
2875 #endif
2878 DEFUN ("file-selinux-context", Ffile_selinux_context,
2879 Sfile_selinux_context, 1, 1, 0,
2880 doc: /* Return SELinux context of file named FILENAME.
2881 The return value is a list (USER ROLE TYPE RANGE), where the list
2882 elements are strings naming the user, role, type, and range of the
2883 file's SELinux security context.
2885 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2886 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2887 (Lisp_Object filename)
2889 Lisp_Object absname;
2890 Lisp_Object values[4];
2891 Lisp_Object handler;
2892 #if HAVE_LIBSELINUX
2893 security_context_t con;
2894 int conlength;
2895 context_t context;
2896 #endif
2898 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2900 /* If the file name has special constructs in it,
2901 call the corresponding file handler. */
2902 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2903 if (!NILP (handler))
2904 return call2 (handler, Qfile_selinux_context, absname);
2906 absname = ENCODE_FILE (absname);
2908 values[0] = Qnil;
2909 values[1] = Qnil;
2910 values[2] = Qnil;
2911 values[3] = Qnil;
2912 #if HAVE_LIBSELINUX
2913 if (is_selinux_enabled ())
2915 conlength = lgetfilecon (SSDATA (absname), &con);
2916 if (conlength > 0)
2918 context = context_new (con);
2919 if (context_user_get (context))
2920 values[0] = build_string (context_user_get (context));
2921 if (context_role_get (context))
2922 values[1] = build_string (context_role_get (context));
2923 if (context_type_get (context))
2924 values[2] = build_string (context_type_get (context));
2925 if (context_range_get (context))
2926 values[3] = build_string (context_range_get (context));
2927 context_free (context);
2928 freecon (con);
2931 #endif
2933 return Flist (ARRAYELTS (values), values);
2936 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2937 Sset_file_selinux_context, 2, 2, 0,
2938 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2939 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2940 elements are strings naming the components of a SELinux context.
2942 Value is t if setting of SELinux context was successful, nil otherwise.
2944 This function does nothing and returns nil if SELinux is disabled,
2945 or if Emacs was not compiled with SELinux support. */)
2946 (Lisp_Object filename, Lisp_Object context)
2948 Lisp_Object absname;
2949 Lisp_Object handler;
2950 #if HAVE_LIBSELINUX
2951 Lisp_Object encoded_absname;
2952 Lisp_Object user = CAR_SAFE (context);
2953 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2954 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2955 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2956 security_context_t con;
2957 bool fail;
2958 int conlength;
2959 context_t parsed_con;
2960 #endif
2962 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2964 /* If the file name has special constructs in it,
2965 call the corresponding file handler. */
2966 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2967 if (!NILP (handler))
2968 return call3 (handler, Qset_file_selinux_context, absname, context);
2970 #if HAVE_LIBSELINUX
2971 if (is_selinux_enabled ())
2973 /* Get current file context. */
2974 encoded_absname = ENCODE_FILE (absname);
2975 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2976 if (conlength > 0)
2978 parsed_con = context_new (con);
2979 /* Change the parts defined in the parameter.*/
2980 if (STRINGP (user))
2982 if (context_user_set (parsed_con, SSDATA (user)))
2983 error ("Doing context_user_set");
2985 if (STRINGP (role))
2987 if (context_role_set (parsed_con, SSDATA (role)))
2988 error ("Doing context_role_set");
2990 if (STRINGP (type))
2992 if (context_type_set (parsed_con, SSDATA (type)))
2993 error ("Doing context_type_set");
2995 if (STRINGP (range))
2997 if (context_range_set (parsed_con, SSDATA (range)))
2998 error ("Doing context_range_set");
3001 /* Set the modified context back to the file. */
3002 fail = (lsetfilecon (SSDATA (encoded_absname),
3003 context_str (parsed_con))
3004 != 0);
3005 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
3006 if (fail && errno != ENOTSUP)
3007 report_file_error ("Doing lsetfilecon", absname);
3009 context_free (parsed_con);
3010 freecon (con);
3011 return fail ? Qnil : Qt;
3013 else
3014 report_file_error ("Doing lgetfilecon", absname);
3016 #endif
3018 return Qnil;
3021 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
3022 doc: /* Return ACL entries of file named FILENAME.
3023 The entries are returned in a format suitable for use in `set-file-acl'
3024 but is otherwise undocumented and subject to change.
3025 Return nil if file does not exist or is not accessible, or if Emacs
3026 was unable to determine the ACL entries. */)
3027 (Lisp_Object filename)
3029 Lisp_Object absname;
3030 Lisp_Object handler;
3031 #ifdef HAVE_ACL_SET_FILE
3032 acl_t acl;
3033 Lisp_Object acl_string;
3034 char *str;
3035 # ifndef HAVE_ACL_TYPE_EXTENDED
3036 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
3037 # endif
3038 #endif
3040 absname = expand_and_dir_to_file (filename,
3041 BVAR (current_buffer, directory));
3043 /* If the file name has special constructs in it,
3044 call the corresponding file handler. */
3045 handler = Ffind_file_name_handler (absname, Qfile_acl);
3046 if (!NILP (handler))
3047 return call2 (handler, Qfile_acl, absname);
3049 #ifdef HAVE_ACL_SET_FILE
3050 absname = ENCODE_FILE (absname);
3052 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3053 if (acl == NULL)
3054 return Qnil;
3056 str = acl_to_text (acl, NULL);
3057 if (str == NULL)
3059 acl_free (acl);
3060 return Qnil;
3063 acl_string = build_string (str);
3064 acl_free (str);
3065 acl_free (acl);
3067 return acl_string;
3068 #endif
3070 return Qnil;
3073 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3074 2, 2, 0,
3075 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3076 ACL-STRING should contain the textual representation of the ACL
3077 entries in a format suitable for the platform.
3079 Value is t if setting of ACL was successful, nil otherwise.
3081 Setting ACL for local files requires Emacs to be built with ACL
3082 support. */)
3083 (Lisp_Object filename, Lisp_Object acl_string)
3085 Lisp_Object absname;
3086 Lisp_Object handler;
3087 #ifdef HAVE_ACL_SET_FILE
3088 Lisp_Object encoded_absname;
3089 acl_t acl;
3090 bool fail;
3091 #endif
3093 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3095 /* If the file name has special constructs in it,
3096 call the corresponding file handler. */
3097 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3098 if (!NILP (handler))
3099 return call3 (handler, Qset_file_acl, absname, acl_string);
3101 #ifdef HAVE_ACL_SET_FILE
3102 if (STRINGP (acl_string))
3104 acl = acl_from_text (SSDATA (acl_string));
3105 if (acl == NULL)
3107 report_file_error ("Converting ACL", absname);
3108 return Qnil;
3111 encoded_absname = ENCODE_FILE (absname);
3113 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3114 acl)
3115 != 0);
3116 if (fail && acl_errno_valid (errno))
3117 report_file_error ("Setting ACL", absname);
3119 acl_free (acl);
3120 return fail ? Qnil : Qt;
3122 #endif
3124 return Qnil;
3127 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3128 doc: /* Return mode bits of file named FILENAME, as an integer.
3129 Return nil, if file does not exist or is not accessible. */)
3130 (Lisp_Object filename)
3132 Lisp_Object absname;
3133 struct stat st;
3134 Lisp_Object handler;
3136 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3138 /* If the file name has special constructs in it,
3139 call the corresponding file handler. */
3140 handler = Ffind_file_name_handler (absname, Qfile_modes);
3141 if (!NILP (handler))
3142 return call2 (handler, Qfile_modes, absname);
3144 absname = ENCODE_FILE (absname);
3146 if (stat (SSDATA (absname), &st) < 0)
3147 return Qnil;
3149 return make_number (st.st_mode & 07777);
3152 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3153 "(let ((file (read-file-name \"File: \"))) \
3154 (list file (read-file-modes nil file)))",
3155 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3156 Only the 12 low bits of MODE are used.
3158 Interactively, mode bits are read by `read-file-modes', which accepts
3159 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3160 (Lisp_Object filename, Lisp_Object mode)
3162 Lisp_Object absname, encoded_absname;
3163 Lisp_Object handler;
3165 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3166 CHECK_NUMBER (mode);
3168 /* If the file name has special constructs in it,
3169 call the corresponding file handler. */
3170 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3171 if (!NILP (handler))
3172 return call3 (handler, Qset_file_modes, absname, mode);
3174 encoded_absname = ENCODE_FILE (absname);
3176 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3177 report_file_error ("Doing chmod", absname);
3179 return Qnil;
3182 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3183 doc: /* Set the file permission bits for newly created files.
3184 The argument MODE should be an integer; only the low 9 bits are used.
3185 This setting is inherited by subprocesses. */)
3186 (Lisp_Object mode)
3188 mode_t oldrealmask, oldumask, newumask;
3189 CHECK_NUMBER (mode);
3190 oldrealmask = realmask;
3191 newumask = ~ XINT (mode) & 0777;
3193 block_input ();
3194 realmask = newumask;
3195 oldumask = umask (newumask);
3196 unblock_input ();
3198 eassert (oldumask == oldrealmask);
3199 return Qnil;
3202 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3203 doc: /* Return the default file protection for created files.
3204 The value is an integer. */)
3205 (void)
3207 Lisp_Object value;
3208 XSETINT (value, (~ realmask) & 0777);
3209 return value;
3213 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3214 doc: /* Set times of file FILENAME to TIMESTAMP.
3215 Set both access and modification times.
3216 Return t on success, else nil.
3217 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3218 `current-time'. */)
3219 (Lisp_Object filename, Lisp_Object timestamp)
3221 Lisp_Object absname, encoded_absname;
3222 Lisp_Object handler;
3223 struct timespec t = lisp_time_argument (timestamp);
3225 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3227 /* If the file name has special constructs in it,
3228 call the corresponding file handler. */
3229 handler = Ffind_file_name_handler (absname, Qset_file_times);
3230 if (!NILP (handler))
3231 return call3 (handler, Qset_file_times, absname, timestamp);
3233 encoded_absname = ENCODE_FILE (absname);
3236 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3238 #ifdef MSDOS
3239 /* Setting times on a directory always fails. */
3240 if (file_directory_p (SSDATA (encoded_absname)))
3241 return Qnil;
3242 #endif
3243 report_file_error ("Setting file times", absname);
3247 return Qt;
3250 #ifdef HAVE_SYNC
3251 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3252 doc: /* Tell Unix to finish all pending disk updates. */)
3253 (void)
3255 sync ();
3256 return Qnil;
3259 #endif /* HAVE_SYNC */
3261 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3262 doc: /* Return t if file FILE1 is newer than file FILE2.
3263 If FILE1 does not exist, the answer is nil;
3264 otherwise, if FILE2 does not exist, the answer is t. */)
3265 (Lisp_Object file1, Lisp_Object file2)
3267 Lisp_Object absname1, absname2;
3268 struct stat st1, st2;
3269 Lisp_Object handler;
3270 struct gcpro gcpro1, gcpro2;
3272 CHECK_STRING (file1);
3273 CHECK_STRING (file2);
3275 absname1 = Qnil;
3276 GCPRO2 (absname1, file2);
3277 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3278 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3279 UNGCPRO;
3281 /* If the file name has special constructs in it,
3282 call the corresponding file handler. */
3283 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3284 if (NILP (handler))
3285 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3286 if (!NILP (handler))
3287 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3289 GCPRO2 (absname1, absname2);
3290 absname1 = ENCODE_FILE (absname1);
3291 absname2 = ENCODE_FILE (absname2);
3292 UNGCPRO;
3294 if (stat (SSDATA (absname1), &st1) < 0)
3295 return Qnil;
3297 if (stat (SSDATA (absname2), &st2) < 0)
3298 return Qt;
3300 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3301 ? Qt : Qnil);
3304 #ifndef READ_BUF_SIZE
3305 #define READ_BUF_SIZE (64 << 10)
3306 #endif
3307 /* Some buffer offsets are stored in 'int' variables. */
3308 verify (READ_BUF_SIZE <= INT_MAX);
3310 /* This function is called after Lisp functions to decide a coding
3311 system are called, or when they cause an error. Before they are
3312 called, the current buffer is set unibyte and it contains only a
3313 newly inserted text (thus the buffer was empty before the
3314 insertion).
3316 The functions may set markers, overlays, text properties, or even
3317 alter the buffer contents, change the current buffer.
3319 Here, we reset all those changes by:
3320 o set back the current buffer.
3321 o move all markers and overlays to BEG.
3322 o remove all text properties.
3323 o set back the buffer multibyteness. */
3325 static void
3326 decide_coding_unwind (Lisp_Object unwind_data)
3328 Lisp_Object multibyte, undo_list, buffer;
3330 multibyte = XCAR (unwind_data);
3331 unwind_data = XCDR (unwind_data);
3332 undo_list = XCAR (unwind_data);
3333 buffer = XCDR (unwind_data);
3335 set_buffer_internal (XBUFFER (buffer));
3336 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3337 adjust_overlays_for_delete (BEG, Z - BEG);
3338 set_buffer_intervals (current_buffer, NULL);
3339 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3341 /* Now we are safe to change the buffer's multibyteness directly. */
3342 bset_enable_multibyte_characters (current_buffer, multibyte);
3343 bset_undo_list (current_buffer, undo_list);
3346 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3347 object where slot 0 is the file descriptor, slot 1 specifies
3348 an offset to put the read bytes, and slot 2 is the maximum
3349 amount of bytes to read. Value is the number of bytes read. */
3351 static Lisp_Object
3352 read_non_regular (Lisp_Object state)
3354 int nbytes;
3356 immediate_quit = 1;
3357 QUIT;
3358 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3359 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3360 + XSAVE_INTEGER (state, 1)),
3361 XSAVE_INTEGER (state, 2));
3362 immediate_quit = 0;
3363 /* Fast recycle this object for the likely next call. */
3364 free_misc (state);
3365 return make_number (nbytes);
3369 /* Condition-case handler used when reading from non-regular files
3370 in insert-file-contents. */
3372 static Lisp_Object
3373 read_non_regular_quit (Lisp_Object ignore)
3375 return Qnil;
3378 /* Return the file offset that VAL represents, checking for type
3379 errors and overflow. */
3380 static off_t
3381 file_offset (Lisp_Object val)
3383 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3384 return XINT (val);
3386 if (FLOATP (val))
3388 double v = XFLOAT_DATA (val);
3389 if (0 <= v
3390 && (sizeof (off_t) < sizeof v
3391 ? v <= TYPE_MAXIMUM (off_t)
3392 : v < TYPE_MAXIMUM (off_t)))
3393 return v;
3396 wrong_type_argument (intern ("file-offset"), val);
3399 /* Return a special time value indicating the error number ERRNUM. */
3400 static struct timespec
3401 time_error_value (int errnum)
3403 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3404 ? NONEXISTENT_MODTIME_NSECS
3405 : UNKNOWN_MODTIME_NSECS);
3406 return make_timespec (0, ns);
3409 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3410 1, 5, 0,
3411 doc: /* Insert contents of file FILENAME after point.
3412 Returns list of absolute file name and number of characters inserted.
3413 If second argument VISIT is non-nil, the buffer's visited filename and
3414 last save file modtime are set, and it is marked unmodified. If
3415 visiting and the file does not exist, visiting is completed before the
3416 error is signaled.
3418 The optional third and fourth arguments BEG and END specify what portion
3419 of the file to insert. These arguments count bytes in the file, not
3420 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3422 If optional fifth argument REPLACE is non-nil, replace the current
3423 buffer contents (in the accessible portion) with the file contents.
3424 This is better than simply deleting and inserting the whole thing
3425 because (1) it preserves some marker positions and (2) it puts less data
3426 in the undo list. When REPLACE is non-nil, the second return value is
3427 the number of characters that replace previous buffer contents.
3429 This function does code conversion according to the value of
3430 `coding-system-for-read' or `file-coding-system-alist', and sets the
3431 variable `last-coding-system-used' to the coding system actually used.
3433 In addition, this function decodes the inserted text from known formats
3434 by calling `format-decode', which see. */)
3435 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3437 struct stat st;
3438 struct timespec mtime;
3439 int fd;
3440 ptrdiff_t inserted = 0;
3441 ptrdiff_t how_much;
3442 off_t beg_offset, end_offset;
3443 int unprocessed;
3444 ptrdiff_t count = SPECPDL_INDEX ();
3445 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3446 Lisp_Object handler, val, insval, orig_filename, old_undo;
3447 Lisp_Object p;
3448 ptrdiff_t total = 0;
3449 bool not_regular = 0;
3450 int save_errno = 0;
3451 char read_buf[READ_BUF_SIZE];
3452 struct coding_system coding;
3453 bool replace_handled = 0;
3454 bool set_coding_system = 0;
3455 Lisp_Object coding_system;
3456 bool read_quit = 0;
3457 /* If the undo log only contains the insertion, there's no point
3458 keeping it. It's typically when we first fill a file-buffer. */
3459 bool empty_undo_list_p
3460 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3461 && BEG == Z);
3462 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3463 bool we_locked_file = 0;
3464 ptrdiff_t fd_index;
3466 if (current_buffer->base_buffer && ! NILP (visit))
3467 error ("Cannot do file visiting in an indirect buffer");
3469 if (!NILP (BVAR (current_buffer, read_only)))
3470 Fbarf_if_buffer_read_only ();
3472 val = Qnil;
3473 p = Qnil;
3474 orig_filename = Qnil;
3475 old_undo = Qnil;
3477 GCPRO5 (filename, val, p, orig_filename, old_undo);
3479 CHECK_STRING (filename);
3480 filename = Fexpand_file_name (filename, Qnil);
3482 /* The value Qnil means that the coding system is not yet
3483 decided. */
3484 coding_system = Qnil;
3486 /* If the file name has special constructs in it,
3487 call the corresponding file handler. */
3488 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3489 if (!NILP (handler))
3491 val = call6 (handler, Qinsert_file_contents, filename,
3492 visit, beg, end, replace);
3493 if (CONSP (val) && CONSP (XCDR (val))
3494 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3495 inserted = XINT (XCAR (XCDR (val)));
3496 goto handled;
3499 orig_filename = filename;
3500 filename = ENCODE_FILE (filename);
3502 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3503 if (fd < 0)
3505 save_errno = errno;
3506 if (NILP (visit))
3507 report_file_error ("Opening input file", orig_filename);
3508 mtime = time_error_value (save_errno);
3509 st.st_size = -1;
3510 if (!NILP (Vcoding_system_for_read))
3511 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3512 goto notfound;
3515 fd_index = SPECPDL_INDEX ();
3516 record_unwind_protect_int (close_file_unwind, fd);
3518 /* Replacement should preserve point as it preserves markers. */
3519 if (!NILP (replace))
3520 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3522 if (fstat (fd, &st) != 0)
3523 report_file_error ("Input file status", orig_filename);
3524 mtime = get_stat_mtime (&st);
3526 /* This code will need to be changed in order to work on named
3527 pipes, and it's probably just not worth it. So we should at
3528 least signal an error. */
3529 if (!S_ISREG (st.st_mode))
3531 not_regular = 1;
3533 if (! NILP (visit))
3534 goto notfound;
3536 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3537 xsignal2 (Qfile_error,
3538 build_string ("not a regular file"), orig_filename);
3541 if (!NILP (visit))
3543 if (!NILP (beg) || !NILP (end))
3544 error ("Attempt to visit less than an entire file");
3545 if (BEG < Z && NILP (replace))
3546 error ("Cannot do file visiting in a non-empty buffer");
3549 if (!NILP (beg))
3550 beg_offset = file_offset (beg);
3551 else
3552 beg_offset = 0;
3554 if (!NILP (end))
3555 end_offset = file_offset (end);
3556 else
3558 if (not_regular)
3559 end_offset = TYPE_MAXIMUM (off_t);
3560 else
3562 end_offset = st.st_size;
3564 /* A negative size can happen on a platform that allows file
3565 sizes greater than the maximum off_t value. */
3566 if (end_offset < 0)
3567 buffer_overflow ();
3569 /* The file size returned from stat may be zero, but data
3570 may be readable nonetheless, for example when this is a
3571 file in the /proc filesystem. */
3572 if (end_offset == 0)
3573 end_offset = READ_BUF_SIZE;
3577 /* Check now whether the buffer will become too large,
3578 in the likely case where the file's length is not changing.
3579 This saves a lot of needless work before a buffer overflow. */
3580 if (! not_regular)
3582 /* The likely offset where we will stop reading. We could read
3583 more (or less), if the file grows (or shrinks) as we read it. */
3584 off_t likely_end = min (end_offset, st.st_size);
3586 if (beg_offset < likely_end)
3588 ptrdiff_t buf_bytes
3589 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3590 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3591 off_t likely_growth = likely_end - beg_offset;
3592 if (buf_growth_max < likely_growth)
3593 buffer_overflow ();
3597 /* Prevent redisplay optimizations. */
3598 current_buffer->clip_changed = 1;
3600 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3602 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3603 setup_coding_system (coding_system, &coding);
3604 /* Ensure we set Vlast_coding_system_used. */
3605 set_coding_system = 1;
3607 else if (BEG < Z)
3609 /* Decide the coding system to use for reading the file now
3610 because we can't use an optimized method for handling
3611 `coding:' tag if the current buffer is not empty. */
3612 if (!NILP (Vcoding_system_for_read))
3613 coding_system = Vcoding_system_for_read;
3614 else
3616 /* Don't try looking inside a file for a coding system
3617 specification if it is not seekable. */
3618 if (! not_regular && ! NILP (Vset_auto_coding_function))
3620 /* Find a coding system specified in the heading two
3621 lines or in the tailing several lines of the file.
3622 We assume that the 1K-byte and 3K-byte for heading
3623 and tailing respectively are sufficient for this
3624 purpose. */
3625 int nread;
3627 if (st.st_size <= (1024 * 4))
3628 nread = emacs_read (fd, read_buf, 1024 * 4);
3629 else
3631 nread = emacs_read (fd, read_buf, 1024);
3632 if (nread == 1024)
3634 int ntail;
3635 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3636 report_file_error ("Setting file position",
3637 orig_filename);
3638 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3639 nread = ntail < 0 ? ntail : nread + ntail;
3643 if (nread < 0)
3644 report_file_error ("Read error", orig_filename);
3645 else if (nread > 0)
3647 struct buffer *prev = current_buffer;
3648 Lisp_Object workbuf;
3649 struct buffer *buf;
3651 record_unwind_current_buffer ();
3653 workbuf = Fget_buffer_create (build_string (" *code-converting-work*"));
3654 buf = XBUFFER (workbuf);
3656 delete_all_overlays (buf);
3657 bset_directory (buf, BVAR (current_buffer, directory));
3658 bset_read_only (buf, Qnil);
3659 bset_filename (buf, Qnil);
3660 bset_undo_list (buf, Qt);
3661 eassert (buf->overlays_before == NULL);
3662 eassert (buf->overlays_after == NULL);
3664 set_buffer_internal (buf);
3665 Ferase_buffer ();
3666 bset_enable_multibyte_characters (buf, Qnil);
3668 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3669 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3670 coding_system = call2 (Vset_auto_coding_function,
3671 filename, make_number (nread));
3672 set_buffer_internal (prev);
3674 /* Discard the unwind protect for recovering the
3675 current buffer. */
3676 specpdl_ptr--;
3678 /* Rewind the file for the actual read done later. */
3679 if (lseek (fd, 0, SEEK_SET) < 0)
3680 report_file_error ("Setting file position", orig_filename);
3684 if (NILP (coding_system))
3686 /* If we have not yet decided a coding system, check
3687 file-coding-system-alist. */
3688 Lisp_Object args[6];
3690 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3691 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3692 coding_system = Ffind_operation_coding_system (6, args);
3693 if (CONSP (coding_system))
3694 coding_system = XCAR (coding_system);
3698 if (NILP (coding_system))
3699 coding_system = Qundecided;
3700 else
3701 CHECK_CODING_SYSTEM (coding_system);
3703 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3704 /* We must suppress all character code conversion except for
3705 end-of-line conversion. */
3706 coding_system = raw_text_coding_system (coding_system);
3708 setup_coding_system (coding_system, &coding);
3709 /* Ensure we set Vlast_coding_system_used. */
3710 set_coding_system = 1;
3713 /* If requested, replace the accessible part of the buffer
3714 with the file contents. Avoid replacing text at the
3715 beginning or end of the buffer that matches the file contents;
3716 that preserves markers pointing to the unchanged parts.
3718 Here we implement this feature in an optimized way
3719 for the case where code conversion is NOT needed.
3720 The following if-statement handles the case of conversion
3721 in a less optimal way.
3723 If the code conversion is "automatic" then we try using this
3724 method and hope for the best.
3725 But if we discover the need for conversion, we give up on this method
3726 and let the following if-statement handle the replace job. */
3727 if (!NILP (replace)
3728 && BEGV < ZV
3729 && (NILP (coding_system)
3730 || ! CODING_REQUIRE_DECODING (&coding)))
3732 /* same_at_start and same_at_end count bytes,
3733 because file access counts bytes
3734 and BEG and END count bytes. */
3735 ptrdiff_t same_at_start = BEGV_BYTE;
3736 ptrdiff_t same_at_end = ZV_BYTE;
3737 ptrdiff_t overlap;
3738 /* There is still a possibility we will find the need to do code
3739 conversion. If that happens, set this variable to
3740 give up on handling REPLACE in the optimized way. */
3741 bool giveup_match_end = 0;
3743 if (beg_offset != 0)
3745 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3746 report_file_error ("Setting file position", orig_filename);
3749 immediate_quit = 1;
3750 QUIT;
3751 /* Count how many chars at the start of the file
3752 match the text at the beginning of the buffer. */
3753 while (1)
3755 int nread, bufpos;
3757 nread = emacs_read (fd, read_buf, sizeof read_buf);
3758 if (nread < 0)
3759 report_file_error ("Read error", orig_filename);
3760 else if (nread == 0)
3761 break;
3763 if (CODING_REQUIRE_DETECTION (&coding))
3765 coding_system = detect_coding_system ((unsigned char *) read_buf,
3766 nread, nread, 1, 0,
3767 coding_system);
3768 setup_coding_system (coding_system, &coding);
3771 if (CODING_REQUIRE_DECODING (&coding))
3772 /* We found that the file should be decoded somehow.
3773 Let's give up here. */
3775 giveup_match_end = 1;
3776 break;
3779 bufpos = 0;
3780 while (bufpos < nread && same_at_start < ZV_BYTE
3781 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3782 same_at_start++, bufpos++;
3783 /* If we found a discrepancy, stop the scan.
3784 Otherwise loop around and scan the next bufferful. */
3785 if (bufpos != nread)
3786 break;
3788 immediate_quit = 0;
3789 /* If the file matches the buffer completely,
3790 there's no need to replace anything. */
3791 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3793 emacs_close (fd);
3794 clear_unwind_protect (fd_index);
3796 /* Truncate the buffer to the size of the file. */
3797 del_range_1 (same_at_start, same_at_end, 0, 0);
3798 goto handled;
3800 immediate_quit = 1;
3801 QUIT;
3802 /* Count how many chars at the end of the file
3803 match the text at the end of the buffer. But, if we have
3804 already found that decoding is necessary, don't waste time. */
3805 while (!giveup_match_end)
3807 int total_read, nread, bufpos, trial;
3808 off_t curpos;
3810 /* At what file position are we now scanning? */
3811 curpos = end_offset - (ZV_BYTE - same_at_end);
3812 /* If the entire file matches the buffer tail, stop the scan. */
3813 if (curpos == 0)
3814 break;
3815 /* How much can we scan in the next step? */
3816 trial = min (curpos, sizeof read_buf);
3817 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3818 report_file_error ("Setting file position", orig_filename);
3820 total_read = nread = 0;
3821 while (total_read < trial)
3823 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3824 if (nread < 0)
3825 report_file_error ("Read error", orig_filename);
3826 else if (nread == 0)
3827 break;
3828 total_read += nread;
3831 /* Scan this bufferful from the end, comparing with
3832 the Emacs buffer. */
3833 bufpos = total_read;
3835 /* Compare with same_at_start to avoid counting some buffer text
3836 as matching both at the file's beginning and at the end. */
3837 while (bufpos > 0 && same_at_end > same_at_start
3838 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3839 same_at_end--, bufpos--;
3841 /* If we found a discrepancy, stop the scan.
3842 Otherwise loop around and scan the preceding bufferful. */
3843 if (bufpos != 0)
3845 /* If this discrepancy is because of code conversion,
3846 we cannot use this method; giveup and try the other. */
3847 if (same_at_end > same_at_start
3848 && FETCH_BYTE (same_at_end - 1) >= 0200
3849 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3850 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3851 giveup_match_end = 1;
3852 break;
3855 if (nread == 0)
3856 break;
3858 immediate_quit = 0;
3860 if (! giveup_match_end)
3862 ptrdiff_t temp;
3864 /* We win! We can handle REPLACE the optimized way. */
3866 /* Extend the start of non-matching text area to multibyte
3867 character boundary. */
3868 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3869 while (same_at_start > BEGV_BYTE
3870 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3871 same_at_start--;
3873 /* Extend the end of non-matching text area to multibyte
3874 character boundary. */
3875 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3876 while (same_at_end < ZV_BYTE
3877 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3878 same_at_end++;
3880 /* Don't try to reuse the same piece of text twice. */
3881 overlap = (same_at_start - BEGV_BYTE
3882 - (same_at_end
3883 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3884 if (overlap > 0)
3885 same_at_end += overlap;
3887 /* Arrange to read only the nonmatching middle part of the file. */
3888 beg_offset += same_at_start - BEGV_BYTE;
3889 end_offset -= ZV_BYTE - same_at_end;
3891 invalidate_buffer_caches (current_buffer,
3892 BYTE_TO_CHAR (same_at_start),
3893 BYTE_TO_CHAR (same_at_end));
3894 del_range_byte (same_at_start, same_at_end, 0);
3895 /* Insert from the file at the proper position. */
3896 temp = BYTE_TO_CHAR (same_at_start);
3897 SET_PT_BOTH (temp, same_at_start);
3899 /* If display currently starts at beginning of line,
3900 keep it that way. */
3901 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3902 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3904 replace_handled = 1;
3908 /* If requested, replace the accessible part of the buffer
3909 with the file contents. Avoid replacing text at the
3910 beginning or end of the buffer that matches the file contents;
3911 that preserves markers pointing to the unchanged parts.
3913 Here we implement this feature for the case where code conversion
3914 is needed, in a simple way that needs a lot of memory.
3915 The preceding if-statement handles the case of no conversion
3916 in a more optimized way. */
3917 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3919 ptrdiff_t same_at_start = BEGV_BYTE;
3920 ptrdiff_t same_at_end = ZV_BYTE;
3921 ptrdiff_t same_at_start_charpos;
3922 ptrdiff_t inserted_chars;
3923 ptrdiff_t overlap;
3924 ptrdiff_t bufpos;
3925 unsigned char *decoded;
3926 ptrdiff_t temp;
3927 ptrdiff_t this = 0;
3928 ptrdiff_t this_count = SPECPDL_INDEX ();
3929 bool multibyte
3930 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3931 Lisp_Object conversion_buffer;
3932 struct gcpro gcpro1;
3934 conversion_buffer = code_conversion_save (1, multibyte);
3936 /* First read the whole file, performing code conversion into
3937 CONVERSION_BUFFER. */
3939 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3940 report_file_error ("Setting file position", orig_filename);
3942 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3943 unprocessed = 0; /* Bytes not processed in previous loop. */
3945 GCPRO1 (conversion_buffer);
3946 while (1)
3948 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3949 quitting while reading a huge file. */
3951 /* Allow quitting out of the actual I/O. */
3952 immediate_quit = 1;
3953 QUIT;
3954 this = emacs_read (fd, read_buf + unprocessed,
3955 READ_BUF_SIZE - unprocessed);
3956 immediate_quit = 0;
3958 if (this <= 0)
3959 break;
3961 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3962 BUF_Z (XBUFFER (conversion_buffer)));
3963 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3964 unprocessed + this, conversion_buffer);
3965 unprocessed = coding.carryover_bytes;
3966 if (coding.carryover_bytes > 0)
3967 memcpy (read_buf, coding.carryover, unprocessed);
3969 UNGCPRO;
3970 if (this < 0)
3971 report_file_error ("Read error", orig_filename);
3972 emacs_close (fd);
3973 clear_unwind_protect (fd_index);
3975 if (unprocessed > 0)
3977 coding.mode |= CODING_MODE_LAST_BLOCK;
3978 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3979 unprocessed, conversion_buffer);
3980 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3983 coding_system = CODING_ID_NAME (coding.id);
3984 set_coding_system = 1;
3985 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3986 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3987 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3989 /* Compare the beginning of the converted string with the buffer
3990 text. */
3992 bufpos = 0;
3993 while (bufpos < inserted && same_at_start < same_at_end
3994 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3995 same_at_start++, bufpos++;
3997 /* If the file matches the head of buffer completely,
3998 there's no need to replace anything. */
4000 if (bufpos == inserted)
4002 /* Truncate the buffer to the size of the file. */
4003 if (same_at_start != same_at_end)
4005 invalidate_buffer_caches (current_buffer,
4006 BYTE_TO_CHAR (same_at_start),
4007 BYTE_TO_CHAR (same_at_end));
4008 del_range_byte (same_at_start, same_at_end, 0);
4010 inserted = 0;
4012 unbind_to (this_count, Qnil);
4013 goto handled;
4016 /* Extend the start of non-matching text area to the previous
4017 multibyte character boundary. */
4018 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4019 while (same_at_start > BEGV_BYTE
4020 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4021 same_at_start--;
4023 /* Scan this bufferful from the end, comparing with
4024 the Emacs buffer. */
4025 bufpos = inserted;
4027 /* Compare with same_at_start to avoid counting some buffer text
4028 as matching both at the file's beginning and at the end. */
4029 while (bufpos > 0 && same_at_end > same_at_start
4030 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4031 same_at_end--, bufpos--;
4033 /* Extend the end of non-matching text area to the next
4034 multibyte character boundary. */
4035 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4036 while (same_at_end < ZV_BYTE
4037 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4038 same_at_end++;
4040 /* Don't try to reuse the same piece of text twice. */
4041 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4042 if (overlap > 0)
4043 same_at_end += overlap;
4045 /* If display currently starts at beginning of line,
4046 keep it that way. */
4047 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4048 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4050 /* Replace the chars that we need to replace,
4051 and update INSERTED to equal the number of bytes
4052 we are taking from the decoded string. */
4053 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4055 if (same_at_end != same_at_start)
4057 invalidate_buffer_caches (current_buffer,
4058 BYTE_TO_CHAR (same_at_start),
4059 BYTE_TO_CHAR (same_at_end));
4060 del_range_byte (same_at_start, same_at_end, 0);
4061 temp = GPT;
4062 eassert (same_at_start == GPT_BYTE);
4063 same_at_start = GPT_BYTE;
4065 else
4067 temp = BYTE_TO_CHAR (same_at_start);
4069 /* Insert from the file at the proper position. */
4070 SET_PT_BOTH (temp, same_at_start);
4071 same_at_start_charpos
4072 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4073 same_at_start - BEGV_BYTE
4074 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4075 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4076 inserted_chars
4077 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4078 same_at_start + inserted - BEGV_BYTE
4079 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4080 - same_at_start_charpos);
4081 /* This binding is to avoid ask-user-about-supersession-threat
4082 being called in insert_from_buffer (via in
4083 prepare_to_modify_buffer). */
4084 specbind (intern ("buffer-file-name"), Qnil);
4085 insert_from_buffer (XBUFFER (conversion_buffer),
4086 same_at_start_charpos, inserted_chars, 0);
4087 /* Set `inserted' to the number of inserted characters. */
4088 inserted = PT - temp;
4089 /* Set point before the inserted characters. */
4090 SET_PT_BOTH (temp, same_at_start);
4092 unbind_to (this_count, Qnil);
4094 goto handled;
4097 if (! not_regular)
4098 total = end_offset - beg_offset;
4099 else
4100 /* For a special file, all we can do is guess. */
4101 total = READ_BUF_SIZE;
4103 if (NILP (visit) && total > 0)
4105 if (!NILP (BVAR (current_buffer, file_truename))
4106 /* Make binding buffer-file-name to nil effective. */
4107 && !NILP (BVAR (current_buffer, filename))
4108 && SAVE_MODIFF >= MODIFF)
4109 we_locked_file = 1;
4110 prepare_to_modify_buffer (PT, PT, NULL);
4113 move_gap_both (PT, PT_BYTE);
4114 if (GAP_SIZE < total)
4115 make_gap (total - GAP_SIZE);
4117 if (beg_offset != 0 || !NILP (replace))
4119 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4120 report_file_error ("Setting file position", orig_filename);
4123 /* In the following loop, HOW_MUCH contains the total bytes read so
4124 far for a regular file, and not changed for a special file. But,
4125 before exiting the loop, it is set to a negative value if I/O
4126 error occurs. */
4127 how_much = 0;
4129 /* Total bytes inserted. */
4130 inserted = 0;
4132 /* Here, we don't do code conversion in the loop. It is done by
4133 decode_coding_gap after all data are read into the buffer. */
4135 ptrdiff_t gap_size = GAP_SIZE;
4137 while (how_much < total)
4139 /* try is reserved in some compilers (Microsoft C) */
4140 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4141 ptrdiff_t this;
4143 if (not_regular)
4145 Lisp_Object nbytes;
4147 /* Maybe make more room. */
4148 if (gap_size < trytry)
4150 make_gap (trytry - gap_size);
4151 gap_size = GAP_SIZE - inserted;
4154 /* Read from the file, capturing `quit'. When an
4155 error occurs, end the loop, and arrange for a quit
4156 to be signaled after decoding the text we read. */
4157 nbytes = internal_condition_case_1
4158 (read_non_regular,
4159 make_save_int_int_int (fd, inserted, trytry),
4160 Qerror, read_non_regular_quit);
4162 if (NILP (nbytes))
4164 read_quit = 1;
4165 break;
4168 this = XINT (nbytes);
4170 else
4172 /* Allow quitting out of the actual I/O. We don't make text
4173 part of the buffer until all the reading is done, so a C-g
4174 here doesn't do any harm. */
4175 immediate_quit = 1;
4176 QUIT;
4177 this = emacs_read (fd,
4178 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4179 + inserted),
4180 trytry);
4181 immediate_quit = 0;
4184 if (this <= 0)
4186 how_much = this;
4187 break;
4190 gap_size -= this;
4192 /* For a regular file, where TOTAL is the real size,
4193 count HOW_MUCH to compare with it.
4194 For a special file, where TOTAL is just a buffer size,
4195 so don't bother counting in HOW_MUCH.
4196 (INSERTED is where we count the number of characters inserted.) */
4197 if (! not_regular)
4198 how_much += this;
4199 inserted += this;
4203 /* Now we have either read all the file data into the gap,
4204 or stop reading on I/O error or quit. If nothing was
4205 read, undo marking the buffer modified. */
4207 if (inserted == 0)
4209 if (we_locked_file)
4210 unlock_file (BVAR (current_buffer, file_truename));
4211 Vdeactivate_mark = old_Vdeactivate_mark;
4213 else
4214 Vdeactivate_mark = Qt;
4216 emacs_close (fd);
4217 clear_unwind_protect (fd_index);
4219 if (how_much < 0)
4220 report_file_error ("Read error", orig_filename);
4222 /* Make the text read part of the buffer. */
4223 GAP_SIZE -= inserted;
4224 GPT += inserted;
4225 GPT_BYTE += inserted;
4226 ZV += inserted;
4227 ZV_BYTE += inserted;
4228 Z += inserted;
4229 Z_BYTE += inserted;
4231 if (GAP_SIZE > 0)
4232 /* Put an anchor to ensure multi-byte form ends at gap. */
4233 *GPT_ADDR = 0;
4235 notfound:
4237 if (NILP (coding_system))
4239 /* The coding system is not yet decided. Decide it by an
4240 optimized method for handling `coding:' tag.
4242 Note that we can get here only if the buffer was empty
4243 before the insertion. */
4245 if (!NILP (Vcoding_system_for_read))
4246 coding_system = Vcoding_system_for_read;
4247 else
4249 /* Since we are sure that the current buffer was empty
4250 before the insertion, we can toggle
4251 enable-multibyte-characters directly here without taking
4252 care of marker adjustment. By this way, we can run Lisp
4253 program safely before decoding the inserted text. */
4254 Lisp_Object unwind_data;
4255 ptrdiff_t count1 = SPECPDL_INDEX ();
4257 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4258 Fcons (BVAR (current_buffer, undo_list),
4259 Fcurrent_buffer ()));
4260 bset_enable_multibyte_characters (current_buffer, Qnil);
4261 bset_undo_list (current_buffer, Qt);
4262 record_unwind_protect (decide_coding_unwind, unwind_data);
4264 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4266 coding_system = call2 (Vset_auto_coding_function,
4267 filename, make_number (inserted));
4270 if (NILP (coding_system))
4272 /* If the coding system is not yet decided, check
4273 file-coding-system-alist. */
4274 Lisp_Object args[6];
4276 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4277 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4278 coding_system = Ffind_operation_coding_system (6, args);
4279 if (CONSP (coding_system))
4280 coding_system = XCAR (coding_system);
4282 unbind_to (count1, Qnil);
4283 inserted = Z_BYTE - BEG_BYTE;
4286 if (NILP (coding_system))
4287 coding_system = Qundecided;
4288 else
4289 CHECK_CODING_SYSTEM (coding_system);
4291 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4292 /* We must suppress all character code conversion except for
4293 end-of-line conversion. */
4294 coding_system = raw_text_coding_system (coding_system);
4295 setup_coding_system (coding_system, &coding);
4296 /* Ensure we set Vlast_coding_system_used. */
4297 set_coding_system = 1;
4300 if (!NILP (visit))
4302 /* When we visit a file by raw-text, we change the buffer to
4303 unibyte. */
4304 if (CODING_FOR_UNIBYTE (&coding)
4305 /* Can't do this if part of the buffer might be preserved. */
4306 && NILP (replace))
4307 /* Visiting a file with these coding system makes the buffer
4308 unibyte. */
4309 bset_enable_multibyte_characters (current_buffer, Qnil);
4312 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4313 if (CODING_MAY_REQUIRE_DECODING (&coding)
4314 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4316 move_gap_both (PT, PT_BYTE);
4317 GAP_SIZE += inserted;
4318 ZV_BYTE -= inserted;
4319 Z_BYTE -= inserted;
4320 ZV -= inserted;
4321 Z -= inserted;
4322 decode_coding_gap (&coding, inserted, inserted);
4323 inserted = coding.produced_char;
4324 coding_system = CODING_ID_NAME (coding.id);
4326 else if (inserted > 0)
4327 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4328 inserted);
4330 /* Call after-change hooks for the inserted text, aside from the case
4331 of normal visiting (not with REPLACE), which is done in a new buffer
4332 "before" the buffer is changed. */
4333 if (inserted > 0 && total > 0
4334 && (NILP (visit) || !NILP (replace)))
4336 signal_after_change (PT, 0, inserted);
4337 update_compositions (PT, PT, CHECK_BORDER);
4340 /* Now INSERTED is measured in characters. */
4342 handled:
4344 if (!NILP (visit))
4346 if (empty_undo_list_p)
4347 bset_undo_list (current_buffer, Qnil);
4349 if (NILP (handler))
4351 current_buffer->modtime = mtime;
4352 current_buffer->modtime_size = st.st_size;
4353 bset_filename (current_buffer, orig_filename);
4356 SAVE_MODIFF = MODIFF;
4357 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4358 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4359 if (NILP (handler))
4361 if (!NILP (BVAR (current_buffer, file_truename)))
4362 unlock_file (BVAR (current_buffer, file_truename));
4363 unlock_file (filename);
4365 if (not_regular)
4366 xsignal2 (Qfile_error,
4367 build_string ("not a regular file"), orig_filename);
4370 if (set_coding_system)
4371 Vlast_coding_system_used = coding_system;
4373 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4375 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4376 visit);
4377 if (! NILP (insval))
4379 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4380 wrong_type_argument (intern ("inserted-chars"), insval);
4381 inserted = XFASTINT (insval);
4385 /* Decode file format. */
4386 if (inserted > 0)
4388 /* Don't run point motion or modification hooks when decoding. */
4389 ptrdiff_t count1 = SPECPDL_INDEX ();
4390 ptrdiff_t old_inserted = inserted;
4391 specbind (Qinhibit_point_motion_hooks, Qt);
4392 specbind (Qinhibit_modification_hooks, Qt);
4394 /* Save old undo list and don't record undo for decoding. */
4395 old_undo = BVAR (current_buffer, undo_list);
4396 bset_undo_list (current_buffer, Qt);
4398 if (NILP (replace))
4400 insval = call3 (Qformat_decode,
4401 Qnil, make_number (inserted), visit);
4402 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4403 wrong_type_argument (intern ("inserted-chars"), insval);
4404 inserted = XFASTINT (insval);
4406 else
4408 /* If REPLACE is non-nil and we succeeded in not replacing the
4409 beginning or end of the buffer text with the file's contents,
4410 call format-decode with `point' positioned at the beginning
4411 of the buffer and `inserted' equaling the number of
4412 characters in the buffer. Otherwise, format-decode might
4413 fail to correctly analyze the beginning or end of the buffer.
4414 Hence we temporarily save `point' and `inserted' here and
4415 restore `point' iff format-decode did not insert or delete
4416 any text. Otherwise we leave `point' at point-min. */
4417 ptrdiff_t opoint = PT;
4418 ptrdiff_t opoint_byte = PT_BYTE;
4419 ptrdiff_t oinserted = ZV - BEGV;
4420 EMACS_INT ochars_modiff = CHARS_MODIFF;
4422 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4423 insval = call3 (Qformat_decode,
4424 Qnil, make_number (oinserted), visit);
4425 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4426 wrong_type_argument (intern ("inserted-chars"), insval);
4427 if (ochars_modiff == CHARS_MODIFF)
4428 /* format_decode didn't modify buffer's characters => move
4429 point back to position before inserted text and leave
4430 value of inserted alone. */
4431 SET_PT_BOTH (opoint, opoint_byte);
4432 else
4433 /* format_decode modified buffer's characters => consider
4434 entire buffer changed and leave point at point-min. */
4435 inserted = XFASTINT (insval);
4438 /* For consistency with format-decode call these now iff inserted > 0
4439 (martin 2007-06-28). */
4440 p = Vafter_insert_file_functions;
4441 while (CONSP (p))
4443 if (NILP (replace))
4445 insval = call1 (XCAR (p), make_number (inserted));
4446 if (!NILP (insval))
4448 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4449 wrong_type_argument (intern ("inserted-chars"), insval);
4450 inserted = XFASTINT (insval);
4453 else
4455 /* For the rationale of this see the comment on
4456 format-decode above. */
4457 ptrdiff_t opoint = PT;
4458 ptrdiff_t opoint_byte = PT_BYTE;
4459 ptrdiff_t oinserted = ZV - BEGV;
4460 EMACS_INT ochars_modiff = CHARS_MODIFF;
4462 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4463 insval = call1 (XCAR (p), make_number (oinserted));
4464 if (!NILP (insval))
4466 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4467 wrong_type_argument (intern ("inserted-chars"), insval);
4468 if (ochars_modiff == CHARS_MODIFF)
4469 /* after_insert_file_functions didn't modify
4470 buffer's characters => move point back to
4471 position before inserted text and leave value of
4472 inserted alone. */
4473 SET_PT_BOTH (opoint, opoint_byte);
4474 else
4475 /* after_insert_file_functions did modify buffer's
4476 characters => consider entire buffer changed and
4477 leave point at point-min. */
4478 inserted = XFASTINT (insval);
4482 QUIT;
4483 p = XCDR (p);
4486 if (!empty_undo_list_p)
4488 bset_undo_list (current_buffer, old_undo);
4489 if (CONSP (old_undo) && inserted != old_inserted)
4491 /* Adjust the last undo record for the size change during
4492 the format conversion. */
4493 Lisp_Object tem = XCAR (old_undo);
4494 if (CONSP (tem) && INTEGERP (XCAR (tem))
4495 && INTEGERP (XCDR (tem))
4496 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4497 XSETCDR (tem, make_number (PT + inserted));
4500 else
4501 /* If undo_list was Qt before, keep it that way.
4502 Otherwise start with an empty undo_list. */
4503 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4505 unbind_to (count1, Qnil);
4508 if (!NILP (visit)
4509 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4511 /* If visiting nonexistent file, return nil. */
4512 report_file_errno ("Opening input file", orig_filename, save_errno);
4515 /* We made a lot of deletions and insertions above, so invalidate
4516 the newline cache for the entire region of the inserted
4517 characters. */
4518 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4519 invalidate_region_cache (current_buffer->base_buffer,
4520 current_buffer->base_buffer->newline_cache,
4521 PT - BEG, Z - PT - inserted);
4522 else if (current_buffer->newline_cache)
4523 invalidate_region_cache (current_buffer,
4524 current_buffer->newline_cache,
4525 PT - BEG, Z - PT - inserted);
4527 if (read_quit)
4528 Fsignal (Qquit, Qnil);
4530 /* Retval needs to be dealt with in all cases consistently. */
4531 if (NILP (val))
4532 val = list2 (orig_filename, make_number (inserted));
4534 RETURN_UNGCPRO (unbind_to (count, val));
4537 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4539 static void
4540 build_annotations_unwind (Lisp_Object arg)
4542 Vwrite_region_annotation_buffers = arg;
4545 /* Decide the coding-system to encode the data with. */
4547 static Lisp_Object
4548 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4549 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4550 struct coding_system *coding)
4552 Lisp_Object val;
4553 Lisp_Object eol_parent = Qnil;
4555 if (auto_saving
4556 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4557 BVAR (current_buffer, auto_save_file_name))))
4559 val = Qutf_8_emacs;
4560 eol_parent = Qunix;
4562 else if (!NILP (Vcoding_system_for_write))
4564 val = Vcoding_system_for_write;
4565 if (coding_system_require_warning
4566 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4567 /* Confirm that VAL can surely encode the current region. */
4568 val = call5 (Vselect_safe_coding_system_function,
4569 start, end, list2 (Qt, val),
4570 Qnil, filename);
4572 else
4574 /* If the variable `buffer-file-coding-system' is set locally,
4575 it means that the file was read with some kind of code
4576 conversion or the variable is explicitly set by users. We
4577 had better write it out with the same coding system even if
4578 `enable-multibyte-characters' is nil.
4580 If it is not set locally, we anyway have to convert EOL
4581 format if the default value of `buffer-file-coding-system'
4582 tells that it is not Unix-like (LF only) format. */
4583 bool using_default_coding = 0;
4584 bool force_raw_text = 0;
4586 val = BVAR (current_buffer, buffer_file_coding_system);
4587 if (NILP (val)
4588 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4590 val = Qnil;
4591 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4592 force_raw_text = 1;
4595 if (NILP (val))
4597 /* Check file-coding-system-alist. */
4598 Lisp_Object args[7], coding_systems;
4600 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4601 args[3] = filename; args[4] = append; args[5] = visit;
4602 args[6] = lockname;
4603 coding_systems = Ffind_operation_coding_system (7, args);
4604 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4605 val = XCDR (coding_systems);
4608 if (NILP (val))
4610 /* If we still have not decided a coding system, use the
4611 default value of buffer-file-coding-system. */
4612 val = BVAR (current_buffer, buffer_file_coding_system);
4613 using_default_coding = 1;
4616 if (! NILP (val) && ! force_raw_text)
4618 Lisp_Object spec, attrs;
4620 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4621 attrs = AREF (spec, 0);
4622 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4623 force_raw_text = 1;
4626 if (!force_raw_text
4627 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4628 /* Confirm that VAL can surely encode the current region. */
4629 val = call5 (Vselect_safe_coding_system_function,
4630 start, end, val, Qnil, filename);
4632 /* If the decided coding-system doesn't specify end-of-line
4633 format, we use that of
4634 `default-buffer-file-coding-system'. */
4635 if (! using_default_coding
4636 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4637 val = (coding_inherit_eol_type
4638 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4640 /* If we decide not to encode text, use `raw-text' or one of its
4641 subsidiaries. */
4642 if (force_raw_text)
4643 val = raw_text_coding_system (val);
4646 val = coding_inherit_eol_type (val, eol_parent);
4647 setup_coding_system (val, coding);
4649 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4650 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4651 return val;
4654 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4655 "r\nFWrite region to file: \ni\ni\ni\np",
4656 doc: /* Write current region into specified file.
4657 When called from a program, requires three arguments:
4658 START, END and FILENAME. START and END are normally buffer positions
4659 specifying the part of the buffer to write.
4660 If START is nil, that means to use the entire buffer contents.
4661 If START is a string, then output that string to the file
4662 instead of any buffer contents; END is ignored.
4664 Optional fourth argument APPEND if non-nil means
4665 append to existing file contents (if any). If it is a number,
4666 seek to that offset in the file before writing.
4667 Optional fifth argument VISIT, if t or a string, means
4668 set the last-save-file-modtime of buffer to this file's modtime
4669 and mark buffer not modified.
4670 If VISIT is a string, it is a second file name;
4671 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4672 VISIT is also the file name to lock and unlock for clash detection.
4673 If VISIT is neither t nor nil nor a string,
4674 that means do not display the \"Wrote file\" message.
4675 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4676 use for locking and unlocking, overriding FILENAME and VISIT.
4677 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4678 for an existing file with the same name. If MUSTBENEW is `excl',
4679 that means to get an error if the file already exists; never overwrite.
4680 If MUSTBENEW is neither nil nor `excl', that means ask for
4681 confirmation before overwriting, but do go ahead and overwrite the file
4682 if the user confirms.
4684 This does code conversion according to the value of
4685 `coding-system-for-write', `buffer-file-coding-system', or
4686 `file-coding-system-alist', and sets the variable
4687 `last-coding-system-used' to the coding system actually used.
4689 This calls `write-region-annotate-functions' at the start, and
4690 `write-region-post-annotation-function' at the end. */)
4691 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4692 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4694 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4695 -1);
4698 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4699 descriptor for FILENAME, so do not open or close FILENAME. */
4701 Lisp_Object
4702 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4703 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4704 Lisp_Object mustbenew, int desc)
4706 int open_flags;
4707 int mode;
4708 off_t offset IF_LINT (= 0);
4709 bool open_and_close_file = desc < 0;
4710 bool ok;
4711 int save_errno = 0;
4712 const char *fn;
4713 struct stat st;
4714 struct timespec modtime;
4715 ptrdiff_t count = SPECPDL_INDEX ();
4716 ptrdiff_t count1 IF_LINT (= 0);
4717 Lisp_Object handler;
4718 Lisp_Object visit_file;
4719 Lisp_Object annotations;
4720 Lisp_Object encoded_filename;
4721 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4722 bool quietly = !NILP (visit);
4723 bool file_locked = 0;
4724 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4725 struct buffer *given_buffer;
4726 struct coding_system coding;
4728 if (current_buffer->base_buffer && visiting)
4729 error ("Cannot do file visiting in an indirect buffer");
4731 if (!NILP (start) && !STRINGP (start))
4732 validate_region (&start, &end);
4734 visit_file = Qnil;
4735 GCPRO5 (start, filename, visit, visit_file, lockname);
4737 filename = Fexpand_file_name (filename, Qnil);
4739 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4740 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4742 if (STRINGP (visit))
4743 visit_file = Fexpand_file_name (visit, Qnil);
4744 else
4745 visit_file = filename;
4747 if (NILP (lockname))
4748 lockname = visit_file;
4750 annotations = Qnil;
4752 /* If the file name has special constructs in it,
4753 call the corresponding file handler. */
4754 handler = Ffind_file_name_handler (filename, Qwrite_region);
4755 /* If FILENAME has no handler, see if VISIT has one. */
4756 if (NILP (handler) && STRINGP (visit))
4757 handler = Ffind_file_name_handler (visit, Qwrite_region);
4759 if (!NILP (handler))
4761 Lisp_Object val;
4762 val = call6 (handler, Qwrite_region, start, end,
4763 filename, append, visit);
4765 if (visiting)
4767 SAVE_MODIFF = MODIFF;
4768 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4769 bset_filename (current_buffer, visit_file);
4771 UNGCPRO;
4772 return val;
4775 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4777 /* Special kludge to simplify auto-saving. */
4778 if (NILP (start))
4780 /* Do it later, so write-region-annotate-function can work differently
4781 if we save "the buffer" vs "a region".
4782 This is useful in tar-mode. --Stef
4783 XSETFASTINT (start, BEG);
4784 XSETFASTINT (end, Z); */
4785 Fwiden ();
4788 record_unwind_protect (build_annotations_unwind,
4789 Vwrite_region_annotation_buffers);
4790 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4792 given_buffer = current_buffer;
4794 if (!STRINGP (start))
4796 annotations = build_annotations (start, end);
4798 if (current_buffer != given_buffer)
4800 XSETFASTINT (start, BEGV);
4801 XSETFASTINT (end, ZV);
4805 if (NILP (start))
4807 XSETFASTINT (start, BEGV);
4808 XSETFASTINT (end, ZV);
4811 UNGCPRO;
4813 GCPRO5 (start, filename, annotations, visit_file, lockname);
4815 /* Decide the coding-system to encode the data with.
4816 We used to make this choice before calling build_annotations, but that
4817 leads to problems when a write-annotate-function takes care of
4818 unsavable chars (as was the case with X-Symbol). */
4819 Vlast_coding_system_used
4820 = choose_write_coding_system (start, end, filename,
4821 append, visit, lockname, &coding);
4823 if (open_and_close_file && !auto_saving)
4825 lock_file (lockname);
4826 file_locked = 1;
4829 encoded_filename = ENCODE_FILE (filename);
4830 fn = SSDATA (encoded_filename);
4831 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4832 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4833 if (NUMBERP (append))
4834 offset = file_offset (append);
4835 else if (!NILP (append))
4836 open_flags |= O_APPEND;
4837 #ifdef DOS_NT
4838 mode = S_IREAD | S_IWRITE;
4839 #else
4840 mode = auto_saving ? auto_save_mode_bits : 0666;
4841 #endif
4843 if (open_and_close_file)
4845 desc = emacs_open (fn, open_flags, mode);
4846 if (desc < 0)
4848 int open_errno = errno;
4849 if (file_locked)
4850 unlock_file (lockname);
4851 UNGCPRO;
4852 report_file_errno ("Opening output file", filename, open_errno);
4855 count1 = SPECPDL_INDEX ();
4856 record_unwind_protect_int (close_file_unwind, desc);
4859 if (NUMBERP (append))
4861 off_t ret = lseek (desc, offset, SEEK_SET);
4862 if (ret < 0)
4864 int lseek_errno = errno;
4865 if (file_locked)
4866 unlock_file (lockname);
4867 UNGCPRO;
4868 report_file_errno ("Lseek error", filename, lseek_errno);
4872 UNGCPRO;
4874 immediate_quit = 1;
4876 if (STRINGP (start))
4877 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4878 else if (XINT (start) != XINT (end))
4879 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4880 &annotations, &coding);
4881 else
4883 /* If file was empty, still need to write the annotations. */
4884 coding.mode |= CODING_MODE_LAST_BLOCK;
4885 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4887 save_errno = errno;
4889 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4890 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4892 /* We have to flush out a data. */
4893 coding.mode |= CODING_MODE_LAST_BLOCK;
4894 ok = e_write (desc, Qnil, 1, 1, &coding);
4895 save_errno = errno;
4898 immediate_quit = 0;
4900 /* fsync is not crucial for temporary files. Nor for auto-save
4901 files, since they might lose some work anyway. */
4902 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4904 /* Transfer data and metadata to disk, retrying if interrupted.
4905 fsync can report a write failure here, e.g., due to disk full
4906 under NFS. But ignore EINVAL, which means fsync is not
4907 supported on this file. */
4908 while (fsync (desc) != 0)
4909 if (errno != EINTR)
4911 if (errno != EINVAL)
4912 ok = 0, save_errno = errno;
4913 break;
4917 modtime = invalid_timespec ();
4918 if (visiting)
4920 if (fstat (desc, &st) == 0)
4921 modtime = get_stat_mtime (&st);
4922 else
4923 ok = 0, save_errno = errno;
4926 if (open_and_close_file)
4928 /* NFS can report a write failure now. */
4929 if (emacs_close (desc) < 0)
4930 ok = 0, save_errno = errno;
4932 /* Discard the unwind protect for close_file_unwind. */
4933 specpdl_ptr = specpdl + count1;
4936 /* Some file systems have a bug where st_mtime is not updated
4937 properly after a write. For example, CIFS might not see the
4938 st_mtime change until after the file is opened again.
4940 Attempt to detect this file system bug, and update MODTIME to the
4941 newer st_mtime if the bug appears to be present. This introduces
4942 a race condition, so to avoid most instances of the race condition
4943 on non-buggy file systems, skip this check if the most recently
4944 encountered non-buggy file system was the current file system.
4946 A race condition can occur if some other process modifies the
4947 file between the fstat above and the fstat below, but the race is
4948 unlikely and a similar race between the last write and the fstat
4949 above cannot possibly be closed anyway. */
4951 if (timespec_valid_p (modtime)
4952 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4954 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4955 if (desc1 >= 0)
4957 struct stat st1;
4958 if (fstat (desc1, &st1) == 0
4959 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4961 /* Use the heuristic if it appears to be valid. With neither
4962 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4963 file, the time stamp won't change. Also, some non-POSIX
4964 systems don't update an empty file's time stamp when
4965 truncating it. Finally, file systems with 100 ns or worse
4966 resolution sometimes seem to have bugs: on a system with ns
4967 resolution, checking ns % 100 incorrectly avoids the heuristic
4968 1% of the time, but the problem should be temporary as we will
4969 try again on the next time stamp. */
4970 bool use_heuristic
4971 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4972 && st.st_size != 0
4973 && modtime.tv_nsec % 100 != 0);
4975 struct timespec modtime1 = get_stat_mtime (&st1);
4976 if (use_heuristic
4977 && timespec_cmp (modtime, modtime1) == 0
4978 && st.st_size == st1.st_size)
4980 timestamp_file_system = st.st_dev;
4981 valid_timestamp_file_system = 1;
4983 else
4985 st.st_size = st1.st_size;
4986 modtime = modtime1;
4989 emacs_close (desc1);
4993 /* Call write-region-post-annotation-function. */
4994 while (CONSP (Vwrite_region_annotation_buffers))
4996 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4997 if (!NILP (Fbuffer_live_p (buf)))
4999 Fset_buffer (buf);
5000 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5001 call0 (Vwrite_region_post_annotation_function);
5003 Vwrite_region_annotation_buffers
5004 = XCDR (Vwrite_region_annotation_buffers);
5007 unbind_to (count, Qnil);
5009 if (file_locked)
5010 unlock_file (lockname);
5012 /* Do this before reporting IO error
5013 to avoid a "file has changed on disk" warning on
5014 next attempt to save. */
5015 if (timespec_valid_p (modtime))
5017 current_buffer->modtime = modtime;
5018 current_buffer->modtime_size = st.st_size;
5021 if (! ok)
5022 report_file_errno ("Write error", filename, save_errno);
5024 if (visiting)
5026 SAVE_MODIFF = MODIFF;
5027 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5028 bset_filename (current_buffer, visit_file);
5029 update_mode_lines = 14;
5031 else if (quietly)
5033 if (auto_saving
5034 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5035 BVAR (current_buffer, auto_save_file_name))))
5036 SAVE_MODIFF = MODIFF;
5038 return Qnil;
5041 if (!auto_saving)
5042 message_with_string ((NUMBERP (append)
5043 ? "Updated %s"
5044 : ! NILP (append)
5045 ? "Added to %s"
5046 : "Wrote %s"),
5047 visit_file, 1);
5049 return Qnil;
5052 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5053 doc: /* Return t if (car A) is numerically less than (car B). */)
5054 (Lisp_Object a, Lisp_Object b)
5056 Lisp_Object args[2];
5057 args[0] = Fcar (a);
5058 args[1] = Fcar (b);
5059 return Flss (2, args);
5062 /* Build the complete list of annotations appropriate for writing out
5063 the text between START and END, by calling all the functions in
5064 write-region-annotate-functions and merging the lists they return.
5065 If one of these functions switches to a different buffer, we assume
5066 that buffer contains altered text. Therefore, the caller must
5067 make sure to restore the current buffer in all cases,
5068 as save-excursion would do. */
5070 static Lisp_Object
5071 build_annotations (Lisp_Object start, Lisp_Object end)
5073 Lisp_Object annotations;
5074 Lisp_Object p, res;
5075 struct gcpro gcpro1, gcpro2;
5076 Lisp_Object original_buffer;
5077 int i;
5078 bool used_global = 0;
5080 XSETBUFFER (original_buffer, current_buffer);
5082 annotations = Qnil;
5083 p = Vwrite_region_annotate_functions;
5084 GCPRO2 (annotations, p);
5085 while (CONSP (p))
5087 struct buffer *given_buffer = current_buffer;
5088 if (EQ (Qt, XCAR (p)) && !used_global)
5089 { /* Use the global value of the hook. */
5090 Lisp_Object arg[2];
5091 used_global = 1;
5092 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
5093 arg[1] = XCDR (p);
5094 p = Fappend (2, arg);
5095 continue;
5097 Vwrite_region_annotations_so_far = annotations;
5098 res = call2 (XCAR (p), start, end);
5099 /* If the function makes a different buffer current,
5100 assume that means this buffer contains altered text to be output.
5101 Reset START and END from the buffer bounds
5102 and discard all previous annotations because they should have
5103 been dealt with by this function. */
5104 if (current_buffer != given_buffer)
5106 Vwrite_region_annotation_buffers
5107 = Fcons (Fcurrent_buffer (),
5108 Vwrite_region_annotation_buffers);
5109 XSETFASTINT (start, BEGV);
5110 XSETFASTINT (end, ZV);
5111 annotations = Qnil;
5113 Flength (res); /* Check basic validity of return value */
5114 annotations = merge (annotations, res, Qcar_less_than_car);
5115 p = XCDR (p);
5118 /* Now do the same for annotation functions implied by the file-format */
5119 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5120 p = BVAR (current_buffer, auto_save_file_format);
5121 else
5122 p = BVAR (current_buffer, file_format);
5123 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5125 struct buffer *given_buffer = current_buffer;
5127 Vwrite_region_annotations_so_far = annotations;
5129 /* Value is either a list of annotations or nil if the function
5130 has written annotations to a temporary buffer, which is now
5131 current. */
5132 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5133 original_buffer, make_number (i));
5134 if (current_buffer != given_buffer)
5136 XSETFASTINT (start, BEGV);
5137 XSETFASTINT (end, ZV);
5138 annotations = Qnil;
5141 if (CONSP (res))
5142 annotations = merge (annotations, res, Qcar_less_than_car);
5145 UNGCPRO;
5146 return annotations;
5150 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5151 If STRING is nil, POS is the character position in the current buffer.
5152 Intersperse with them the annotations from *ANNOT
5153 which fall within the range of POS to POS + NCHARS,
5154 each at its appropriate position.
5156 We modify *ANNOT by discarding elements as we use them up.
5158 Return true if successful. */
5160 static bool
5161 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5162 ptrdiff_t nchars, Lisp_Object *annot,
5163 struct coding_system *coding)
5165 Lisp_Object tem;
5166 ptrdiff_t nextpos;
5167 ptrdiff_t lastpos = pos + nchars;
5169 while (NILP (*annot) || CONSP (*annot))
5171 tem = Fcar_safe (Fcar (*annot));
5172 nextpos = pos - 1;
5173 if (INTEGERP (tem))
5174 nextpos = XFASTINT (tem);
5176 /* If there are no more annotations in this range,
5177 output the rest of the range all at once. */
5178 if (! (nextpos >= pos && nextpos <= lastpos))
5179 return e_write (desc, string, pos, lastpos, coding);
5181 /* Output buffer text up to the next annotation's position. */
5182 if (nextpos > pos)
5184 if (!e_write (desc, string, pos, nextpos, coding))
5185 return 0;
5186 pos = nextpos;
5188 /* Output the annotation. */
5189 tem = Fcdr (Fcar (*annot));
5190 if (STRINGP (tem))
5192 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5193 return 0;
5195 *annot = Fcdr (*annot);
5197 return 1;
5200 /* Maximum number of characters that the next
5201 function encodes per one loop iteration. */
5203 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5205 /* Write text in the range START and END into descriptor DESC,
5206 encoding them with coding system CODING. If STRING is nil, START
5207 and END are character positions of the current buffer, else they
5208 are indexes to the string STRING. Return true if successful. */
5210 static bool
5211 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5212 struct coding_system *coding)
5214 if (STRINGP (string))
5216 start = 0;
5217 end = SCHARS (string);
5220 /* We used to have a code for handling selective display here. But,
5221 now it is handled within encode_coding. */
5223 while (start < end)
5225 if (STRINGP (string))
5227 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5228 if (CODING_REQUIRE_ENCODING (coding))
5230 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5232 /* Avoid creating huge Lisp string in encode_coding_object. */
5233 if (nchars == E_WRITE_MAX)
5234 coding->raw_destination = 1;
5236 encode_coding_object
5237 (coding, string, start, string_char_to_byte (string, start),
5238 start + nchars, string_char_to_byte (string, start + nchars),
5239 Qt);
5241 else
5243 coding->dst_object = string;
5244 coding->consumed_char = SCHARS (string);
5245 coding->produced = SBYTES (string);
5248 else
5250 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5251 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5253 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5254 if (CODING_REQUIRE_ENCODING (coding))
5256 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5258 /* Likewise. */
5259 if (nchars == E_WRITE_MAX)
5260 coding->raw_destination = 1;
5262 encode_coding_object
5263 (coding, Fcurrent_buffer (), start, start_byte,
5264 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5266 else
5268 coding->dst_object = Qnil;
5269 coding->dst_pos_byte = start_byte;
5270 if (start >= GPT || end <= GPT)
5272 coding->consumed_char = end - start;
5273 coding->produced = end_byte - start_byte;
5275 else
5277 coding->consumed_char = GPT - start;
5278 coding->produced = GPT_BYTE - start_byte;
5283 if (coding->produced > 0)
5285 char *buf = (coding->raw_destination ? (char *) coding->destination
5286 : (STRINGP (coding->dst_object)
5287 ? SSDATA (coding->dst_object)
5288 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5289 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5291 if (coding->raw_destination)
5293 /* We're responsible for freeing this, see
5294 encode_coding_object to check why. */
5295 xfree (coding->destination);
5296 coding->raw_destination = 0;
5298 if (coding->produced)
5299 return 0;
5301 start += coding->consumed_char;
5304 return 1;
5307 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5308 Sverify_visited_file_modtime, 0, 1, 0,
5309 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5310 This means that the file has not been changed since it was visited or saved.
5311 If BUF is omitted or nil, it defaults to the current buffer.
5312 See Info node `(elisp)Modification Time' for more details. */)
5313 (Lisp_Object buf)
5315 struct buffer *b = decode_buffer (buf);
5316 struct stat st;
5317 Lisp_Object handler;
5318 Lisp_Object filename;
5319 struct timespec mtime;
5321 if (!STRINGP (BVAR (b, filename))) return Qt;
5322 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5324 /* If the file name has special constructs in it,
5325 call the corresponding file handler. */
5326 handler = Ffind_file_name_handler (BVAR (b, filename),
5327 Qverify_visited_file_modtime);
5328 if (!NILP (handler))
5329 return call2 (handler, Qverify_visited_file_modtime, buf);
5331 filename = ENCODE_FILE (BVAR (b, filename));
5333 mtime = (stat (SSDATA (filename), &st) == 0
5334 ? get_stat_mtime (&st)
5335 : time_error_value (errno));
5336 if (timespec_cmp (mtime, b->modtime) == 0
5337 && (b->modtime_size < 0
5338 || st.st_size == b->modtime_size))
5339 return Qt;
5340 return Qnil;
5343 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5344 Svisited_file_modtime, 0, 0, 0,
5345 doc: /* Return the current buffer's recorded visited file modification time.
5346 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5347 `file-attributes' returns. If the current buffer has no recorded file
5348 modification time, this function returns 0. If the visited file
5349 doesn't exist, return -1.
5350 See Info node `(elisp)Modification Time' for more details. */)
5351 (void)
5353 int ns = current_buffer->modtime.tv_nsec;
5354 if (ns < 0)
5355 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5356 return make_lisp_time (current_buffer->modtime);
5359 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5360 Sset_visited_file_modtime, 0, 1, 0,
5361 doc: /* Update buffer's recorded modification time from the visited file's time.
5362 Useful if the buffer was not read from the file normally
5363 or if the file itself has been changed for some known benign reason.
5364 An argument specifies the modification time value to use
5365 \(instead of that of the visited file), in the form of a list
5366 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5367 `visited-file-modtime'. */)
5368 (Lisp_Object time_flag)
5370 if (!NILP (time_flag))
5372 struct timespec mtime;
5373 if (INTEGERP (time_flag))
5375 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5376 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5378 else
5379 mtime = lisp_time_argument (time_flag);
5381 current_buffer->modtime = mtime;
5382 current_buffer->modtime_size = -1;
5384 else
5386 register Lisp_Object filename;
5387 struct stat st;
5388 Lisp_Object handler;
5390 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5392 /* If the file name has special constructs in it,
5393 call the corresponding file handler. */
5394 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5395 if (!NILP (handler))
5396 /* The handler can find the file name the same way we did. */
5397 return call2 (handler, Qset_visited_file_modtime, Qnil);
5399 filename = ENCODE_FILE (filename);
5401 if (stat (SSDATA (filename), &st) >= 0)
5403 current_buffer->modtime = get_stat_mtime (&st);
5404 current_buffer->modtime_size = st.st_size;
5408 return Qnil;
5411 static Lisp_Object
5412 auto_save_error (Lisp_Object error_val)
5414 Lisp_Object msg;
5415 int i;
5416 struct gcpro gcpro1;
5418 auto_save_error_occurred = 1;
5420 ring_bell (XFRAME (selected_frame));
5422 msg = Fformat (3, ((Lisp_Object [])
5423 { build_local_string ("Auto-saving %s: %s"),
5424 BVAR (current_buffer, name),
5425 Ferror_message_string (error_val) }));
5426 GCPRO1 (msg);
5428 for (i = 0; i < 3; ++i)
5430 if (i == 0)
5431 message3 (msg);
5432 else
5433 message3_nolog (msg);
5434 Fsleep_for (make_number (1), Qnil);
5437 UNGCPRO;
5438 return Qnil;
5441 static Lisp_Object
5442 auto_save_1 (void)
5444 struct stat st;
5445 Lisp_Object modes;
5447 auto_save_mode_bits = 0666;
5449 /* Get visited file's mode to become the auto save file's mode. */
5450 if (! NILP (BVAR (current_buffer, filename)))
5452 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5453 /* But make sure we can overwrite it later! */
5454 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5455 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5456 INTEGERP (modes))
5457 /* Remote files don't cooperate with stat. */
5458 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5461 return
5462 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5463 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5464 Qnil, Qnil);
5467 struct auto_save_unwind
5469 FILE *stream;
5470 bool auto_raise;
5473 static void
5474 do_auto_save_unwind (void *arg)
5476 struct auto_save_unwind *p = arg;
5477 FILE *stream = p->stream;
5478 minibuffer_auto_raise = p->auto_raise;
5479 auto_saving = 0;
5480 if (stream != NULL)
5482 block_input ();
5483 fclose (stream);
5484 unblock_input ();
5488 static Lisp_Object
5489 do_auto_save_make_dir (Lisp_Object dir)
5491 Lisp_Object result;
5493 auto_saving_dir_umask = 077;
5494 result = call2 (Qmake_directory, dir, Qt);
5495 auto_saving_dir_umask = 0;
5496 return result;
5499 static Lisp_Object
5500 do_auto_save_eh (Lisp_Object ignore)
5502 auto_saving_dir_umask = 0;
5503 return Qnil;
5506 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5507 doc: /* Auto-save all buffers that need it.
5508 This is all buffers that have auto-saving enabled
5509 and are changed since last auto-saved.
5510 Auto-saving writes the buffer into a file
5511 so that your editing is not lost if the system crashes.
5512 This file is not the file you visited; that changes only when you save.
5513 Normally we run the normal hook `auto-save-hook' before saving.
5515 A non-nil NO-MESSAGE argument means do not print any message if successful.
5516 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5517 (Lisp_Object no_message, Lisp_Object current_only)
5519 struct buffer *old = current_buffer, *b;
5520 Lisp_Object tail, buf, hook;
5521 bool auto_saved = 0;
5522 int do_handled_files;
5523 Lisp_Object oquit;
5524 FILE *stream = NULL;
5525 ptrdiff_t count = SPECPDL_INDEX ();
5526 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5527 bool old_message_p = 0;
5528 struct auto_save_unwind auto_save_unwind;
5529 struct gcpro gcpro1, gcpro2;
5531 if (max_specpdl_size < specpdl_size + 40)
5532 max_specpdl_size = specpdl_size + 40;
5534 if (minibuf_level)
5535 no_message = Qt;
5537 if (NILP (no_message))
5539 old_message_p = push_message ();
5540 record_unwind_protect_void (pop_message_unwind);
5543 /* Ordinarily don't quit within this function,
5544 but don't make it impossible to quit (in case we get hung in I/O). */
5545 oquit = Vquit_flag;
5546 Vquit_flag = Qnil;
5548 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5549 point to non-strings reached from Vbuffer_alist. */
5551 hook = intern ("auto-save-hook");
5552 safe_run_hooks (hook);
5554 if (STRINGP (Vauto_save_list_file_name))
5556 Lisp_Object listfile;
5558 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5560 /* Don't try to create the directory when shutting down Emacs,
5561 because creating the directory might signal an error, and
5562 that would leave Emacs in a strange state. */
5563 if (!NILP (Vrun_hooks))
5565 Lisp_Object dir;
5566 dir = Qnil;
5567 GCPRO2 (dir, listfile);
5568 dir = Ffile_name_directory (listfile);
5569 if (NILP (Ffile_directory_p (dir)))
5570 internal_condition_case_1 (do_auto_save_make_dir,
5571 dir, Qt,
5572 do_auto_save_eh);
5573 UNGCPRO;
5576 stream = emacs_fopen (SSDATA (listfile), "w");
5579 auto_save_unwind.stream = stream;
5580 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5581 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5582 minibuffer_auto_raise = 0;
5583 auto_saving = 1;
5584 auto_save_error_occurred = 0;
5586 /* On first pass, save all files that don't have handlers.
5587 On second pass, save all files that do have handlers.
5589 If Emacs is crashing, the handlers may tweak what is causing
5590 Emacs to crash in the first place, and it would be a shame if
5591 Emacs failed to autosave perfectly ordinary files because it
5592 couldn't handle some ange-ftp'd file. */
5594 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5595 FOR_EACH_LIVE_BUFFER (tail, buf)
5597 b = XBUFFER (buf);
5599 /* Record all the buffers that have auto save mode
5600 in the special file that lists them. For each of these buffers,
5601 Record visited name (if any) and auto save name. */
5602 if (STRINGP (BVAR (b, auto_save_file_name))
5603 && stream != NULL && do_handled_files == 0)
5605 block_input ();
5606 if (!NILP (BVAR (b, filename)))
5608 fwrite (SDATA (BVAR (b, filename)), 1,
5609 SBYTES (BVAR (b, filename)), stream);
5611 putc ('\n', stream);
5612 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5613 SBYTES (BVAR (b, auto_save_file_name)), stream);
5614 putc ('\n', stream);
5615 unblock_input ();
5618 if (!NILP (current_only)
5619 && b != current_buffer)
5620 continue;
5622 /* Don't auto-save indirect buffers.
5623 The base buffer takes care of it. */
5624 if (b->base_buffer)
5625 continue;
5627 /* Check for auto save enabled
5628 and file changed since last auto save
5629 and file changed since last real save. */
5630 if (STRINGP (BVAR (b, auto_save_file_name))
5631 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5632 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5633 /* -1 means we've turned off autosaving for a while--see below. */
5634 && XINT (BVAR (b, save_length)) >= 0
5635 && (do_handled_files
5636 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5637 Qwrite_region))))
5639 struct timespec before_time = current_timespec ();
5640 struct timespec after_time;
5642 /* If we had a failure, don't try again for 20 minutes. */
5643 if (b->auto_save_failure_time > 0
5644 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5645 continue;
5647 set_buffer_internal (b);
5648 if (NILP (Vauto_save_include_big_deletions)
5649 && (XFASTINT (BVAR (b, save_length)) * 10
5650 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5651 /* A short file is likely to change a large fraction;
5652 spare the user annoying messages. */
5653 && XFASTINT (BVAR (b, save_length)) > 5000
5654 /* These messages are frequent and annoying for `*mail*'. */
5655 && !EQ (BVAR (b, filename), Qnil)
5656 && NILP (no_message))
5658 /* It has shrunk too much; turn off auto-saving here. */
5659 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5660 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5661 BVAR (b, name), 1);
5662 minibuffer_auto_raise = 0;
5663 /* Turn off auto-saving until there's a real save,
5664 and prevent any more warnings. */
5665 XSETINT (BVAR (b, save_length), -1);
5666 Fsleep_for (make_number (1), Qnil);
5667 continue;
5669 if (!auto_saved && NILP (no_message))
5670 message1 ("Auto-saving...");
5671 internal_condition_case (auto_save_1, Qt, auto_save_error);
5672 auto_saved = 1;
5673 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5674 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5675 set_buffer_internal (old);
5677 after_time = current_timespec ();
5679 /* If auto-save took more than 60 seconds,
5680 assume it was an NFS failure that got a timeout. */
5681 if (after_time.tv_sec - before_time.tv_sec > 60)
5682 b->auto_save_failure_time = after_time.tv_sec;
5686 /* Prevent another auto save till enough input events come in. */
5687 record_auto_save ();
5689 if (auto_saved && NILP (no_message))
5691 if (old_message_p)
5693 /* If we are going to restore an old message,
5694 give time to read ours. */
5695 sit_for (make_number (1), 0, 0);
5696 restore_message ();
5698 else if (!auto_save_error_occurred)
5699 /* Don't overwrite the error message if an error occurred.
5700 If we displayed a message and then restored a state
5701 with no message, leave a "done" message on the screen. */
5702 message1 ("Auto-saving...done");
5705 Vquit_flag = oquit;
5707 /* This restores the message-stack status. */
5708 unbind_to (count, Qnil);
5709 return Qnil;
5712 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5713 Sset_buffer_auto_saved, 0, 0, 0,
5714 doc: /* Mark current buffer as auto-saved with its current text.
5715 No auto-save file will be written until the buffer changes again. */)
5716 (void)
5718 /* FIXME: This should not be called in indirect buffers, since
5719 they're not autosaved. */
5720 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5721 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5722 current_buffer->auto_save_failure_time = 0;
5723 return Qnil;
5726 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5727 Sclear_buffer_auto_save_failure, 0, 0, 0,
5728 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5729 (void)
5731 current_buffer->auto_save_failure_time = 0;
5732 return Qnil;
5735 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5736 0, 0, 0,
5737 doc: /* Return t if current buffer has been auto-saved recently.
5738 More precisely, if it has been auto-saved since last read from or saved
5739 in the visited file. If the buffer has no visited file,
5740 then any auto-save counts as "recent". */)
5741 (void)
5743 /* FIXME: maybe we should return nil for indirect buffers since
5744 they're never autosaved. */
5745 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5748 /* Reading and completing file names */
5750 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5751 Snext_read_file_uses_dialog_p, 0, 0, 0,
5752 doc: /* Return t if a call to `read-file-name' will use a dialog.
5753 The return value is only relevant for a call to `read-file-name' that happens
5754 before any other event (mouse or keypress) is handled. */)
5755 (void)
5757 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) \
5758 || defined (HAVE_NS)
5759 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5760 && use_dialog_box
5761 && use_file_dialog
5762 && window_system_available (SELECTED_FRAME ()))
5763 return Qt;
5764 #endif
5765 return Qnil;
5768 void
5769 init_fileio (void)
5771 realmask = umask (0);
5772 umask (realmask);
5774 valid_timestamp_file_system = 0;
5776 /* fsync can be a significant performance hit. Often it doesn't
5777 suffice to make the file-save operation survive a crash. For
5778 batch scripts, which are typically part of larger shell commands
5779 that don't fsync other files, its effect on performance can be
5780 significant so its utility is particularly questionable.
5781 Hence, for now by default fsync is used only when interactive.
5783 For more on why fsync often fails to work on today's hardware, see:
5784 Zheng M et al. Understanding the robustness of SSDs under power fault.
5785 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5786 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5788 For more on why fsync does not suffice even if it works properly, see:
5789 Roche X. Necessary step(s) to synchronize filename operations on disk.
5790 Austin Group Defect 672, 2013-03-19
5791 http://austingroupbugs.net/view.php?id=672 */
5792 write_region_inhibit_fsync = noninteractive;
5795 void
5796 syms_of_fileio (void)
5798 DEFSYM (Qoperations, "operations");
5799 DEFSYM (Qexpand_file_name, "expand-file-name");
5800 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5801 DEFSYM (Qdirectory_file_name, "directory-file-name");
5802 DEFSYM (Qfile_name_directory, "file-name-directory");
5803 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5804 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5805 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5806 DEFSYM (Qcopy_file, "copy-file");
5807 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5808 DEFSYM (Qmake_directory, "make-directory");
5809 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5810 DEFSYM (Qdelete_file, "delete-file");
5811 DEFSYM (Qrename_file, "rename-file");
5812 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5813 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5814 DEFSYM (Qfile_exists_p, "file-exists-p");
5815 DEFSYM (Qfile_executable_p, "file-executable-p");
5816 DEFSYM (Qfile_readable_p, "file-readable-p");
5817 DEFSYM (Qfile_writable_p, "file-writable-p");
5818 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5819 DEFSYM (Qaccess_file, "access-file");
5820 DEFSYM (Qfile_directory_p, "file-directory-p");
5821 DEFSYM (Qfile_regular_p, "file-regular-p");
5822 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5823 DEFSYM (Qfile_modes, "file-modes");
5824 DEFSYM (Qset_file_modes, "set-file-modes");
5825 DEFSYM (Qset_file_times, "set-file-times");
5826 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5827 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5828 DEFSYM (Qfile_acl, "file-acl");
5829 DEFSYM (Qset_file_acl, "set-file-acl");
5830 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5831 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5832 DEFSYM (Qwrite_region, "write-region");
5833 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5834 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5835 DEFSYM (Qauto_save_coding, "auto-save-coding");
5837 DEFSYM (Qfile_name_history, "file-name-history");
5838 Fset (Qfile_name_history, Qnil);
5840 DEFSYM (Qfile_error, "file-error");
5841 DEFSYM (Qfile_already_exists, "file-already-exists");
5842 DEFSYM (Qfile_date_error, "file-date-error");
5843 DEFSYM (Qfile_notify_error, "file-notify-error");
5844 DEFSYM (Qexcl, "excl");
5846 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5847 doc: /* Coding system for encoding file names.
5848 If it is nil, `default-file-name-coding-system' (which see) is used.
5850 On MS-Windows, the value of this variable is largely ignored if
5851 \`w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5852 behaves as if file names were encoded in `utf-8'. */);
5853 Vfile_name_coding_system = Qnil;
5855 DEFVAR_LISP ("default-file-name-coding-system",
5856 Vdefault_file_name_coding_system,
5857 doc: /* Default coding system for encoding file names.
5858 This variable is used only when `file-name-coding-system' is nil.
5860 This variable is set/changed by the command `set-language-environment'.
5861 User should not set this variable manually,
5862 instead use `file-name-coding-system' to get a constant encoding
5863 of file names regardless of the current language environment.
5865 On MS-Windows, the value of this variable is largely ignored if
5866 \`w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5867 behaves as if file names were encoded in `utf-8'. */);
5868 Vdefault_file_name_coding_system = Qnil;
5870 DEFSYM (Qformat_decode, "format-decode");
5871 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5872 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5873 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5875 Fput (Qfile_error, Qerror_conditions,
5876 Fpurecopy (list2 (Qfile_error, Qerror)));
5877 Fput (Qfile_error, Qerror_message,
5878 build_pure_c_string ("File error"));
5880 Fput (Qfile_already_exists, Qerror_conditions,
5881 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5882 Fput (Qfile_already_exists, Qerror_message,
5883 build_pure_c_string ("File already exists"));
5885 Fput (Qfile_date_error, Qerror_conditions,
5886 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5887 Fput (Qfile_date_error, Qerror_message,
5888 build_pure_c_string ("Cannot set file date"));
5890 Fput (Qfile_notify_error, Qerror_conditions,
5891 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5892 Fput (Qfile_notify_error, Qerror_message,
5893 build_pure_c_string ("File notification error"));
5895 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5896 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5897 If a file name matches REGEXP, all I/O on that file is done by calling
5898 HANDLER. If a file name matches more than one handler, the handler
5899 whose match starts last in the file name gets precedence. The
5900 function `find-file-name-handler' checks this list for a handler for
5901 its argument.
5903 HANDLER should be a function. The first argument given to it is the
5904 name of the I/O primitive to be handled; the remaining arguments are
5905 the arguments that were passed to that primitive. For example, if you
5906 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5907 HANDLER is called like this:
5909 (funcall HANDLER 'file-exists-p FILENAME)
5911 Note that HANDLER must be able to handle all I/O primitives; if it has
5912 nothing special to do for a primitive, it should reinvoke the
5913 primitive to handle the operation \"the usual way\".
5914 See Info node `(elisp)Magic File Names' for more details. */);
5915 Vfile_name_handler_alist = Qnil;
5917 DEFVAR_LISP ("set-auto-coding-function",
5918 Vset_auto_coding_function,
5919 doc: /* If non-nil, a function to call to decide a coding system of file.
5920 Two arguments are passed to this function: the file name
5921 and the length of a file contents following the point.
5922 This function should return a coding system to decode the file contents.
5923 It should check the file name against `auto-coding-alist'.
5924 If no coding system is decided, it should check a coding system
5925 specified in the heading lines with the format:
5926 -*- ... coding: CODING-SYSTEM; ... -*-
5927 or local variable spec of the tailing lines with `coding:' tag. */);
5928 Vset_auto_coding_function = Qnil;
5930 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5931 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5932 Each is passed one argument, the number of characters inserted,
5933 with point at the start of the inserted text. Each function
5934 should leave point the same, and return the new character count.
5935 If `insert-file-contents' is intercepted by a handler from
5936 `file-name-handler-alist', that handler is responsible for calling the
5937 functions in `after-insert-file-functions' if appropriate. */);
5938 Vafter_insert_file_functions = Qnil;
5940 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5941 doc: /* A list of functions to be called at the start of `write-region'.
5942 Each is passed two arguments, START and END as for `write-region'.
5943 These are usually two numbers but not always; see the documentation
5944 for `write-region'. The function should return a list of pairs
5945 of the form (POSITION . STRING), consisting of strings to be effectively
5946 inserted at the specified positions of the file being written (1 means to
5947 insert before the first byte written). The POSITIONs must be sorted into
5948 increasing order.
5950 If there are several annotation functions, the lists returned by these
5951 functions are merged destructively. As each annotation function runs,
5952 the variable `write-region-annotations-so-far' contains a list of all
5953 annotations returned by previous annotation functions.
5955 An annotation function can return with a different buffer current.
5956 Doing so removes the annotations returned by previous functions, and
5957 resets START and END to `point-min' and `point-max' of the new buffer.
5959 After `write-region' completes, Emacs calls the function stored in
5960 `write-region-post-annotation-function', once for each buffer that was
5961 current when building the annotations (i.e., at least once), with that
5962 buffer current. */);
5963 Vwrite_region_annotate_functions = Qnil;
5964 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5966 DEFVAR_LISP ("write-region-post-annotation-function",
5967 Vwrite_region_post_annotation_function,
5968 doc: /* Function to call after `write-region' completes.
5969 The function is called with no arguments. If one or more of the
5970 annotation functions in `write-region-annotate-functions' changed the
5971 current buffer, the function stored in this variable is called for
5972 each of those additional buffers as well, in addition to the original
5973 buffer. The relevant buffer is current during each function call. */);
5974 Vwrite_region_post_annotation_function = Qnil;
5975 staticpro (&Vwrite_region_annotation_buffers);
5977 DEFVAR_LISP ("write-region-annotations-so-far",
5978 Vwrite_region_annotations_so_far,
5979 doc: /* When an annotation function is called, this holds the previous annotations.
5980 These are the annotations made by other annotation functions
5981 that were already called. See also `write-region-annotate-functions'. */);
5982 Vwrite_region_annotations_so_far = Qnil;
5984 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5985 doc: /* A list of file name handlers that temporarily should not be used.
5986 This applies only to the operation `inhibit-file-name-operation'. */);
5987 Vinhibit_file_name_handlers = Qnil;
5989 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5990 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5991 Vinhibit_file_name_operation = Qnil;
5993 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
5994 doc: /* File name in which we write a list of all auto save file names.
5995 This variable is initialized automatically from `auto-save-list-file-prefix'
5996 shortly after Emacs reads your init file, if you have not yet given it
5997 a non-nil value. */);
5998 Vauto_save_list_file_name = Qnil;
6000 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6001 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6002 Normally auto-save files are written under other names. */);
6003 Vauto_save_visited_file_name = Qnil;
6005 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6006 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6007 If nil, deleting a substantial portion of the text disables auto-save
6008 in the buffer; this is the default behavior, because the auto-save
6009 file is usually more useful if it contains the deleted text. */);
6010 Vauto_save_include_big_deletions = Qnil;
6012 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6013 doc: /* Non-nil means don't call fsync in `write-region'.
6014 This variable affects calls to `write-region' as well as save commands.
6015 Setting this to nil may avoid data loss if the system loses power or
6016 the operating system crashes. By default, it is non-nil in batch mode. */);
6017 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6019 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6020 doc: /* Specifies whether to use the system's trash can.
6021 When non-nil, certain file deletion commands use the function
6022 `move-file-to-trash' instead of deleting files outright.
6023 This includes interactive calls to `delete-file' and
6024 `delete-directory' and the Dired deletion commands. */);
6025 delete_by_moving_to_trash = 0;
6026 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
6028 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6029 DEFSYM (Qcopy_directory, "copy-directory");
6030 DEFSYM (Qdelete_directory, "delete-directory");
6031 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6033 defsubr (&Sfind_file_name_handler);
6034 defsubr (&Sfile_name_directory);
6035 defsubr (&Sfile_name_nondirectory);
6036 defsubr (&Sunhandled_file_name_directory);
6037 defsubr (&Sfile_name_as_directory);
6038 defsubr (&Sdirectory_file_name);
6039 defsubr (&Smake_temp_name);
6040 defsubr (&Sexpand_file_name);
6041 defsubr (&Ssubstitute_in_file_name);
6042 defsubr (&Scopy_file);
6043 defsubr (&Smake_directory_internal);
6044 defsubr (&Sdelete_directory_internal);
6045 defsubr (&Sdelete_file);
6046 defsubr (&Srename_file);
6047 defsubr (&Sadd_name_to_file);
6048 defsubr (&Smake_symbolic_link);
6049 defsubr (&Sfile_name_absolute_p);
6050 defsubr (&Sfile_exists_p);
6051 defsubr (&Sfile_executable_p);
6052 defsubr (&Sfile_readable_p);
6053 defsubr (&Sfile_writable_p);
6054 defsubr (&Saccess_file);
6055 defsubr (&Sfile_symlink_p);
6056 defsubr (&Sfile_directory_p);
6057 defsubr (&Sfile_accessible_directory_p);
6058 defsubr (&Sfile_regular_p);
6059 defsubr (&Sfile_modes);
6060 defsubr (&Sset_file_modes);
6061 defsubr (&Sset_file_times);
6062 defsubr (&Sfile_selinux_context);
6063 defsubr (&Sfile_acl);
6064 defsubr (&Sset_file_acl);
6065 defsubr (&Sset_file_selinux_context);
6066 defsubr (&Sset_default_file_modes);
6067 defsubr (&Sdefault_file_modes);
6068 defsubr (&Sfile_newer_than_file_p);
6069 defsubr (&Sinsert_file_contents);
6070 defsubr (&Swrite_region);
6071 defsubr (&Scar_less_than_car);
6072 defsubr (&Sverify_visited_file_modtime);
6073 defsubr (&Svisited_file_modtime);
6074 defsubr (&Sset_visited_file_modtime);
6075 defsubr (&Sdo_auto_save);
6076 defsubr (&Sset_buffer_auto_saved);
6077 defsubr (&Sclear_buffer_auto_save_failure);
6078 defsubr (&Srecent_auto_save_p);
6080 defsubr (&Snext_read_file_uses_dialog_p);
6082 #ifdef HAVE_SYNC
6083 defsubr (&Sunix_sync);
6084 #endif