* src/fileio.c (Fmake_temp_name): Doc tweaks.
[emacs.git] / src / fileio.c
blobc87a87ca7c6431f33c696b678c96bc4f372ae1db
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2015 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 #ifndef DOS_NT
400 register const char *beg;
401 #else
402 register char *beg;
403 Lisp_Object tem_fn;
404 #endif
405 register const char *p;
406 Lisp_Object handler;
408 CHECK_STRING (filename);
410 /* If the file name has special constructs in it,
411 call the corresponding file handler. */
412 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
413 if (!NILP (handler))
415 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
416 filename);
417 return STRINGP (handled_name) ? handled_name : Qnil;
420 #ifdef DOS_NT
421 beg = xlispstrdupa (filename);
422 #else
423 beg = SSDATA (filename);
424 #endif
425 p = beg + SBYTES (filename);
427 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
428 #ifdef DOS_NT
429 /* only recognize drive specifier at the beginning */
430 && !(p[-1] == ':'
431 /* handle the "/:d:foo" and "/:foo" cases correctly */
432 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
433 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
434 #endif
435 ) p--;
437 if (p == beg)
438 return Qnil;
439 #ifdef DOS_NT
440 /* Expansion of "c:" to drive and default directory. */
441 if (p[-1] == ':')
443 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
444 char *res = alloca (MAXPATHLEN + 1);
445 char *r = res;
447 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
449 memcpy (res, beg, 2);
450 beg += 2;
451 r += 2;
454 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
456 size_t l = strlen (res);
458 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
459 strcat (res, "/");
460 beg = res;
461 p = beg + strlen (beg);
462 dostounix_filename (beg);
463 tem_fn = make_specified_string (beg, -1, p - beg,
464 STRING_MULTIBYTE (filename));
466 else
467 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
468 STRING_MULTIBYTE (filename));
470 else if (STRING_MULTIBYTE (filename))
472 tem_fn = make_specified_string (beg, -1, p - beg, 1);
473 dostounix_filename (SSDATA (tem_fn));
474 #ifdef WINDOWSNT
475 if (!NILP (Vw32_downcase_file_names))
476 tem_fn = Fdowncase (tem_fn);
477 #endif
479 else
481 dostounix_filename (beg);
482 tem_fn = make_specified_string (beg, -1, p - beg, 0);
484 return tem_fn;
485 #else /* DOS_NT */
486 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
487 #endif /* DOS_NT */
490 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
491 Sfile_name_nondirectory, 1, 1, 0,
492 doc: /* Return file name FILENAME sans its directory.
493 For example, in a Unix-syntax file name,
494 this is everything after the last slash,
495 or the entire name if it contains no slash. */)
496 (Lisp_Object filename)
498 register const char *beg, *p, *end;
499 Lisp_Object handler;
501 CHECK_STRING (filename);
503 /* If the file name has special constructs in it,
504 call the corresponding file handler. */
505 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
506 if (!NILP (handler))
508 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
509 filename);
510 if (STRINGP (handled_name))
511 return handled_name;
512 error ("Invalid handler in `file-name-handler-alist'");
515 beg = SSDATA (filename);
516 end = p = beg + SBYTES (filename);
518 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
519 #ifdef DOS_NT
520 /* only recognize drive specifier at beginning */
521 && !(p[-1] == ':'
522 /* handle the "/:d:foo" case correctly */
523 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
524 #endif
526 p--;
528 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
531 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
532 Sunhandled_file_name_directory, 1, 1, 0,
533 doc: /* Return a directly usable directory name somehow associated with FILENAME.
534 A `directly usable' directory name is one that may be used without the
535 intervention of any file handler.
536 If FILENAME is a directly usable file itself, return
537 \(file-name-directory FILENAME).
538 If FILENAME refers to a file which is not accessible from a local process,
539 then this should return nil.
540 The `call-process' and `start-process' functions use this function to
541 get a current directory to run processes in. */)
542 (Lisp_Object filename)
544 Lisp_Object handler;
546 /* If the file name has special constructs in it,
547 call the corresponding file handler. */
548 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
549 if (!NILP (handler))
551 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
552 filename);
553 return STRINGP (handled_name) ? handled_name : Qnil;
556 return Ffile_name_directory (filename);
559 /* Maximum number of bytes that DST will be longer than SRC
560 in file_name_as_directory. This occurs when SRCLEN == 0. */
561 enum { file_name_as_directory_slop = 2 };
563 /* Convert from file name SRC of length SRCLEN to directory name in
564 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
565 string. On UNIX, just make sure there is a terminating /. Return
566 the length of DST in bytes. */
568 static ptrdiff_t
569 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
570 bool multibyte)
572 if (srclen == 0)
574 dst[0] = '.';
575 dst[1] = '/';
576 dst[2] = '\0';
577 return 2;
580 memcpy (dst, src, srclen);
581 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
582 dst[srclen++] = DIRECTORY_SEP;
583 dst[srclen] = 0;
584 #ifdef DOS_NT
585 dostounix_filename (dst);
586 #endif
587 return srclen;
590 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
591 Sfile_name_as_directory, 1, 1, 0,
592 doc: /* Return a string representing the file name FILE interpreted as a directory.
593 This operation exists because a directory is also a file, but its name as
594 a directory is different from its name as a file.
595 The result can be used as the value of `default-directory'
596 or passed as second argument to `expand-file-name'.
597 For a Unix-syntax file name, just appends a slash. */)
598 (Lisp_Object file)
600 char *buf;
601 ptrdiff_t length;
602 Lisp_Object handler, val;
603 USE_SAFE_ALLOCA;
605 CHECK_STRING (file);
606 if (NILP (file))
607 return Qnil;
609 /* If the file name has special constructs in it,
610 call the corresponding file handler. */
611 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
612 if (!NILP (handler))
614 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
615 file);
616 if (STRINGP (handled_name))
617 return handled_name;
618 error ("Invalid handler in `file-name-handler-alist'");
621 #ifdef WINDOWSNT
622 if (!NILP (Vw32_downcase_file_names))
623 file = Fdowncase (file);
624 #endif
625 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
626 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
627 STRING_MULTIBYTE (file));
628 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
629 SAFE_FREE ();
630 return val;
633 /* Convert from directory name SRC of length SRCLEN to file name in
634 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
635 string. On UNIX, just make sure there isn't a terminating /.
636 Return the length of DST in bytes. */
638 static ptrdiff_t
639 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
641 /* Process as Unix format: just remove any final slash.
642 But leave "/" and "//" unchanged. */
643 while (srclen > 1
644 #ifdef DOS_NT
645 && !IS_ANY_SEP (src[srclen - 2])
646 #endif
647 && IS_DIRECTORY_SEP (src[srclen - 1])
648 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
649 srclen--;
651 memcpy (dst, src, srclen);
652 dst[srclen] = 0;
653 #ifdef DOS_NT
654 dostounix_filename (dst);
655 #endif
656 return srclen;
659 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
660 1, 1, 0,
661 doc: /* Returns the file name of the directory named DIRECTORY.
662 This is the name of the file that holds the data for the directory DIRECTORY.
663 This operation exists because a directory is also a file, but its name as
664 a directory is different from its name as a file.
665 In Unix-syntax, this function just removes the final slash. */)
666 (Lisp_Object directory)
668 char *buf;
669 ptrdiff_t length;
670 Lisp_Object handler, val;
671 USE_SAFE_ALLOCA;
673 CHECK_STRING (directory);
675 if (NILP (directory))
676 return Qnil;
678 /* If the file name has special constructs in it,
679 call the corresponding file handler. */
680 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
681 if (!NILP (handler))
683 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
684 directory);
685 if (STRINGP (handled_name))
686 return handled_name;
687 error ("Invalid handler in `file-name-handler-alist'");
690 #ifdef WINDOWSNT
691 if (!NILP (Vw32_downcase_file_names))
692 directory = Fdowncase (directory);
693 #endif
694 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
695 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
696 STRING_MULTIBYTE (directory));
697 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
698 SAFE_FREE ();
699 return val;
702 static const char make_temp_name_tbl[64] =
704 'A','B','C','D','E','F','G','H',
705 'I','J','K','L','M','N','O','P',
706 'Q','R','S','T','U','V','W','X',
707 'Y','Z','a','b','c','d','e','f',
708 'g','h','i','j','k','l','m','n',
709 'o','p','q','r','s','t','u','v',
710 'w','x','y','z','0','1','2','3',
711 '4','5','6','7','8','9','-','_'
714 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
716 /* Value is a temporary file name starting with PREFIX, a string.
718 The Emacs process number forms part of the result, so there is
719 no danger of generating a name being used by another process.
720 In addition, this function makes an attempt to choose a name
721 which has no existing file. To make this work, PREFIX should be
722 an absolute file name.
724 BASE64_P means add the pid as 3 characters in base64
725 encoding. In this case, 6 characters will be added to PREFIX to
726 form the file name. Otherwise, if Emacs is running on a system
727 with long file names, add the pid as a decimal number.
729 This function signals an error if no unique file name could be
730 generated. */
732 Lisp_Object
733 make_temp_name (Lisp_Object prefix, bool base64_p)
735 Lisp_Object val, encoded_prefix;
736 ptrdiff_t len;
737 printmax_t pid;
738 char *p, *data;
739 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
740 int pidlen;
742 CHECK_STRING (prefix);
744 /* VAL is created by adding 6 characters to PREFIX. The first
745 three are the PID of this process, in base 64, and the second
746 three are incremented if the file already exists. This ensures
747 262144 unique file names per PID per PREFIX. */
749 pid = getpid ();
751 if (base64_p)
753 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
754 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
755 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
756 pidlen = 3;
758 else
760 #ifdef HAVE_LONG_FILE_NAMES
761 pidlen = sprintf (pidbuf, "%"pMd, pid);
762 #else
763 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
764 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
765 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
766 pidlen = 3;
767 #endif
770 encoded_prefix = ENCODE_FILE (prefix);
771 len = SBYTES (encoded_prefix);
772 val = make_uninit_string (len + 3 + pidlen);
773 data = SSDATA (val);
774 memcpy (data, SSDATA (encoded_prefix), len);
775 p = data + len;
777 memcpy (p, pidbuf, pidlen);
778 p += pidlen;
780 /* Here we try to minimize useless stat'ing when this function is
781 invoked many times successively with the same PREFIX. We achieve
782 this by initializing count to a random value, and incrementing it
783 afterwards.
785 We don't want make-temp-name to be called while dumping,
786 because then make_temp_name_count_initialized_p would get set
787 and then make_temp_name_count would not be set when Emacs starts. */
789 if (!make_temp_name_count_initialized_p)
791 make_temp_name_count = time (NULL);
792 make_temp_name_count_initialized_p = 1;
795 while (1)
797 unsigned num = make_temp_name_count;
799 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
800 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
801 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
803 /* Poor man's congruential RN generator. Replace with
804 ++make_temp_name_count for debugging. */
805 make_temp_name_count += 25229;
806 make_temp_name_count %= 225307;
808 if (!check_existing (data))
810 /* We want to return only if errno is ENOENT. */
811 if (errno == ENOENT)
812 return DECODE_FILE (val);
813 else
814 /* The error here is dubious, but there is little else we
815 can do. The alternatives are to return nil, which is
816 as bad as (and in many cases worse than) throwing the
817 error, or to ignore the error, which will likely result
818 in looping through 225307 stat's, which is not only
819 dog-slow, but also useless since eventually nil would
820 have to be returned anyway. */
821 report_file_error ("Cannot create temporary name for prefix",
822 prefix);
823 /* not reached */
829 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
830 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
831 The Emacs process number forms part of the result, so there is no
832 danger of generating a name being used by another Emacs process
833 \(so long as only a single host can access the containing directory...).
835 This function tries to choose a name that has no existing file.
836 For this to work, PREFIX should be an absolute file name.
838 There is a race condition between calling `make-temp-name' and creating the
839 file, which opens all kinds of security holes. For that reason, you should
840 normally use `make-temp-file' instead. */)
841 (Lisp_Object prefix)
843 return make_temp_name (prefix, 0);
848 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
849 doc: /* Convert filename NAME to absolute, and canonicalize it.
850 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
851 \(does not start with slash or tilde); both the directory name and
852 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
853 missing, the current buffer's value of `default-directory' is used.
854 NAME should be a string that is a valid file name for the underlying
855 filesystem.
856 File name components that are `.' are removed, and
857 so are file name components followed by `..', along with the `..' itself;
858 note that these simplifications are done without checking the resulting
859 file names in the file system.
860 Multiple consecutive slashes are collapsed into a single slash,
861 except at the beginning of the file name when they are significant (e.g.,
862 UNC file names on MS-Windows.)
863 An initial `~/' expands to your home directory.
864 An initial `~USER/' expands to USER's home directory.
865 See also the function `substitute-in-file-name'.
867 For technical reasons, this function can return correct but
868 non-intuitive results for the root directory; for instance,
869 \(expand-file-name ".." "/") returns "/..". For this reason, use
870 \(directory-file-name (file-name-directory dirname)) to traverse a
871 filesystem tree, not (expand-file-name ".." dirname). */)
872 (Lisp_Object name, Lisp_Object default_directory)
874 /* These point to SDATA and need to be careful with string-relocation
875 during GC (via DECODE_FILE). */
876 char *nm;
877 const char *newdir;
878 /* This should only point to alloca'd data. */
879 char *target;
881 ptrdiff_t tlen;
882 struct passwd *pw;
883 #ifdef DOS_NT
884 int drive = 0;
885 bool collapse_newdir = 1;
886 bool is_escaped = 0;
887 #endif /* DOS_NT */
888 ptrdiff_t length;
889 Lisp_Object handler, result, handled_name;
890 bool multibyte;
891 Lisp_Object hdir;
892 USE_SAFE_ALLOCA;
894 CHECK_STRING (name);
896 /* If the file name has special constructs in it,
897 call the corresponding file handler. */
898 handler = Ffind_file_name_handler (name, Qexpand_file_name);
899 if (!NILP (handler))
901 handled_name = call3 (handler, Qexpand_file_name,
902 name, default_directory);
903 if (STRINGP (handled_name))
904 return handled_name;
905 error ("Invalid handler in `file-name-handler-alist'");
909 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
910 if (NILP (default_directory))
911 default_directory = BVAR (current_buffer, directory);
912 if (! STRINGP (default_directory))
914 #ifdef DOS_NT
915 /* "/" is not considered a root directory on DOS_NT, so using "/"
916 here causes an infinite recursion in, e.g., the following:
918 (let (default-directory)
919 (expand-file-name "a"))
921 To avoid this, we set default_directory to the root of the
922 current drive. */
923 default_directory = build_string (emacs_root_dir ());
924 #else
925 default_directory = build_string ("/");
926 #endif
929 if (!NILP (default_directory))
931 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
932 if (!NILP (handler))
934 handled_name = call3 (handler, Qexpand_file_name,
935 name, default_directory);
936 if (STRINGP (handled_name))
937 return handled_name;
938 error ("Invalid handler in `file-name-handler-alist'");
943 char *o = SSDATA (default_directory);
945 /* Make sure DEFAULT_DIRECTORY is properly expanded.
946 It would be better to do this down below where we actually use
947 default_directory. Unfortunately, calling Fexpand_file_name recursively
948 could invoke GC, and the strings might be relocated. This would
949 be annoying because we have pointers into strings lying around
950 that would need adjusting, and people would add new pointers to
951 the code and forget to adjust them, resulting in intermittent bugs.
952 Putting this call here avoids all that crud.
954 The EQ test avoids infinite recursion. */
955 if (! NILP (default_directory) && !EQ (default_directory, name)
956 /* Save time in some common cases - as long as default_directory
957 is not relative, it can be canonicalized with name below (if it
958 is needed at all) without requiring it to be expanded now. */
959 #ifdef DOS_NT
960 /* Detect MSDOS file names with drive specifiers. */
961 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
962 && IS_DIRECTORY_SEP (o[2]))
963 #ifdef WINDOWSNT
964 /* Detect Windows file names in UNC format. */
965 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
966 #endif
967 #else /* not DOS_NT */
968 /* Detect Unix absolute file names (/... alone is not absolute on
969 DOS or Windows). */
970 && ! (IS_DIRECTORY_SEP (o[0]))
971 #endif /* not DOS_NT */
974 struct gcpro gcpro1;
976 GCPRO1 (name);
977 default_directory = Fexpand_file_name (default_directory, Qnil);
978 UNGCPRO;
981 multibyte = STRING_MULTIBYTE (name);
982 if (multibyte != STRING_MULTIBYTE (default_directory))
984 if (multibyte)
986 unsigned char *p = SDATA (name);
988 while (*p && ASCII_BYTE_P (*p))
989 p++;
990 if (*p == '\0')
992 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
993 unibyte. Do not convert DEFAULT_DIRECTORY to
994 multibyte; instead, convert NAME to a unibyte string,
995 so that the result of this function is also a unibyte
996 string. This is needed during bootstrapping and
997 dumping, when Emacs cannot decode file names, because
998 the locale environment is not set up. */
999 name = make_unibyte_string (SSDATA (name), SBYTES (name));
1000 multibyte = 0;
1002 else
1003 default_directory = string_to_multibyte (default_directory);
1005 else
1007 name = string_to_multibyte (name);
1008 multibyte = 1;
1012 #ifdef WINDOWSNT
1013 if (!NILP (Vw32_downcase_file_names))
1014 default_directory = Fdowncase (default_directory);
1015 #endif
1017 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
1018 nm = xlispstrdupa (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, strlen (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_string (temp), name);
1116 #ifdef WINDOWSNT
1117 if (!NILP (Vw32_downcase_file_names))
1118 name = Fdowncase (name);
1119 #endif
1120 return name;
1121 #else /* not DOS_NT */
1122 if (strcmp (nm, SSDATA (name)) == 0)
1123 return name;
1124 return make_specified_string (nm, -1, strlen (nm), multibyte);
1125 #endif /* not DOS_NT */
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 = 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 = "";
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 = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1167 else
1168 #endif
1169 tem = build_string (newdir);
1170 if (multibyte && !STRING_MULTIBYTE (tem))
1172 hdir = DECODE_FILE (tem);
1173 newdir = SSDATA (hdir);
1175 #ifdef DOS_NT
1176 collapse_newdir = 0;
1177 #endif
1179 else /* ~user/filename */
1181 char *o, *p;
1182 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1183 continue;
1184 o = SAFE_ALLOCA (p - nm + 1);
1185 memcpy (o, nm, p - nm);
1186 o[p - nm] = 0;
1188 block_input ();
1189 pw = getpwnam (o + 1);
1190 unblock_input ();
1191 if (pw)
1193 Lisp_Object tem;
1195 newdir = pw->pw_dir;
1196 /* `getpwnam' may return a unibyte string, which will
1197 bite us since we expect the directory to be
1198 multibyte. */
1199 tem = make_unibyte_string (newdir, strlen (newdir));
1200 if (multibyte && !STRING_MULTIBYTE (tem))
1202 hdir = DECODE_FILE (tem);
1203 newdir = SSDATA (hdir);
1205 nm = p;
1206 #ifdef DOS_NT
1207 collapse_newdir = 0;
1208 #endif
1211 /* If we don't find a user of that name, leave the name
1212 unchanged; don't move nm forward to p. */
1216 #ifdef DOS_NT
1217 /* On DOS and Windows, nm is absolute if a drive name was specified;
1218 use the drive's current directory as the prefix if needed. */
1219 if (!newdir && drive)
1221 /* Get default directory if needed to make nm absolute. */
1222 char *adir = NULL;
1223 if (!IS_DIRECTORY_SEP (nm[0]))
1225 adir = alloca (MAXPATHLEN + 1);
1226 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1227 adir = NULL;
1228 else if (multibyte)
1230 Lisp_Object tem = build_string (adir);
1232 tem = DECODE_FILE (tem);
1233 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1236 if (!adir)
1238 /* Either nm starts with /, or drive isn't mounted. */
1239 adir = alloca (4);
1240 adir[0] = DRIVE_LETTER (drive);
1241 adir[1] = ':';
1242 adir[2] = '/';
1243 adir[3] = 0;
1245 newdir = adir;
1247 #endif /* DOS_NT */
1249 /* Finally, if no prefix has been specified and nm is not absolute,
1250 then it must be expanded relative to default_directory. */
1252 if (1
1253 #ifndef DOS_NT
1254 /* /... alone is not absolute on DOS and Windows. */
1255 && !IS_DIRECTORY_SEP (nm[0])
1256 #endif
1257 #ifdef WINDOWSNT
1258 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1259 && !IS_DIRECTORY_SEP (nm[2]))
1260 #endif
1261 && !newdir)
1263 newdir = SSDATA (default_directory);
1264 #ifdef DOS_NT
1265 /* Note if special escape prefix is present, but remove for now. */
1266 if (newdir[0] == '/' && newdir[1] == ':')
1268 is_escaped = 1;
1269 newdir += 2;
1271 #endif
1274 #ifdef DOS_NT
1275 if (newdir)
1277 /* First ensure newdir is an absolute name. */
1278 if (
1279 /* Detect MSDOS file names with drive specifiers. */
1280 ! (IS_DRIVE (newdir[0])
1281 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1282 #ifdef WINDOWSNT
1283 /* Detect Windows file names in UNC format. */
1284 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1285 && !IS_DIRECTORY_SEP (newdir[2]))
1286 #endif
1289 /* Effectively, let newdir be (expand-file-name newdir cwd).
1290 Because of the admonition against calling expand-file-name
1291 when we have pointers into lisp strings, we accomplish this
1292 indirectly by prepending newdir to nm if necessary, and using
1293 cwd (or the wd of newdir's drive) as the new newdir. */
1294 char *adir;
1295 #ifdef WINDOWSNT
1296 const int adir_size = MAX_UTF8_PATH;
1297 #else
1298 const int adir_size = MAXPATHLEN + 1;
1299 #endif
1301 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1303 drive = (unsigned char) newdir[0];
1304 newdir += 2;
1306 if (!IS_DIRECTORY_SEP (nm[0]))
1308 ptrdiff_t newlen = strlen (newdir);
1309 char *tmp = alloca (newlen + file_name_as_directory_slop
1310 + strlen (nm) + 1);
1311 file_name_as_directory (tmp, newdir, newlen, multibyte);
1312 strcat (tmp, nm);
1313 nm = tmp;
1315 adir = alloca (adir_size);
1316 if (drive)
1318 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1319 strcpy (adir, "/");
1321 else
1322 getcwd (adir, adir_size);
1323 if (multibyte)
1325 Lisp_Object tem = build_string (adir);
1327 tem = DECODE_FILE (tem);
1328 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1330 newdir = adir;
1333 /* Strip off drive name from prefix, if present. */
1334 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1336 drive = newdir[0];
1337 newdir += 2;
1340 /* Keep only a prefix from newdir if nm starts with slash
1341 (//server/share for UNC, nothing otherwise). */
1342 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1344 #ifdef WINDOWSNT
1345 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1346 && !IS_DIRECTORY_SEP (newdir[2]))
1348 char *adir = strcpy (alloca (strlen (newdir) + 1), newdir);
1349 char *p = adir + 2;
1350 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1351 p++;
1352 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1353 *p = 0;
1354 newdir = adir;
1356 else
1357 #endif
1358 newdir = "";
1361 #endif /* DOS_NT */
1363 if (newdir)
1365 /* Ignore any slash at the end of newdir, unless newdir is
1366 just "/" or "//". */
1367 length = strlen (newdir);
1368 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1369 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1370 length--;
1372 else
1373 length = 0;
1375 /* Now concatenate the directory and name to new space in the stack frame. */
1376 tlen = length + file_name_as_directory_slop + strlen (nm) + 1;
1377 #ifdef DOS_NT
1378 /* Reserve space for drive specifier and escape prefix, since either
1379 or both may need to be inserted. (The Microsoft x86 compiler
1380 produces incorrect code if the following two lines are combined.) */
1381 target = alloca (tlen + 4);
1382 target += 4;
1383 #else /* not DOS_NT */
1384 target = SAFE_ALLOCA (tlen);
1385 #endif /* not DOS_NT */
1386 *target = 0;
1388 if (newdir)
1390 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1392 #ifdef DOS_NT
1393 /* If newdir is effectively "C:/", then the drive letter will have
1394 been stripped and newdir will be "/". Concatenating with an
1395 absolute directory in nm produces "//", which will then be
1396 incorrectly treated as a network share. Ignore newdir in
1397 this case (keeping the drive letter). */
1398 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1399 && newdir[1] == '\0'))
1400 #endif
1402 memcpy (target, newdir, length);
1403 target[length] = 0;
1406 else
1407 file_name_as_directory (target, newdir, length, multibyte);
1410 strcat (target, nm);
1412 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1413 appear. */
1415 char *p = target;
1416 char *o = target;
1418 while (*p)
1420 if (!IS_DIRECTORY_SEP (*p))
1422 *o++ = *p++;
1424 else if (p[1] == '.'
1425 && (IS_DIRECTORY_SEP (p[2])
1426 || p[2] == 0))
1428 /* If "/." is the entire filename, keep the "/". Otherwise,
1429 just delete the whole "/.". */
1430 if (o == target && p[2] == '\0')
1431 *o++ = *p;
1432 p += 2;
1434 else if (p[1] == '.' && p[2] == '.'
1435 /* `/../' is the "superroot" on certain file systems.
1436 Turned off on DOS_NT systems because they have no
1437 "superroot" and because this causes us to produce
1438 file names like "d:/../foo" which fail file-related
1439 functions of the underlying OS. (To reproduce, try a
1440 long series of "../../" in default_directory, longer
1441 than the number of levels from the root.) */
1442 #ifndef DOS_NT
1443 && o != target
1444 #endif
1445 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1447 #ifdef WINDOWSNT
1448 char *prev_o = o;
1449 #endif
1450 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1451 continue;
1452 #ifdef WINDOWSNT
1453 /* Don't go below server level in UNC filenames. */
1454 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1455 && IS_DIRECTORY_SEP (*target))
1456 o = prev_o;
1457 else
1458 #endif
1459 /* Keep initial / only if this is the whole name. */
1460 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1461 ++o;
1462 p += 3;
1464 else if (IS_DIRECTORY_SEP (p[1])
1465 && (p != target || IS_DIRECTORY_SEP (p[2])))
1466 /* Collapse multiple "/", except leave leading "//" alone. */
1467 p++;
1468 else
1470 *o++ = *p++;
1474 #ifdef DOS_NT
1475 /* At last, set drive name. */
1476 #ifdef WINDOWSNT
1477 /* Except for network file name. */
1478 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1479 #endif /* WINDOWSNT */
1481 if (!drive) emacs_abort ();
1482 target -= 2;
1483 target[0] = DRIVE_LETTER (drive);
1484 target[1] = ':';
1486 /* Reinsert the escape prefix if required. */
1487 if (is_escaped)
1489 target -= 2;
1490 target[0] = '/';
1491 target[1] = ':';
1493 result = make_specified_string (target, -1, o - target, multibyte);
1494 dostounix_filename (SSDATA (result));
1495 #ifdef WINDOWSNT
1496 if (!NILP (Vw32_downcase_file_names))
1497 result = Fdowncase (result);
1498 #endif
1499 #else /* !DOS_NT */
1500 result = make_specified_string (target, -1, o - target, multibyte);
1501 #endif /* !DOS_NT */
1504 /* Again look to see if the file name has special constructs in it
1505 and perhaps call the corresponding file handler. This is needed
1506 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1507 the ".." component gives us "/user@host:/bar/../baz" which needs
1508 to be expanded again. */
1509 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1510 if (!NILP (handler))
1512 handled_name = call3 (handler, Qexpand_file_name,
1513 result, default_directory);
1514 if (! STRINGP (handled_name))
1515 error ("Invalid handler in `file-name-handler-alist'");
1516 result = handled_name;
1519 SAFE_FREE ();
1520 return result;
1523 #if 0
1524 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1525 This is the old version of expand-file-name, before it was thoroughly
1526 rewritten for Emacs 10.31. We leave this version here commented-out,
1527 because the code is very complex and likely to have subtle bugs. If
1528 bugs _are_ found, it might be of interest to look at the old code and
1529 see what did it do in the relevant situation.
1531 Don't remove this code: it's true that it will be accessible
1532 from the repository, but a few years from deletion, people will
1533 forget it is there. */
1535 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1536 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1537 "Convert FILENAME to absolute, and canonicalize it.\n\
1538 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1539 \(does not start with slash); if DEFAULT is nil or missing,\n\
1540 the current buffer's value of default-directory is used.\n\
1541 Filenames containing `.' or `..' as components are simplified;\n\
1542 initial `~/' expands to your home directory.\n\
1543 See also the function `substitute-in-file-name'.")
1544 (name, defalt)
1545 Lisp_Object name, defalt;
1547 unsigned char *nm;
1549 register unsigned char *newdir, *p, *o;
1550 ptrdiff_t tlen;
1551 unsigned char *target;
1552 struct passwd *pw;
1554 CHECK_STRING (name);
1555 nm = SDATA (name);
1557 /* If nm is absolute, flush ...// and detect /./ and /../.
1558 If no /./ or /../ we can return right away. */
1559 if (nm[0] == '/')
1561 bool lose = 0;
1562 p = nm;
1563 while (*p)
1565 if (p[0] == '/' && p[1] == '/')
1566 nm = p + 1;
1567 if (p[0] == '/' && p[1] == '~')
1568 nm = p + 1, lose = 1;
1569 if (p[0] == '/' && p[1] == '.'
1570 && (p[2] == '/' || p[2] == 0
1571 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1572 lose = 1;
1573 p++;
1575 if (!lose)
1577 if (nm == SDATA (name))
1578 return name;
1579 return build_string (nm);
1583 /* Now determine directory to start with and put it in NEWDIR. */
1585 newdir = 0;
1587 if (nm[0] == '~') /* prefix ~ */
1588 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1590 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1591 newdir = (unsigned char *) "";
1592 nm++;
1594 else /* ~user/filename */
1596 /* Get past ~ to user. */
1597 unsigned char *user = nm + 1;
1598 /* Find end of name. */
1599 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1600 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1601 /* Copy the user name into temp storage. */
1602 o = alloca (len + 1);
1603 memcpy (o, user, len);
1604 o[len] = 0;
1606 /* Look up the user name. */
1607 block_input ();
1608 pw = (struct passwd *) getpwnam (o + 1);
1609 unblock_input ();
1610 if (!pw)
1611 error ("\"%s\" isn't a registered user", o + 1);
1613 newdir = (unsigned char *) pw->pw_dir;
1615 /* Discard the user name from NM. */
1616 nm += len;
1619 if (nm[0] != '/' && !newdir)
1621 if (NILP (defalt))
1622 defalt = current_buffer->directory;
1623 CHECK_STRING (defalt);
1624 newdir = SDATA (defalt);
1627 /* Now concatenate the directory and name to new space in the stack frame. */
1629 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1630 target = alloca (tlen);
1631 *target = 0;
1633 if (newdir)
1635 if (nm[0] == 0 || nm[0] == '/')
1636 strcpy (target, newdir);
1637 else
1638 file_name_as_directory (target, newdir);
1641 strcat (target, nm);
1643 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1645 p = target;
1646 o = target;
1648 while (*p)
1650 if (*p != '/')
1652 *o++ = *p++;
1654 else if (!strncmp (p, "//", 2)
1657 o = target;
1658 p++;
1660 else if (p[0] == '/' && p[1] == '.'
1661 && (p[2] == '/' || p[2] == 0))
1662 p += 2;
1663 else if (!strncmp (p, "/..", 3)
1664 /* `/../' is the "superroot" on certain file systems. */
1665 && o != target
1666 && (p[3] == '/' || p[3] == 0))
1668 while (o != target && *--o != '/')
1670 if (o == target && *o == '/')
1671 ++o;
1672 p += 3;
1674 else
1676 *o++ = *p++;
1680 return make_string (target, o - target);
1682 #endif
1684 /* If /~ or // appears, discard everything through first slash. */
1685 static bool
1686 file_name_absolute_p (const char *filename)
1688 return
1689 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1690 #ifdef DOS_NT
1691 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1692 && IS_DIRECTORY_SEP (filename[2]))
1693 #endif
1697 static char *
1698 search_embedded_absfilename (char *nm, char *endp)
1700 char *p, *s;
1702 for (p = nm + 1; p < endp; p++)
1704 if (IS_DIRECTORY_SEP (p[-1])
1705 && file_name_absolute_p (p)
1706 #if defined (WINDOWSNT) || defined (CYGWIN)
1707 /* // at start of file name is meaningful in Apollo,
1708 WindowsNT and Cygwin systems. */
1709 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1710 #endif /* not (WINDOWSNT || CYGWIN) */
1713 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1714 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1716 char *o = alloca (s - p + 1);
1717 struct passwd *pw;
1718 memcpy (o, p, s - p);
1719 o [s - p] = 0;
1721 /* If we have ~user and `user' exists, discard
1722 everything up to ~. But if `user' does not exist, leave
1723 ~user alone, it might be a literal file name. */
1724 block_input ();
1725 pw = getpwnam (o + 1);
1726 unblock_input ();
1727 if (pw)
1728 return p;
1730 else
1731 return p;
1734 return NULL;
1737 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1738 Ssubstitute_in_file_name, 1, 1, 0,
1739 doc: /* Substitute environment variables referred to in FILENAME.
1740 `$FOO' where FOO is an environment variable name means to substitute
1741 the value of that variable. The variable name should be terminated
1742 with a character not a letter, digit or underscore; otherwise, enclose
1743 the entire variable name in braces.
1745 If `/~' appears, all of FILENAME through that `/' is discarded.
1746 If `//' appears, everything up to and including the first of
1747 those `/' is discarded. */)
1748 (Lisp_Object filename)
1750 char *nm, *p, *x, *endp;
1751 bool substituted = false;
1752 bool multibyte;
1753 char *xnm;
1754 Lisp_Object handler;
1756 CHECK_STRING (filename);
1758 multibyte = STRING_MULTIBYTE (filename);
1760 /* If the file name has special constructs in it,
1761 call the corresponding file handler. */
1762 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1763 if (!NILP (handler))
1765 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1766 filename);
1767 if (STRINGP (handled_name))
1768 return handled_name;
1769 error ("Invalid handler in `file-name-handler-alist'");
1772 /* Always work on a copy of the string, in case GC happens during
1773 decode of environment variables, causing the original Lisp_String
1774 data to be relocated. */
1775 nm = xlispstrdupa (filename);
1777 #ifdef DOS_NT
1778 dostounix_filename (nm);
1779 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1780 #endif
1781 endp = nm + SBYTES (filename);
1783 /* If /~ or // appears, discard everything through first slash. */
1784 p = search_embedded_absfilename (nm, endp);
1785 if (p)
1786 /* Start over with the new string, so we check the file-name-handler
1787 again. Important with filenames like "/home/foo//:/hello///there"
1788 which would substitute to "/:/hello///there" rather than "/there". */
1789 return Fsubstitute_in_file_name
1790 (make_specified_string (p, -1, endp - p, multibyte));
1792 /* See if any variables are substituted into the string. */
1794 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1796 Lisp_Object name
1797 = (!substituted ? filename
1798 : make_specified_string (nm, -1, endp - nm, multibyte));
1799 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1800 CHECK_STRING (tmp);
1801 if (!EQ (tmp, name))
1802 substituted = true;
1803 filename = tmp;
1806 if (!substituted)
1808 #ifdef WINDOWSNT
1809 if (!NILP (Vw32_downcase_file_names))
1810 filename = Fdowncase (filename);
1811 #endif
1812 return filename;
1815 xnm = SSDATA (filename);
1816 x = xnm + SBYTES (filename);
1818 /* If /~ or // appears, discard everything through first slash. */
1819 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1820 /* This time we do not start over because we've already expanded envvars
1821 and replaced $$ with $. Maybe we should start over as well, but we'd
1822 need to quote some $ to $$ first. */
1823 xnm = p;
1825 #ifdef WINDOWSNT
1826 if (!NILP (Vw32_downcase_file_names))
1828 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1830 xname = Fdowncase (xname);
1831 return xname;
1833 else
1834 #endif
1835 return (xnm == SSDATA (filename)
1836 ? filename
1837 : make_specified_string (xnm, -1, x - xnm, multibyte));
1840 /* A slightly faster and more convenient way to get
1841 (directory-file-name (expand-file-name FOO)). */
1843 Lisp_Object
1844 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1846 register Lisp_Object absname;
1848 absname = Fexpand_file_name (filename, defdir);
1850 /* Remove final slash, if any (unless this is the root dir).
1851 stat behaves differently depending! */
1852 if (SCHARS (absname) > 1
1853 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1854 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1855 /* We cannot take shortcuts; they might be wrong for magic file names. */
1856 absname = Fdirectory_file_name (absname);
1857 return absname;
1860 /* Signal an error if the file ABSNAME already exists.
1861 If KNOWN_TO_EXIST, the file is known to exist.
1862 QUERYSTRING is a name for the action that is being considered
1863 to alter the file.
1864 If INTERACTIVE, ask the user whether to proceed,
1865 and bypass the error if the user says to go ahead.
1866 If QUICK, ask for y or n, not yes or no. */
1868 static void
1869 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1870 const char *querystring, bool interactive,
1871 bool quick)
1873 Lisp_Object tem, encoded_filename;
1874 struct stat statbuf;
1875 struct gcpro gcpro1;
1877 encoded_filename = ENCODE_FILE (absname);
1879 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1881 if (S_ISDIR (statbuf.st_mode))
1882 xsignal2 (Qfile_error,
1883 build_string ("File is a directory"), absname);
1884 known_to_exist = true;
1887 if (known_to_exist)
1889 if (! interactive)
1890 xsignal2 (Qfile_already_exists,
1891 build_string ("File already exists"), absname);
1892 GCPRO1 (absname);
1893 tem = format2 ("File %s already exists; %s anyway? ",
1894 absname, build_string (querystring));
1895 if (quick)
1896 tem = call1 (intern ("y-or-n-p"), tem);
1897 else
1898 tem = do_yes_or_no_p (tem);
1899 UNGCPRO;
1900 if (NILP (tem))
1901 xsignal2 (Qfile_already_exists,
1902 build_string ("File already exists"), absname);
1906 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1907 "fCopy file: \nGCopy %s to file: \np\nP",
1908 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1909 If NEWNAME names a directory, copy FILE there.
1911 This function always sets the file modes of the output file to match
1912 the input file.
1914 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1915 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1916 signal a `file-already-exists' error without overwriting. If
1917 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1918 about overwriting; this is what happens in interactive use with M-x.
1919 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1920 existing file.
1922 Fourth arg KEEP-TIME non-nil means give the output file the same
1923 last-modified time as the old one. (This works on only some systems.)
1925 A prefix arg makes KEEP-TIME non-nil.
1927 If PRESERVE-UID-GID is non-nil, we try to transfer the
1928 uid and gid of FILE to NEWNAME.
1930 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1931 this includes the file modes, along with ACL entries and SELinux
1932 context if present. Otherwise, if NEWNAME is created its file
1933 permission bits are those of FILE, masked by the default file
1934 permissions. */)
1935 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1936 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1937 Lisp_Object preserve_permissions)
1939 Lisp_Object handler;
1940 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1941 ptrdiff_t count = SPECPDL_INDEX ();
1942 Lisp_Object encoded_file, encoded_newname;
1943 #if HAVE_LIBSELINUX
1944 security_context_t con;
1945 int conlength = 0;
1946 #endif
1947 #ifdef WINDOWSNT
1948 int result;
1949 #else
1950 bool already_exists = false;
1951 mode_t new_mask;
1952 int ifd, ofd;
1953 int n;
1954 char buf[16 * 1024];
1955 struct stat st;
1956 #endif
1958 encoded_file = encoded_newname = Qnil;
1959 GCPRO4 (file, newname, encoded_file, encoded_newname);
1960 CHECK_STRING (file);
1961 CHECK_STRING (newname);
1963 if (!NILP (Ffile_directory_p (newname)))
1964 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1965 else
1966 newname = Fexpand_file_name (newname, Qnil);
1968 file = Fexpand_file_name (file, Qnil);
1970 /* If the input file name has special constructs in it,
1971 call the corresponding file handler. */
1972 handler = Ffind_file_name_handler (file, Qcopy_file);
1973 /* Likewise for output file name. */
1974 if (NILP (handler))
1975 handler = Ffind_file_name_handler (newname, Qcopy_file);
1976 if (!NILP (handler))
1977 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1978 ok_if_already_exists, keep_time, preserve_uid_gid,
1979 preserve_permissions));
1981 encoded_file = ENCODE_FILE (file);
1982 encoded_newname = ENCODE_FILE (newname);
1984 #ifdef WINDOWSNT
1985 if (NILP (ok_if_already_exists)
1986 || INTEGERP (ok_if_already_exists))
1987 barf_or_query_if_file_exists (newname, false, "copy to it",
1988 INTEGERP (ok_if_already_exists), false);
1990 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1991 !NILP (keep_time), !NILP (preserve_uid_gid),
1992 !NILP (preserve_permissions));
1993 switch (result)
1995 case -1:
1996 report_file_error ("Copying file", list2 (file, newname));
1997 case -2:
1998 report_file_error ("Copying permissions from", file);
1999 case -3:
2000 xsignal2 (Qfile_date_error,
2001 build_string ("Resetting file times"), newname);
2002 case -4:
2003 report_file_error ("Copying permissions to", newname);
2005 #else /* not WINDOWSNT */
2006 immediate_quit = 1;
2007 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
2008 immediate_quit = 0;
2010 if (ifd < 0)
2011 report_file_error ("Opening input file", file);
2013 record_unwind_protect_int (close_file_unwind, ifd);
2015 if (fstat (ifd, &st) != 0)
2016 report_file_error ("Input file status", file);
2018 if (!NILP (preserve_permissions))
2020 #if HAVE_LIBSELINUX
2021 if (is_selinux_enabled ())
2023 conlength = fgetfilecon (ifd, &con);
2024 if (conlength == -1)
2025 report_file_error ("Doing fgetfilecon", file);
2027 #endif
2030 /* We can copy only regular files. */
2031 if (!S_ISREG (st.st_mode))
2032 report_file_errno ("Non-regular file", file,
2033 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
2035 #ifndef MSDOS
2036 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
2037 #else
2038 new_mask = S_IREAD | S_IWRITE;
2039 #endif
2041 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
2042 new_mask);
2043 if (ofd < 0 && errno == EEXIST)
2045 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
2046 barf_or_query_if_file_exists (newname, true, "copy to it",
2047 INTEGERP (ok_if_already_exists), false);
2048 already_exists = true;
2049 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
2051 if (ofd < 0)
2052 report_file_error ("Opening output file", newname);
2054 record_unwind_protect_int (close_file_unwind, ofd);
2056 if (already_exists)
2058 struct stat out_st;
2059 if (fstat (ofd, &out_st) != 0)
2060 report_file_error ("Output file status", newname);
2061 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2062 report_file_errno ("Input and output files are the same",
2063 list2 (file, newname), 0);
2064 if (ftruncate (ofd, 0) != 0)
2065 report_file_error ("Truncating output file", newname);
2068 immediate_quit = 1;
2069 QUIT;
2070 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2071 if (emacs_write_sig (ofd, buf, n) != n)
2072 report_file_error ("Write error", newname);
2073 immediate_quit = 0;
2075 #ifndef MSDOS
2076 /* Preserve the original file permissions, and if requested, also its
2077 owner and group. */
2079 mode_t preserved_permissions = st.st_mode & 07777;
2080 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2081 if (!NILP (preserve_uid_gid))
2083 /* Attempt to change owner and group. If that doesn't work
2084 attempt to change just the group, as that is sometimes allowed.
2085 Adjust the mode mask to eliminate setuid or setgid bits
2086 or group permissions bits that are inappropriate if the
2087 owner or group are wrong. */
2088 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2090 if (fchown (ofd, -1, st.st_gid) == 0)
2091 preserved_permissions &= ~04000;
2092 else
2094 preserved_permissions &= ~06000;
2096 /* Copy the other bits to the group bits, since the
2097 group is wrong. */
2098 preserved_permissions &= ~070;
2099 preserved_permissions |= (preserved_permissions & 7) << 3;
2100 default_permissions &= ~070;
2101 default_permissions |= (default_permissions & 7) << 3;
2106 switch (!NILP (preserve_permissions)
2107 ? qcopy_acl (SSDATA (encoded_file), ifd,
2108 SSDATA (encoded_newname), ofd,
2109 preserved_permissions)
2110 : (already_exists
2111 || (new_mask & ~realmask) == default_permissions)
2113 : fchmod (ofd, default_permissions))
2115 case -2: report_file_error ("Copying permissions from", file);
2116 case -1: report_file_error ("Copying permissions to", newname);
2119 #endif /* not MSDOS */
2121 #if HAVE_LIBSELINUX
2122 if (conlength > 0)
2124 /* Set the modified context back to the file. */
2125 bool fail = fsetfilecon (ofd, con) != 0;
2126 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2127 if (fail && errno != ENOTSUP)
2128 report_file_error ("Doing fsetfilecon", newname);
2130 freecon (con);
2132 #endif
2134 if (!NILP (keep_time))
2136 struct timespec atime = get_stat_atime (&st);
2137 struct timespec mtime = get_stat_mtime (&st);
2138 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2139 xsignal2 (Qfile_date_error,
2140 build_string ("Cannot set file date"), newname);
2143 if (emacs_close (ofd) < 0)
2144 report_file_error ("Write error", newname);
2146 emacs_close (ifd);
2148 #ifdef MSDOS
2149 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2150 and if it can't, it tells so. Otherwise, under MSDOS we usually
2151 get only the READ bit, which will make the copied file read-only,
2152 so it's better not to chmod at all. */
2153 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2154 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2155 #endif /* MSDOS */
2156 #endif /* not WINDOWSNT */
2158 /* Discard the unwind protects. */
2159 specpdl_ptr = specpdl + count;
2161 UNGCPRO;
2162 return Qnil;
2165 DEFUN ("make-directory-internal", Fmake_directory_internal,
2166 Smake_directory_internal, 1, 1, 0,
2167 doc: /* Create a new directory named DIRECTORY. */)
2168 (Lisp_Object directory)
2170 const char *dir;
2171 Lisp_Object handler;
2172 Lisp_Object encoded_dir;
2174 CHECK_STRING (directory);
2175 directory = Fexpand_file_name (directory, Qnil);
2177 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2178 if (!NILP (handler))
2179 return call2 (handler, Qmake_directory_internal, directory);
2181 encoded_dir = ENCODE_FILE (directory);
2183 dir = SSDATA (encoded_dir);
2185 #ifdef WINDOWSNT
2186 if (mkdir (dir) != 0)
2187 #else
2188 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2189 #endif
2190 report_file_error ("Creating directory", directory);
2192 return Qnil;
2195 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2196 Sdelete_directory_internal, 1, 1, 0,
2197 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2198 (Lisp_Object directory)
2200 const char *dir;
2201 Lisp_Object encoded_dir;
2203 CHECK_STRING (directory);
2204 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2205 encoded_dir = ENCODE_FILE (directory);
2206 dir = SSDATA (encoded_dir);
2208 if (rmdir (dir) != 0)
2209 report_file_error ("Removing directory", directory);
2211 return Qnil;
2214 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2215 "(list (read-file-name \
2216 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2217 \"Move file to trash: \" \"Delete file: \") \
2218 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2219 (null current-prefix-arg))",
2220 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2221 If file has multiple names, it continues to exist with the other names.
2222 TRASH non-nil means to trash the file instead of deleting, provided
2223 `delete-by-moving-to-trash' is non-nil.
2225 When called interactively, TRASH is t if no prefix argument is given.
2226 With a prefix argument, TRASH is nil. */)
2227 (Lisp_Object filename, Lisp_Object trash)
2229 Lisp_Object handler;
2230 Lisp_Object encoded_file;
2231 struct gcpro gcpro1;
2233 GCPRO1 (filename);
2234 if (!NILP (Ffile_directory_p (filename))
2235 && NILP (Ffile_symlink_p (filename)))
2236 xsignal2 (Qfile_error,
2237 build_string ("Removing old name: is a directory"),
2238 filename);
2239 UNGCPRO;
2240 filename = Fexpand_file_name (filename, Qnil);
2242 handler = Ffind_file_name_handler (filename, Qdelete_file);
2243 if (!NILP (handler))
2244 return call3 (handler, Qdelete_file, filename, trash);
2246 if (delete_by_moving_to_trash && !NILP (trash))
2247 return call1 (Qmove_file_to_trash, filename);
2249 encoded_file = ENCODE_FILE (filename);
2251 if (unlink (SSDATA (encoded_file)) < 0)
2252 report_file_error ("Removing old name", filename);
2253 return Qnil;
2256 static Lisp_Object
2257 internal_delete_file_1 (Lisp_Object ignore)
2259 return Qt;
2262 /* Delete file FILENAME, returning true if successful.
2263 This ignores `delete-by-moving-to-trash'. */
2265 bool
2266 internal_delete_file (Lisp_Object filename)
2268 Lisp_Object tem;
2270 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2271 Qt, internal_delete_file_1);
2272 return NILP (tem);
2275 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2276 "fRename file: \nGRename %s to file: \np",
2277 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2278 If file has names other than FILE, it continues to have those names.
2279 Signals a `file-already-exists' error if a file NEWNAME already exists
2280 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2281 A number as third arg means request confirmation if NEWNAME already exists.
2282 This is what happens in interactive use with M-x. */)
2283 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2285 Lisp_Object handler;
2286 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2287 Lisp_Object encoded_file, encoded_newname, symlink_target;
2289 symlink_target = encoded_file = encoded_newname = Qnil;
2290 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2291 CHECK_STRING (file);
2292 CHECK_STRING (newname);
2293 file = Fexpand_file_name (file, Qnil);
2295 if ((!NILP (Ffile_directory_p (newname)))
2296 #ifdef DOS_NT
2297 /* If the file names are identical but for the case,
2298 don't attempt to move directory to itself. */
2299 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2300 #endif
2303 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2304 ? file : Fdirectory_file_name (file));
2305 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2307 else
2308 newname = Fexpand_file_name (newname, Qnil);
2310 /* If the file name has special constructs in it,
2311 call the corresponding file handler. */
2312 handler = Ffind_file_name_handler (file, Qrename_file);
2313 if (NILP (handler))
2314 handler = Ffind_file_name_handler (newname, Qrename_file);
2315 if (!NILP (handler))
2316 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2317 file, newname, ok_if_already_exists));
2319 encoded_file = ENCODE_FILE (file);
2320 encoded_newname = ENCODE_FILE (newname);
2322 #ifdef DOS_NT
2323 /* If the file names are identical but for the case, don't ask for
2324 confirmation: they simply want to change the letter-case of the
2325 file name. */
2326 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2327 #endif
2328 if (NILP (ok_if_already_exists)
2329 || INTEGERP (ok_if_already_exists))
2330 barf_or_query_if_file_exists (newname, false, "rename to it",
2331 INTEGERP (ok_if_already_exists), false);
2332 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2334 int rename_errno = errno;
2335 if (rename_errno == EXDEV)
2337 ptrdiff_t count;
2338 symlink_target = Ffile_symlink_p (file);
2339 if (! NILP (symlink_target))
2340 Fmake_symbolic_link (symlink_target, newname,
2341 NILP (ok_if_already_exists) ? Qnil : Qt);
2342 else if (!NILP (Ffile_directory_p (file)))
2343 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2344 else
2345 /* We have already prompted if it was an integer, so don't
2346 have copy-file prompt again. */
2347 Fcopy_file (file, newname,
2348 NILP (ok_if_already_exists) ? Qnil : Qt,
2349 Qt, Qt, Qt);
2351 count = SPECPDL_INDEX ();
2352 specbind (Qdelete_by_moving_to_trash, Qnil);
2354 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2355 call2 (Qdelete_directory, file, Qt);
2356 else
2357 Fdelete_file (file, Qnil);
2358 unbind_to (count, Qnil);
2360 else
2361 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2363 UNGCPRO;
2364 return Qnil;
2367 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2368 "fAdd name to file: \nGName to add to %s: \np",
2369 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2370 Signals a `file-already-exists' error if a file NEWNAME already exists
2371 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2372 A number as third arg means request confirmation if NEWNAME already exists.
2373 This is what happens in interactive use with M-x. */)
2374 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2376 Lisp_Object handler;
2377 Lisp_Object encoded_file, encoded_newname;
2378 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2380 GCPRO4 (file, newname, encoded_file, encoded_newname);
2381 encoded_file = encoded_newname = Qnil;
2382 CHECK_STRING (file);
2383 CHECK_STRING (newname);
2384 file = Fexpand_file_name (file, Qnil);
2386 if (!NILP (Ffile_directory_p (newname)))
2387 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2388 else
2389 newname = Fexpand_file_name (newname, Qnil);
2391 /* If the file name has special constructs in it,
2392 call the corresponding file handler. */
2393 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2394 if (!NILP (handler))
2395 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2396 newname, ok_if_already_exists));
2398 /* If the new name has special constructs in it,
2399 call the corresponding file handler. */
2400 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2401 if (!NILP (handler))
2402 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2403 newname, ok_if_already_exists));
2405 encoded_file = ENCODE_FILE (file);
2406 encoded_newname = ENCODE_FILE (newname);
2408 if (NILP (ok_if_already_exists)
2409 || INTEGERP (ok_if_already_exists))
2410 barf_or_query_if_file_exists (newname, false, "make it a new name",
2411 INTEGERP (ok_if_already_exists), false);
2413 unlink (SSDATA (newname));
2414 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2416 int link_errno = errno;
2417 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2420 UNGCPRO;
2421 return Qnil;
2424 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2425 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2426 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2427 Both args must be strings.
2428 Signals a `file-already-exists' error if a file LINKNAME already exists
2429 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2430 A number as third arg means request confirmation if LINKNAME already exists.
2431 This happens for interactive use with M-x. */)
2432 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2434 Lisp_Object handler;
2435 Lisp_Object encoded_filename, encoded_linkname;
2436 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2438 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2439 encoded_filename = encoded_linkname = Qnil;
2440 CHECK_STRING (filename);
2441 CHECK_STRING (linkname);
2442 /* If the link target has a ~, we must expand it to get
2443 a truly valid file name. Otherwise, do not expand;
2444 we want to permit links to relative file names. */
2445 if (SREF (filename, 0) == '~')
2446 filename = Fexpand_file_name (filename, Qnil);
2448 if (!NILP (Ffile_directory_p (linkname)))
2449 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2450 else
2451 linkname = Fexpand_file_name (linkname, Qnil);
2453 /* If the file name has special constructs in it,
2454 call the corresponding file handler. */
2455 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2456 if (!NILP (handler))
2457 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2458 linkname, ok_if_already_exists));
2460 /* If the new link name has special constructs in it,
2461 call the corresponding file handler. */
2462 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2463 if (!NILP (handler))
2464 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2465 linkname, ok_if_already_exists));
2467 encoded_filename = ENCODE_FILE (filename);
2468 encoded_linkname = ENCODE_FILE (linkname);
2470 if (NILP (ok_if_already_exists)
2471 || INTEGERP (ok_if_already_exists))
2472 barf_or_query_if_file_exists (linkname, false, "make it a link",
2473 INTEGERP (ok_if_already_exists), false);
2474 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname)) < 0)
2476 /* If we didn't complain already, silently delete existing file. */
2477 int symlink_errno;
2478 if (errno == EEXIST)
2480 unlink (SSDATA (encoded_linkname));
2481 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname))
2482 >= 0)
2484 UNGCPRO;
2485 return Qnil;
2488 if (errno == ENOSYS)
2490 UNGCPRO;
2491 xsignal1 (Qfile_error,
2492 build_string ("Symbolic links are not supported"));
2495 symlink_errno = errno;
2496 report_file_errno ("Making symbolic link", list2 (filename, linkname),
2497 symlink_errno);
2499 UNGCPRO;
2500 return Qnil;
2504 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2505 1, 1, 0,
2506 doc: /* Return t if file FILENAME specifies an absolute file name.
2507 On Unix, this is a name starting with a `/' or a `~'. */)
2508 (Lisp_Object filename)
2510 CHECK_STRING (filename);
2511 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2514 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2515 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2516 See also `file-readable-p' and `file-attributes'.
2517 This returns nil for a symlink to a nonexistent file.
2518 Use `file-symlink-p' to test for such links. */)
2519 (Lisp_Object filename)
2521 Lisp_Object absname;
2522 Lisp_Object handler;
2524 CHECK_STRING (filename);
2525 absname = Fexpand_file_name (filename, Qnil);
2527 /* If the file name has special constructs in it,
2528 call the corresponding file handler. */
2529 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2530 if (!NILP (handler))
2532 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2533 errno = 0;
2534 return result;
2537 absname = ENCODE_FILE (absname);
2539 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2542 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2543 doc: /* Return t if FILENAME can be executed by you.
2544 For a directory, this means you can access files in that directory.
2545 \(It is generally better to use `file-accessible-directory-p' for that
2546 purpose, though.) */)
2547 (Lisp_Object filename)
2549 Lisp_Object absname;
2550 Lisp_Object handler;
2552 CHECK_STRING (filename);
2553 absname = Fexpand_file_name (filename, Qnil);
2555 /* If the file name has special constructs in it,
2556 call the corresponding file handler. */
2557 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2558 if (!NILP (handler))
2559 return call2 (handler, Qfile_executable_p, absname);
2561 absname = ENCODE_FILE (absname);
2563 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2566 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2567 doc: /* Return t if file FILENAME exists and you can read it.
2568 See also `file-exists-p' and `file-attributes'. */)
2569 (Lisp_Object filename)
2571 Lisp_Object absname;
2572 Lisp_Object handler;
2574 CHECK_STRING (filename);
2575 absname = Fexpand_file_name (filename, Qnil);
2577 /* If the file name has special constructs in it,
2578 call the corresponding file handler. */
2579 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2580 if (!NILP (handler))
2581 return call2 (handler, Qfile_readable_p, absname);
2583 absname = ENCODE_FILE (absname);
2584 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2585 ? Qt : Qnil);
2588 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2589 doc: /* Return t if file FILENAME can be written or created by you. */)
2590 (Lisp_Object filename)
2592 Lisp_Object absname, dir, encoded;
2593 Lisp_Object handler;
2595 CHECK_STRING (filename);
2596 absname = Fexpand_file_name (filename, Qnil);
2598 /* If the file name has special constructs in it,
2599 call the corresponding file handler. */
2600 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2601 if (!NILP (handler))
2602 return call2 (handler, Qfile_writable_p, absname);
2604 encoded = ENCODE_FILE (absname);
2605 if (check_writable (SSDATA (encoded), W_OK))
2606 return Qt;
2607 if (errno != ENOENT)
2608 return Qnil;
2610 dir = Ffile_name_directory (absname);
2611 eassert (!NILP (dir));
2612 #ifdef MSDOS
2613 dir = Fdirectory_file_name (dir);
2614 #endif /* MSDOS */
2616 dir = ENCODE_FILE (dir);
2617 #ifdef WINDOWSNT
2618 /* The read-only attribute of the parent directory doesn't affect
2619 whether a file or directory can be created within it. Some day we
2620 should check ACLs though, which do affect this. */
2621 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2622 #else
2623 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2624 #endif
2627 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2628 doc: /* Access file FILENAME, and get an error if that does not work.
2629 The second argument STRING is used in the error message.
2630 If there is no error, returns nil. */)
2631 (Lisp_Object filename, Lisp_Object string)
2633 Lisp_Object handler, encoded_filename, absname;
2635 CHECK_STRING (filename);
2636 absname = Fexpand_file_name (filename, Qnil);
2638 CHECK_STRING (string);
2640 /* If the file name has special constructs in it,
2641 call the corresponding file handler. */
2642 handler = Ffind_file_name_handler (absname, Qaccess_file);
2643 if (!NILP (handler))
2644 return call3 (handler, Qaccess_file, absname, string);
2646 encoded_filename = ENCODE_FILE (absname);
2648 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2649 report_file_error (SSDATA (string), filename);
2651 return Qnil;
2654 /* Relative to directory FD, return the symbolic link value of FILENAME.
2655 On failure, return nil. */
2656 Lisp_Object
2657 emacs_readlinkat (int fd, char const *filename)
2659 static struct allocator const emacs_norealloc_allocator =
2660 { xmalloc, NULL, xfree, memory_full };
2661 Lisp_Object val;
2662 char readlink_buf[1024];
2663 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2664 &emacs_norealloc_allocator, readlinkat);
2665 if (!buf)
2666 return Qnil;
2668 val = build_unibyte_string (buf);
2669 if (buf[0] == '/' && strchr (buf, ':'))
2670 val = concat2 (build_unibyte_string ("/:"), val);
2671 if (buf != readlink_buf)
2672 xfree (buf);
2673 val = DECODE_FILE (val);
2674 return val;
2677 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2678 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2679 The value is the link target, as a string.
2680 Otherwise it returns nil.
2682 This function does not check whether the link target exists. */)
2683 (Lisp_Object filename)
2685 Lisp_Object handler;
2687 CHECK_STRING (filename);
2688 filename = Fexpand_file_name (filename, Qnil);
2690 /* If the file name has special constructs in it,
2691 call the corresponding file handler. */
2692 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2693 if (!NILP (handler))
2694 return call2 (handler, Qfile_symlink_p, filename);
2696 filename = ENCODE_FILE (filename);
2698 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2701 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2702 doc: /* Return t if FILENAME names an existing directory.
2703 Symbolic links to directories count as directories.
2704 See `file-symlink-p' to distinguish symlinks. */)
2705 (Lisp_Object filename)
2707 Lisp_Object absname;
2708 Lisp_Object handler;
2710 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2712 /* If the file name has special constructs in it,
2713 call the corresponding file handler. */
2714 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2715 if (!NILP (handler))
2716 return call2 (handler, Qfile_directory_p, absname);
2718 absname = ENCODE_FILE (absname);
2720 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2723 /* Return true if FILE is a directory or a symlink to a directory. */
2724 bool
2725 file_directory_p (char const *file)
2727 #ifdef WINDOWSNT
2728 /* This is cheaper than 'stat'. */
2729 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2730 #else
2731 struct stat st;
2732 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2733 #endif
2736 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2737 Sfile_accessible_directory_p, 1, 1, 0,
2738 doc: /* Return t if file FILENAME names a directory you can open.
2739 For the value to be t, FILENAME must specify the name of a directory as a file,
2740 and the directory must allow you to open files in it. In order to use a
2741 directory as a buffer's current directory, this predicate must return true.
2742 A directory name spec may be given instead; then the value is t
2743 if the directory so specified exists and really is a readable and
2744 searchable directory. */)
2745 (Lisp_Object filename)
2747 Lisp_Object absname;
2748 Lisp_Object handler;
2750 CHECK_STRING (filename);
2751 absname = Fexpand_file_name (filename, Qnil);
2753 /* If the file name has special constructs in it,
2754 call the corresponding file handler. */
2755 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2756 if (!NILP (handler))
2758 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2759 errno = 0;
2760 return r;
2763 absname = ENCODE_FILE (absname);
2764 return file_accessible_directory_p (SSDATA (absname)) ? Qt : Qnil;
2767 /* If FILE is a searchable directory or a symlink to a
2768 searchable directory, return true. Otherwise return
2769 false and set errno to an error number. */
2770 bool
2771 file_accessible_directory_p (char const *file)
2773 #ifdef DOS_NT
2774 /* There's no need to test whether FILE is searchable, as the
2775 searchable/executable bit is invented on DOS_NT platforms. */
2776 return file_directory_p (file);
2777 #else
2778 /* On POSIXish platforms, use just one system call; this avoids a
2779 race and is typically faster. */
2780 ptrdiff_t len = strlen (file);
2781 char const *dir;
2782 bool ok;
2783 int saved_errno;
2784 USE_SAFE_ALLOCA;
2786 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2787 There are three exceptions: "", "/", and "//". Leave "" alone,
2788 as it's invalid. Append only "." to the other two exceptions as
2789 "/" and "//" are distinct on some platforms, whereas "/", "///",
2790 "////", etc. are all equivalent. */
2791 if (! len)
2792 dir = file;
2793 else
2795 /* Just check for trailing '/' when deciding whether to append '/'.
2796 That's simpler than testing the two special cases "/" and "//",
2797 and it's a safe optimization here. */
2798 char *buf = SAFE_ALLOCA (len + 3);
2799 memcpy (buf, file, len);
2800 strcpy (buf + len, &"/."[file[len - 1] == '/']);
2801 dir = buf;
2804 ok = check_existing (dir);
2805 saved_errno = errno;
2806 SAFE_FREE ();
2807 errno = saved_errno;
2808 return ok;
2809 #endif
2812 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2813 doc: /* Return t if FILENAME names a regular file.
2814 This is the sort of file that holds an ordinary stream of data bytes.
2815 Symbolic links to regular files count as regular files.
2816 See `file-symlink-p' to distinguish symlinks. */)
2817 (Lisp_Object filename)
2819 register Lisp_Object absname;
2820 struct stat st;
2821 Lisp_Object handler;
2823 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2825 /* If the file name has special constructs in it,
2826 call the corresponding file handler. */
2827 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2828 if (!NILP (handler))
2829 return call2 (handler, Qfile_regular_p, absname);
2831 absname = ENCODE_FILE (absname);
2833 #ifdef WINDOWSNT
2835 int result;
2836 Lisp_Object tem = Vw32_get_true_file_attributes;
2838 /* Tell stat to use expensive method to get accurate info. */
2839 Vw32_get_true_file_attributes = Qt;
2840 result = stat (SDATA (absname), &st);
2841 Vw32_get_true_file_attributes = tem;
2843 if (result < 0)
2844 return Qnil;
2845 return S_ISREG (st.st_mode) ? Qt : Qnil;
2847 #else
2848 if (stat (SSDATA (absname), &st) < 0)
2849 return Qnil;
2850 return S_ISREG (st.st_mode) ? Qt : Qnil;
2851 #endif
2854 DEFUN ("file-selinux-context", Ffile_selinux_context,
2855 Sfile_selinux_context, 1, 1, 0,
2856 doc: /* Return SELinux context of file named FILENAME.
2857 The return value is a list (USER ROLE TYPE RANGE), where the list
2858 elements are strings naming the user, role, type, and range of the
2859 file's SELinux security context.
2861 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2862 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2863 (Lisp_Object filename)
2865 Lisp_Object absname;
2866 Lisp_Object values[4];
2867 Lisp_Object handler;
2868 #if HAVE_LIBSELINUX
2869 security_context_t con;
2870 int conlength;
2871 context_t context;
2872 #endif
2874 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2876 /* If the file name has special constructs in it,
2877 call the corresponding file handler. */
2878 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2879 if (!NILP (handler))
2880 return call2 (handler, Qfile_selinux_context, absname);
2882 absname = ENCODE_FILE (absname);
2884 values[0] = Qnil;
2885 values[1] = Qnil;
2886 values[2] = Qnil;
2887 values[3] = Qnil;
2888 #if HAVE_LIBSELINUX
2889 if (is_selinux_enabled ())
2891 conlength = lgetfilecon (SSDATA (absname), &con);
2892 if (conlength > 0)
2894 context = context_new (con);
2895 if (context_user_get (context))
2896 values[0] = build_string (context_user_get (context));
2897 if (context_role_get (context))
2898 values[1] = build_string (context_role_get (context));
2899 if (context_type_get (context))
2900 values[2] = build_string (context_type_get (context));
2901 if (context_range_get (context))
2902 values[3] = build_string (context_range_get (context));
2903 context_free (context);
2904 freecon (con);
2907 #endif
2909 return Flist (sizeof (values) / sizeof (values[0]), values);
2912 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2913 Sset_file_selinux_context, 2, 2, 0,
2914 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2915 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2916 elements are strings naming the components of a SELinux context.
2918 Value is t if setting of SELinux context was successful, nil otherwise.
2920 This function does nothing and returns nil if SELinux is disabled,
2921 or if Emacs was not compiled with SELinux support. */)
2922 (Lisp_Object filename, Lisp_Object context)
2924 Lisp_Object absname;
2925 Lisp_Object handler;
2926 #if HAVE_LIBSELINUX
2927 Lisp_Object encoded_absname;
2928 Lisp_Object user = CAR_SAFE (context);
2929 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2930 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2931 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2932 security_context_t con;
2933 bool fail;
2934 int conlength;
2935 context_t parsed_con;
2936 #endif
2938 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2940 /* If the file name has special constructs in it,
2941 call the corresponding file handler. */
2942 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2943 if (!NILP (handler))
2944 return call3 (handler, Qset_file_selinux_context, absname, context);
2946 #if HAVE_LIBSELINUX
2947 if (is_selinux_enabled ())
2949 /* Get current file context. */
2950 encoded_absname = ENCODE_FILE (absname);
2951 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2952 if (conlength > 0)
2954 parsed_con = context_new (con);
2955 /* Change the parts defined in the parameter.*/
2956 if (STRINGP (user))
2958 if (context_user_set (parsed_con, SSDATA (user)))
2959 error ("Doing context_user_set");
2961 if (STRINGP (role))
2963 if (context_role_set (parsed_con, SSDATA (role)))
2964 error ("Doing context_role_set");
2966 if (STRINGP (type))
2968 if (context_type_set (parsed_con, SSDATA (type)))
2969 error ("Doing context_type_set");
2971 if (STRINGP (range))
2973 if (context_range_set (parsed_con, SSDATA (range)))
2974 error ("Doing context_range_set");
2977 /* Set the modified context back to the file. */
2978 fail = (lsetfilecon (SSDATA (encoded_absname),
2979 context_str (parsed_con))
2980 != 0);
2981 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2982 if (fail && errno != ENOTSUP)
2983 report_file_error ("Doing lsetfilecon", absname);
2985 context_free (parsed_con);
2986 freecon (con);
2987 return fail ? Qnil : Qt;
2989 else
2990 report_file_error ("Doing lgetfilecon", absname);
2992 #endif
2994 return Qnil;
2997 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2998 doc: /* Return ACL entries of file named FILENAME.
2999 The entries are returned in a format suitable for use in `set-file-acl'
3000 but is otherwise undocumented and subject to change.
3001 Return nil if file does not exist or is not accessible, or if Emacs
3002 was unable to determine the ACL entries. */)
3003 (Lisp_Object filename)
3005 Lisp_Object absname;
3006 Lisp_Object handler;
3007 #ifdef HAVE_ACL_SET_FILE
3008 acl_t acl;
3009 Lisp_Object acl_string;
3010 char *str;
3011 # ifndef HAVE_ACL_TYPE_EXTENDED
3012 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
3013 # endif
3014 #endif
3016 absname = expand_and_dir_to_file (filename,
3017 BVAR (current_buffer, directory));
3019 /* If the file name has special constructs in it,
3020 call the corresponding file handler. */
3021 handler = Ffind_file_name_handler (absname, Qfile_acl);
3022 if (!NILP (handler))
3023 return call2 (handler, Qfile_acl, absname);
3025 #ifdef HAVE_ACL_SET_FILE
3026 absname = ENCODE_FILE (absname);
3028 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3029 if (acl == NULL)
3030 return Qnil;
3032 str = acl_to_text (acl, NULL);
3033 if (str == NULL)
3035 acl_free (acl);
3036 return Qnil;
3039 acl_string = build_string (str);
3040 acl_free (str);
3041 acl_free (acl);
3043 return acl_string;
3044 #endif
3046 return Qnil;
3049 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3050 2, 2, 0,
3051 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3052 ACL-STRING should contain the textual representation of the ACL
3053 entries in a format suitable for the platform.
3055 Value is t if setting of ACL was successful, nil otherwise.
3057 Setting ACL for local files requires Emacs to be built with ACL
3058 support. */)
3059 (Lisp_Object filename, Lisp_Object acl_string)
3061 Lisp_Object absname;
3062 Lisp_Object handler;
3063 #ifdef HAVE_ACL_SET_FILE
3064 Lisp_Object encoded_absname;
3065 acl_t acl;
3066 bool fail;
3067 #endif
3069 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3071 /* If the file name has special constructs in it,
3072 call the corresponding file handler. */
3073 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3074 if (!NILP (handler))
3075 return call3 (handler, Qset_file_acl, absname, acl_string);
3077 #ifdef HAVE_ACL_SET_FILE
3078 if (STRINGP (acl_string))
3080 acl = acl_from_text (SSDATA (acl_string));
3081 if (acl == NULL)
3083 report_file_error ("Converting ACL", absname);
3084 return Qnil;
3087 encoded_absname = ENCODE_FILE (absname);
3089 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3090 acl)
3091 != 0);
3092 if (fail && acl_errno_valid (errno))
3093 report_file_error ("Setting ACL", absname);
3095 acl_free (acl);
3096 return fail ? Qnil : Qt;
3098 #endif
3100 return Qnil;
3103 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3104 doc: /* Return mode bits of file named FILENAME, as an integer.
3105 Return nil, if file does not exist or is not accessible. */)
3106 (Lisp_Object filename)
3108 Lisp_Object absname;
3109 struct stat st;
3110 Lisp_Object handler;
3112 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3114 /* If the file name has special constructs in it,
3115 call the corresponding file handler. */
3116 handler = Ffind_file_name_handler (absname, Qfile_modes);
3117 if (!NILP (handler))
3118 return call2 (handler, Qfile_modes, absname);
3120 absname = ENCODE_FILE (absname);
3122 if (stat (SSDATA (absname), &st) < 0)
3123 return Qnil;
3125 return make_number (st.st_mode & 07777);
3128 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3129 "(let ((file (read-file-name \"File: \"))) \
3130 (list file (read-file-modes nil file)))",
3131 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3132 Only the 12 low bits of MODE are used.
3134 Interactively, mode bits are read by `read-file-modes', which accepts
3135 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3136 (Lisp_Object filename, Lisp_Object mode)
3138 Lisp_Object absname, encoded_absname;
3139 Lisp_Object handler;
3141 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3142 CHECK_NUMBER (mode);
3144 /* If the file name has special constructs in it,
3145 call the corresponding file handler. */
3146 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3147 if (!NILP (handler))
3148 return call3 (handler, Qset_file_modes, absname, mode);
3150 encoded_absname = ENCODE_FILE (absname);
3152 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3153 report_file_error ("Doing chmod", absname);
3155 return Qnil;
3158 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3159 doc: /* Set the file permission bits for newly created files.
3160 The argument MODE should be an integer; only the low 9 bits are used.
3161 This setting is inherited by subprocesses. */)
3162 (Lisp_Object mode)
3164 mode_t oldrealmask, oldumask, newumask;
3165 CHECK_NUMBER (mode);
3166 oldrealmask = realmask;
3167 newumask = ~ XINT (mode) & 0777;
3169 block_input ();
3170 realmask = newumask;
3171 oldumask = umask (newumask);
3172 unblock_input ();
3174 eassert (oldumask == oldrealmask);
3175 return Qnil;
3178 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3179 doc: /* Return the default file protection for created files.
3180 The value is an integer. */)
3181 (void)
3183 Lisp_Object value;
3184 XSETINT (value, (~ realmask) & 0777);
3185 return value;
3189 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3190 doc: /* Set times of file FILENAME to TIMESTAMP.
3191 Set both access and modification times.
3192 Return t on success, else nil.
3193 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3194 `current-time'. */)
3195 (Lisp_Object filename, Lisp_Object timestamp)
3197 Lisp_Object absname, encoded_absname;
3198 Lisp_Object handler;
3199 struct timespec t = lisp_time_argument (timestamp);
3201 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3203 /* If the file name has special constructs in it,
3204 call the corresponding file handler. */
3205 handler = Ffind_file_name_handler (absname, Qset_file_times);
3206 if (!NILP (handler))
3207 return call3 (handler, Qset_file_times, absname, timestamp);
3209 encoded_absname = ENCODE_FILE (absname);
3212 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3214 #ifdef MSDOS
3215 /* Setting times on a directory always fails. */
3216 if (file_directory_p (SSDATA (encoded_absname)))
3217 return Qnil;
3218 #endif
3219 report_file_error ("Setting file times", absname);
3223 return Qt;
3226 #ifdef HAVE_SYNC
3227 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3228 doc: /* Tell Unix to finish all pending disk updates. */)
3229 (void)
3231 sync ();
3232 return Qnil;
3235 #endif /* HAVE_SYNC */
3237 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3238 doc: /* Return t if file FILE1 is newer than file FILE2.
3239 If FILE1 does not exist, the answer is nil;
3240 otherwise, if FILE2 does not exist, the answer is t. */)
3241 (Lisp_Object file1, Lisp_Object file2)
3243 Lisp_Object absname1, absname2;
3244 struct stat st1, st2;
3245 Lisp_Object handler;
3246 struct gcpro gcpro1, gcpro2;
3248 CHECK_STRING (file1);
3249 CHECK_STRING (file2);
3251 absname1 = Qnil;
3252 GCPRO2 (absname1, file2);
3253 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3254 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3255 UNGCPRO;
3257 /* If the file name has special constructs in it,
3258 call the corresponding file handler. */
3259 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3260 if (NILP (handler))
3261 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3262 if (!NILP (handler))
3263 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3265 GCPRO2 (absname1, absname2);
3266 absname1 = ENCODE_FILE (absname1);
3267 absname2 = ENCODE_FILE (absname2);
3268 UNGCPRO;
3270 if (stat (SSDATA (absname1), &st1) < 0)
3271 return Qnil;
3273 if (stat (SSDATA (absname2), &st2) < 0)
3274 return Qt;
3276 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3277 ? Qt : Qnil);
3280 #ifndef READ_BUF_SIZE
3281 #define READ_BUF_SIZE (64 << 10)
3282 #endif
3283 /* Some buffer offsets are stored in 'int' variables. */
3284 verify (READ_BUF_SIZE <= INT_MAX);
3286 /* This function is called after Lisp functions to decide a coding
3287 system are called, or when they cause an error. Before they are
3288 called, the current buffer is set unibyte and it contains only a
3289 newly inserted text (thus the buffer was empty before the
3290 insertion).
3292 The functions may set markers, overlays, text properties, or even
3293 alter the buffer contents, change the current buffer.
3295 Here, we reset all those changes by:
3296 o set back the current buffer.
3297 o move all markers and overlays to BEG.
3298 o remove all text properties.
3299 o set back the buffer multibyteness. */
3301 static void
3302 decide_coding_unwind (Lisp_Object unwind_data)
3304 Lisp_Object multibyte, undo_list, buffer;
3306 multibyte = XCAR (unwind_data);
3307 unwind_data = XCDR (unwind_data);
3308 undo_list = XCAR (unwind_data);
3309 buffer = XCDR (unwind_data);
3311 set_buffer_internal (XBUFFER (buffer));
3312 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3313 adjust_overlays_for_delete (BEG, Z - BEG);
3314 set_buffer_intervals (current_buffer, NULL);
3315 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3317 /* Now we are safe to change the buffer's multibyteness directly. */
3318 bset_enable_multibyte_characters (current_buffer, multibyte);
3319 bset_undo_list (current_buffer, undo_list);
3322 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3323 object where slot 0 is the file descriptor, slot 1 specifies
3324 an offset to put the read bytes, and slot 2 is the maximum
3325 amount of bytes to read. Value is the number of bytes read. */
3327 static Lisp_Object
3328 read_non_regular (Lisp_Object state)
3330 int nbytes;
3332 immediate_quit = 1;
3333 QUIT;
3334 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3335 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3336 + XSAVE_INTEGER (state, 1)),
3337 XSAVE_INTEGER (state, 2));
3338 immediate_quit = 0;
3339 /* Fast recycle this object for the likely next call. */
3340 free_misc (state);
3341 return make_number (nbytes);
3345 /* Condition-case handler used when reading from non-regular files
3346 in insert-file-contents. */
3348 static Lisp_Object
3349 read_non_regular_quit (Lisp_Object ignore)
3351 return Qnil;
3354 /* Return the file offset that VAL represents, checking for type
3355 errors and overflow. */
3356 static off_t
3357 file_offset (Lisp_Object val)
3359 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3360 return XINT (val);
3362 if (FLOATP (val))
3364 double v = XFLOAT_DATA (val);
3365 if (0 <= v
3366 && (sizeof (off_t) < sizeof v
3367 ? v <= TYPE_MAXIMUM (off_t)
3368 : v < TYPE_MAXIMUM (off_t)))
3369 return v;
3372 wrong_type_argument (intern ("file-offset"), val);
3375 /* Return a special time value indicating the error number ERRNUM. */
3376 static struct timespec
3377 time_error_value (int errnum)
3379 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3380 ? NONEXISTENT_MODTIME_NSECS
3381 : UNKNOWN_MODTIME_NSECS);
3382 return make_timespec (0, ns);
3385 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3386 1, 5, 0,
3387 doc: /* Insert contents of file FILENAME after point.
3388 Returns list of absolute file name and number of characters inserted.
3389 If second argument VISIT is non-nil, the buffer's visited filename and
3390 last save file modtime are set, and it is marked unmodified. If
3391 visiting and the file does not exist, visiting is completed before the
3392 error is signaled.
3394 The optional third and fourth arguments BEG and END specify what portion
3395 of the file to insert. These arguments count bytes in the file, not
3396 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3398 If optional fifth argument REPLACE is non-nil, replace the current
3399 buffer contents (in the accessible portion) with the file contents.
3400 This is better than simply deleting and inserting the whole thing
3401 because (1) it preserves some marker positions and (2) it puts less data
3402 in the undo list. When REPLACE is non-nil, the second return value is
3403 the number of characters that replace previous buffer contents.
3405 This function does code conversion according to the value of
3406 `coding-system-for-read' or `file-coding-system-alist', and sets the
3407 variable `last-coding-system-used' to the coding system actually used.
3409 In addition, this function decodes the inserted text from known formats
3410 by calling `format-decode', which see. */)
3411 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3413 struct stat st;
3414 struct timespec mtime;
3415 int fd;
3416 ptrdiff_t inserted = 0;
3417 ptrdiff_t how_much;
3418 off_t beg_offset, end_offset;
3419 int unprocessed;
3420 ptrdiff_t count = SPECPDL_INDEX ();
3421 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3422 Lisp_Object handler, val, insval, orig_filename, old_undo;
3423 Lisp_Object p;
3424 ptrdiff_t total = 0;
3425 bool not_regular = 0;
3426 int save_errno = 0;
3427 char read_buf[READ_BUF_SIZE];
3428 struct coding_system coding;
3429 bool replace_handled = 0;
3430 bool set_coding_system = 0;
3431 Lisp_Object coding_system;
3432 bool read_quit = 0;
3433 /* If the undo log only contains the insertion, there's no point
3434 keeping it. It's typically when we first fill a file-buffer. */
3435 bool empty_undo_list_p
3436 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3437 && BEG == Z);
3438 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3439 bool we_locked_file = 0;
3440 ptrdiff_t fd_index;
3442 if (current_buffer->base_buffer && ! NILP (visit))
3443 error ("Cannot do file visiting in an indirect buffer");
3445 if (!NILP (BVAR (current_buffer, read_only)))
3446 Fbarf_if_buffer_read_only ();
3448 val = Qnil;
3449 p = Qnil;
3450 orig_filename = Qnil;
3451 old_undo = Qnil;
3453 GCPRO5 (filename, val, p, orig_filename, old_undo);
3455 CHECK_STRING (filename);
3456 filename = Fexpand_file_name (filename, Qnil);
3458 /* The value Qnil means that the coding system is not yet
3459 decided. */
3460 coding_system = Qnil;
3462 /* If the file name has special constructs in it,
3463 call the corresponding file handler. */
3464 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3465 if (!NILP (handler))
3467 val = call6 (handler, Qinsert_file_contents, filename,
3468 visit, beg, end, replace);
3469 if (CONSP (val) && CONSP (XCDR (val))
3470 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3471 inserted = XINT (XCAR (XCDR (val)));
3472 goto handled;
3475 orig_filename = filename;
3476 filename = ENCODE_FILE (filename);
3478 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3479 if (fd < 0)
3481 save_errno = errno;
3482 if (NILP (visit))
3483 report_file_error ("Opening input file", orig_filename);
3484 mtime = time_error_value (save_errno);
3485 st.st_size = -1;
3486 if (!NILP (Vcoding_system_for_read))
3487 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3488 goto notfound;
3491 fd_index = SPECPDL_INDEX ();
3492 record_unwind_protect_int (close_file_unwind, fd);
3494 /* Replacement should preserve point as it preserves markers. */
3495 if (!NILP (replace))
3496 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3498 if (fstat (fd, &st) != 0)
3499 report_file_error ("Input file status", orig_filename);
3500 mtime = get_stat_mtime (&st);
3502 /* This code will need to be changed in order to work on named
3503 pipes, and it's probably just not worth it. So we should at
3504 least signal an error. */
3505 if (!S_ISREG (st.st_mode))
3507 not_regular = 1;
3509 if (! NILP (visit))
3510 goto notfound;
3512 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3513 xsignal2 (Qfile_error,
3514 build_string ("not a regular file"), orig_filename);
3517 if (!NILP (visit))
3519 if (!NILP (beg) || !NILP (end))
3520 error ("Attempt to visit less than an entire file");
3521 if (BEG < Z && NILP (replace))
3522 error ("Cannot do file visiting in a non-empty buffer");
3525 if (!NILP (beg))
3526 beg_offset = file_offset (beg);
3527 else
3528 beg_offset = 0;
3530 if (!NILP (end))
3531 end_offset = file_offset (end);
3532 else
3534 if (not_regular)
3535 end_offset = TYPE_MAXIMUM (off_t);
3536 else
3538 end_offset = st.st_size;
3540 /* A negative size can happen on a platform that allows file
3541 sizes greater than the maximum off_t value. */
3542 if (end_offset < 0)
3543 buffer_overflow ();
3545 /* The file size returned from stat may be zero, but data
3546 may be readable nonetheless, for example when this is a
3547 file in the /proc filesystem. */
3548 if (end_offset == 0)
3549 end_offset = READ_BUF_SIZE;
3553 /* Check now whether the buffer will become too large,
3554 in the likely case where the file's length is not changing.
3555 This saves a lot of needless work before a buffer overflow. */
3556 if (! not_regular)
3558 /* The likely offset where we will stop reading. We could read
3559 more (or less), if the file grows (or shrinks) as we read it. */
3560 off_t likely_end = min (end_offset, st.st_size);
3562 if (beg_offset < likely_end)
3564 ptrdiff_t buf_bytes
3565 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3566 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3567 off_t likely_growth = likely_end - beg_offset;
3568 if (buf_growth_max < likely_growth)
3569 buffer_overflow ();
3573 /* Prevent redisplay optimizations. */
3574 current_buffer->clip_changed = 1;
3576 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3578 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3579 setup_coding_system (coding_system, &coding);
3580 /* Ensure we set Vlast_coding_system_used. */
3581 set_coding_system = 1;
3583 else if (BEG < Z)
3585 /* Decide the coding system to use for reading the file now
3586 because we can't use an optimized method for handling
3587 `coding:' tag if the current buffer is not empty. */
3588 if (!NILP (Vcoding_system_for_read))
3589 coding_system = Vcoding_system_for_read;
3590 else
3592 /* Don't try looking inside a file for a coding system
3593 specification if it is not seekable. */
3594 if (! not_regular && ! NILP (Vset_auto_coding_function))
3596 /* Find a coding system specified in the heading two
3597 lines or in the tailing several lines of the file.
3598 We assume that the 1K-byte and 3K-byte for heading
3599 and tailing respectively are sufficient for this
3600 purpose. */
3601 int nread;
3603 if (st.st_size <= (1024 * 4))
3604 nread = emacs_read (fd, read_buf, 1024 * 4);
3605 else
3607 nread = emacs_read (fd, read_buf, 1024);
3608 if (nread == 1024)
3610 int ntail;
3611 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3612 report_file_error ("Setting file position",
3613 orig_filename);
3614 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3615 nread = ntail < 0 ? ntail : nread + ntail;
3619 if (nread < 0)
3620 report_file_error ("Read error", orig_filename);
3621 else if (nread > 0)
3623 struct buffer *prev = current_buffer;
3624 Lisp_Object workbuf;
3625 struct buffer *buf;
3627 record_unwind_current_buffer ();
3629 workbuf = Fget_buffer_create (build_string (" *code-converting-work*"));
3630 buf = XBUFFER (workbuf);
3632 delete_all_overlays (buf);
3633 bset_directory (buf, BVAR (current_buffer, directory));
3634 bset_read_only (buf, Qnil);
3635 bset_filename (buf, Qnil);
3636 bset_undo_list (buf, Qt);
3637 eassert (buf->overlays_before == NULL);
3638 eassert (buf->overlays_after == NULL);
3640 set_buffer_internal (buf);
3641 Ferase_buffer ();
3642 bset_enable_multibyte_characters (buf, Qnil);
3644 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3645 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3646 coding_system = call2 (Vset_auto_coding_function,
3647 filename, make_number (nread));
3648 set_buffer_internal (prev);
3650 /* Discard the unwind protect for recovering the
3651 current buffer. */
3652 specpdl_ptr--;
3654 /* Rewind the file for the actual read done later. */
3655 if (lseek (fd, 0, SEEK_SET) < 0)
3656 report_file_error ("Setting file position", orig_filename);
3660 if (NILP (coding_system))
3662 /* If we have not yet decided a coding system, check
3663 file-coding-system-alist. */
3664 Lisp_Object args[6];
3666 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3667 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3668 coding_system = Ffind_operation_coding_system (6, args);
3669 if (CONSP (coding_system))
3670 coding_system = XCAR (coding_system);
3674 if (NILP (coding_system))
3675 coding_system = Qundecided;
3676 else
3677 CHECK_CODING_SYSTEM (coding_system);
3679 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3680 /* We must suppress all character code conversion except for
3681 end-of-line conversion. */
3682 coding_system = raw_text_coding_system (coding_system);
3684 setup_coding_system (coding_system, &coding);
3685 /* Ensure we set Vlast_coding_system_used. */
3686 set_coding_system = 1;
3689 /* If requested, replace the accessible part of the buffer
3690 with the file contents. Avoid replacing text at the
3691 beginning or end of the buffer that matches the file contents;
3692 that preserves markers pointing to the unchanged parts.
3694 Here we implement this feature in an optimized way
3695 for the case where code conversion is NOT needed.
3696 The following if-statement handles the case of conversion
3697 in a less optimal way.
3699 If the code conversion is "automatic" then we try using this
3700 method and hope for the best.
3701 But if we discover the need for conversion, we give up on this method
3702 and let the following if-statement handle the replace job. */
3703 if (!NILP (replace)
3704 && BEGV < ZV
3705 && (NILP (coding_system)
3706 || ! CODING_REQUIRE_DECODING (&coding)))
3708 /* same_at_start and same_at_end count bytes,
3709 because file access counts bytes
3710 and BEG and END count bytes. */
3711 ptrdiff_t same_at_start = BEGV_BYTE;
3712 ptrdiff_t same_at_end = ZV_BYTE;
3713 ptrdiff_t overlap;
3714 /* There is still a possibility we will find the need to do code
3715 conversion. If that happens, set this variable to
3716 give up on handling REPLACE in the optimized way. */
3717 bool giveup_match_end = 0;
3719 if (beg_offset != 0)
3721 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3722 report_file_error ("Setting file position", orig_filename);
3725 immediate_quit = 1;
3726 QUIT;
3727 /* Count how many chars at the start of the file
3728 match the text at the beginning of the buffer. */
3729 while (1)
3731 int nread, bufpos;
3733 nread = emacs_read (fd, read_buf, sizeof read_buf);
3734 if (nread < 0)
3735 report_file_error ("Read error", orig_filename);
3736 else if (nread == 0)
3737 break;
3739 if (CODING_REQUIRE_DETECTION (&coding))
3741 coding_system = detect_coding_system ((unsigned char *) read_buf,
3742 nread, nread, 1, 0,
3743 coding_system);
3744 setup_coding_system (coding_system, &coding);
3747 if (CODING_REQUIRE_DECODING (&coding))
3748 /* We found that the file should be decoded somehow.
3749 Let's give up here. */
3751 giveup_match_end = 1;
3752 break;
3755 bufpos = 0;
3756 while (bufpos < nread && same_at_start < ZV_BYTE
3757 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3758 same_at_start++, bufpos++;
3759 /* If we found a discrepancy, stop the scan.
3760 Otherwise loop around and scan the next bufferful. */
3761 if (bufpos != nread)
3762 break;
3764 immediate_quit = 0;
3765 /* If the file matches the buffer completely,
3766 there's no need to replace anything. */
3767 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3769 emacs_close (fd);
3770 clear_unwind_protect (fd_index);
3772 /* Truncate the buffer to the size of the file. */
3773 del_range_1 (same_at_start, same_at_end, 0, 0);
3774 goto handled;
3776 immediate_quit = 1;
3777 QUIT;
3778 /* Count how many chars at the end of the file
3779 match the text at the end of the buffer. But, if we have
3780 already found that decoding is necessary, don't waste time. */
3781 while (!giveup_match_end)
3783 int total_read, nread, bufpos, trial;
3784 off_t curpos;
3786 /* At what file position are we now scanning? */
3787 curpos = end_offset - (ZV_BYTE - same_at_end);
3788 /* If the entire file matches the buffer tail, stop the scan. */
3789 if (curpos == 0)
3790 break;
3791 /* How much can we scan in the next step? */
3792 trial = min (curpos, sizeof read_buf);
3793 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3794 report_file_error ("Setting file position", orig_filename);
3796 total_read = nread = 0;
3797 while (total_read < trial)
3799 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3800 if (nread < 0)
3801 report_file_error ("Read error", orig_filename);
3802 else if (nread == 0)
3803 break;
3804 total_read += nread;
3807 /* Scan this bufferful from the end, comparing with
3808 the Emacs buffer. */
3809 bufpos = total_read;
3811 /* Compare with same_at_start to avoid counting some buffer text
3812 as matching both at the file's beginning and at the end. */
3813 while (bufpos > 0 && same_at_end > same_at_start
3814 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3815 same_at_end--, bufpos--;
3817 /* If we found a discrepancy, stop the scan.
3818 Otherwise loop around and scan the preceding bufferful. */
3819 if (bufpos != 0)
3821 /* If this discrepancy is because of code conversion,
3822 we cannot use this method; giveup and try the other. */
3823 if (same_at_end > same_at_start
3824 && FETCH_BYTE (same_at_end - 1) >= 0200
3825 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3826 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3827 giveup_match_end = 1;
3828 break;
3831 if (nread == 0)
3832 break;
3834 immediate_quit = 0;
3836 if (! giveup_match_end)
3838 ptrdiff_t temp;
3840 /* We win! We can handle REPLACE the optimized way. */
3842 /* Extend the start of non-matching text area to multibyte
3843 character boundary. */
3844 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3845 while (same_at_start > BEGV_BYTE
3846 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3847 same_at_start--;
3849 /* Extend the end of non-matching text area to multibyte
3850 character boundary. */
3851 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3852 while (same_at_end < ZV_BYTE
3853 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3854 same_at_end++;
3856 /* Don't try to reuse the same piece of text twice. */
3857 overlap = (same_at_start - BEGV_BYTE
3858 - (same_at_end
3859 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3860 if (overlap > 0)
3861 same_at_end += overlap;
3863 /* Arrange to read only the nonmatching middle part of the file. */
3864 beg_offset += same_at_start - BEGV_BYTE;
3865 end_offset -= ZV_BYTE - same_at_end;
3867 invalidate_buffer_caches (current_buffer,
3868 BYTE_TO_CHAR (same_at_start),
3869 BYTE_TO_CHAR (same_at_end));
3870 del_range_byte (same_at_start, same_at_end, 0);
3871 /* Insert from the file at the proper position. */
3872 temp = BYTE_TO_CHAR (same_at_start);
3873 SET_PT_BOTH (temp, same_at_start);
3875 /* If display currently starts at beginning of line,
3876 keep it that way. */
3877 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3878 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3880 replace_handled = 1;
3884 /* If requested, replace the accessible part of the buffer
3885 with the file contents. Avoid replacing text at the
3886 beginning or end of the buffer that matches the file contents;
3887 that preserves markers pointing to the unchanged parts.
3889 Here we implement this feature for the case where code conversion
3890 is needed, in a simple way that needs a lot of memory.
3891 The preceding if-statement handles the case of no conversion
3892 in a more optimized way. */
3893 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3895 ptrdiff_t same_at_start = BEGV_BYTE;
3896 ptrdiff_t same_at_end = ZV_BYTE;
3897 ptrdiff_t same_at_start_charpos;
3898 ptrdiff_t inserted_chars;
3899 ptrdiff_t overlap;
3900 ptrdiff_t bufpos;
3901 unsigned char *decoded;
3902 ptrdiff_t temp;
3903 ptrdiff_t this = 0;
3904 ptrdiff_t this_count = SPECPDL_INDEX ();
3905 bool multibyte
3906 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3907 Lisp_Object conversion_buffer;
3908 struct gcpro gcpro1;
3910 conversion_buffer = code_conversion_save (1, multibyte);
3912 /* First read the whole file, performing code conversion into
3913 CONVERSION_BUFFER. */
3915 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3916 report_file_error ("Setting file position", orig_filename);
3918 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3919 unprocessed = 0; /* Bytes not processed in previous loop. */
3921 GCPRO1 (conversion_buffer);
3922 while (1)
3924 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3925 quitting while reading a huge file. */
3927 /* Allow quitting out of the actual I/O. */
3928 immediate_quit = 1;
3929 QUIT;
3930 this = emacs_read (fd, read_buf + unprocessed,
3931 READ_BUF_SIZE - unprocessed);
3932 immediate_quit = 0;
3934 if (this <= 0)
3935 break;
3937 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3938 BUF_Z (XBUFFER (conversion_buffer)));
3939 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3940 unprocessed + this, conversion_buffer);
3941 unprocessed = coding.carryover_bytes;
3942 if (coding.carryover_bytes > 0)
3943 memcpy (read_buf, coding.carryover, unprocessed);
3945 UNGCPRO;
3946 if (this < 0)
3947 report_file_error ("Read error", orig_filename);
3948 emacs_close (fd);
3949 clear_unwind_protect (fd_index);
3951 if (unprocessed > 0)
3953 coding.mode |= CODING_MODE_LAST_BLOCK;
3954 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3955 unprocessed, conversion_buffer);
3956 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3959 coding_system = CODING_ID_NAME (coding.id);
3960 set_coding_system = 1;
3961 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3962 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3963 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3965 /* Compare the beginning of the converted string with the buffer
3966 text. */
3968 bufpos = 0;
3969 while (bufpos < inserted && same_at_start < same_at_end
3970 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3971 same_at_start++, bufpos++;
3973 /* If the file matches the head of buffer completely,
3974 there's no need to replace anything. */
3976 if (bufpos == inserted)
3978 /* Truncate the buffer to the size of the file. */
3979 if (same_at_start != same_at_end)
3981 invalidate_buffer_caches (current_buffer,
3982 BYTE_TO_CHAR (same_at_start),
3983 BYTE_TO_CHAR (same_at_end));
3984 del_range_byte (same_at_start, same_at_end, 0);
3986 inserted = 0;
3988 unbind_to (this_count, Qnil);
3989 goto handled;
3992 /* Extend the start of non-matching text area to the previous
3993 multibyte character boundary. */
3994 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3995 while (same_at_start > BEGV_BYTE
3996 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3997 same_at_start--;
3999 /* Scan this bufferful from the end, comparing with
4000 the Emacs buffer. */
4001 bufpos = inserted;
4003 /* Compare with same_at_start to avoid counting some buffer text
4004 as matching both at the file's beginning and at the end. */
4005 while (bufpos > 0 && same_at_end > same_at_start
4006 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4007 same_at_end--, bufpos--;
4009 /* Extend the end of non-matching text area to the next
4010 multibyte character boundary. */
4011 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4012 while (same_at_end < ZV_BYTE
4013 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4014 same_at_end++;
4016 /* Don't try to reuse the same piece of text twice. */
4017 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4018 if (overlap > 0)
4019 same_at_end += overlap;
4021 /* If display currently starts at beginning of line,
4022 keep it that way. */
4023 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4024 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4026 /* Replace the chars that we need to replace,
4027 and update INSERTED to equal the number of bytes
4028 we are taking from the decoded string. */
4029 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4031 if (same_at_end != same_at_start)
4033 invalidate_buffer_caches (current_buffer,
4034 BYTE_TO_CHAR (same_at_start),
4035 BYTE_TO_CHAR (same_at_end));
4036 del_range_byte (same_at_start, same_at_end, 0);
4037 temp = GPT;
4038 eassert (same_at_start == GPT_BYTE);
4039 same_at_start = GPT_BYTE;
4041 else
4043 temp = BYTE_TO_CHAR (same_at_start);
4045 /* Insert from the file at the proper position. */
4046 SET_PT_BOTH (temp, same_at_start);
4047 same_at_start_charpos
4048 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4049 same_at_start - BEGV_BYTE
4050 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4051 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4052 inserted_chars
4053 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4054 same_at_start + inserted - BEGV_BYTE
4055 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4056 - same_at_start_charpos);
4057 /* This binding is to avoid ask-user-about-supersession-threat
4058 being called in insert_from_buffer (via in
4059 prepare_to_modify_buffer). */
4060 specbind (intern ("buffer-file-name"), Qnil);
4061 insert_from_buffer (XBUFFER (conversion_buffer),
4062 same_at_start_charpos, inserted_chars, 0);
4063 /* Set `inserted' to the number of inserted characters. */
4064 inserted = PT - temp;
4065 /* Set point before the inserted characters. */
4066 SET_PT_BOTH (temp, same_at_start);
4068 unbind_to (this_count, Qnil);
4070 goto handled;
4073 if (! not_regular)
4074 total = end_offset - beg_offset;
4075 else
4076 /* For a special file, all we can do is guess. */
4077 total = READ_BUF_SIZE;
4079 if (NILP (visit) && total > 0)
4081 #ifdef CLASH_DETECTION
4082 if (!NILP (BVAR (current_buffer, file_truename))
4083 /* Make binding buffer-file-name to nil effective. */
4084 && !NILP (BVAR (current_buffer, filename))
4085 && SAVE_MODIFF >= MODIFF)
4086 we_locked_file = 1;
4087 #endif /* CLASH_DETECTION */
4088 prepare_to_modify_buffer (PT, PT, NULL);
4091 move_gap_both (PT, PT_BYTE);
4092 if (GAP_SIZE < total)
4093 make_gap (total - GAP_SIZE);
4095 if (beg_offset != 0 || !NILP (replace))
4097 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4098 report_file_error ("Setting file position", orig_filename);
4101 /* In the following loop, HOW_MUCH contains the total bytes read so
4102 far for a regular file, and not changed for a special file. But,
4103 before exiting the loop, it is set to a negative value if I/O
4104 error occurs. */
4105 how_much = 0;
4107 /* Total bytes inserted. */
4108 inserted = 0;
4110 /* Here, we don't do code conversion in the loop. It is done by
4111 decode_coding_gap after all data are read into the buffer. */
4113 ptrdiff_t gap_size = GAP_SIZE;
4115 while (how_much < total)
4117 /* try is reserved in some compilers (Microsoft C) */
4118 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4119 ptrdiff_t this;
4121 if (not_regular)
4123 Lisp_Object nbytes;
4125 /* Maybe make more room. */
4126 if (gap_size < trytry)
4128 make_gap (trytry - gap_size);
4129 gap_size = GAP_SIZE - inserted;
4132 /* Read from the file, capturing `quit'. When an
4133 error occurs, end the loop, and arrange for a quit
4134 to be signaled after decoding the text we read. */
4135 nbytes = internal_condition_case_1
4136 (read_non_regular,
4137 make_save_int_int_int (fd, inserted, trytry),
4138 Qerror, read_non_regular_quit);
4140 if (NILP (nbytes))
4142 read_quit = 1;
4143 break;
4146 this = XINT (nbytes);
4148 else
4150 /* Allow quitting out of the actual I/O. We don't make text
4151 part of the buffer until all the reading is done, so a C-g
4152 here doesn't do any harm. */
4153 immediate_quit = 1;
4154 QUIT;
4155 this = emacs_read (fd,
4156 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4157 + inserted),
4158 trytry);
4159 immediate_quit = 0;
4162 if (this <= 0)
4164 how_much = this;
4165 break;
4168 gap_size -= this;
4170 /* For a regular file, where TOTAL is the real size,
4171 count HOW_MUCH to compare with it.
4172 For a special file, where TOTAL is just a buffer size,
4173 so don't bother counting in HOW_MUCH.
4174 (INSERTED is where we count the number of characters inserted.) */
4175 if (! not_regular)
4176 how_much += this;
4177 inserted += this;
4181 /* Now we have either read all the file data into the gap,
4182 or stop reading on I/O error or quit. If nothing was
4183 read, undo marking the buffer modified. */
4185 if (inserted == 0)
4187 #ifdef CLASH_DETECTION
4188 if (we_locked_file)
4189 unlock_file (BVAR (current_buffer, file_truename));
4190 #endif
4191 Vdeactivate_mark = old_Vdeactivate_mark;
4193 else
4194 Vdeactivate_mark = Qt;
4196 emacs_close (fd);
4197 clear_unwind_protect (fd_index);
4199 if (how_much < 0)
4200 report_file_error ("Read error", orig_filename);
4202 /* Make the text read part of the buffer. */
4203 GAP_SIZE -= inserted;
4204 GPT += inserted;
4205 GPT_BYTE += inserted;
4206 ZV += inserted;
4207 ZV_BYTE += inserted;
4208 Z += inserted;
4209 Z_BYTE += inserted;
4211 if (GAP_SIZE > 0)
4212 /* Put an anchor to ensure multi-byte form ends at gap. */
4213 *GPT_ADDR = 0;
4215 notfound:
4217 if (NILP (coding_system))
4219 /* The coding system is not yet decided. Decide it by an
4220 optimized method for handling `coding:' tag.
4222 Note that we can get here only if the buffer was empty
4223 before the insertion. */
4225 if (!NILP (Vcoding_system_for_read))
4226 coding_system = Vcoding_system_for_read;
4227 else
4229 /* Since we are sure that the current buffer was empty
4230 before the insertion, we can toggle
4231 enable-multibyte-characters directly here without taking
4232 care of marker adjustment. By this way, we can run Lisp
4233 program safely before decoding the inserted text. */
4234 Lisp_Object unwind_data;
4235 ptrdiff_t count1 = SPECPDL_INDEX ();
4237 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4238 Fcons (BVAR (current_buffer, undo_list),
4239 Fcurrent_buffer ()));
4240 bset_enable_multibyte_characters (current_buffer, Qnil);
4241 bset_undo_list (current_buffer, Qt);
4242 record_unwind_protect (decide_coding_unwind, unwind_data);
4244 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4246 coding_system = call2 (Vset_auto_coding_function,
4247 filename, make_number (inserted));
4250 if (NILP (coding_system))
4252 /* If the coding system is not yet decided, check
4253 file-coding-system-alist. */
4254 Lisp_Object args[6];
4256 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4257 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4258 coding_system = Ffind_operation_coding_system (6, args);
4259 if (CONSP (coding_system))
4260 coding_system = XCAR (coding_system);
4262 unbind_to (count1, Qnil);
4263 inserted = Z_BYTE - BEG_BYTE;
4266 if (NILP (coding_system))
4267 coding_system = Qundecided;
4268 else
4269 CHECK_CODING_SYSTEM (coding_system);
4271 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4272 /* We must suppress all character code conversion except for
4273 end-of-line conversion. */
4274 coding_system = raw_text_coding_system (coding_system);
4275 setup_coding_system (coding_system, &coding);
4276 /* Ensure we set Vlast_coding_system_used. */
4277 set_coding_system = 1;
4280 if (!NILP (visit))
4282 /* When we visit a file by raw-text, we change the buffer to
4283 unibyte. */
4284 if (CODING_FOR_UNIBYTE (&coding)
4285 /* Can't do this if part of the buffer might be preserved. */
4286 && NILP (replace))
4287 /* Visiting a file with these coding system makes the buffer
4288 unibyte. */
4289 bset_enable_multibyte_characters (current_buffer, Qnil);
4292 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4293 if (CODING_MAY_REQUIRE_DECODING (&coding)
4294 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4296 move_gap_both (PT, PT_BYTE);
4297 GAP_SIZE += inserted;
4298 ZV_BYTE -= inserted;
4299 Z_BYTE -= inserted;
4300 ZV -= inserted;
4301 Z -= inserted;
4302 decode_coding_gap (&coding, inserted, inserted);
4303 inserted = coding.produced_char;
4304 coding_system = CODING_ID_NAME (coding.id);
4306 else if (inserted > 0)
4308 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4309 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4310 inserted);
4313 /* Call after-change hooks for the inserted text, aside from the case
4314 of normal visiting (not with REPLACE), which is done in a new buffer
4315 "before" the buffer is changed. */
4316 if (inserted > 0 && total > 0
4317 && (NILP (visit) || !NILP (replace)))
4319 signal_after_change (PT, 0, inserted);
4320 update_compositions (PT, PT, CHECK_BORDER);
4323 /* Now INSERTED is measured in characters. */
4325 handled:
4327 if (!NILP (visit))
4329 if (empty_undo_list_p)
4330 bset_undo_list (current_buffer, Qnil);
4332 if (NILP (handler))
4334 current_buffer->modtime = mtime;
4335 current_buffer->modtime_size = st.st_size;
4336 bset_filename (current_buffer, orig_filename);
4339 SAVE_MODIFF = MODIFF;
4340 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4341 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4342 #ifdef CLASH_DETECTION
4343 if (NILP (handler))
4345 if (!NILP (BVAR (current_buffer, file_truename)))
4346 unlock_file (BVAR (current_buffer, file_truename));
4347 unlock_file (filename);
4349 #endif /* CLASH_DETECTION */
4350 if (not_regular)
4351 xsignal2 (Qfile_error,
4352 build_string ("not a regular file"), orig_filename);
4355 if (set_coding_system)
4356 Vlast_coding_system_used = coding_system;
4358 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4360 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4361 visit);
4362 if (! NILP (insval))
4364 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4365 wrong_type_argument (intern ("inserted-chars"), insval);
4366 inserted = XFASTINT (insval);
4370 /* Decode file format. */
4371 if (inserted > 0)
4373 /* Don't run point motion or modification hooks when decoding. */
4374 ptrdiff_t count1 = SPECPDL_INDEX ();
4375 ptrdiff_t old_inserted = inserted;
4376 specbind (Qinhibit_point_motion_hooks, Qt);
4377 specbind (Qinhibit_modification_hooks, Qt);
4379 /* Save old undo list and don't record undo for decoding. */
4380 old_undo = BVAR (current_buffer, undo_list);
4381 bset_undo_list (current_buffer, Qt);
4383 if (NILP (replace))
4385 insval = call3 (Qformat_decode,
4386 Qnil, make_number (inserted), visit);
4387 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4388 wrong_type_argument (intern ("inserted-chars"), insval);
4389 inserted = XFASTINT (insval);
4391 else
4393 /* If REPLACE is non-nil and we succeeded in not replacing the
4394 beginning or end of the buffer text with the file's contents,
4395 call format-decode with `point' positioned at the beginning
4396 of the buffer and `inserted' equaling the number of
4397 characters in the buffer. Otherwise, format-decode might
4398 fail to correctly analyze the beginning or end of the buffer.
4399 Hence we temporarily save `point' and `inserted' here and
4400 restore `point' iff format-decode did not insert or delete
4401 any text. Otherwise we leave `point' at point-min. */
4402 ptrdiff_t opoint = PT;
4403 ptrdiff_t opoint_byte = PT_BYTE;
4404 ptrdiff_t oinserted = ZV - BEGV;
4405 EMACS_INT ochars_modiff = CHARS_MODIFF;
4407 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4408 insval = call3 (Qformat_decode,
4409 Qnil, make_number (oinserted), visit);
4410 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4411 wrong_type_argument (intern ("inserted-chars"), insval);
4412 if (ochars_modiff == CHARS_MODIFF)
4413 /* format_decode didn't modify buffer's characters => move
4414 point back to position before inserted text and leave
4415 value of inserted alone. */
4416 SET_PT_BOTH (opoint, opoint_byte);
4417 else
4418 /* format_decode modified buffer's characters => consider
4419 entire buffer changed and leave point at point-min. */
4420 inserted = XFASTINT (insval);
4423 /* For consistency with format-decode call these now iff inserted > 0
4424 (martin 2007-06-28). */
4425 p = Vafter_insert_file_functions;
4426 while (CONSP (p))
4428 if (NILP (replace))
4430 insval = call1 (XCAR (p), make_number (inserted));
4431 if (!NILP (insval))
4433 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4434 wrong_type_argument (intern ("inserted-chars"), insval);
4435 inserted = XFASTINT (insval);
4438 else
4440 /* For the rationale of this see the comment on
4441 format-decode above. */
4442 ptrdiff_t opoint = PT;
4443 ptrdiff_t opoint_byte = PT_BYTE;
4444 ptrdiff_t oinserted = ZV - BEGV;
4445 EMACS_INT ochars_modiff = CHARS_MODIFF;
4447 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4448 insval = call1 (XCAR (p), make_number (oinserted));
4449 if (!NILP (insval))
4451 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4452 wrong_type_argument (intern ("inserted-chars"), insval);
4453 if (ochars_modiff == CHARS_MODIFF)
4454 /* after_insert_file_functions didn't modify
4455 buffer's characters => move point back to
4456 position before inserted text and leave value of
4457 inserted alone. */
4458 SET_PT_BOTH (opoint, opoint_byte);
4459 else
4460 /* after_insert_file_functions did modify buffer's
4461 characters => consider entire buffer changed and
4462 leave point at point-min. */
4463 inserted = XFASTINT (insval);
4467 QUIT;
4468 p = XCDR (p);
4471 if (!empty_undo_list_p)
4473 bset_undo_list (current_buffer, old_undo);
4474 if (CONSP (old_undo) && inserted != old_inserted)
4476 /* Adjust the last undo record for the size change during
4477 the format conversion. */
4478 Lisp_Object tem = XCAR (old_undo);
4479 if (CONSP (tem) && INTEGERP (XCAR (tem))
4480 && INTEGERP (XCDR (tem))
4481 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4482 XSETCDR (tem, make_number (PT + inserted));
4485 else
4486 /* If undo_list was Qt before, keep it that way.
4487 Otherwise start with an empty undo_list. */
4488 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4490 unbind_to (count1, Qnil);
4493 if (!NILP (visit)
4494 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4496 /* If visiting nonexistent file, return nil. */
4497 report_file_errno ("Opening input file", orig_filename, save_errno);
4500 /* We made a lot of deletions and insertions above, so invalidate
4501 the newline cache for the entire region of the inserted
4502 characters. */
4503 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4504 invalidate_region_cache (current_buffer->base_buffer,
4505 current_buffer->base_buffer->newline_cache,
4506 PT - BEG, Z - PT - inserted);
4507 else if (current_buffer->newline_cache)
4508 invalidate_region_cache (current_buffer,
4509 current_buffer->newline_cache,
4510 PT - BEG, Z - PT - inserted);
4512 if (read_quit)
4513 Fsignal (Qquit, Qnil);
4515 /* Retval needs to be dealt with in all cases consistently. */
4516 if (NILP (val))
4517 val = list2 (orig_filename, make_number (inserted));
4519 RETURN_UNGCPRO (unbind_to (count, val));
4522 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4524 static void
4525 build_annotations_unwind (Lisp_Object arg)
4527 Vwrite_region_annotation_buffers = arg;
4530 /* Decide the coding-system to encode the data with. */
4532 static Lisp_Object
4533 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4534 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4535 struct coding_system *coding)
4537 Lisp_Object val;
4538 Lisp_Object eol_parent = Qnil;
4540 if (auto_saving
4541 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4542 BVAR (current_buffer, auto_save_file_name))))
4544 val = Qutf_8_emacs;
4545 eol_parent = Qunix;
4547 else if (!NILP (Vcoding_system_for_write))
4549 val = Vcoding_system_for_write;
4550 if (coding_system_require_warning
4551 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4552 /* Confirm that VAL can surely encode the current region. */
4553 val = call5 (Vselect_safe_coding_system_function,
4554 start, end, list2 (Qt, val),
4555 Qnil, filename);
4557 else
4559 /* If the variable `buffer-file-coding-system' is set locally,
4560 it means that the file was read with some kind of code
4561 conversion or the variable is explicitly set by users. We
4562 had better write it out with the same coding system even if
4563 `enable-multibyte-characters' is nil.
4565 If it is not set locally, we anyway have to convert EOL
4566 format if the default value of `buffer-file-coding-system'
4567 tells that it is not Unix-like (LF only) format. */
4568 bool using_default_coding = 0;
4569 bool force_raw_text = 0;
4571 val = BVAR (current_buffer, buffer_file_coding_system);
4572 if (NILP (val)
4573 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4575 val = Qnil;
4576 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4577 force_raw_text = 1;
4580 if (NILP (val))
4582 /* Check file-coding-system-alist. */
4583 Lisp_Object args[7], coding_systems;
4585 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4586 args[3] = filename; args[4] = append; args[5] = visit;
4587 args[6] = lockname;
4588 coding_systems = Ffind_operation_coding_system (7, args);
4589 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4590 val = XCDR (coding_systems);
4593 if (NILP (val))
4595 /* If we still have not decided a coding system, use the
4596 default value of buffer-file-coding-system. */
4597 val = BVAR (current_buffer, buffer_file_coding_system);
4598 using_default_coding = 1;
4601 if (! NILP (val) && ! force_raw_text)
4603 Lisp_Object spec, attrs;
4605 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4606 attrs = AREF (spec, 0);
4607 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4608 force_raw_text = 1;
4611 if (!force_raw_text
4612 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4613 /* Confirm that VAL can surely encode the current region. */
4614 val = call5 (Vselect_safe_coding_system_function,
4615 start, end, val, Qnil, filename);
4617 /* If the decided coding-system doesn't specify end-of-line
4618 format, we use that of
4619 `default-buffer-file-coding-system'. */
4620 if (! using_default_coding
4621 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4622 val = (coding_inherit_eol_type
4623 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4625 /* If we decide not to encode text, use `raw-text' or one of its
4626 subsidiaries. */
4627 if (force_raw_text)
4628 val = raw_text_coding_system (val);
4631 val = coding_inherit_eol_type (val, eol_parent);
4632 setup_coding_system (val, coding);
4634 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4635 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4636 return val;
4639 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4640 "r\nFWrite region to file: \ni\ni\ni\np",
4641 doc: /* Write current region into specified file.
4642 When called from a program, requires three arguments:
4643 START, END and FILENAME. START and END are normally buffer positions
4644 specifying the part of the buffer to write.
4645 If START is nil, that means to use the entire buffer contents.
4646 If START is a string, then output that string to the file
4647 instead of any buffer contents; END is ignored.
4649 Optional fourth argument APPEND if non-nil means
4650 append to existing file contents (if any). If it is a number,
4651 seek to that offset in the file before writing.
4652 Optional fifth argument VISIT, if t or a string, means
4653 set the last-save-file-modtime of buffer to this file's modtime
4654 and mark buffer not modified.
4655 If VISIT is a string, it is a second file name;
4656 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4657 VISIT is also the file name to lock and unlock for clash detection.
4658 If VISIT is neither t nor nil nor a string,
4659 that means do not display the \"Wrote file\" message.
4660 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4661 use for locking and unlocking, overriding FILENAME and VISIT.
4662 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4663 for an existing file with the same name. If MUSTBENEW is `excl',
4664 that means to get an error if the file already exists; never overwrite.
4665 If MUSTBENEW is neither nil nor `excl', that means ask for
4666 confirmation before overwriting, but do go ahead and overwrite the file
4667 if the user confirms.
4669 This does code conversion according to the value of
4670 `coding-system-for-write', `buffer-file-coding-system', or
4671 `file-coding-system-alist', and sets the variable
4672 `last-coding-system-used' to the coding system actually used.
4674 This calls `write-region-annotate-functions' at the start, and
4675 `write-region-post-annotation-function' at the end. */)
4676 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4677 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4679 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4680 -1);
4683 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4684 descriptor for FILENAME, so do not open or close FILENAME. */
4686 Lisp_Object
4687 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4688 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4689 Lisp_Object mustbenew, int desc)
4691 int open_flags;
4692 int mode;
4693 off_t offset IF_LINT (= 0);
4694 bool open_and_close_file = desc < 0;
4695 bool ok;
4696 int save_errno = 0;
4697 const char *fn;
4698 struct stat st;
4699 struct timespec modtime;
4700 ptrdiff_t count = SPECPDL_INDEX ();
4701 ptrdiff_t count1 IF_LINT (= 0);
4702 Lisp_Object handler;
4703 Lisp_Object visit_file;
4704 Lisp_Object annotations;
4705 Lisp_Object encoded_filename;
4706 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4707 bool quietly = !NILP (visit);
4708 bool file_locked = 0;
4709 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4710 struct buffer *given_buffer;
4711 struct coding_system coding;
4713 if (current_buffer->base_buffer && visiting)
4714 error ("Cannot do file visiting in an indirect buffer");
4716 if (!NILP (start) && !STRINGP (start))
4717 validate_region (&start, &end);
4719 visit_file = Qnil;
4720 GCPRO5 (start, filename, visit, visit_file, lockname);
4722 filename = Fexpand_file_name (filename, Qnil);
4724 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4725 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4727 if (STRINGP (visit))
4728 visit_file = Fexpand_file_name (visit, Qnil);
4729 else
4730 visit_file = filename;
4732 if (NILP (lockname))
4733 lockname = visit_file;
4735 annotations = Qnil;
4737 /* If the file name has special constructs in it,
4738 call the corresponding file handler. */
4739 handler = Ffind_file_name_handler (filename, Qwrite_region);
4740 /* If FILENAME has no handler, see if VISIT has one. */
4741 if (NILP (handler) && STRINGP (visit))
4742 handler = Ffind_file_name_handler (visit, Qwrite_region);
4744 if (!NILP (handler))
4746 Lisp_Object val;
4747 val = call6 (handler, Qwrite_region, start, end,
4748 filename, append, visit);
4750 if (visiting)
4752 SAVE_MODIFF = MODIFF;
4753 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4754 bset_filename (current_buffer, visit_file);
4756 UNGCPRO;
4757 return val;
4760 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4762 /* Special kludge to simplify auto-saving. */
4763 if (NILP (start))
4765 /* Do it later, so write-region-annotate-function can work differently
4766 if we save "the buffer" vs "a region".
4767 This is useful in tar-mode. --Stef
4768 XSETFASTINT (start, BEG);
4769 XSETFASTINT (end, Z); */
4770 Fwiden ();
4773 record_unwind_protect (build_annotations_unwind,
4774 Vwrite_region_annotation_buffers);
4775 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4777 given_buffer = current_buffer;
4779 if (!STRINGP (start))
4781 annotations = build_annotations (start, end);
4783 if (current_buffer != given_buffer)
4785 XSETFASTINT (start, BEGV);
4786 XSETFASTINT (end, ZV);
4790 if (NILP (start))
4792 XSETFASTINT (start, BEGV);
4793 XSETFASTINT (end, ZV);
4796 UNGCPRO;
4798 GCPRO5 (start, filename, annotations, visit_file, lockname);
4800 /* Decide the coding-system to encode the data with.
4801 We used to make this choice before calling build_annotations, but that
4802 leads to problems when a write-annotate-function takes care of
4803 unsavable chars (as was the case with X-Symbol). */
4804 Vlast_coding_system_used
4805 = choose_write_coding_system (start, end, filename,
4806 append, visit, lockname, &coding);
4808 #ifdef CLASH_DETECTION
4809 if (open_and_close_file && !auto_saving)
4811 lock_file (lockname);
4812 file_locked = 1;
4814 #endif /* CLASH_DETECTION */
4816 encoded_filename = ENCODE_FILE (filename);
4817 fn = SSDATA (encoded_filename);
4818 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4819 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4820 if (NUMBERP (append))
4821 offset = file_offset (append);
4822 else if (!NILP (append))
4823 open_flags |= O_APPEND;
4824 #ifdef DOS_NT
4825 mode = S_IREAD | S_IWRITE;
4826 #else
4827 mode = auto_saving ? auto_save_mode_bits : 0666;
4828 #endif
4830 if (open_and_close_file)
4832 desc = emacs_open (fn, open_flags, mode);
4833 if (desc < 0)
4835 int open_errno = errno;
4836 #ifdef CLASH_DETECTION
4837 if (file_locked)
4838 unlock_file (lockname);
4839 #endif /* CLASH_DETECTION */
4840 UNGCPRO;
4841 report_file_errno ("Opening output file", filename, open_errno);
4844 count1 = SPECPDL_INDEX ();
4845 record_unwind_protect_int (close_file_unwind, desc);
4848 if (NUMBERP (append))
4850 off_t ret = lseek (desc, offset, SEEK_SET);
4851 if (ret < 0)
4853 int lseek_errno = errno;
4854 #ifdef CLASH_DETECTION
4855 if (file_locked)
4856 unlock_file (lockname);
4857 #endif /* CLASH_DETECTION */
4858 UNGCPRO;
4859 report_file_errno ("Lseek error", filename, lseek_errno);
4863 UNGCPRO;
4865 immediate_quit = 1;
4867 if (STRINGP (start))
4868 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4869 else if (XINT (start) != XINT (end))
4870 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4871 &annotations, &coding);
4872 else
4874 /* If file was empty, still need to write the annotations. */
4875 coding.mode |= CODING_MODE_LAST_BLOCK;
4876 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4878 save_errno = errno;
4880 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4881 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4883 /* We have to flush out a data. */
4884 coding.mode |= CODING_MODE_LAST_BLOCK;
4885 ok = e_write (desc, Qnil, 1, 1, &coding);
4886 save_errno = errno;
4889 immediate_quit = 0;
4891 /* fsync is not crucial for temporary files. Nor for auto-save
4892 files, since they might lose some work anyway. */
4893 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4895 /* Transfer data and metadata to disk, retrying if interrupted.
4896 fsync can report a write failure here, e.g., due to disk full
4897 under NFS. But ignore EINVAL, which means fsync is not
4898 supported on this file. */
4899 while (fsync (desc) != 0)
4900 if (errno != EINTR)
4902 if (errno != EINVAL)
4903 ok = 0, save_errno = errno;
4904 break;
4908 modtime = invalid_timespec ();
4909 if (visiting)
4911 if (fstat (desc, &st) == 0)
4912 modtime = get_stat_mtime (&st);
4913 else
4914 ok = 0, save_errno = errno;
4917 if (open_and_close_file)
4919 /* NFS can report a write failure now. */
4920 if (emacs_close (desc) < 0)
4921 ok = 0, save_errno = errno;
4923 /* Discard the unwind protect for close_file_unwind. */
4924 specpdl_ptr = specpdl + count1;
4927 /* Some file systems have a bug where st_mtime is not updated
4928 properly after a write. For example, CIFS might not see the
4929 st_mtime change until after the file is opened again.
4931 Attempt to detect this file system bug, and update MODTIME to the
4932 newer st_mtime if the bug appears to be present. This introduces
4933 a race condition, so to avoid most instances of the race condition
4934 on non-buggy file systems, skip this check if the most recently
4935 encountered non-buggy file system was the current file system.
4937 A race condition can occur if some other process modifies the
4938 file between the fstat above and the fstat below, but the race is
4939 unlikely and a similar race between the last write and the fstat
4940 above cannot possibly be closed anyway. */
4942 if (timespec_valid_p (modtime)
4943 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4945 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4946 if (desc1 >= 0)
4948 struct stat st1;
4949 if (fstat (desc1, &st1) == 0
4950 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4952 /* Use the heuristic if it appears to be valid. With neither
4953 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4954 file, the time stamp won't change. Also, some non-POSIX
4955 systems don't update an empty file's time stamp when
4956 truncating it. Finally, file systems with 100 ns or worse
4957 resolution sometimes seem to have bugs: on a system with ns
4958 resolution, checking ns % 100 incorrectly avoids the heuristic
4959 1% of the time, but the problem should be temporary as we will
4960 try again on the next time stamp. */
4961 bool use_heuristic
4962 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4963 && st.st_size != 0
4964 && modtime.tv_nsec % 100 != 0);
4966 struct timespec modtime1 = get_stat_mtime (&st1);
4967 if (use_heuristic
4968 && timespec_cmp (modtime, modtime1) == 0
4969 && st.st_size == st1.st_size)
4971 timestamp_file_system = st.st_dev;
4972 valid_timestamp_file_system = 1;
4974 else
4976 st.st_size = st1.st_size;
4977 modtime = modtime1;
4980 emacs_close (desc1);
4984 /* Call write-region-post-annotation-function. */
4985 while (CONSP (Vwrite_region_annotation_buffers))
4987 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4988 if (!NILP (Fbuffer_live_p (buf)))
4990 Fset_buffer (buf);
4991 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4992 call0 (Vwrite_region_post_annotation_function);
4994 Vwrite_region_annotation_buffers
4995 = XCDR (Vwrite_region_annotation_buffers);
4998 unbind_to (count, Qnil);
5000 #ifdef CLASH_DETECTION
5001 if (file_locked)
5002 unlock_file (lockname);
5003 #endif /* CLASH_DETECTION */
5005 /* Do this before reporting IO error
5006 to avoid a "file has changed on disk" warning on
5007 next attempt to save. */
5008 if (timespec_valid_p (modtime))
5010 current_buffer->modtime = modtime;
5011 current_buffer->modtime_size = st.st_size;
5014 if (! ok)
5015 report_file_errno ("Write error", filename, save_errno);
5017 if (visiting)
5019 SAVE_MODIFF = MODIFF;
5020 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5021 bset_filename (current_buffer, visit_file);
5022 update_mode_lines = 14;
5024 else if (quietly)
5026 if (auto_saving
5027 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5028 BVAR (current_buffer, auto_save_file_name))))
5029 SAVE_MODIFF = MODIFF;
5031 return Qnil;
5034 if (!auto_saving)
5035 message_with_string ((NUMBERP (append)
5036 ? "Updated %s"
5037 : ! NILP (append)
5038 ? "Added to %s"
5039 : "Wrote %s"),
5040 visit_file, 1);
5042 return Qnil;
5045 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5046 doc: /* Return t if (car A) is numerically less than (car B). */)
5047 (Lisp_Object a, Lisp_Object b)
5049 Lisp_Object args[2];
5050 args[0] = Fcar (a);
5051 args[1] = Fcar (b);
5052 return Flss (2, args);
5055 /* Build the complete list of annotations appropriate for writing out
5056 the text between START and END, by calling all the functions in
5057 write-region-annotate-functions and merging the lists they return.
5058 If one of these functions switches to a different buffer, we assume
5059 that buffer contains altered text. Therefore, the caller must
5060 make sure to restore the current buffer in all cases,
5061 as save-excursion would do. */
5063 static Lisp_Object
5064 build_annotations (Lisp_Object start, Lisp_Object end)
5066 Lisp_Object annotations;
5067 Lisp_Object p, res;
5068 struct gcpro gcpro1, gcpro2;
5069 Lisp_Object original_buffer;
5070 int i;
5071 bool used_global = 0;
5073 XSETBUFFER (original_buffer, current_buffer);
5075 annotations = Qnil;
5076 p = Vwrite_region_annotate_functions;
5077 GCPRO2 (annotations, p);
5078 while (CONSP (p))
5080 struct buffer *given_buffer = current_buffer;
5081 if (EQ (Qt, XCAR (p)) && !used_global)
5082 { /* Use the global value of the hook. */
5083 Lisp_Object arg[2];
5084 used_global = 1;
5085 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
5086 arg[1] = XCDR (p);
5087 p = Fappend (2, arg);
5088 continue;
5090 Vwrite_region_annotations_so_far = annotations;
5091 res = call2 (XCAR (p), start, end);
5092 /* If the function makes a different buffer current,
5093 assume that means this buffer contains altered text to be output.
5094 Reset START and END from the buffer bounds
5095 and discard all previous annotations because they should have
5096 been dealt with by this function. */
5097 if (current_buffer != given_buffer)
5099 Vwrite_region_annotation_buffers
5100 = Fcons (Fcurrent_buffer (),
5101 Vwrite_region_annotation_buffers);
5102 XSETFASTINT (start, BEGV);
5103 XSETFASTINT (end, ZV);
5104 annotations = Qnil;
5106 Flength (res); /* Check basic validity of return value */
5107 annotations = merge (annotations, res, Qcar_less_than_car);
5108 p = XCDR (p);
5111 /* Now do the same for annotation functions implied by the file-format */
5112 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5113 p = BVAR (current_buffer, auto_save_file_format);
5114 else
5115 p = BVAR (current_buffer, file_format);
5116 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5118 struct buffer *given_buffer = current_buffer;
5120 Vwrite_region_annotations_so_far = annotations;
5122 /* Value is either a list of annotations or nil if the function
5123 has written annotations to a temporary buffer, which is now
5124 current. */
5125 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5126 original_buffer, make_number (i));
5127 if (current_buffer != given_buffer)
5129 XSETFASTINT (start, BEGV);
5130 XSETFASTINT (end, ZV);
5131 annotations = Qnil;
5134 if (CONSP (res))
5135 annotations = merge (annotations, res, Qcar_less_than_car);
5138 UNGCPRO;
5139 return annotations;
5143 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5144 If STRING is nil, POS is the character position in the current buffer.
5145 Intersperse with them the annotations from *ANNOT
5146 which fall within the range of POS to POS + NCHARS,
5147 each at its appropriate position.
5149 We modify *ANNOT by discarding elements as we use them up.
5151 Return true if successful. */
5153 static bool
5154 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5155 ptrdiff_t nchars, Lisp_Object *annot,
5156 struct coding_system *coding)
5158 Lisp_Object tem;
5159 ptrdiff_t nextpos;
5160 ptrdiff_t lastpos = pos + nchars;
5162 while (NILP (*annot) || CONSP (*annot))
5164 tem = Fcar_safe (Fcar (*annot));
5165 nextpos = pos - 1;
5166 if (INTEGERP (tem))
5167 nextpos = XFASTINT (tem);
5169 /* If there are no more annotations in this range,
5170 output the rest of the range all at once. */
5171 if (! (nextpos >= pos && nextpos <= lastpos))
5172 return e_write (desc, string, pos, lastpos, coding);
5174 /* Output buffer text up to the next annotation's position. */
5175 if (nextpos > pos)
5177 if (!e_write (desc, string, pos, nextpos, coding))
5178 return 0;
5179 pos = nextpos;
5181 /* Output the annotation. */
5182 tem = Fcdr (Fcar (*annot));
5183 if (STRINGP (tem))
5185 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5186 return 0;
5188 *annot = Fcdr (*annot);
5190 return 1;
5193 /* Maximum number of characters that the next
5194 function encodes per one loop iteration. */
5196 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5198 /* Write text in the range START and END into descriptor DESC,
5199 encoding them with coding system CODING. If STRING is nil, START
5200 and END are character positions of the current buffer, else they
5201 are indexes to the string STRING. Return true if successful. */
5203 static bool
5204 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5205 struct coding_system *coding)
5207 if (STRINGP (string))
5209 start = 0;
5210 end = SCHARS (string);
5213 /* We used to have a code for handling selective display here. But,
5214 now it is handled within encode_coding. */
5216 while (start < end)
5218 if (STRINGP (string))
5220 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5221 if (CODING_REQUIRE_ENCODING (coding))
5223 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5225 /* Avoid creating huge Lisp string in encode_coding_object. */
5226 if (nchars == E_WRITE_MAX)
5227 coding->raw_destination = 1;
5229 encode_coding_object
5230 (coding, string, start, string_char_to_byte (string, start),
5231 start + nchars, string_char_to_byte (string, start + nchars),
5232 Qt);
5234 else
5236 coding->dst_object = string;
5237 coding->consumed_char = SCHARS (string);
5238 coding->produced = SBYTES (string);
5241 else
5243 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5244 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5246 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5247 if (CODING_REQUIRE_ENCODING (coding))
5249 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5251 /* Likewise. */
5252 if (nchars == E_WRITE_MAX)
5253 coding->raw_destination = 1;
5255 encode_coding_object
5256 (coding, Fcurrent_buffer (), start, start_byte,
5257 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5259 else
5261 coding->dst_object = Qnil;
5262 coding->dst_pos_byte = start_byte;
5263 if (start >= GPT || end <= GPT)
5265 coding->consumed_char = end - start;
5266 coding->produced = end_byte - start_byte;
5268 else
5270 coding->consumed_char = GPT - start;
5271 coding->produced = GPT_BYTE - start_byte;
5276 if (coding->produced > 0)
5278 char *buf = (coding->raw_destination ? (char *) coding->destination
5279 : (STRINGP (coding->dst_object)
5280 ? SSDATA (coding->dst_object)
5281 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5282 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5284 if (coding->raw_destination)
5286 /* We're responsible for freeing this, see
5287 encode_coding_object to check why. */
5288 xfree (coding->destination);
5289 coding->raw_destination = 0;
5291 if (coding->produced)
5292 return 0;
5294 start += coding->consumed_char;
5297 return 1;
5300 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5301 Sverify_visited_file_modtime, 0, 1, 0,
5302 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5303 This means that the file has not been changed since it was visited or saved.
5304 If BUF is omitted or nil, it defaults to the current buffer.
5305 See Info node `(elisp)Modification Time' for more details. */)
5306 (Lisp_Object buf)
5308 struct buffer *b;
5309 struct stat st;
5310 Lisp_Object handler;
5311 Lisp_Object filename;
5312 struct timespec mtime;
5314 if (NILP (buf))
5315 b = current_buffer;
5316 else
5318 CHECK_BUFFER (buf);
5319 b = XBUFFER (buf);
5322 if (!STRINGP (BVAR (b, filename))) return Qt;
5323 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5325 /* If the file name has special constructs in it,
5326 call the corresponding file handler. */
5327 handler = Ffind_file_name_handler (BVAR (b, filename),
5328 Qverify_visited_file_modtime);
5329 if (!NILP (handler))
5330 return call2 (handler, Qverify_visited_file_modtime, buf);
5332 filename = ENCODE_FILE (BVAR (b, filename));
5334 mtime = (stat (SSDATA (filename), &st) == 0
5335 ? get_stat_mtime (&st)
5336 : time_error_value (errno));
5337 if (timespec_cmp (mtime, b->modtime) == 0
5338 && (b->modtime_size < 0
5339 || st.st_size == b->modtime_size))
5340 return Qt;
5341 return Qnil;
5344 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5345 Svisited_file_modtime, 0, 0, 0,
5346 doc: /* Return the current buffer's recorded visited file modification time.
5347 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5348 `file-attributes' returns. If the current buffer has no recorded file
5349 modification time, this function returns 0. If the visited file
5350 doesn't exist, return -1.
5351 See Info node `(elisp)Modification Time' for more details. */)
5352 (void)
5354 int ns = current_buffer->modtime.tv_nsec;
5355 if (ns < 0)
5356 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5357 return make_lisp_time (current_buffer->modtime);
5360 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5361 Sset_visited_file_modtime, 0, 1, 0,
5362 doc: /* Update buffer's recorded modification time from the visited file's time.
5363 Useful if the buffer was not read from the file normally
5364 or if the file itself has been changed for some known benign reason.
5365 An argument specifies the modification time value to use
5366 \(instead of that of the visited file), in the form of a list
5367 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5368 `visited-file-modtime'. */)
5369 (Lisp_Object time_flag)
5371 if (!NILP (time_flag))
5373 struct timespec mtime;
5374 if (INTEGERP (time_flag))
5376 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5377 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5379 else
5380 mtime = lisp_time_argument (time_flag);
5382 current_buffer->modtime = mtime;
5383 current_buffer->modtime_size = -1;
5385 else
5387 register Lisp_Object filename;
5388 struct stat st;
5389 Lisp_Object handler;
5391 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5393 /* If the file name has special constructs in it,
5394 call the corresponding file handler. */
5395 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5396 if (!NILP (handler))
5397 /* The handler can find the file name the same way we did. */
5398 return call2 (handler, Qset_visited_file_modtime, Qnil);
5400 filename = ENCODE_FILE (filename);
5402 if (stat (SSDATA (filename), &st) >= 0)
5404 current_buffer->modtime = get_stat_mtime (&st);
5405 current_buffer->modtime_size = st.st_size;
5409 return Qnil;
5412 static Lisp_Object
5413 auto_save_error (Lisp_Object error_val)
5415 Lisp_Object args[3], msg;
5416 int i;
5417 struct gcpro gcpro1;
5419 auto_save_error_occurred = 1;
5421 ring_bell (XFRAME (selected_frame));
5423 args[0] = build_string ("Auto-saving %s: %s");
5424 args[1] = BVAR (current_buffer, name);
5425 args[2] = Ferror_message_string (error_val);
5426 msg = Fformat (3, args);
5427 GCPRO1 (msg);
5429 for (i = 0; i < 3; ++i)
5431 if (i == 0)
5432 message3 (msg);
5433 else
5434 message3_nolog (msg);
5435 Fsleep_for (make_number (1), Qnil);
5438 UNGCPRO;
5439 return Qnil;
5442 static Lisp_Object
5443 auto_save_1 (void)
5445 struct stat st;
5446 Lisp_Object modes;
5448 auto_save_mode_bits = 0666;
5450 /* Get visited file's mode to become the auto save file's mode. */
5451 if (! NILP (BVAR (current_buffer, filename)))
5453 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5454 /* But make sure we can overwrite it later! */
5455 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5456 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5457 INTEGERP (modes))
5458 /* Remote files don't cooperate with stat. */
5459 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5462 return
5463 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5464 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5465 Qnil, Qnil);
5468 struct auto_save_unwind
5470 FILE *stream;
5471 bool auto_raise;
5474 static void
5475 do_auto_save_unwind (void *arg)
5477 struct auto_save_unwind *p = arg;
5478 FILE *stream = p->stream;
5479 minibuffer_auto_raise = p->auto_raise;
5480 auto_saving = 0;
5481 if (stream != NULL)
5483 block_input ();
5484 fclose (stream);
5485 unblock_input ();
5489 static Lisp_Object
5490 do_auto_save_make_dir (Lisp_Object dir)
5492 Lisp_Object result;
5494 auto_saving_dir_umask = 077;
5495 result = call2 (Qmake_directory, dir, Qt);
5496 auto_saving_dir_umask = 0;
5497 return result;
5500 static Lisp_Object
5501 do_auto_save_eh (Lisp_Object ignore)
5503 auto_saving_dir_umask = 0;
5504 return Qnil;
5507 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5508 doc: /* Auto-save all buffers that need it.
5509 This is all buffers that have auto-saving enabled
5510 and are changed since last auto-saved.
5511 Auto-saving writes the buffer into a file
5512 so that your editing is not lost if the system crashes.
5513 This file is not the file you visited; that changes only when you save.
5514 Normally we run the normal hook `auto-save-hook' before saving.
5516 A non-nil NO-MESSAGE argument means do not print any message if successful.
5517 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5518 (Lisp_Object no_message, Lisp_Object current_only)
5520 struct buffer *old = current_buffer, *b;
5521 Lisp_Object tail, buf, hook;
5522 bool auto_saved = 0;
5523 int do_handled_files;
5524 Lisp_Object oquit;
5525 FILE *stream = NULL;
5526 ptrdiff_t count = SPECPDL_INDEX ();
5527 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5528 bool old_message_p = 0;
5529 struct auto_save_unwind auto_save_unwind;
5530 struct gcpro gcpro1, gcpro2;
5532 if (max_specpdl_size < specpdl_size + 40)
5533 max_specpdl_size = specpdl_size + 40;
5535 if (minibuf_level)
5536 no_message = Qt;
5538 if (NILP (no_message))
5540 old_message_p = push_message ();
5541 record_unwind_protect_void (pop_message_unwind);
5544 /* Ordinarily don't quit within this function,
5545 but don't make it impossible to quit (in case we get hung in I/O). */
5546 oquit = Vquit_flag;
5547 Vquit_flag = Qnil;
5549 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5550 point to non-strings reached from Vbuffer_alist. */
5552 hook = intern ("auto-save-hook");
5553 safe_run_hooks (hook);
5555 if (STRINGP (Vauto_save_list_file_name))
5557 Lisp_Object listfile;
5559 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5561 /* Don't try to create the directory when shutting down Emacs,
5562 because creating the directory might signal an error, and
5563 that would leave Emacs in a strange state. */
5564 if (!NILP (Vrun_hooks))
5566 Lisp_Object dir;
5567 dir = Qnil;
5568 GCPRO2 (dir, listfile);
5569 dir = Ffile_name_directory (listfile);
5570 if (NILP (Ffile_directory_p (dir)))
5571 internal_condition_case_1 (do_auto_save_make_dir,
5572 dir, Qt,
5573 do_auto_save_eh);
5574 UNGCPRO;
5577 stream = emacs_fopen (SSDATA (listfile), "w");
5580 auto_save_unwind.stream = stream;
5581 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5582 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5583 minibuffer_auto_raise = 0;
5584 auto_saving = 1;
5585 auto_save_error_occurred = 0;
5587 /* On first pass, save all files that don't have handlers.
5588 On second pass, save all files that do have handlers.
5590 If Emacs is crashing, the handlers may tweak what is causing
5591 Emacs to crash in the first place, and it would be a shame if
5592 Emacs failed to autosave perfectly ordinary files because it
5593 couldn't handle some ange-ftp'd file. */
5595 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5596 FOR_EACH_LIVE_BUFFER (tail, buf)
5598 b = XBUFFER (buf);
5600 /* Record all the buffers that have auto save mode
5601 in the special file that lists them. For each of these buffers,
5602 Record visited name (if any) and auto save name. */
5603 if (STRINGP (BVAR (b, auto_save_file_name))
5604 && stream != NULL && do_handled_files == 0)
5606 block_input ();
5607 if (!NILP (BVAR (b, filename)))
5609 fwrite (SDATA (BVAR (b, filename)), 1,
5610 SBYTES (BVAR (b, filename)), stream);
5612 putc ('\n', stream);
5613 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5614 SBYTES (BVAR (b, auto_save_file_name)), stream);
5615 putc ('\n', stream);
5616 unblock_input ();
5619 if (!NILP (current_only)
5620 && b != current_buffer)
5621 continue;
5623 /* Don't auto-save indirect buffers.
5624 The base buffer takes care of it. */
5625 if (b->base_buffer)
5626 continue;
5628 /* Check for auto save enabled
5629 and file changed since last auto save
5630 and file changed since last real save. */
5631 if (STRINGP (BVAR (b, auto_save_file_name))
5632 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5633 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5634 /* -1 means we've turned off autosaving for a while--see below. */
5635 && XINT (BVAR (b, save_length)) >= 0
5636 && (do_handled_files
5637 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5638 Qwrite_region))))
5640 struct timespec before_time = current_timespec ();
5641 struct timespec after_time;
5643 /* If we had a failure, don't try again for 20 minutes. */
5644 if (b->auto_save_failure_time > 0
5645 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5646 continue;
5648 set_buffer_internal (b);
5649 if (NILP (Vauto_save_include_big_deletions)
5650 && (XFASTINT (BVAR (b, save_length)) * 10
5651 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5652 /* A short file is likely to change a large fraction;
5653 spare the user annoying messages. */
5654 && XFASTINT (BVAR (b, save_length)) > 5000
5655 /* These messages are frequent and annoying for `*mail*'. */
5656 && !EQ (BVAR (b, filename), Qnil)
5657 && NILP (no_message))
5659 /* It has shrunk too much; turn off auto-saving here. */
5660 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5661 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5662 BVAR (b, name), 1);
5663 minibuffer_auto_raise = 0;
5664 /* Turn off auto-saving until there's a real save,
5665 and prevent any more warnings. */
5666 XSETINT (BVAR (b, save_length), -1);
5667 Fsleep_for (make_number (1), Qnil);
5668 continue;
5670 if (!auto_saved && NILP (no_message))
5671 message1 ("Auto-saving...");
5672 internal_condition_case (auto_save_1, Qt, auto_save_error);
5673 auto_saved = 1;
5674 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5675 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5676 set_buffer_internal (old);
5678 after_time = current_timespec ();
5680 /* If auto-save took more than 60 seconds,
5681 assume it was an NFS failure that got a timeout. */
5682 if (after_time.tv_sec - before_time.tv_sec > 60)
5683 b->auto_save_failure_time = after_time.tv_sec;
5687 /* Prevent another auto save till enough input events come in. */
5688 record_auto_save ();
5690 if (auto_saved && NILP (no_message))
5692 if (old_message_p)
5694 /* If we are going to restore an old message,
5695 give time to read ours. */
5696 sit_for (make_number (1), 0, 0);
5697 restore_message ();
5699 else if (!auto_save_error_occurred)
5700 /* Don't overwrite the error message if an error occurred.
5701 If we displayed a message and then restored a state
5702 with no message, leave a "done" message on the screen. */
5703 message1 ("Auto-saving...done");
5706 Vquit_flag = oquit;
5708 /* This restores the message-stack status. */
5709 unbind_to (count, Qnil);
5710 return Qnil;
5713 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5714 Sset_buffer_auto_saved, 0, 0, 0,
5715 doc: /* Mark current buffer as auto-saved with its current text.
5716 No auto-save file will be written until the buffer changes again. */)
5717 (void)
5719 /* FIXME: This should not be called in indirect buffers, since
5720 they're not autosaved. */
5721 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5722 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5723 current_buffer->auto_save_failure_time = 0;
5724 return Qnil;
5727 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5728 Sclear_buffer_auto_save_failure, 0, 0, 0,
5729 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5730 (void)
5732 current_buffer->auto_save_failure_time = 0;
5733 return Qnil;
5736 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5737 0, 0, 0,
5738 doc: /* Return t if current buffer has been auto-saved recently.
5739 More precisely, if it has been auto-saved since last read from or saved
5740 in the visited file. If the buffer has no visited file,
5741 then any auto-save counts as "recent". */)
5742 (void)
5744 /* FIXME: maybe we should return nil for indirect buffers since
5745 they're never autosaved. */
5746 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5749 /* Reading and completing file names */
5751 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5752 Snext_read_file_uses_dialog_p, 0, 0, 0,
5753 doc: /* Return t if a call to `read-file-name' will use a dialog.
5754 The return value is only relevant for a call to `read-file-name' that happens
5755 before any other event (mouse or keypress) is handled. */)
5756 (void)
5758 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) \
5759 || defined (HAVE_NS)
5760 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5761 && use_dialog_box
5762 && use_file_dialog
5763 && window_system_available (SELECTED_FRAME ()))
5764 return Qt;
5765 #endif
5766 return Qnil;
5769 Lisp_Object
5770 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5772 struct gcpro gcpro1;
5773 Lisp_Object args[7];
5775 GCPRO1 (default_filename);
5776 args[0] = intern ("read-file-name");
5777 args[1] = prompt;
5778 args[2] = dir;
5779 args[3] = default_filename;
5780 args[4] = mustmatch;
5781 args[5] = initial;
5782 args[6] = predicate;
5783 RETURN_UNGCPRO (Ffuncall (7, args));
5787 void
5788 init_fileio (void)
5790 realmask = umask (0);
5791 umask (realmask);
5793 valid_timestamp_file_system = 0;
5795 /* fsync can be a significant performance hit. Often it doesn't
5796 suffice to make the file-save operation survive a crash. For
5797 batch scripts, which are typically part of larger shell commands
5798 that don't fsync other files, its effect on performance can be
5799 significant so its utility is particularly questionable.
5800 Hence, for now by default fsync is used only when interactive.
5802 For more on why fsync often fails to work on today's hardware, see:
5803 Zheng M et al. Understanding the robustness of SSDs under power fault.
5804 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5805 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5807 For more on why fsync does not suffice even if it works properly, see:
5808 Roche X. Necessary step(s) to synchronize filename operations on disk.
5809 Austin Group Defect 672, 2013-03-19
5810 http://austingroupbugs.net/view.php?id=672 */
5811 write_region_inhibit_fsync = noninteractive;
5814 void
5815 syms_of_fileio (void)
5817 DEFSYM (Qoperations, "operations");
5818 DEFSYM (Qexpand_file_name, "expand-file-name");
5819 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5820 DEFSYM (Qdirectory_file_name, "directory-file-name");
5821 DEFSYM (Qfile_name_directory, "file-name-directory");
5822 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5823 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5824 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5825 DEFSYM (Qcopy_file, "copy-file");
5826 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5827 DEFSYM (Qmake_directory, "make-directory");
5828 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5829 DEFSYM (Qdelete_file, "delete-file");
5830 DEFSYM (Qrename_file, "rename-file");
5831 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5832 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5833 DEFSYM (Qfile_exists_p, "file-exists-p");
5834 DEFSYM (Qfile_executable_p, "file-executable-p");
5835 DEFSYM (Qfile_readable_p, "file-readable-p");
5836 DEFSYM (Qfile_writable_p, "file-writable-p");
5837 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5838 DEFSYM (Qaccess_file, "access-file");
5839 DEFSYM (Qfile_directory_p, "file-directory-p");
5840 DEFSYM (Qfile_regular_p, "file-regular-p");
5841 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5842 DEFSYM (Qfile_modes, "file-modes");
5843 DEFSYM (Qset_file_modes, "set-file-modes");
5844 DEFSYM (Qset_file_times, "set-file-times");
5845 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5846 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5847 DEFSYM (Qfile_acl, "file-acl");
5848 DEFSYM (Qset_file_acl, "set-file-acl");
5849 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5850 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5851 DEFSYM (Qwrite_region, "write-region");
5852 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5853 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5854 DEFSYM (Qauto_save_coding, "auto-save-coding");
5856 DEFSYM (Qfile_name_history, "file-name-history");
5857 Fset (Qfile_name_history, Qnil);
5859 DEFSYM (Qfile_error, "file-error");
5860 DEFSYM (Qfile_already_exists, "file-already-exists");
5861 DEFSYM (Qfile_date_error, "file-date-error");
5862 DEFSYM (Qfile_notify_error, "file-notify-error");
5863 DEFSYM (Qexcl, "excl");
5865 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5866 doc: /* Coding system for encoding file names.
5867 If it is nil, `default-file-name-coding-system' (which see) is used.
5869 On MS-Windows, the value of this variable is largely ignored if
5870 \`w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5871 behaves as if file names were encoded in `utf-8'. */);
5872 Vfile_name_coding_system = Qnil;
5874 DEFVAR_LISP ("default-file-name-coding-system",
5875 Vdefault_file_name_coding_system,
5876 doc: /* Default coding system for encoding file names.
5877 This variable is used only when `file-name-coding-system' is nil.
5879 This variable is set/changed by the command `set-language-environment'.
5880 User should not set this variable manually,
5881 instead use `file-name-coding-system' to get a constant encoding
5882 of file names regardless of the current language environment.
5884 On MS-Windows, the value of this variable is largely ignored if
5885 \`w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5886 behaves as if file names were encoded in `utf-8'. */);
5887 Vdefault_file_name_coding_system = Qnil;
5889 DEFSYM (Qformat_decode, "format-decode");
5890 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5891 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5892 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5894 Fput (Qfile_error, Qerror_conditions,
5895 Fpurecopy (list2 (Qfile_error, Qerror)));
5896 Fput (Qfile_error, Qerror_message,
5897 build_pure_c_string ("File error"));
5899 Fput (Qfile_already_exists, Qerror_conditions,
5900 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5901 Fput (Qfile_already_exists, Qerror_message,
5902 build_pure_c_string ("File already exists"));
5904 Fput (Qfile_date_error, Qerror_conditions,
5905 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5906 Fput (Qfile_date_error, Qerror_message,
5907 build_pure_c_string ("Cannot set file date"));
5909 Fput (Qfile_notify_error, Qerror_conditions,
5910 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5911 Fput (Qfile_notify_error, Qerror_message,
5912 build_pure_c_string ("File notification error"));
5914 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5915 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5916 If a file name matches REGEXP, all I/O on that file is done by calling
5917 HANDLER. If a file name matches more than one handler, the handler
5918 whose match starts last in the file name gets precedence. The
5919 function `find-file-name-handler' checks this list for a handler for
5920 its argument.
5922 HANDLER should be a function. The first argument given to it is the
5923 name of the I/O primitive to be handled; the remaining arguments are
5924 the arguments that were passed to that primitive. For example, if you
5925 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5926 HANDLER is called like this:
5928 (funcall HANDLER 'file-exists-p FILENAME)
5930 Note that HANDLER must be able to handle all I/O primitives; if it has
5931 nothing special to do for a primitive, it should reinvoke the
5932 primitive to handle the operation \"the usual way\".
5933 See Info node `(elisp)Magic File Names' for more details. */);
5934 Vfile_name_handler_alist = Qnil;
5936 DEFVAR_LISP ("set-auto-coding-function",
5937 Vset_auto_coding_function,
5938 doc: /* If non-nil, a function to call to decide a coding system of file.
5939 Two arguments are passed to this function: the file name
5940 and the length of a file contents following the point.
5941 This function should return a coding system to decode the file contents.
5942 It should check the file name against `auto-coding-alist'.
5943 If no coding system is decided, it should check a coding system
5944 specified in the heading lines with the format:
5945 -*- ... coding: CODING-SYSTEM; ... -*-
5946 or local variable spec of the tailing lines with `coding:' tag. */);
5947 Vset_auto_coding_function = Qnil;
5949 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5950 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5951 Each is passed one argument, the number of characters inserted,
5952 with point at the start of the inserted text. Each function
5953 should leave point the same, and return the new character count.
5954 If `insert-file-contents' is intercepted by a handler from
5955 `file-name-handler-alist', that handler is responsible for calling the
5956 functions in `after-insert-file-functions' if appropriate. */);
5957 Vafter_insert_file_functions = Qnil;
5959 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5960 doc: /* A list of functions to be called at the start of `write-region'.
5961 Each is passed two arguments, START and END as for `write-region'.
5962 These are usually two numbers but not always; see the documentation
5963 for `write-region'. The function should return a list of pairs
5964 of the form (POSITION . STRING), consisting of strings to be effectively
5965 inserted at the specified positions of the file being written (1 means to
5966 insert before the first byte written). The POSITIONs must be sorted into
5967 increasing order.
5969 If there are several annotation functions, the lists returned by these
5970 functions are merged destructively. As each annotation function runs,
5971 the variable `write-region-annotations-so-far' contains a list of all
5972 annotations returned by previous annotation functions.
5974 An annotation function can return with a different buffer current.
5975 Doing so removes the annotations returned by previous functions, and
5976 resets START and END to `point-min' and `point-max' of the new buffer.
5978 After `write-region' completes, Emacs calls the function stored in
5979 `write-region-post-annotation-function', once for each buffer that was
5980 current when building the annotations (i.e., at least once), with that
5981 buffer current. */);
5982 Vwrite_region_annotate_functions = Qnil;
5983 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5985 DEFVAR_LISP ("write-region-post-annotation-function",
5986 Vwrite_region_post_annotation_function,
5987 doc: /* Function to call after `write-region' completes.
5988 The function is called with no arguments. If one or more of the
5989 annotation functions in `write-region-annotate-functions' changed the
5990 current buffer, the function stored in this variable is called for
5991 each of those additional buffers as well, in addition to the original
5992 buffer. The relevant buffer is current during each function call. */);
5993 Vwrite_region_post_annotation_function = Qnil;
5994 staticpro (&Vwrite_region_annotation_buffers);
5996 DEFVAR_LISP ("write-region-annotations-so-far",
5997 Vwrite_region_annotations_so_far,
5998 doc: /* When an annotation function is called, this holds the previous annotations.
5999 These are the annotations made by other annotation functions
6000 that were already called. See also `write-region-annotate-functions'. */);
6001 Vwrite_region_annotations_so_far = Qnil;
6003 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6004 doc: /* A list of file name handlers that temporarily should not be used.
6005 This applies only to the operation `inhibit-file-name-operation'. */);
6006 Vinhibit_file_name_handlers = Qnil;
6008 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6009 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6010 Vinhibit_file_name_operation = Qnil;
6012 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6013 doc: /* File name in which we write a list of all auto save file names.
6014 This variable is initialized automatically from `auto-save-list-file-prefix'
6015 shortly after Emacs reads your init file, if you have not yet given it
6016 a non-nil value. */);
6017 Vauto_save_list_file_name = Qnil;
6019 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6020 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6021 Normally auto-save files are written under other names. */);
6022 Vauto_save_visited_file_name = Qnil;
6024 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6025 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6026 If nil, deleting a substantial portion of the text disables auto-save
6027 in the buffer; this is the default behavior, because the auto-save
6028 file is usually more useful if it contains the deleted text. */);
6029 Vauto_save_include_big_deletions = Qnil;
6031 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6032 doc: /* Non-nil means don't call fsync in `write-region'.
6033 This variable affects calls to `write-region' as well as save commands.
6034 Setting this to nil may avoid data loss if the system loses power or
6035 the operating system crashes. By default, it is non-nil in batch mode. */);
6036 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6038 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6039 doc: /* Specifies whether to use the system's trash can.
6040 When non-nil, certain file deletion commands use the function
6041 `move-file-to-trash' instead of deleting files outright.
6042 This includes interactive calls to `delete-file' and
6043 `delete-directory' and the Dired deletion commands. */);
6044 delete_by_moving_to_trash = 0;
6045 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
6047 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6048 DEFSYM (Qcopy_directory, "copy-directory");
6049 DEFSYM (Qdelete_directory, "delete-directory");
6050 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6052 defsubr (&Sfind_file_name_handler);
6053 defsubr (&Sfile_name_directory);
6054 defsubr (&Sfile_name_nondirectory);
6055 defsubr (&Sunhandled_file_name_directory);
6056 defsubr (&Sfile_name_as_directory);
6057 defsubr (&Sdirectory_file_name);
6058 defsubr (&Smake_temp_name);
6059 defsubr (&Sexpand_file_name);
6060 defsubr (&Ssubstitute_in_file_name);
6061 defsubr (&Scopy_file);
6062 defsubr (&Smake_directory_internal);
6063 defsubr (&Sdelete_directory_internal);
6064 defsubr (&Sdelete_file);
6065 defsubr (&Srename_file);
6066 defsubr (&Sadd_name_to_file);
6067 defsubr (&Smake_symbolic_link);
6068 defsubr (&Sfile_name_absolute_p);
6069 defsubr (&Sfile_exists_p);
6070 defsubr (&Sfile_executable_p);
6071 defsubr (&Sfile_readable_p);
6072 defsubr (&Sfile_writable_p);
6073 defsubr (&Saccess_file);
6074 defsubr (&Sfile_symlink_p);
6075 defsubr (&Sfile_directory_p);
6076 defsubr (&Sfile_accessible_directory_p);
6077 defsubr (&Sfile_regular_p);
6078 defsubr (&Sfile_modes);
6079 defsubr (&Sset_file_modes);
6080 defsubr (&Sset_file_times);
6081 defsubr (&Sfile_selinux_context);
6082 defsubr (&Sfile_acl);
6083 defsubr (&Sset_file_acl);
6084 defsubr (&Sset_file_selinux_context);
6085 defsubr (&Sset_default_file_modes);
6086 defsubr (&Sdefault_file_modes);
6087 defsubr (&Sfile_newer_than_file_p);
6088 defsubr (&Sinsert_file_contents);
6089 defsubr (&Swrite_region);
6090 defsubr (&Scar_less_than_car);
6091 defsubr (&Sverify_visited_file_modtime);
6092 defsubr (&Svisited_file_modtime);
6093 defsubr (&Sset_visited_file_modtime);
6094 defsubr (&Sdo_auto_save);
6095 defsubr (&Sset_buffer_auto_saved);
6096 defsubr (&Sclear_buffer_auto_save_failure);
6097 defsubr (&Srecent_auto_save_p);
6099 defsubr (&Snext_read_file_uses_dialog_p);
6101 #ifdef HAVE_SYNC
6102 defsubr (&Sunix_sync);
6103 #endif