Merge from origin/emacs-25
[emacs.git] / src / fileio.c
blobea6e4aef9be5abfc1f5d92890c31324fccf7e83a
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2016 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 (at
10 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 #if USE_ACL && defined HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "composite.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"
55 #ifdef HAVE_LINUX_FS_H
56 # include <sys/ioctl.h>
57 # include <linux/fs.h>
58 #endif
60 #ifdef WINDOWSNT
61 #define NOMINMAX 1
62 #include <windows.h>
63 /* The redundant #ifdef is to avoid compiler warning about unused macro. */
64 #ifdef NOMINMAX
65 #undef NOMINMAX
66 #endif
67 #include <sys/file.h>
68 #include "w32.h"
69 #endif /* not WINDOWSNT */
71 #ifdef MSDOS
72 #include "msdos.h"
73 #include <sys/param.h>
74 #endif
76 #ifdef DOS_NT
77 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
78 redirector allows the six letters between 'Z' and 'a' as well. */
79 #ifdef MSDOS
80 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
81 #endif
82 #ifdef WINDOWSNT
83 #define IS_DRIVE(x) c_isalpha (x)
84 #endif
85 /* Need to lower-case the drive letter, or else expanded
86 filenames will sometimes compare unequal, because
87 `expand-file-name' doesn't always down-case the drive letter. */
88 #define DRIVE_LETTER(x) c_tolower (x)
89 #endif
91 #include "systime.h"
92 #include <acl.h>
93 #include <allocator.h>
94 #include <careadlinkat.h>
95 #include <stat-time.h>
97 #include <binary-io.h>
99 #ifdef HPUX
100 #include <netio.h>
101 #endif
103 #include "commands.h"
105 /* True during writing of auto-save files. */
106 static bool auto_saving;
108 /* Emacs's real umask. */
109 static mode_t realmask;
111 /* Nonzero umask during creation of auto-save directories. */
112 static mode_t auto_saving_dir_umask;
114 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
115 a new file with the same mode as the original. */
116 static mode_t auto_save_mode_bits;
118 /* Set by auto_save_1 if an error occurred during the last auto-save. */
119 static bool auto_save_error_occurred;
121 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
122 number of a file system where time stamps were observed to to work. */
123 static bool valid_timestamp_file_system;
124 static dev_t timestamp_file_system;
126 /* Each time an annotation function changes the buffer, the new buffer
127 is added here. */
128 static Lisp_Object Vwrite_region_annotation_buffers;
130 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
131 Lisp_Object *, struct coding_system *);
132 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
133 struct coding_system *);
136 /* Return true if FILENAME exists. */
138 static bool
139 check_existing (const char *filename)
141 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
144 /* Return true if file FILENAME exists and can be executed. */
146 static bool
147 check_executable (char *filename)
149 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
152 /* Return true if file FILENAME exists and can be accessed
153 according to AMODE, which should include W_OK.
154 On failure, return false and set errno. */
156 static bool
157 check_writable (const char *filename, int amode)
159 #ifdef MSDOS
160 /* FIXME: an faccessat implementation should be added to the
161 DOS/Windows ports and this #ifdef branch should be removed. */
162 struct stat st;
163 if (stat (filename, &st) < 0)
164 return 0;
165 errno = EPERM;
166 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
167 #else /* not MSDOS */
168 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
169 #ifdef CYGWIN
170 /* faccessat may have returned failure because Cygwin couldn't
171 determine the file's UID or GID; if so, we return success. */
172 if (!res)
174 int faccessat_errno = errno;
175 struct stat st;
176 if (stat (filename, &st) < 0)
177 return 0;
178 res = (st.st_uid == -1 || st.st_gid == -1);
179 errno = faccessat_errno;
181 #endif /* CYGWIN */
182 return res;
183 #endif /* not MSDOS */
186 /* Signal a file-access failure. STRING describes the failure,
187 NAME the file involved, and ERRORNO the errno value.
189 If NAME is neither null nor a pair, package it up as a singleton
190 list before reporting it; this saves report_file_errno's caller the
191 trouble of preserving errno before calling list1. */
193 void
194 report_file_errno (char const *string, Lisp_Object name, int errorno)
196 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
197 char *str = emacs_strerror (errorno);
198 AUTO_STRING (unibyte_str, str);
199 Lisp_Object errstring
200 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
201 Lisp_Object errdata = Fcons (errstring, data);
203 if (errorno == EEXIST)
204 xsignal (Qfile_already_exists, errdata);
205 else
206 xsignal (errorno == ENOENT ? Qfile_missing : Qfile_error,
207 Fcons (build_string (string), errdata));
210 /* Signal a file-access failure that set errno. STRING describes the
211 failure, NAME the file involved. When invoking this function, take
212 care to not use arguments such as build_string ("foo") that involve
213 side effects that may set errno. */
215 void
216 report_file_error (char const *string, Lisp_Object name)
218 report_file_errno (string, name, errno);
221 /* Like report_file_error, but reports a file-notify-error instead. */
223 void
224 report_file_notify_error (const char *string, Lisp_Object name)
226 char *str = emacs_strerror (errno);
227 AUTO_STRING (unibyte_str, str);
228 Lisp_Object errstring
229 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
230 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
231 Lisp_Object errdata = Fcons (errstring, data);
233 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
236 void
237 close_file_unwind (int fd)
239 emacs_close (fd);
242 void
243 fclose_unwind (void *arg)
245 FILE *stream = arg;
246 fclose (stream);
249 /* Restore point, having saved it as a marker. */
251 void
252 restore_point_unwind (Lisp_Object location)
254 Fgoto_char (location);
255 unchain_marker (XMARKER (location));
259 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
260 Sfind_file_name_handler, 2, 2, 0,
261 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
262 Otherwise, return nil.
263 A file name is handled if one of the regular expressions in
264 `file-name-handler-alist' matches it.
266 If OPERATION equals `inhibit-file-name-operation', then we ignore
267 any handlers that are members of `inhibit-file-name-handlers',
268 but we still do run any other handlers. This lets handlers
269 use the standard functions without calling themselves recursively. */)
270 (Lisp_Object filename, Lisp_Object operation)
272 /* This function must not munge the match data. */
273 Lisp_Object chain, inhibited_handlers, result;
274 ptrdiff_t pos = -1;
276 result = Qnil;
277 CHECK_STRING (filename);
279 if (EQ (operation, Vinhibit_file_name_operation))
280 inhibited_handlers = Vinhibit_file_name_handlers;
281 else
282 inhibited_handlers = Qnil;
284 for (chain = Vfile_name_handler_alist; CONSP (chain);
285 chain = XCDR (chain))
287 Lisp_Object elt;
288 elt = XCAR (chain);
289 if (CONSP (elt))
291 Lisp_Object string = XCAR (elt);
292 ptrdiff_t match_pos;
293 Lisp_Object handler = XCDR (elt);
294 Lisp_Object operations = Qnil;
296 if (SYMBOLP (handler))
297 operations = Fget (handler, Qoperations);
299 if (STRINGP (string)
300 && (match_pos = fast_string_match (string, filename)) > pos
301 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
303 Lisp_Object tem;
305 handler = XCDR (elt);
306 tem = Fmemq (handler, inhibited_handlers);
307 if (NILP (tem))
309 result = handler;
310 pos = match_pos;
315 QUIT;
317 return result;
320 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
321 1, 1, 0,
322 doc: /* Return the directory component in file name FILENAME.
323 Return nil if FILENAME does not include a directory.
324 Otherwise return a directory name.
325 Given a Unix syntax file name, returns a string ending in slash. */)
326 (Lisp_Object filename)
328 Lisp_Object handler;
330 CHECK_STRING (filename);
332 /* If the file name has special constructs in it,
333 call the corresponding file handler. */
334 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
335 if (!NILP (handler))
337 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
338 filename);
339 return STRINGP (handled_name) ? handled_name : Qnil;
342 char *beg = SSDATA (filename);
343 char const *p = beg + SBYTES (filename);
345 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
346 #ifdef DOS_NT
347 /* only recognize drive specifier at the beginning */
348 && !(p[-1] == ':'
349 /* handle the "/:d:foo" and "/:foo" cases correctly */
350 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
351 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
352 #endif
353 ) p--;
355 if (p == beg)
356 return Qnil;
357 #ifdef DOS_NT
358 /* Expansion of "c:" to drive and default directory. */
359 Lisp_Object tem_fn;
360 USE_SAFE_ALLOCA;
361 SAFE_ALLOCA_STRING (beg, filename);
362 p = beg + (p - SSDATA (filename));
364 if (p[-1] == ':')
366 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
367 char *res = alloca (MAXPATHLEN + 1);
368 char *r = res;
370 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
372 memcpy (res, beg, 2);
373 beg += 2;
374 r += 2;
377 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
379 size_t l = strlen (res);
381 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
382 strcat (res, "/");
383 beg = res;
384 p = beg + strlen (beg);
385 dostounix_filename (beg);
386 tem_fn = make_specified_string (beg, -1, p - beg,
387 STRING_MULTIBYTE (filename));
389 else
390 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
391 STRING_MULTIBYTE (filename));
393 else if (STRING_MULTIBYTE (filename))
395 tem_fn = make_specified_string (beg, -1, p - beg, 1);
396 dostounix_filename (SSDATA (tem_fn));
397 #ifdef WINDOWSNT
398 if (!NILP (Vw32_downcase_file_names))
399 tem_fn = Fdowncase (tem_fn);
400 #endif
402 else
404 dostounix_filename (beg);
405 tem_fn = make_specified_string (beg, -1, p - beg, 0);
407 SAFE_FREE ();
408 return tem_fn;
409 #else /* DOS_NT */
410 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
411 #endif /* DOS_NT */
414 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
415 Sfile_name_nondirectory, 1, 1, 0,
416 doc: /* Return file name FILENAME sans its directory.
417 For example, in a Unix-syntax file name,
418 this is everything after the last slash,
419 or the entire name if it contains no slash. */)
420 (Lisp_Object filename)
422 register const char *beg, *p, *end;
423 Lisp_Object handler;
425 CHECK_STRING (filename);
427 /* If the file name has special constructs in it,
428 call the corresponding file handler. */
429 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
430 if (!NILP (handler))
432 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
433 filename);
434 if (STRINGP (handled_name))
435 return handled_name;
436 error ("Invalid handler in `file-name-handler-alist'");
439 beg = SSDATA (filename);
440 end = p = beg + SBYTES (filename);
442 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
443 #ifdef DOS_NT
444 /* only recognize drive specifier at beginning */
445 && !(p[-1] == ':'
446 /* handle the "/:d:foo" case correctly */
447 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
448 #endif
450 p--;
452 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
455 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
456 Sunhandled_file_name_directory, 1, 1, 0,
457 doc: /* Return a directly usable directory name somehow associated with FILENAME.
458 A `directly usable' directory name is one that may be used without the
459 intervention of any file handler.
460 If FILENAME is a directly usable file itself, return
461 \(file-name-as-directory FILENAME).
462 If FILENAME refers to a file which is not accessible from a local process,
463 then this should return nil.
464 The `call-process' and `start-process' functions use this function to
465 get a current directory to run processes in. */)
466 (Lisp_Object filename)
468 Lisp_Object handler;
470 /* If the file name has special constructs in it,
471 call the corresponding file handler. */
472 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
473 if (!NILP (handler))
475 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
476 filename);
477 return STRINGP (handled_name) ? handled_name : Qnil;
480 return Ffile_name_as_directory (filename);
483 /* Maximum number of bytes that DST will be longer than SRC
484 in file_name_as_directory. This occurs when SRCLEN == 0. */
485 enum { file_name_as_directory_slop = 2 };
487 /* Convert from file name SRC of length SRCLEN to directory name in
488 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
489 string. On UNIX, just make sure there is a terminating /. Return
490 the length of DST in bytes. */
492 static ptrdiff_t
493 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
494 bool multibyte)
496 if (srclen == 0)
498 dst[0] = '.';
499 dst[1] = '/';
500 dst[2] = '\0';
501 return 2;
504 memcpy (dst, src, srclen);
505 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
506 dst[srclen++] = DIRECTORY_SEP;
507 dst[srclen] = 0;
508 #ifdef DOS_NT
509 dostounix_filename (dst);
510 #endif
511 return srclen;
514 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
515 Sfile_name_as_directory, 1, 1, 0,
516 doc: /* Return a string representing the file name FILE interpreted as a directory.
517 This operation exists because a directory is also a file, but its name as
518 a directory is different from its name as a file.
519 The result can be used as the value of `default-directory'
520 or passed as second argument to `expand-file-name'.
521 For a Unix-syntax file name, just appends a slash unless a trailing slash
522 is already present. */)
523 (Lisp_Object file)
525 char *buf;
526 ptrdiff_t length;
527 Lisp_Object handler, val;
528 USE_SAFE_ALLOCA;
530 CHECK_STRING (file);
532 /* If the file name has special constructs in it,
533 call the corresponding file handler. */
534 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
535 if (!NILP (handler))
537 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
538 file);
539 if (STRINGP (handled_name))
540 return handled_name;
541 error ("Invalid handler in `file-name-handler-alist'");
544 #ifdef WINDOWSNT
545 if (!NILP (Vw32_downcase_file_names))
546 file = Fdowncase (file);
547 #endif
548 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
549 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
550 STRING_MULTIBYTE (file));
551 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
552 SAFE_FREE ();
553 return val;
556 /* Convert from directory name SRC of length SRCLEN to file name in
557 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
558 string. On UNIX, just make sure there isn't a terminating /.
559 Return the length of DST in bytes. */
561 static ptrdiff_t
562 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
564 /* Process as Unix format: just remove any final slash.
565 But leave "/" and "//" unchanged. */
566 while (srclen > 1
567 #ifdef DOS_NT
568 && !IS_ANY_SEP (src[srclen - 2])
569 #endif
570 && IS_DIRECTORY_SEP (src[srclen - 1])
571 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
572 srclen--;
574 memcpy (dst, src, srclen);
575 dst[srclen] = 0;
576 #ifdef DOS_NT
577 dostounix_filename (dst);
578 #endif
579 return srclen;
582 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
583 1, 1, 0,
584 doc: /* Returns the file name of the directory named DIRECTORY.
585 This is the name of the file that holds the data for the directory DIRECTORY.
586 This operation exists because a directory is also a file, but its name as
587 a directory is different from its name as a file.
588 In Unix-syntax, this function just removes the final slash. */)
589 (Lisp_Object directory)
591 char *buf;
592 ptrdiff_t length;
593 Lisp_Object handler, val;
594 USE_SAFE_ALLOCA;
596 CHECK_STRING (directory);
598 /* If the file name has special constructs in it,
599 call the corresponding file handler. */
600 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
601 if (!NILP (handler))
603 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
604 directory);
605 if (STRINGP (handled_name))
606 return handled_name;
607 error ("Invalid handler in `file-name-handler-alist'");
610 #ifdef WINDOWSNT
611 if (!NILP (Vw32_downcase_file_names))
612 directory = Fdowncase (directory);
613 #endif
614 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
615 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
616 STRING_MULTIBYTE (directory));
617 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
618 SAFE_FREE ();
619 return val;
622 static const char make_temp_name_tbl[64] =
624 'A','B','C','D','E','F','G','H',
625 'I','J','K','L','M','N','O','P',
626 'Q','R','S','T','U','V','W','X',
627 'Y','Z','a','b','c','d','e','f',
628 'g','h','i','j','k','l','m','n',
629 'o','p','q','r','s','t','u','v',
630 'w','x','y','z','0','1','2','3',
631 '4','5','6','7','8','9','-','_'
634 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
636 /* Value is a temporary file name starting with PREFIX, a string.
638 The Emacs process number forms part of the result, so there is
639 no danger of generating a name being used by another process.
640 In addition, this function makes an attempt to choose a name
641 which has no existing file. To make this work, PREFIX should be
642 an absolute file name.
644 BASE64_P means add the pid as 3 characters in base64
645 encoding. In this case, 6 characters will be added to PREFIX to
646 form the file name. Otherwise, if Emacs is running on a system
647 with long file names, add the pid as a decimal number.
649 This function signals an error if no unique file name could be
650 generated. */
652 Lisp_Object
653 make_temp_name (Lisp_Object prefix, bool base64_p)
655 Lisp_Object val, encoded_prefix;
656 ptrdiff_t len;
657 printmax_t pid;
658 char *p, *data;
659 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
660 int pidlen;
662 CHECK_STRING (prefix);
664 /* VAL is created by adding 6 characters to PREFIX. The first
665 three are the PID of this process, in base 64, and the second
666 three are incremented if the file already exists. This ensures
667 262144 unique file names per PID per PREFIX. */
669 pid = getpid ();
671 if (base64_p)
673 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
674 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
675 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
676 pidlen = 3;
678 else
680 #ifdef HAVE_LONG_FILE_NAMES
681 pidlen = sprintf (pidbuf, "%"pMd, pid);
682 #else
683 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
684 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
685 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
686 pidlen = 3;
687 #endif
690 encoded_prefix = ENCODE_FILE (prefix);
691 len = SBYTES (encoded_prefix);
692 val = make_uninit_string (len + 3 + pidlen);
693 data = SSDATA (val);
694 memcpy (data, SSDATA (encoded_prefix), len);
695 p = data + len;
697 memcpy (p, pidbuf, pidlen);
698 p += pidlen;
700 /* Here we try to minimize useless stat'ing when this function is
701 invoked many times successively with the same PREFIX. We achieve
702 this by initializing count to a random value, and incrementing it
703 afterwards.
705 We don't want make-temp-name to be called while dumping,
706 because then make_temp_name_count_initialized_p would get set
707 and then make_temp_name_count would not be set when Emacs starts. */
709 if (!make_temp_name_count_initialized_p)
711 make_temp_name_count = time (NULL);
712 make_temp_name_count_initialized_p = 1;
715 while (1)
717 unsigned num = make_temp_name_count;
719 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
720 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
721 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
723 /* Poor man's congruential RN generator. Replace with
724 ++make_temp_name_count for debugging. */
725 make_temp_name_count += 25229;
726 make_temp_name_count %= 225307;
728 if (!check_existing (data))
730 /* We want to return only if errno is ENOENT. */
731 if (errno == ENOENT)
732 return DECODE_FILE (val);
733 else
734 /* The error here is dubious, but there is little else we
735 can do. The alternatives are to return nil, which is
736 as bad as (and in many cases worse than) throwing the
737 error, or to ignore the error, which will likely result
738 in looping through 225307 stat's, which is not only
739 dog-slow, but also useless since eventually nil would
740 have to be returned anyway. */
741 report_file_error ("Cannot create temporary name for prefix",
742 prefix);
743 /* not reached */
749 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
750 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
751 The Emacs process number forms part of the result, so there is no
752 danger of generating a name being used by another Emacs process
753 \(so long as only a single host can access the containing directory...).
755 This function tries to choose a name that has no existing file.
756 For this to work, PREFIX should be an absolute file name.
758 There is a race condition between calling `make-temp-name' and creating the
759 file, which opens all kinds of security holes. For that reason, you should
760 normally use `make-temp-file' instead. */)
761 (Lisp_Object prefix)
763 return make_temp_name (prefix, 0);
766 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
767 doc: /* Convert filename NAME to absolute, and canonicalize it.
768 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
769 \(does not start with slash or tilde); both the directory name and
770 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
771 missing, the current buffer's value of `default-directory' is used.
772 NAME should be a string that is a valid file name for the underlying
773 filesystem.
774 File name components that are `.' are removed, and
775 so are file name components followed by `..', along with the `..' itself;
776 note that these simplifications are done without checking the resulting
777 file names in the file system.
778 Multiple consecutive slashes are collapsed into a single slash,
779 except at the beginning of the file name when they are significant (e.g.,
780 UNC file names on MS-Windows.)
781 An initial `~/' expands to your home directory.
782 An initial `~USER/' expands to USER's home directory.
783 See also the function `substitute-in-file-name'.
785 For technical reasons, this function can return correct but
786 non-intuitive results for the root directory; for instance,
787 \(expand-file-name ".." "/") returns "/..". For this reason, use
788 \(directory-file-name (file-name-directory dirname)) to traverse a
789 filesystem tree, not (expand-file-name ".." dirname). */)
790 (Lisp_Object name, Lisp_Object default_directory)
792 /* These point to SDATA and need to be careful with string-relocation
793 during GC (via DECODE_FILE). */
794 char *nm;
795 char *nmlim;
796 const char *newdir;
797 const char *newdirlim;
798 /* This should only point to alloca'd data. */
799 char *target;
801 ptrdiff_t tlen;
802 struct passwd *pw;
803 #ifdef DOS_NT
804 int drive = 0;
805 bool collapse_newdir = true;
806 bool is_escaped = 0;
807 #endif /* DOS_NT */
808 ptrdiff_t length, nbytes;
809 Lisp_Object handler, result, handled_name;
810 bool multibyte;
811 Lisp_Object hdir;
812 USE_SAFE_ALLOCA;
814 CHECK_STRING (name);
816 /* If the file name has special constructs in it,
817 call the corresponding file handler. */
818 handler = Ffind_file_name_handler (name, Qexpand_file_name);
819 if (!NILP (handler))
821 handled_name = call3 (handler, Qexpand_file_name,
822 name, default_directory);
823 if (STRINGP (handled_name))
824 return handled_name;
825 error ("Invalid handler in `file-name-handler-alist'");
829 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
830 if (NILP (default_directory))
831 default_directory = BVAR (current_buffer, directory);
832 if (! STRINGP (default_directory))
834 #ifdef DOS_NT
835 /* "/" is not considered a root directory on DOS_NT, so using "/"
836 here causes an infinite recursion in, e.g., the following:
838 (let (default-directory)
839 (expand-file-name "a"))
841 To avoid this, we set default_directory to the root of the
842 current drive. */
843 default_directory = build_string (emacs_root_dir ());
844 #else
845 default_directory = build_string ("/");
846 #endif
849 if (!NILP (default_directory))
851 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
852 if (!NILP (handler))
854 handled_name = call3 (handler, Qexpand_file_name,
855 name, default_directory);
856 if (STRINGP (handled_name))
857 return handled_name;
858 error ("Invalid handler in `file-name-handler-alist'");
863 char *o = SSDATA (default_directory);
865 /* Make sure DEFAULT_DIRECTORY is properly expanded.
866 It would be better to do this down below where we actually use
867 default_directory. Unfortunately, calling Fexpand_file_name recursively
868 could invoke GC, and the strings might be relocated. This would
869 be annoying because we have pointers into strings lying around
870 that would need adjusting, and people would add new pointers to
871 the code and forget to adjust them, resulting in intermittent bugs.
872 Putting this call here avoids all that crud.
874 The EQ test avoids infinite recursion. */
875 if (! NILP (default_directory) && !EQ (default_directory, name)
876 /* Save time in some common cases - as long as default_directory
877 is not relative, it can be canonicalized with name below (if it
878 is needed at all) without requiring it to be expanded now. */
879 #ifdef DOS_NT
880 /* Detect MSDOS file names with drive specifiers. */
881 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
882 && IS_DIRECTORY_SEP (o[2]))
883 #ifdef WINDOWSNT
884 /* Detect Windows file names in UNC format. */
885 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
886 #endif
887 #else /* not DOS_NT */
888 /* Detect Unix absolute file names (/... alone is not absolute on
889 DOS or Windows). */
890 && ! (IS_DIRECTORY_SEP (o[0]))
891 #endif /* not DOS_NT */
894 default_directory = Fexpand_file_name (default_directory, Qnil);
897 multibyte = STRING_MULTIBYTE (name);
898 if (multibyte != STRING_MULTIBYTE (default_directory))
900 if (multibyte)
902 unsigned char *p = SDATA (name);
904 while (*p && ASCII_CHAR_P (*p))
905 p++;
906 if (*p == '\0')
908 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
909 unibyte. Do not convert DEFAULT_DIRECTORY to
910 multibyte; instead, convert NAME to a unibyte string,
911 so that the result of this function is also a unibyte
912 string. This is needed during bootstrapping and
913 dumping, when Emacs cannot decode file names, because
914 the locale environment is not set up. */
915 name = make_unibyte_string (SSDATA (name), SBYTES (name));
916 multibyte = 0;
918 else
919 default_directory = string_to_multibyte (default_directory);
921 else
923 name = string_to_multibyte (name);
924 multibyte = 1;
928 #ifdef WINDOWSNT
929 if (!NILP (Vw32_downcase_file_names))
930 default_directory = Fdowncase (default_directory);
931 #endif
933 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
934 SAFE_ALLOCA_STRING (nm, name);
935 nmlim = nm + SBYTES (name);
937 #ifdef DOS_NT
938 /* Note if special escape prefix is present, but remove for now. */
939 if (nm[0] == '/' && nm[1] == ':')
941 is_escaped = 1;
942 nm += 2;
945 /* Find and remove drive specifier if present; this makes nm absolute
946 even if the rest of the name appears to be relative. Only look for
947 drive specifier at the beginning. */
948 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
950 drive = (unsigned char) nm[0];
951 nm += 2;
954 #ifdef WINDOWSNT
955 /* If we see "c://somedir", we want to strip the first slash after the
956 colon when stripping the drive letter. Otherwise, this expands to
957 "//somedir". */
958 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
959 nm++;
961 /* Discard any previous drive specifier if nm is now in UNC format. */
962 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
963 && !IS_DIRECTORY_SEP (nm[2]))
964 drive = 0;
965 #endif /* WINDOWSNT */
966 #endif /* DOS_NT */
968 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
969 none are found, we can probably return right away. We will avoid
970 allocating a new string if name is already fully expanded. */
971 if (
972 IS_DIRECTORY_SEP (nm[0])
973 #ifdef MSDOS
974 && drive && !is_escaped
975 #endif
976 #ifdef WINDOWSNT
977 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
978 #endif
981 /* If it turns out that the filename we want to return is just a
982 suffix of FILENAME, we don't need to go through and edit
983 things; we just need to construct a new string using data
984 starting at the middle of FILENAME. If we set LOSE, that
985 means we've discovered that we can't do that cool trick. */
986 bool lose = 0;
987 char *p = nm;
989 while (*p)
991 /* Since we know the name is absolute, we can assume that each
992 element starts with a "/". */
994 /* "." and ".." are hairy. */
995 if (IS_DIRECTORY_SEP (p[0])
996 && p[1] == '.'
997 && (IS_DIRECTORY_SEP (p[2])
998 || p[2] == 0
999 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1000 || p[3] == 0))))
1001 lose = 1;
1002 /* Replace multiple slashes with a single one, except
1003 leave leading "//" alone. */
1004 else if (IS_DIRECTORY_SEP (p[0])
1005 && IS_DIRECTORY_SEP (p[1])
1006 && (p != nm || IS_DIRECTORY_SEP (p[2])))
1007 lose = 1;
1008 p++;
1010 if (!lose)
1012 #ifdef DOS_NT
1013 /* Make sure directories are all separated with /, but
1014 avoid allocation of a new string when not required. */
1015 dostounix_filename (nm);
1016 #ifdef WINDOWSNT
1017 if (IS_DIRECTORY_SEP (nm[1]))
1019 if (strcmp (nm, SSDATA (name)) != 0)
1020 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1022 else
1023 #endif
1024 /* Drive must be set, so this is okay. */
1025 if (strcmp (nm - 2, SSDATA (name)) != 0)
1027 name = make_specified_string (nm, -1, p - nm, multibyte);
1028 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1029 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1030 name = concat2 (drive_prefix, name);
1032 #ifdef WINDOWSNT
1033 if (!NILP (Vw32_downcase_file_names))
1034 name = Fdowncase (name);
1035 #endif
1036 #else /* not DOS_NT */
1037 if (strcmp (nm, SSDATA (name)) != 0)
1038 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1039 #endif /* not DOS_NT */
1040 SAFE_FREE ();
1041 return name;
1045 /* At this point, nm might or might not be an absolute file name. We
1046 need to expand ~ or ~user if present, otherwise prefix nm with
1047 default_directory if nm is not absolute, and finally collapse /./
1048 and /foo/../ sequences.
1050 We set newdir to be the appropriate prefix if one is needed:
1051 - the relevant user directory if nm starts with ~ or ~user
1052 - the specified drive's working dir (DOS/NT only) if nm does not
1053 start with /
1054 - the value of default_directory.
1056 Note that these prefixes are not guaranteed to be absolute (except
1057 for the working dir of a drive). Therefore, to ensure we always
1058 return an absolute name, if the final prefix is not absolute we
1059 append it to the current working directory. */
1061 newdir = newdirlim = 0;
1063 if (nm[0] == '~') /* prefix ~ */
1065 if (IS_DIRECTORY_SEP (nm[1])
1066 || nm[1] == 0) /* ~ by itself */
1068 Lisp_Object tem;
1070 if (!(newdir = egetenv ("HOME")))
1071 newdir = newdirlim = "";
1072 nm++;
1073 /* `egetenv' may return a unibyte string, which will bite us since
1074 we expect the directory to be multibyte. */
1075 #ifdef WINDOWSNT
1076 if (newdir[0])
1078 char newdir_utf8[MAX_UTF8_PATH];
1080 filename_from_ansi (newdir, newdir_utf8);
1081 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1083 else
1084 #endif
1085 tem = build_string (newdir);
1086 newdirlim = newdir + SBYTES (tem);
1087 if (multibyte && !STRING_MULTIBYTE (tem))
1089 hdir = DECODE_FILE (tem);
1090 newdir = SSDATA (hdir);
1091 newdirlim = newdir + SBYTES (hdir);
1093 #ifdef DOS_NT
1094 collapse_newdir = false;
1095 #endif
1097 else /* ~user/filename */
1099 char *o, *p;
1100 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1101 continue;
1102 o = SAFE_ALLOCA (p - nm + 1);
1103 memcpy (o, nm, p - nm);
1104 o[p - nm] = 0;
1106 block_input ();
1107 pw = getpwnam (o + 1);
1108 unblock_input ();
1109 if (pw)
1111 Lisp_Object tem;
1113 newdir = pw->pw_dir;
1114 /* `getpwnam' may return a unibyte string, which will
1115 bite us since we expect the directory to be
1116 multibyte. */
1117 tem = make_unibyte_string (newdir, strlen (newdir));
1118 newdirlim = newdir + SBYTES (tem);
1119 if (multibyte && !STRING_MULTIBYTE (tem))
1121 hdir = DECODE_FILE (tem);
1122 newdir = SSDATA (hdir);
1123 newdirlim = newdir + SBYTES (hdir);
1125 nm = p;
1126 #ifdef DOS_NT
1127 collapse_newdir = false;
1128 #endif
1131 /* If we don't find a user of that name, leave the name
1132 unchanged; don't move nm forward to p. */
1136 #ifdef DOS_NT
1137 /* On DOS and Windows, nm is absolute if a drive name was specified;
1138 use the drive's current directory as the prefix if needed. */
1139 if (!newdir && drive)
1141 /* Get default directory if needed to make nm absolute. */
1142 char *adir = NULL;
1143 if (!IS_DIRECTORY_SEP (nm[0]))
1145 adir = alloca (MAXPATHLEN + 1);
1146 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1147 adir = NULL;
1148 else if (multibyte)
1150 Lisp_Object tem = build_string (adir);
1152 tem = DECODE_FILE (tem);
1153 newdirlim = adir + SBYTES (tem);
1154 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1156 else
1157 newdirlim = adir + strlen (adir);
1159 if (!adir)
1161 /* Either nm starts with /, or drive isn't mounted. */
1162 adir = alloca (4);
1163 adir[0] = DRIVE_LETTER (drive);
1164 adir[1] = ':';
1165 adir[2] = '/';
1166 adir[3] = 0;
1167 newdirlim = adir + 3;
1169 newdir = adir;
1171 #endif /* DOS_NT */
1173 /* Finally, if no prefix has been specified and nm is not absolute,
1174 then it must be expanded relative to default_directory. */
1176 if (1
1177 #ifndef DOS_NT
1178 /* /... alone is not absolute on DOS and Windows. */
1179 && !IS_DIRECTORY_SEP (nm[0])
1180 #endif
1181 #ifdef WINDOWSNT
1182 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1183 && !IS_DIRECTORY_SEP (nm[2]))
1184 #endif
1185 && !newdir)
1187 newdir = SSDATA (default_directory);
1188 newdirlim = newdir + SBYTES (default_directory);
1189 #ifdef DOS_NT
1190 /* Note if special escape prefix is present, but remove for now. */
1191 if (newdir[0] == '/' && newdir[1] == ':')
1193 is_escaped = 1;
1194 newdir += 2;
1196 #endif
1199 #ifdef DOS_NT
1200 if (newdir)
1202 /* First ensure newdir is an absolute name. */
1203 if (
1204 /* Detect MSDOS file names with drive specifiers. */
1205 ! (IS_DRIVE (newdir[0])
1206 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1207 #ifdef WINDOWSNT
1208 /* Detect Windows file names in UNC format. */
1209 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1210 && !IS_DIRECTORY_SEP (newdir[2]))
1211 #endif
1214 /* Effectively, let newdir be (expand-file-name newdir cwd).
1215 Because of the admonition against calling expand-file-name
1216 when we have pointers into lisp strings, we accomplish this
1217 indirectly by prepending newdir to nm if necessary, and using
1218 cwd (or the wd of newdir's drive) as the new newdir. */
1219 char *adir;
1220 #ifdef WINDOWSNT
1221 const int adir_size = MAX_UTF8_PATH;
1222 #else
1223 const int adir_size = MAXPATHLEN + 1;
1224 #endif
1226 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1228 drive = (unsigned char) newdir[0];
1229 newdir += 2;
1231 if (!IS_DIRECTORY_SEP (nm[0]))
1233 ptrdiff_t nmlen = nmlim - nm;
1234 ptrdiff_t newdirlen = newdirlim - newdir;
1235 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1236 + nmlen + 1);
1237 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1238 multibyte);
1239 memcpy (tmp + dlen, nm, nmlen + 1);
1240 nm = tmp;
1241 nmlim = nm + dlen + nmlen;
1243 adir = alloca (adir_size);
1244 if (drive)
1246 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1247 strcpy (adir, "/");
1249 else
1250 getcwd (adir, adir_size);
1251 if (multibyte)
1253 Lisp_Object tem = build_string (adir);
1255 tem = DECODE_FILE (tem);
1256 newdirlim = adir + SBYTES (tem);
1257 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1259 else
1260 newdirlim = adir + strlen (adir);
1261 newdir = adir;
1264 /* Strip off drive name from prefix, if present. */
1265 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1267 drive = newdir[0];
1268 newdir += 2;
1271 /* Keep only a prefix from newdir if nm starts with slash
1272 (//server/share for UNC, nothing otherwise). */
1273 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1275 #ifdef WINDOWSNT
1276 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1277 && !IS_DIRECTORY_SEP (newdir[2]))
1279 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1280 char *p = adir + 2;
1281 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1282 p++;
1283 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1284 *p = 0;
1285 newdir = adir;
1286 newdirlim = newdir + strlen (adir);
1288 else
1289 #endif
1290 newdir = newdirlim = "";
1293 #endif /* DOS_NT */
1295 /* Ignore any slash at the end of newdir, unless newdir is
1296 just "/" or "//". */
1297 length = newdirlim - newdir;
1298 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1299 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1300 length--;
1302 /* Now concatenate the directory and name to new space in the stack frame. */
1303 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1304 eassert (tlen > file_name_as_directory_slop + 1);
1305 #ifdef DOS_NT
1306 /* Reserve space for drive specifier and escape prefix, since either
1307 or both may need to be inserted. (The Microsoft x86 compiler
1308 produces incorrect code if the following two lines are combined.) */
1309 target = alloca (tlen + 4);
1310 target += 4;
1311 #else /* not DOS_NT */
1312 target = SAFE_ALLOCA (tlen);
1313 #endif /* not DOS_NT */
1314 *target = 0;
1315 nbytes = 0;
1317 if (newdir)
1319 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1321 #ifdef DOS_NT
1322 /* If newdir is effectively "C:/", then the drive letter will have
1323 been stripped and newdir will be "/". Concatenating with an
1324 absolute directory in nm produces "//", which will then be
1325 incorrectly treated as a network share. Ignore newdir in
1326 this case (keeping the drive letter). */
1327 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1328 && newdir[1] == '\0'))
1329 #endif
1331 memcpy (target, newdir, length);
1332 target[length] = 0;
1333 nbytes = length;
1336 else
1337 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1340 memcpy (target + nbytes, nm, nmlim - nm + 1);
1342 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1343 appear. */
1345 char *p = target;
1346 char *o = target;
1348 while (*p)
1350 if (!IS_DIRECTORY_SEP (*p))
1352 *o++ = *p++;
1354 else if (p[1] == '.'
1355 && (IS_DIRECTORY_SEP (p[2])
1356 || p[2] == 0))
1358 /* If "/." is the entire filename, keep the "/". Otherwise,
1359 just delete the whole "/.". */
1360 if (o == target && p[2] == '\0')
1361 *o++ = *p;
1362 p += 2;
1364 else if (p[1] == '.' && p[2] == '.'
1365 /* `/../' is the "superroot" on certain file systems.
1366 Turned off on DOS_NT systems because they have no
1367 "superroot" and because this causes us to produce
1368 file names like "d:/../foo" which fail file-related
1369 functions of the underlying OS. (To reproduce, try a
1370 long series of "../../" in default_directory, longer
1371 than the number of levels from the root.) */
1372 #ifndef DOS_NT
1373 && o != target
1374 #endif
1375 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1377 #ifdef WINDOWSNT
1378 char *prev_o = o;
1379 #endif
1380 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1381 continue;
1382 #ifdef WINDOWSNT
1383 /* Don't go below server level in UNC filenames. */
1384 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1385 && IS_DIRECTORY_SEP (*target))
1386 o = prev_o;
1387 else
1388 #endif
1389 /* Keep initial / only if this is the whole name. */
1390 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1391 ++o;
1392 p += 3;
1394 else if (IS_DIRECTORY_SEP (p[1])
1395 && (p != target || IS_DIRECTORY_SEP (p[2])))
1396 /* Collapse multiple "/", except leave leading "//" alone. */
1397 p++;
1398 else
1400 *o++ = *p++;
1404 #ifdef DOS_NT
1405 /* At last, set drive name. */
1406 #ifdef WINDOWSNT
1407 /* Except for network file name. */
1408 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1409 #endif /* WINDOWSNT */
1411 if (!drive) emacs_abort ();
1412 target -= 2;
1413 target[0] = DRIVE_LETTER (drive);
1414 target[1] = ':';
1416 /* Reinsert the escape prefix if required. */
1417 if (is_escaped)
1419 target -= 2;
1420 target[0] = '/';
1421 target[1] = ':';
1423 result = make_specified_string (target, -1, o - target, multibyte);
1424 dostounix_filename (SSDATA (result));
1425 #ifdef WINDOWSNT
1426 if (!NILP (Vw32_downcase_file_names))
1427 result = Fdowncase (result);
1428 #endif
1429 #else /* !DOS_NT */
1430 result = make_specified_string (target, -1, o - target, multibyte);
1431 #endif /* !DOS_NT */
1434 /* Again look to see if the file name has special constructs in it
1435 and perhaps call the corresponding file handler. This is needed
1436 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1437 the ".." component gives us "/user@host:/bar/../baz" which needs
1438 to be expanded again. */
1439 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1440 if (!NILP (handler))
1442 handled_name = call3 (handler, Qexpand_file_name,
1443 result, default_directory);
1444 if (! STRINGP (handled_name))
1445 error ("Invalid handler in `file-name-handler-alist'");
1446 result = handled_name;
1449 SAFE_FREE ();
1450 return result;
1453 #if 0
1454 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1455 This is the old version of expand-file-name, before it was thoroughly
1456 rewritten for Emacs 10.31. We leave this version here commented-out,
1457 because the code is very complex and likely to have subtle bugs. If
1458 bugs _are_ found, it might be of interest to look at the old code and
1459 see what did it do in the relevant situation.
1461 Don't remove this code: it's true that it will be accessible
1462 from the repository, but a few years from deletion, people will
1463 forget it is there. */
1465 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1466 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1467 "Convert FILENAME to absolute, and canonicalize it.\n\
1468 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1469 \(does not start with slash); if DEFAULT is nil or missing,\n\
1470 the current buffer's value of default-directory is used.\n\
1471 Filenames containing `.' or `..' as components are simplified;\n\
1472 initial `~/' expands to your home directory.\n\
1473 See also the function `substitute-in-file-name'.")
1474 (name, defalt)
1475 Lisp_Object name, defalt;
1477 unsigned char *nm;
1479 register unsigned char *newdir, *p, *o;
1480 ptrdiff_t tlen;
1481 unsigned char *target;
1482 struct passwd *pw;
1484 CHECK_STRING (name);
1485 nm = SDATA (name);
1487 /* If nm is absolute, flush ...// and detect /./ and /../.
1488 If no /./ or /../ we can return right away. */
1489 if (nm[0] == '/')
1491 bool lose = 0;
1492 p = nm;
1493 while (*p)
1495 if (p[0] == '/' && p[1] == '/')
1496 nm = p + 1;
1497 if (p[0] == '/' && p[1] == '~')
1498 nm = p + 1, lose = 1;
1499 if (p[0] == '/' && p[1] == '.'
1500 && (p[2] == '/' || p[2] == 0
1501 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1502 lose = 1;
1503 p++;
1505 if (!lose)
1507 if (nm == SDATA (name))
1508 return name;
1509 return build_string (nm);
1513 /* Now determine directory to start with and put it in NEWDIR. */
1515 newdir = 0;
1517 if (nm[0] == '~') /* prefix ~ */
1518 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1520 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1521 newdir = (unsigned char *) "";
1522 nm++;
1524 else /* ~user/filename */
1526 /* Get past ~ to user. */
1527 unsigned char *user = nm + 1;
1528 /* Find end of name. */
1529 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1530 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1531 /* Copy the user name into temp storage. */
1532 o = alloca (len + 1);
1533 memcpy (o, user, len);
1534 o[len] = 0;
1536 /* Look up the user name. */
1537 block_input ();
1538 pw = (struct passwd *) getpwnam (o + 1);
1539 unblock_input ();
1540 if (!pw)
1541 error ("\"%s\" isn't a registered user", o + 1);
1543 newdir = (unsigned char *) pw->pw_dir;
1545 /* Discard the user name from NM. */
1546 nm += len;
1549 if (nm[0] != '/' && !newdir)
1551 if (NILP (defalt))
1552 defalt = current_buffer->directory;
1553 CHECK_STRING (defalt);
1554 newdir = SDATA (defalt);
1557 /* Now concatenate the directory and name to new space in the stack frame. */
1559 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1560 target = alloca (tlen);
1561 *target = 0;
1563 if (newdir)
1565 if (nm[0] == 0 || nm[0] == '/')
1566 strcpy (target, newdir);
1567 else
1568 file_name_as_directory (target, newdir);
1571 strcat (target, nm);
1573 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1575 p = target;
1576 o = target;
1578 while (*p)
1580 if (*p != '/')
1582 *o++ = *p++;
1584 else if (!strncmp (p, "//", 2)
1587 o = target;
1588 p++;
1590 else if (p[0] == '/' && p[1] == '.'
1591 && (p[2] == '/' || p[2] == 0))
1592 p += 2;
1593 else if (!strncmp (p, "/..", 3)
1594 /* `/../' is the "superroot" on certain file systems. */
1595 && o != target
1596 && (p[3] == '/' || p[3] == 0))
1598 while (o != target && *--o != '/')
1600 if (o == target && *o == '/')
1601 ++o;
1602 p += 3;
1604 else
1606 *o++ = *p++;
1610 return make_string (target, o - target);
1612 #endif
1614 /* If /~ or // appears, discard everything through first slash. */
1615 static bool
1616 file_name_absolute_p (const char *filename)
1618 return
1619 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1620 #ifdef DOS_NT
1621 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1622 && IS_DIRECTORY_SEP (filename[2]))
1623 #endif
1627 static char *
1628 search_embedded_absfilename (char *nm, char *endp)
1630 char *p, *s;
1632 for (p = nm + 1; p < endp; p++)
1634 if (IS_DIRECTORY_SEP (p[-1])
1635 && file_name_absolute_p (p)
1636 #if defined (WINDOWSNT) || defined (CYGWIN)
1637 /* // at start of file name is meaningful in Apollo,
1638 WindowsNT and Cygwin systems. */
1639 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1640 #endif /* not (WINDOWSNT || CYGWIN) */
1643 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1644 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1646 USE_SAFE_ALLOCA;
1647 char *o = SAFE_ALLOCA (s - p + 1);
1648 struct passwd *pw;
1649 memcpy (o, p, s - p);
1650 o [s - p] = 0;
1652 /* If we have ~user and `user' exists, discard
1653 everything up to ~. But if `user' does not exist, leave
1654 ~user alone, it might be a literal file name. */
1655 block_input ();
1656 pw = getpwnam (o + 1);
1657 unblock_input ();
1658 SAFE_FREE ();
1659 if (pw)
1660 return p;
1662 else
1663 return p;
1666 return NULL;
1669 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1670 Ssubstitute_in_file_name, 1, 1, 0,
1671 doc: /* Substitute environment variables referred to in FILENAME.
1672 `$FOO' where FOO is an environment variable name means to substitute
1673 the value of that variable. The variable name should be terminated
1674 with a character not a letter, digit or underscore; otherwise, enclose
1675 the entire variable name in braces.
1677 If `/~' appears, all of FILENAME through that `/' is discarded.
1678 If `//' appears, everything up to and including the first of
1679 those `/' is discarded. */)
1680 (Lisp_Object filename)
1682 char *nm, *p, *x, *endp;
1683 bool substituted = false;
1684 bool multibyte;
1685 char *xnm;
1686 Lisp_Object handler;
1688 CHECK_STRING (filename);
1690 multibyte = STRING_MULTIBYTE (filename);
1692 /* If the file name has special constructs in it,
1693 call the corresponding file handler. */
1694 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1695 if (!NILP (handler))
1697 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1698 filename);
1699 if (STRINGP (handled_name))
1700 return handled_name;
1701 error ("Invalid handler in `file-name-handler-alist'");
1704 /* Always work on a copy of the string, in case GC happens during
1705 decode of environment variables, causing the original Lisp_String
1706 data to be relocated. */
1707 USE_SAFE_ALLOCA;
1708 SAFE_ALLOCA_STRING (nm, filename);
1710 #ifdef DOS_NT
1711 dostounix_filename (nm);
1712 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1713 #endif
1714 endp = nm + SBYTES (filename);
1716 /* If /~ or // appears, discard everything through first slash. */
1717 p = search_embedded_absfilename (nm, endp);
1718 if (p)
1719 /* Start over with the new string, so we check the file-name-handler
1720 again. Important with filenames like "/home/foo//:/hello///there"
1721 which would substitute to "/:/hello///there" rather than "/there". */
1723 Lisp_Object result
1724 = (Fsubstitute_in_file_name
1725 (make_specified_string (p, -1, endp - p, multibyte)));
1726 SAFE_FREE ();
1727 return result;
1730 /* See if any variables are substituted into the string. */
1732 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1734 Lisp_Object name
1735 = (!substituted ? filename
1736 : make_specified_string (nm, -1, endp - nm, multibyte));
1737 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1738 CHECK_STRING (tmp);
1739 if (!EQ (tmp, name))
1740 substituted = true;
1741 filename = tmp;
1744 if (!substituted)
1746 #ifdef WINDOWSNT
1747 if (!NILP (Vw32_downcase_file_names))
1748 filename = Fdowncase (filename);
1749 #endif
1750 SAFE_FREE ();
1751 return filename;
1754 xnm = SSDATA (filename);
1755 x = xnm + SBYTES (filename);
1757 /* If /~ or // appears, discard everything through first slash. */
1758 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1759 /* This time we do not start over because we've already expanded envvars
1760 and replaced $$ with $. Maybe we should start over as well, but we'd
1761 need to quote some $ to $$ first. */
1762 xnm = p;
1764 #ifdef WINDOWSNT
1765 if (!NILP (Vw32_downcase_file_names))
1767 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1769 filename = Fdowncase (xname);
1771 else
1772 #endif
1773 if (xnm != SSDATA (filename))
1774 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1775 SAFE_FREE ();
1776 return filename;
1779 /* A slightly faster and more convenient way to get
1780 (directory-file-name (expand-file-name FOO)). */
1782 Lisp_Object
1783 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1785 register Lisp_Object absname;
1787 absname = Fexpand_file_name (filename, defdir);
1789 /* Remove final slash, if any (unless this is the root dir).
1790 stat behaves differently depending! */
1791 if (SCHARS (absname) > 1
1792 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1793 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1794 /* We cannot take shortcuts; they might be wrong for magic file names. */
1795 absname = Fdirectory_file_name (absname);
1796 return absname;
1799 /* Signal an error if the file ABSNAME already exists.
1800 If KNOWN_TO_EXIST, the file is known to exist.
1801 QUERYSTRING is a name for the action that is being considered
1802 to alter the file.
1803 If INTERACTIVE, ask the user whether to proceed,
1804 and bypass the error if the user says to go ahead.
1805 If QUICK, ask for y or n, not yes or no. */
1807 static void
1808 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1809 const char *querystring, bool interactive,
1810 bool quick)
1812 Lisp_Object tem, encoded_filename;
1813 struct stat statbuf;
1815 encoded_filename = ENCODE_FILE (absname);
1817 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1819 if (S_ISDIR (statbuf.st_mode))
1820 xsignal2 (Qfile_error,
1821 build_string ("File is a directory"), absname);
1822 known_to_exist = true;
1825 if (known_to_exist)
1827 if (! interactive)
1828 xsignal2 (Qfile_already_exists,
1829 build_string ("File already exists"), absname);
1830 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1831 tem = CALLN (Fformat, format, absname, build_string (querystring));
1832 if (quick)
1833 tem = call1 (intern ("y-or-n-p"), tem);
1834 else
1835 tem = do_yes_or_no_p (tem);
1836 if (NILP (tem))
1837 xsignal2 (Qfile_already_exists,
1838 build_string ("File already exists"), absname);
1842 #ifndef WINDOWSNT
1843 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1844 static bool
1845 clone_file (int dest, int source)
1847 #ifdef FICLONE
1848 return ioctl (dest, FICLONE, source) == 0;
1849 #endif
1850 return false;
1852 #endif
1854 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1855 "fCopy file: \nGCopy %s to file: \np\nP",
1856 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1857 If NEWNAME names a directory, copy FILE there.
1859 This function always sets the file modes of the output file to match
1860 the input file.
1862 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1863 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1864 signal a `file-already-exists' error without overwriting. If
1865 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1866 about overwriting; this is what happens in interactive use with M-x.
1867 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1868 existing file.
1870 Fourth arg KEEP-TIME non-nil means give the output file the same
1871 last-modified time as the old one. (This works on only some systems.)
1873 A prefix arg makes KEEP-TIME non-nil.
1875 If PRESERVE-UID-GID is non-nil, we try to transfer the
1876 uid and gid of FILE to NEWNAME.
1878 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1879 this includes the file modes, along with ACL entries and SELinux
1880 context if present. Otherwise, if NEWNAME is created its file
1881 permission bits are those of FILE, masked by the default file
1882 permissions. */)
1883 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1884 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1885 Lisp_Object preserve_permissions)
1887 Lisp_Object handler;
1888 ptrdiff_t count = SPECPDL_INDEX ();
1889 Lisp_Object encoded_file, encoded_newname;
1890 #if HAVE_LIBSELINUX
1891 security_context_t con;
1892 int conlength = 0;
1893 #endif
1894 #ifdef WINDOWSNT
1895 int result;
1896 #else
1897 bool already_exists = false;
1898 mode_t new_mask;
1899 int ifd, ofd;
1900 struct stat st;
1901 #endif
1903 encoded_file = encoded_newname = Qnil;
1904 CHECK_STRING (file);
1905 CHECK_STRING (newname);
1907 if (!NILP (Ffile_directory_p (newname)))
1908 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1909 else
1910 newname = Fexpand_file_name (newname, Qnil);
1912 file = Fexpand_file_name (file, Qnil);
1914 /* If the input file name has special constructs in it,
1915 call the corresponding file handler. */
1916 handler = Ffind_file_name_handler (file, Qcopy_file);
1917 /* Likewise for output file name. */
1918 if (NILP (handler))
1919 handler = Ffind_file_name_handler (newname, Qcopy_file);
1920 if (!NILP (handler))
1921 return call7 (handler, Qcopy_file, file, newname,
1922 ok_if_already_exists, keep_time, preserve_uid_gid,
1923 preserve_permissions);
1925 encoded_file = ENCODE_FILE (file);
1926 encoded_newname = ENCODE_FILE (newname);
1928 #ifdef WINDOWSNT
1929 if (NILP (ok_if_already_exists)
1930 || INTEGERP (ok_if_already_exists))
1931 barf_or_query_if_file_exists (newname, false, "copy to it",
1932 INTEGERP (ok_if_already_exists), false);
1934 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1935 !NILP (keep_time), !NILP (preserve_uid_gid),
1936 !NILP (preserve_permissions));
1937 switch (result)
1939 case -1:
1940 report_file_error ("Copying file", list2 (file, newname));
1941 case -2:
1942 report_file_error ("Copying permissions from", file);
1943 case -3:
1944 xsignal2 (Qfile_date_error,
1945 build_string ("Resetting file times"), newname);
1946 case -4:
1947 report_file_error ("Copying permissions to", newname);
1949 #else /* not WINDOWSNT */
1950 immediate_quit = 1;
1951 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1952 immediate_quit = 0;
1954 if (ifd < 0)
1955 report_file_error ("Opening input file", file);
1957 record_unwind_protect_int (close_file_unwind, ifd);
1959 if (fstat (ifd, &st) != 0)
1960 report_file_error ("Input file status", file);
1962 if (!NILP (preserve_permissions))
1964 #if HAVE_LIBSELINUX
1965 if (is_selinux_enabled ())
1967 conlength = fgetfilecon (ifd, &con);
1968 if (conlength == -1)
1969 report_file_error ("Doing fgetfilecon", file);
1971 #endif
1974 /* We can copy only regular files. */
1975 if (!S_ISREG (st.st_mode))
1976 report_file_errno ("Non-regular file", file,
1977 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1979 #ifndef MSDOS
1980 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1981 #else
1982 new_mask = S_IREAD | S_IWRITE;
1983 #endif
1985 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1986 new_mask);
1987 if (ofd < 0 && errno == EEXIST)
1989 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1990 barf_or_query_if_file_exists (newname, true, "copy to it",
1991 INTEGERP (ok_if_already_exists), false);
1992 already_exists = true;
1993 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1995 if (ofd < 0)
1996 report_file_error ("Opening output file", newname);
1998 record_unwind_protect_int (close_file_unwind, ofd);
2000 off_t oldsize = 0, newsize;
2002 if (already_exists)
2004 struct stat out_st;
2005 if (fstat (ofd, &out_st) != 0)
2006 report_file_error ("Output file status", newname);
2007 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2008 report_file_errno ("Input and output files are the same",
2009 list2 (file, newname), 0);
2010 if (S_ISREG (out_st.st_mode))
2011 oldsize = out_st.st_size;
2014 immediate_quit = 1;
2015 QUIT;
2017 if (clone_file (ofd, ifd))
2018 newsize = st.st_size;
2019 else
2021 char buf[MAX_ALLOCA];
2022 ptrdiff_t n;
2023 for (newsize = 0; 0 < (n = emacs_read (ifd, buf, sizeof buf));
2024 newsize += n)
2025 if (emacs_write_sig (ofd, buf, n) != n)
2026 report_file_error ("Write error", newname);
2027 if (n < 0)
2028 report_file_error ("Read error", file);
2031 /* Truncate any existing output file after writing the data. This
2032 is more likely to work than truncation before writing, if the
2033 file system is out of space or the user is over disk quota. */
2034 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2035 report_file_error ("Truncating output file", newname);
2037 immediate_quit = 0;
2039 #ifndef MSDOS
2040 /* Preserve the original file permissions, and if requested, also its
2041 owner and group. */
2043 mode_t preserved_permissions = st.st_mode & 07777;
2044 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2045 if (!NILP (preserve_uid_gid))
2047 /* Attempt to change owner and group. If that doesn't work
2048 attempt to change just the group, as that is sometimes allowed.
2049 Adjust the mode mask to eliminate setuid or setgid bits
2050 or group permissions bits that are inappropriate if the
2051 owner or group are wrong. */
2052 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2054 if (fchown (ofd, -1, st.st_gid) == 0)
2055 preserved_permissions &= ~04000;
2056 else
2058 preserved_permissions &= ~06000;
2060 /* Copy the other bits to the group bits, since the
2061 group is wrong. */
2062 preserved_permissions &= ~070;
2063 preserved_permissions |= (preserved_permissions & 7) << 3;
2064 default_permissions &= ~070;
2065 default_permissions |= (default_permissions & 7) << 3;
2070 switch (!NILP (preserve_permissions)
2071 ? qcopy_acl (SSDATA (encoded_file), ifd,
2072 SSDATA (encoded_newname), ofd,
2073 preserved_permissions)
2074 : (already_exists
2075 || (new_mask & ~realmask) == default_permissions)
2077 : fchmod (ofd, default_permissions))
2079 case -2: report_file_error ("Copying permissions from", file);
2080 case -1: report_file_error ("Copying permissions to", newname);
2083 #endif /* not MSDOS */
2085 #if HAVE_LIBSELINUX
2086 if (conlength > 0)
2088 /* Set the modified context back to the file. */
2089 bool fail = fsetfilecon (ofd, con) != 0;
2090 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2091 if (fail && errno != ENOTSUP)
2092 report_file_error ("Doing fsetfilecon", newname);
2094 freecon (con);
2096 #endif
2098 if (!NILP (keep_time))
2100 struct timespec atime = get_stat_atime (&st);
2101 struct timespec mtime = get_stat_mtime (&st);
2102 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2103 xsignal2 (Qfile_date_error,
2104 build_string ("Cannot set file date"), newname);
2107 if (emacs_close (ofd) < 0)
2108 report_file_error ("Write error", newname);
2110 emacs_close (ifd);
2112 #ifdef MSDOS
2113 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2114 and if it can't, it tells so. Otherwise, under MSDOS we usually
2115 get only the READ bit, which will make the copied file read-only,
2116 so it's better not to chmod at all. */
2117 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2118 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2119 #endif /* MSDOS */
2120 #endif /* not WINDOWSNT */
2122 /* Discard the unwind protects. */
2123 specpdl_ptr = specpdl + count;
2125 return Qnil;
2128 DEFUN ("make-directory-internal", Fmake_directory_internal,
2129 Smake_directory_internal, 1, 1, 0,
2130 doc: /* Create a new directory named DIRECTORY. */)
2131 (Lisp_Object directory)
2133 const char *dir;
2134 Lisp_Object handler;
2135 Lisp_Object encoded_dir;
2137 CHECK_STRING (directory);
2138 directory = Fexpand_file_name (directory, Qnil);
2140 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2141 if (!NILP (handler))
2142 return call2 (handler, Qmake_directory_internal, directory);
2144 encoded_dir = ENCODE_FILE (directory);
2146 dir = SSDATA (encoded_dir);
2148 #ifdef WINDOWSNT
2149 if (mkdir (dir) != 0)
2150 #else
2151 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2152 #endif
2153 report_file_error ("Creating directory", directory);
2155 return Qnil;
2158 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2159 Sdelete_directory_internal, 1, 1, 0,
2160 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2161 (Lisp_Object directory)
2163 const char *dir;
2164 Lisp_Object encoded_dir;
2166 CHECK_STRING (directory);
2167 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2168 encoded_dir = ENCODE_FILE (directory);
2169 dir = SSDATA (encoded_dir);
2171 if (rmdir (dir) != 0)
2172 report_file_error ("Removing directory", directory);
2174 return Qnil;
2177 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2178 "(list (read-file-name \
2179 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2180 \"Move file to trash: \" \"Delete file: \") \
2181 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2182 (null current-prefix-arg))",
2183 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2184 If file has multiple names, it continues to exist with the other names.
2185 TRASH non-nil means to trash the file instead of deleting, provided
2186 `delete-by-moving-to-trash' is non-nil.
2188 When called interactively, TRASH is t if no prefix argument is given.
2189 With a prefix argument, TRASH is nil. */)
2190 (Lisp_Object filename, Lisp_Object trash)
2192 Lisp_Object handler;
2193 Lisp_Object encoded_file;
2195 if (!NILP (Ffile_directory_p (filename))
2196 && NILP (Ffile_symlink_p (filename)))
2197 xsignal2 (Qfile_error,
2198 build_string ("Removing old name: is a directory"),
2199 filename);
2200 filename = Fexpand_file_name (filename, Qnil);
2202 handler = Ffind_file_name_handler (filename, Qdelete_file);
2203 if (!NILP (handler))
2204 return call3 (handler, Qdelete_file, filename, trash);
2206 if (delete_by_moving_to_trash && !NILP (trash))
2207 return call1 (Qmove_file_to_trash, filename);
2209 encoded_file = ENCODE_FILE (filename);
2211 if (unlink (SSDATA (encoded_file)) < 0)
2212 report_file_error ("Removing old name", filename);
2213 return Qnil;
2216 static Lisp_Object
2217 internal_delete_file_1 (Lisp_Object ignore)
2219 return Qt;
2222 /* Delete file FILENAME, returning true if successful.
2223 This ignores `delete-by-moving-to-trash'. */
2225 bool
2226 internal_delete_file (Lisp_Object filename)
2228 Lisp_Object tem;
2230 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2231 Qt, internal_delete_file_1);
2232 return NILP (tem);
2235 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2236 "fRename file: \nGRename %s to file: \np",
2237 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2238 If file has names other than FILE, it continues to have those names.
2239 Signals a `file-already-exists' error if a file NEWNAME already exists
2240 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2241 A number as third arg means request confirmation if NEWNAME already exists.
2242 This is what happens in interactive use with M-x. */)
2243 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2245 Lisp_Object handler;
2246 Lisp_Object encoded_file, encoded_newname, symlink_target;
2248 symlink_target = encoded_file = encoded_newname = Qnil;
2249 CHECK_STRING (file);
2250 CHECK_STRING (newname);
2251 file = Fexpand_file_name (file, Qnil);
2253 if ((!NILP (Ffile_directory_p (newname)))
2254 #ifdef DOS_NT
2255 /* If the file names are identical but for the case,
2256 don't attempt to move directory to itself. */
2257 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2258 #endif
2261 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2262 ? file : Fdirectory_file_name (file));
2263 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2265 else
2266 newname = Fexpand_file_name (newname, Qnil);
2268 /* If the file name has special constructs in it,
2269 call the corresponding file handler. */
2270 handler = Ffind_file_name_handler (file, Qrename_file);
2271 if (NILP (handler))
2272 handler = Ffind_file_name_handler (newname, Qrename_file);
2273 if (!NILP (handler))
2274 return call4 (handler, Qrename_file,
2275 file, newname, ok_if_already_exists);
2277 encoded_file = ENCODE_FILE (file);
2278 encoded_newname = ENCODE_FILE (newname);
2280 #ifdef DOS_NT
2281 /* If the file names are identical but for the case, don't ask for
2282 confirmation: they simply want to change the letter-case of the
2283 file name. */
2284 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2285 #endif
2286 if (NILP (ok_if_already_exists)
2287 || INTEGERP (ok_if_already_exists))
2288 barf_or_query_if_file_exists (newname, false, "rename to it",
2289 INTEGERP (ok_if_already_exists), false);
2290 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2292 int rename_errno = errno;
2293 if (rename_errno == EXDEV)
2295 ptrdiff_t count;
2296 symlink_target = Ffile_symlink_p (file);
2297 if (! NILP (symlink_target))
2298 Fmake_symbolic_link (symlink_target, newname,
2299 NILP (ok_if_already_exists) ? Qnil : Qt);
2300 else if (!NILP (Ffile_directory_p (file)))
2301 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2302 else
2303 /* We have already prompted if it was an integer, so don't
2304 have copy-file prompt again. */
2305 Fcopy_file (file, newname,
2306 NILP (ok_if_already_exists) ? Qnil : Qt,
2307 Qt, Qt, Qt);
2309 count = SPECPDL_INDEX ();
2310 specbind (Qdelete_by_moving_to_trash, Qnil);
2312 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2313 call2 (Qdelete_directory, file, Qt);
2314 else
2315 Fdelete_file (file, Qnil);
2316 unbind_to (count, Qnil);
2318 else
2319 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2322 return Qnil;
2325 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2326 "fAdd name to file: \nGName to add to %s: \np",
2327 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2328 Signals a `file-already-exists' error if a file NEWNAME already exists
2329 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2330 A number as third arg means request confirmation if NEWNAME already exists.
2331 This is what happens in interactive use with M-x. */)
2332 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2334 Lisp_Object handler;
2335 Lisp_Object encoded_file, encoded_newname;
2337 encoded_file = encoded_newname = Qnil;
2338 CHECK_STRING (file);
2339 CHECK_STRING (newname);
2340 file = Fexpand_file_name (file, Qnil);
2342 if (!NILP (Ffile_directory_p (newname)))
2343 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2344 else
2345 newname = Fexpand_file_name (newname, Qnil);
2347 /* If the file name has special constructs in it,
2348 call the corresponding file handler. */
2349 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2350 if (!NILP (handler))
2351 return call4 (handler, Qadd_name_to_file, file,
2352 newname, ok_if_already_exists);
2354 /* If the new name has special constructs in it,
2355 call the corresponding file handler. */
2356 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2357 if (!NILP (handler))
2358 return call4 (handler, Qadd_name_to_file, file,
2359 newname, ok_if_already_exists);
2361 encoded_file = ENCODE_FILE (file);
2362 encoded_newname = ENCODE_FILE (newname);
2364 if (NILP (ok_if_already_exists)
2365 || INTEGERP (ok_if_already_exists))
2366 barf_or_query_if_file_exists (newname, false, "make it a new name",
2367 INTEGERP (ok_if_already_exists), false);
2369 unlink (SSDATA (newname));
2370 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2372 int link_errno = errno;
2373 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2376 return Qnil;
2379 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2380 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2381 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2382 Both args must be strings.
2383 Signals a `file-already-exists' error if a file LINKNAME already exists
2384 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2385 A number as third arg means request confirmation if LINKNAME already exists.
2386 This happens for interactive use with M-x. */)
2387 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2389 Lisp_Object handler;
2390 Lisp_Object encoded_target, encoded_linkname;
2392 encoded_target = encoded_linkname = Qnil;
2393 CHECK_STRING (target);
2394 CHECK_STRING (linkname);
2395 /* If the link target has a ~, we must expand it to get
2396 a truly valid file name. Otherwise, do not expand;
2397 we want to permit links to relative file names. */
2398 if (SREF (target, 0) == '~')
2399 target = Fexpand_file_name (target, Qnil);
2401 if (!NILP (Ffile_directory_p (linkname)))
2402 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2403 else
2404 linkname = Fexpand_file_name (linkname, Qnil);
2406 /* If the file name has special constructs in it,
2407 call the corresponding file handler. */
2408 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2409 if (!NILP (handler))
2410 return call4 (handler, Qmake_symbolic_link, target,
2411 linkname, ok_if_already_exists);
2413 /* If the new link name has special constructs in it,
2414 call the corresponding file handler. */
2415 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2416 if (!NILP (handler))
2417 return call4 (handler, Qmake_symbolic_link, target,
2418 linkname, ok_if_already_exists);
2420 encoded_target = ENCODE_FILE (target);
2421 encoded_linkname = ENCODE_FILE (linkname);
2423 if (NILP (ok_if_already_exists)
2424 || INTEGERP (ok_if_already_exists))
2425 barf_or_query_if_file_exists (linkname, false, "make it a link",
2426 INTEGERP (ok_if_already_exists), false);
2427 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2429 /* If we didn't complain already, silently delete existing file. */
2430 int symlink_errno;
2431 if (errno == EEXIST)
2433 unlink (SSDATA (encoded_linkname));
2434 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2435 >= 0)
2436 return Qnil;
2438 if (errno == ENOSYS)
2439 xsignal1 (Qfile_error,
2440 build_string ("Symbolic links are not supported"));
2442 symlink_errno = errno;
2443 report_file_errno ("Making symbolic link", list2 (target, linkname),
2444 symlink_errno);
2447 return Qnil;
2451 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2452 1, 1, 0,
2453 doc: /* Return t if file FILENAME specifies an absolute file name.
2454 On Unix, this is a name starting with a `/' or a `~'. */)
2455 (Lisp_Object filename)
2457 CHECK_STRING (filename);
2458 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2461 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2462 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2463 See also `file-readable-p' and `file-attributes'.
2464 This returns nil for a symlink to a nonexistent file.
2465 Use `file-symlink-p' to test for such links. */)
2466 (Lisp_Object filename)
2468 Lisp_Object absname;
2469 Lisp_Object handler;
2471 CHECK_STRING (filename);
2472 absname = Fexpand_file_name (filename, Qnil);
2474 /* If the file name has special constructs in it,
2475 call the corresponding file handler. */
2476 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2477 if (!NILP (handler))
2479 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2480 errno = 0;
2481 return result;
2484 absname = ENCODE_FILE (absname);
2486 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2489 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2490 doc: /* Return t if FILENAME can be executed by you.
2491 For a directory, this means you can access files in that directory.
2492 \(It is generally better to use `file-accessible-directory-p' for that
2493 purpose, though.) */)
2494 (Lisp_Object filename)
2496 Lisp_Object absname;
2497 Lisp_Object handler;
2499 CHECK_STRING (filename);
2500 absname = Fexpand_file_name (filename, Qnil);
2502 /* If the file name has special constructs in it,
2503 call the corresponding file handler. */
2504 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2505 if (!NILP (handler))
2506 return call2 (handler, Qfile_executable_p, absname);
2508 absname = ENCODE_FILE (absname);
2510 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2513 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2514 doc: /* Return t if file FILENAME exists and you can read it.
2515 See also `file-exists-p' and `file-attributes'. */)
2516 (Lisp_Object filename)
2518 Lisp_Object absname;
2519 Lisp_Object handler;
2521 CHECK_STRING (filename);
2522 absname = Fexpand_file_name (filename, Qnil);
2524 /* If the file name has special constructs in it,
2525 call the corresponding file handler. */
2526 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2527 if (!NILP (handler))
2528 return call2 (handler, Qfile_readable_p, absname);
2530 absname = ENCODE_FILE (absname);
2531 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2532 ? Qt : Qnil);
2535 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2536 doc: /* Return t if file FILENAME can be written or created by you. */)
2537 (Lisp_Object filename)
2539 Lisp_Object absname, dir, encoded;
2540 Lisp_Object handler;
2542 CHECK_STRING (filename);
2543 absname = Fexpand_file_name (filename, Qnil);
2545 /* If the file name has special constructs in it,
2546 call the corresponding file handler. */
2547 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2548 if (!NILP (handler))
2549 return call2 (handler, Qfile_writable_p, absname);
2551 encoded = ENCODE_FILE (absname);
2552 if (check_writable (SSDATA (encoded), W_OK))
2553 return Qt;
2554 if (errno != ENOENT)
2555 return Qnil;
2557 dir = Ffile_name_directory (absname);
2558 eassert (!NILP (dir));
2559 #ifdef MSDOS
2560 dir = Fdirectory_file_name (dir);
2561 #endif /* MSDOS */
2563 dir = ENCODE_FILE (dir);
2564 #ifdef WINDOWSNT
2565 /* The read-only attribute of the parent directory doesn't affect
2566 whether a file or directory can be created within it. Some day we
2567 should check ACLs though, which do affect this. */
2568 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2569 #else
2570 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2571 #endif
2574 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2575 doc: /* Access file FILENAME, and get an error if that does not work.
2576 The second argument STRING is used in the error message.
2577 If there is no error, returns nil. */)
2578 (Lisp_Object filename, Lisp_Object string)
2580 Lisp_Object handler, encoded_filename, absname;
2582 CHECK_STRING (filename);
2583 absname = Fexpand_file_name (filename, Qnil);
2585 CHECK_STRING (string);
2587 /* If the file name has special constructs in it,
2588 call the corresponding file handler. */
2589 handler = Ffind_file_name_handler (absname, Qaccess_file);
2590 if (!NILP (handler))
2591 return call3 (handler, Qaccess_file, absname, string);
2593 encoded_filename = ENCODE_FILE (absname);
2595 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2596 report_file_error (SSDATA (string), filename);
2598 return Qnil;
2601 /* Relative to directory FD, return the symbolic link value of FILENAME.
2602 On failure, return nil. */
2603 Lisp_Object
2604 emacs_readlinkat (int fd, char const *filename)
2606 static struct allocator const emacs_norealloc_allocator =
2607 { xmalloc, NULL, xfree, memory_full };
2608 Lisp_Object val;
2609 char readlink_buf[1024];
2610 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2611 &emacs_norealloc_allocator, readlinkat);
2612 if (!buf)
2613 return Qnil;
2615 val = build_unibyte_string (buf);
2616 if (buf[0] == '/' && strchr (buf, ':'))
2618 AUTO_STRING (slash_colon, "/:");
2619 val = concat2 (slash_colon, val);
2621 if (buf != readlink_buf)
2622 xfree (buf);
2623 val = DECODE_FILE (val);
2624 return val;
2627 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2628 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2629 The value is the link target, as a string.
2630 Otherwise it returns nil.
2632 This function does not check whether the link target exists. */)
2633 (Lisp_Object filename)
2635 Lisp_Object handler;
2637 CHECK_STRING (filename);
2638 filename = Fexpand_file_name (filename, Qnil);
2640 /* If the file name has special constructs in it,
2641 call the corresponding file handler. */
2642 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2643 if (!NILP (handler))
2644 return call2 (handler, Qfile_symlink_p, filename);
2646 filename = ENCODE_FILE (filename);
2648 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2651 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2652 doc: /* Return t if FILENAME names an existing directory.
2653 Symbolic links to directories count as directories.
2654 See `file-symlink-p' to distinguish symlinks. */)
2655 (Lisp_Object filename)
2657 Lisp_Object absname;
2658 Lisp_Object handler;
2660 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2662 /* If the file name has special constructs in it,
2663 call the corresponding file handler. */
2664 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2665 if (!NILP (handler))
2666 return call2 (handler, Qfile_directory_p, absname);
2668 absname = ENCODE_FILE (absname);
2670 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2673 /* Return true if FILE is a directory or a symlink to a directory. */
2674 bool
2675 file_directory_p (char const *file)
2677 #ifdef WINDOWSNT
2678 /* This is cheaper than 'stat'. */
2679 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2680 #else
2681 struct stat st;
2682 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2683 #endif
2686 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2687 Sfile_accessible_directory_p, 1, 1, 0,
2688 doc: /* Return t if FILENAME names a directory you can open.
2689 For the value to be t, FILENAME must specify the name of a directory
2690 as a file, and the directory must allow you to open files in it. In
2691 order to use a directory as a buffer's current directory, this
2692 predicate must return true. A directory name spec may be given
2693 instead; then the value is t if the directory so specified exists and
2694 really is a readable and searchable directory. */)
2695 (Lisp_Object filename)
2697 Lisp_Object absname;
2698 Lisp_Object handler;
2700 CHECK_STRING (filename);
2701 absname = Fexpand_file_name (filename, Qnil);
2703 /* If the file name has special constructs in it,
2704 call the corresponding file handler. */
2705 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2706 if (!NILP (handler))
2708 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2709 errno = 0;
2710 return r;
2713 absname = ENCODE_FILE (absname);
2714 return file_accessible_directory_p (absname) ? Qt : Qnil;
2717 /* If FILE is a searchable directory or a symlink to a
2718 searchable directory, return true. Otherwise return
2719 false and set errno to an error number. */
2720 bool
2721 file_accessible_directory_p (Lisp_Object file)
2723 #ifdef DOS_NT
2724 # ifdef WINDOWSNT
2725 /* We need a special-purpose test because (a) NTFS security data is
2726 not reflected in Posix-style mode bits, and (b) the trick with
2727 accessing "DIR/.", used below on Posix hosts, doesn't work on
2728 Windows, because "DIR/." is normalized to just "DIR" before
2729 hitting the disk. */
2730 return (SBYTES (file) == 0
2731 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2732 # else /* MSDOS */
2733 return file_directory_p (SSDATA (file));
2734 # endif /* MSDOS */
2735 #else /* !DOS_NT */
2736 /* On POSIXish platforms, use just one system call; this avoids a
2737 race and is typically faster. */
2738 const char *data = SSDATA (file);
2739 ptrdiff_t len = SBYTES (file);
2740 char const *dir;
2741 bool ok;
2742 int saved_errno;
2743 USE_SAFE_ALLOCA;
2745 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2746 There are three exceptions: "", "/", and "//". Leave "" alone,
2747 as it's invalid. Append only "." to the other two exceptions as
2748 "/" and "//" are distinct on some platforms, whereas "/", "///",
2749 "////", etc. are all equivalent. */
2750 if (! len)
2751 dir = data;
2752 else
2754 /* Just check for trailing '/' when deciding whether to append '/'.
2755 That's simpler than testing the two special cases "/" and "//",
2756 and it's a safe optimization here. */
2757 char *buf = SAFE_ALLOCA (len + 3);
2758 memcpy (buf, data, len);
2759 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2760 dir = buf;
2763 ok = check_existing (dir);
2764 saved_errno = errno;
2765 SAFE_FREE ();
2766 errno = saved_errno;
2767 return ok;
2768 #endif /* !DOS_NT */
2771 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2772 doc: /* Return t if FILENAME names a regular file.
2773 This is the sort of file that holds an ordinary stream of data bytes.
2774 Symbolic links to regular files count as regular files.
2775 See `file-symlink-p' to distinguish symlinks. */)
2776 (Lisp_Object filename)
2778 register Lisp_Object absname;
2779 struct stat st;
2780 Lisp_Object handler;
2782 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2784 /* If the file name has special constructs in it,
2785 call the corresponding file handler. */
2786 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2787 if (!NILP (handler))
2788 return call2 (handler, Qfile_regular_p, absname);
2790 absname = ENCODE_FILE (absname);
2792 #ifdef WINDOWSNT
2794 int result;
2795 Lisp_Object tem = Vw32_get_true_file_attributes;
2797 /* Tell stat to use expensive method to get accurate info. */
2798 Vw32_get_true_file_attributes = Qt;
2799 result = stat (SSDATA (absname), &st);
2800 Vw32_get_true_file_attributes = tem;
2802 if (result < 0)
2803 return Qnil;
2804 return S_ISREG (st.st_mode) ? Qt : Qnil;
2806 #else
2807 if (stat (SSDATA (absname), &st) < 0)
2808 return Qnil;
2809 return S_ISREG (st.st_mode) ? Qt : Qnil;
2810 #endif
2813 DEFUN ("file-selinux-context", Ffile_selinux_context,
2814 Sfile_selinux_context, 1, 1, 0,
2815 doc: /* Return SELinux context of file named FILENAME.
2816 The return value is a list (USER ROLE TYPE RANGE), where the list
2817 elements are strings naming the user, role, type, and range of the
2818 file's SELinux security context.
2820 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2821 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2822 (Lisp_Object filename)
2824 Lisp_Object absname;
2825 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2827 Lisp_Object handler;
2828 #if HAVE_LIBSELINUX
2829 security_context_t con;
2830 int conlength;
2831 context_t context;
2832 #endif
2834 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2836 /* If the file name has special constructs in it,
2837 call the corresponding file handler. */
2838 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2839 if (!NILP (handler))
2840 return call2 (handler, Qfile_selinux_context, absname);
2842 absname = ENCODE_FILE (absname);
2844 #if HAVE_LIBSELINUX
2845 if (is_selinux_enabled ())
2847 conlength = lgetfilecon (SSDATA (absname), &con);
2848 if (conlength > 0)
2850 context = context_new (con);
2851 if (context_user_get (context))
2852 user = build_string (context_user_get (context));
2853 if (context_role_get (context))
2854 role = build_string (context_role_get (context));
2855 if (context_type_get (context))
2856 type = build_string (context_type_get (context));
2857 if (context_range_get (context))
2858 range = build_string (context_range_get (context));
2859 context_free (context);
2860 freecon (con);
2863 #endif
2865 return list4 (user, role, type, range);
2868 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2869 Sset_file_selinux_context, 2, 2, 0,
2870 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2871 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2872 elements are strings naming the components of a SELinux context.
2874 Value is t if setting of SELinux context was successful, nil otherwise.
2876 This function does nothing and returns nil if SELinux is disabled,
2877 or if Emacs was not compiled with SELinux support. */)
2878 (Lisp_Object filename, Lisp_Object context)
2880 Lisp_Object absname;
2881 Lisp_Object handler;
2882 #if HAVE_LIBSELINUX
2883 Lisp_Object encoded_absname;
2884 Lisp_Object user = CAR_SAFE (context);
2885 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2886 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2887 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2888 security_context_t con;
2889 bool fail;
2890 int conlength;
2891 context_t parsed_con;
2892 #endif
2894 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2896 /* If the file name has special constructs in it,
2897 call the corresponding file handler. */
2898 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2899 if (!NILP (handler))
2900 return call3 (handler, Qset_file_selinux_context, absname, context);
2902 #if HAVE_LIBSELINUX
2903 if (is_selinux_enabled ())
2905 /* Get current file context. */
2906 encoded_absname = ENCODE_FILE (absname);
2907 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2908 if (conlength > 0)
2910 parsed_con = context_new (con);
2911 /* Change the parts defined in the parameter.*/
2912 if (STRINGP (user))
2914 if (context_user_set (parsed_con, SSDATA (user)))
2915 error ("Doing context_user_set");
2917 if (STRINGP (role))
2919 if (context_role_set (parsed_con, SSDATA (role)))
2920 error ("Doing context_role_set");
2922 if (STRINGP (type))
2924 if (context_type_set (parsed_con, SSDATA (type)))
2925 error ("Doing context_type_set");
2927 if (STRINGP (range))
2929 if (context_range_set (parsed_con, SSDATA (range)))
2930 error ("Doing context_range_set");
2933 /* Set the modified context back to the file. */
2934 fail = (lsetfilecon (SSDATA (encoded_absname),
2935 context_str (parsed_con))
2936 != 0);
2937 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2938 if (fail && errno != ENOTSUP)
2939 report_file_error ("Doing lsetfilecon", absname);
2941 context_free (parsed_con);
2942 freecon (con);
2943 return fail ? Qnil : Qt;
2945 else
2946 report_file_error ("Doing lgetfilecon", absname);
2948 #endif
2950 return Qnil;
2953 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2954 doc: /* Return ACL entries of file named FILENAME.
2955 The entries are returned in a format suitable for use in `set-file-acl'
2956 but is otherwise undocumented and subject to change.
2957 Return nil if file does not exist or is not accessible, or if Emacs
2958 was unable to determine the ACL entries. */)
2959 (Lisp_Object filename)
2961 #if USE_ACL
2962 Lisp_Object absname;
2963 Lisp_Object handler;
2964 # ifdef HAVE_ACL_SET_FILE
2965 acl_t acl;
2966 Lisp_Object acl_string;
2967 char *str;
2968 # ifndef HAVE_ACL_TYPE_EXTENDED
2969 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2970 # endif
2971 # endif
2973 absname = expand_and_dir_to_file (filename,
2974 BVAR (current_buffer, directory));
2976 /* If the file name has special constructs in it,
2977 call the corresponding file handler. */
2978 handler = Ffind_file_name_handler (absname, Qfile_acl);
2979 if (!NILP (handler))
2980 return call2 (handler, Qfile_acl, absname);
2982 # ifdef HAVE_ACL_SET_FILE
2983 absname = ENCODE_FILE (absname);
2985 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2986 if (acl == NULL)
2987 return Qnil;
2989 str = acl_to_text (acl, NULL);
2990 if (str == NULL)
2992 acl_free (acl);
2993 return Qnil;
2996 acl_string = build_string (str);
2997 acl_free (str);
2998 acl_free (acl);
3000 return acl_string;
3001 # endif
3002 #endif
3004 return Qnil;
3007 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3008 2, 2, 0,
3009 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3010 ACL-STRING should contain the textual representation of the ACL
3011 entries in a format suitable for the platform.
3013 Value is t if setting of ACL was successful, nil otherwise.
3015 Setting ACL for local files requires Emacs to be built with ACL
3016 support. */)
3017 (Lisp_Object filename, Lisp_Object acl_string)
3019 #if USE_ACL
3020 Lisp_Object absname;
3021 Lisp_Object handler;
3022 # ifdef HAVE_ACL_SET_FILE
3023 Lisp_Object encoded_absname;
3024 acl_t acl;
3025 bool fail;
3026 # endif
3028 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3030 /* If the file name has special constructs in it,
3031 call the corresponding file handler. */
3032 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3033 if (!NILP (handler))
3034 return call3 (handler, Qset_file_acl, absname, acl_string);
3036 # ifdef HAVE_ACL_SET_FILE
3037 if (STRINGP (acl_string))
3039 acl = acl_from_text (SSDATA (acl_string));
3040 if (acl == NULL)
3042 report_file_error ("Converting ACL", absname);
3043 return Qnil;
3046 encoded_absname = ENCODE_FILE (absname);
3048 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3049 acl)
3050 != 0);
3051 if (fail && acl_errno_valid (errno))
3052 report_file_error ("Setting ACL", absname);
3054 acl_free (acl);
3055 return fail ? Qnil : Qt;
3057 # endif
3058 #endif
3060 return Qnil;
3063 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3064 doc: /* Return mode bits of file named FILENAME, as an integer.
3065 Return nil, if file does not exist or is not accessible. */)
3066 (Lisp_Object filename)
3068 Lisp_Object absname;
3069 struct stat st;
3070 Lisp_Object handler;
3072 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3074 /* If the file name has special constructs in it,
3075 call the corresponding file handler. */
3076 handler = Ffind_file_name_handler (absname, Qfile_modes);
3077 if (!NILP (handler))
3078 return call2 (handler, Qfile_modes, absname);
3080 absname = ENCODE_FILE (absname);
3082 if (stat (SSDATA (absname), &st) < 0)
3083 return Qnil;
3085 return make_number (st.st_mode & 07777);
3088 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3089 "(let ((file (read-file-name \"File: \"))) \
3090 (list file (read-file-modes nil file)))",
3091 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3092 Only the 12 low bits of MODE are used.
3094 Interactively, mode bits are read by `read-file-modes', which accepts
3095 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3096 (Lisp_Object filename, Lisp_Object mode)
3098 Lisp_Object absname, encoded_absname;
3099 Lisp_Object handler;
3101 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3102 CHECK_NUMBER (mode);
3104 /* If the file name has special constructs in it,
3105 call the corresponding file handler. */
3106 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3107 if (!NILP (handler))
3108 return call3 (handler, Qset_file_modes, absname, mode);
3110 encoded_absname = ENCODE_FILE (absname);
3112 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3113 report_file_error ("Doing chmod", absname);
3115 return Qnil;
3118 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3119 doc: /* Set the file permission bits for newly created files.
3120 The argument MODE should be an integer; only the low 9 bits are used.
3121 This setting is inherited by subprocesses. */)
3122 (Lisp_Object mode)
3124 mode_t oldrealmask, oldumask, newumask;
3125 CHECK_NUMBER (mode);
3126 oldrealmask = realmask;
3127 newumask = ~ XINT (mode) & 0777;
3129 block_input ();
3130 realmask = newumask;
3131 oldumask = umask (newumask);
3132 unblock_input ();
3134 eassert (oldumask == oldrealmask);
3135 return Qnil;
3138 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3139 doc: /* Return the default file protection for created files.
3140 The value is an integer. */)
3141 (void)
3143 Lisp_Object value;
3144 XSETINT (value, (~ realmask) & 0777);
3145 return value;
3149 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3150 doc: /* Set times of file FILENAME to TIMESTAMP.
3151 Set both access and modification times.
3152 Return t on success, else nil.
3153 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3154 `current-time'. */)
3155 (Lisp_Object filename, Lisp_Object timestamp)
3157 Lisp_Object absname, encoded_absname;
3158 Lisp_Object handler;
3159 struct timespec t = lisp_time_argument (timestamp);
3161 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3163 /* If the file name has special constructs in it,
3164 call the corresponding file handler. */
3165 handler = Ffind_file_name_handler (absname, Qset_file_times);
3166 if (!NILP (handler))
3167 return call3 (handler, Qset_file_times, absname, timestamp);
3169 encoded_absname = ENCODE_FILE (absname);
3172 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3174 #ifdef MSDOS
3175 /* Setting times on a directory always fails. */
3176 if (file_directory_p (SSDATA (encoded_absname)))
3177 return Qnil;
3178 #endif
3179 report_file_error ("Setting file times", absname);
3183 return Qt;
3186 #ifdef HAVE_SYNC
3187 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3188 doc: /* Tell Unix to finish all pending disk updates. */)
3189 (void)
3191 sync ();
3192 return Qnil;
3195 #endif /* HAVE_SYNC */
3197 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3198 doc: /* Return t if file FILE1 is newer than file FILE2.
3199 If FILE1 does not exist, the answer is nil;
3200 otherwise, if FILE2 does not exist, the answer is t. */)
3201 (Lisp_Object file1, Lisp_Object file2)
3203 Lisp_Object absname1, absname2;
3204 struct stat st1, st2;
3205 Lisp_Object handler;
3207 CHECK_STRING (file1);
3208 CHECK_STRING (file2);
3210 absname1 = Qnil;
3211 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3212 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3214 /* If the file name has special constructs in it,
3215 call the corresponding file handler. */
3216 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3217 if (NILP (handler))
3218 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3219 if (!NILP (handler))
3220 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3222 absname1 = ENCODE_FILE (absname1);
3223 absname2 = ENCODE_FILE (absname2);
3225 if (stat (SSDATA (absname1), &st1) < 0)
3226 return Qnil;
3228 if (stat (SSDATA (absname2), &st2) < 0)
3229 return Qt;
3231 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3232 ? Qt : Qnil);
3235 #ifndef READ_BUF_SIZE
3236 #define READ_BUF_SIZE (64 << 10)
3237 #endif
3238 /* Some buffer offsets are stored in 'int' variables. */
3239 verify (READ_BUF_SIZE <= INT_MAX);
3241 /* This function is called after Lisp functions to decide a coding
3242 system are called, or when they cause an error. Before they are
3243 called, the current buffer is set unibyte and it contains only a
3244 newly inserted text (thus the buffer was empty before the
3245 insertion).
3247 The functions may set markers, overlays, text properties, or even
3248 alter the buffer contents, change the current buffer.
3250 Here, we reset all those changes by:
3251 o set back the current buffer.
3252 o move all markers and overlays to BEG.
3253 o remove all text properties.
3254 o set back the buffer multibyteness. */
3256 static void
3257 decide_coding_unwind (Lisp_Object unwind_data)
3259 Lisp_Object multibyte, undo_list, buffer;
3261 multibyte = XCAR (unwind_data);
3262 unwind_data = XCDR (unwind_data);
3263 undo_list = XCAR (unwind_data);
3264 buffer = XCDR (unwind_data);
3266 set_buffer_internal (XBUFFER (buffer));
3267 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3268 adjust_overlays_for_delete (BEG, Z - BEG);
3269 set_buffer_intervals (current_buffer, NULL);
3270 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3272 /* Now we are safe to change the buffer's multibyteness directly. */
3273 bset_enable_multibyte_characters (current_buffer, multibyte);
3274 bset_undo_list (current_buffer, undo_list);
3277 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3278 object where slot 0 is the file descriptor, slot 1 specifies
3279 an offset to put the read bytes, and slot 2 is the maximum
3280 amount of bytes to read. Value is the number of bytes read. */
3282 static Lisp_Object
3283 read_non_regular (Lisp_Object state)
3285 int nbytes;
3287 immediate_quit = 1;
3288 QUIT;
3289 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3290 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3291 + XSAVE_INTEGER (state, 1)),
3292 XSAVE_INTEGER (state, 2));
3293 immediate_quit = 0;
3294 /* Fast recycle this object for the likely next call. */
3295 free_misc (state);
3296 return make_number (nbytes);
3300 /* Condition-case handler used when reading from non-regular files
3301 in insert-file-contents. */
3303 static Lisp_Object
3304 read_non_regular_quit (Lisp_Object ignore)
3306 return Qnil;
3309 /* Return the file offset that VAL represents, checking for type
3310 errors and overflow. */
3311 static off_t
3312 file_offset (Lisp_Object val)
3314 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3315 return XINT (val);
3317 if (FLOATP (val))
3319 double v = XFLOAT_DATA (val);
3320 if (0 <= v
3321 && (sizeof (off_t) < sizeof v
3322 ? v <= TYPE_MAXIMUM (off_t)
3323 : v < TYPE_MAXIMUM (off_t)))
3324 return v;
3327 wrong_type_argument (intern ("file-offset"), val);
3330 /* Return a special time value indicating the error number ERRNUM. */
3331 static struct timespec
3332 time_error_value (int errnum)
3334 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3335 ? NONEXISTENT_MODTIME_NSECS
3336 : UNKNOWN_MODTIME_NSECS);
3337 return make_timespec (0, ns);
3340 static Lisp_Object
3341 get_window_points_and_markers (void)
3343 Lisp_Object pt_marker = Fpoint_marker ();
3344 Lisp_Object windows
3345 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3346 Lisp_Object window_markers = windows;
3347 /* Window markers (and point) are handled specially: rather than move to
3348 just before or just after the modified text, we try to keep the
3349 markers at the same distance (bug#19161).
3350 In general, this is wrong, but for window-markers, this should be harmless
3351 and is convenient for the end user when most of the file is unmodified,
3352 except for a few minor details near the beginning and near the end. */
3353 for (; CONSP (windows); windows = XCDR (windows))
3354 if (WINDOWP (XCAR (windows)))
3356 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3357 XSETCAR (windows,
3358 Fcons (window_marker, Fmarker_position (window_marker)));
3360 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3363 static void
3364 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3365 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3367 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3368 if (CONSP (XCAR (window_markers)))
3370 Lisp_Object car = XCAR (window_markers);
3371 Lisp_Object marker = XCAR (car);
3372 Lisp_Object oldpos = XCDR (car);
3373 if (MARKERP (marker) && INTEGERP (oldpos)
3374 && XINT (oldpos) > same_at_start
3375 && XINT (oldpos) < same_at_end)
3377 ptrdiff_t oldsize = same_at_end - same_at_start;
3378 ptrdiff_t newsize = inserted;
3379 double growth = newsize / (double)oldsize;
3380 ptrdiff_t newpos
3381 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3382 Fset_marker (marker, make_number (newpos), Qnil);
3387 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3388 text as a linear C char array. */
3389 static void
3390 maybe_move_gap (struct buffer *b)
3392 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3394 struct buffer *cb = current_buffer;
3396 set_buffer_internal (b);
3397 move_gap_both (Z, Z_BYTE);
3398 set_buffer_internal (cb);
3402 /* FIXME: insert-file-contents should be split with the top-level moved to
3403 Elisp and only the core kept in C. */
3405 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3406 1, 5, 0,
3407 doc: /* Insert contents of file FILENAME after point.
3408 Returns list of absolute file name and number of characters inserted.
3409 If second argument VISIT is non-nil, the buffer's visited filename and
3410 last save file modtime are set, and it is marked unmodified. If
3411 visiting and the file does not exist, visiting is completed before the
3412 error is signaled.
3414 The optional third and fourth arguments BEG and END specify what portion
3415 of the file to insert. These arguments count bytes in the file, not
3416 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3418 If optional fifth argument REPLACE is non-nil, replace the current
3419 buffer contents (in the accessible portion) with the file contents.
3420 This is better than simply deleting and inserting the whole thing
3421 because (1) it preserves some marker positions and (2) it puts less data
3422 in the undo list. When REPLACE is non-nil, the second return value is
3423 the number of characters that replace previous buffer contents.
3425 This function does code conversion according to the value of
3426 `coding-system-for-read' or `file-coding-system-alist', and sets the
3427 variable `last-coding-system-used' to the coding system actually used.
3429 In addition, this function decodes the inserted text from known formats
3430 by calling `format-decode', which see. */)
3431 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3433 struct stat st;
3434 struct timespec mtime;
3435 int fd;
3436 ptrdiff_t inserted = 0;
3437 ptrdiff_t how_much;
3438 off_t beg_offset, end_offset;
3439 int unprocessed;
3440 ptrdiff_t count = SPECPDL_INDEX ();
3441 Lisp_Object handler, val, insval, orig_filename, old_undo;
3442 Lisp_Object p;
3443 ptrdiff_t total = 0;
3444 bool not_regular = 0;
3445 int save_errno = 0;
3446 char read_buf[READ_BUF_SIZE];
3447 struct coding_system coding;
3448 bool replace_handled = false;
3449 bool set_coding_system = false;
3450 Lisp_Object coding_system;
3451 bool read_quit = false;
3452 /* If the undo log only contains the insertion, there's no point
3453 keeping it. It's typically when we first fill a file-buffer. */
3454 bool empty_undo_list_p
3455 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3456 && BEG == Z);
3457 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3458 bool we_locked_file = false;
3459 ptrdiff_t fd_index;
3460 Lisp_Object window_markers = Qnil;
3461 /* same_at_start and same_at_end count bytes, because file access counts
3462 bytes and BEG and END count bytes. */
3463 ptrdiff_t same_at_start = BEGV_BYTE;
3464 ptrdiff_t same_at_end = ZV_BYTE;
3465 /* SAME_AT_END_CHARPOS counts characters, because
3466 restore_window_points needs the old character count. */
3467 ptrdiff_t same_at_end_charpos = ZV;
3469 if (current_buffer->base_buffer && ! NILP (visit))
3470 error ("Cannot do file visiting in an indirect buffer");
3472 if (!NILP (BVAR (current_buffer, read_only)))
3473 Fbarf_if_buffer_read_only (Qnil);
3475 val = Qnil;
3476 p = Qnil;
3477 orig_filename = Qnil;
3478 old_undo = Qnil;
3480 CHECK_STRING (filename);
3481 filename = Fexpand_file_name (filename, Qnil);
3483 /* The value Qnil means that the coding system is not yet
3484 decided. */
3485 coding_system = Qnil;
3487 /* If the file name has special constructs in it,
3488 call the corresponding file handler. */
3489 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3490 if (!NILP (handler))
3492 val = call6 (handler, Qinsert_file_contents, filename,
3493 visit, beg, end, replace);
3494 if (CONSP (val) && CONSP (XCDR (val))
3495 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3496 inserted = XINT (XCAR (XCDR (val)));
3497 goto handled;
3500 orig_filename = filename;
3501 filename = ENCODE_FILE (filename);
3503 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3504 if (fd < 0)
3506 save_errno = errno;
3507 if (NILP (visit))
3508 report_file_error ("Opening input file", orig_filename);
3509 mtime = time_error_value (save_errno);
3510 st.st_size = -1;
3511 if (!NILP (Vcoding_system_for_read))
3513 /* Don't let invalid values into buffer-file-coding-system. */
3514 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3515 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3517 goto notfound;
3520 fd_index = SPECPDL_INDEX ();
3521 record_unwind_protect_int (close_file_unwind, fd);
3523 /* Replacement should preserve point as it preserves markers. */
3524 if (!NILP (replace))
3526 window_markers = get_window_points_and_markers ();
3527 record_unwind_protect (restore_point_unwind,
3528 XCAR (XCAR (window_markers)));
3531 if (fstat (fd, &st) != 0)
3532 report_file_error ("Input file status", orig_filename);
3533 mtime = get_stat_mtime (&st);
3535 /* This code will need to be changed in order to work on named
3536 pipes, and it's probably just not worth it. So we should at
3537 least signal an error. */
3538 if (!S_ISREG (st.st_mode))
3540 not_regular = 1;
3542 if (! NILP (visit))
3543 goto notfound;
3545 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3546 xsignal2 (Qfile_error,
3547 build_string ("not a regular file"), orig_filename);
3550 if (!NILP (visit))
3552 if (!NILP (beg) || !NILP (end))
3553 error ("Attempt to visit less than an entire file");
3554 if (BEG < Z && NILP (replace))
3555 error ("Cannot do file visiting in a non-empty buffer");
3558 if (!NILP (beg))
3559 beg_offset = file_offset (beg);
3560 else
3561 beg_offset = 0;
3563 if (!NILP (end))
3564 end_offset = file_offset (end);
3565 else
3567 if (not_regular)
3568 end_offset = TYPE_MAXIMUM (off_t);
3569 else
3571 end_offset = st.st_size;
3573 /* A negative size can happen on a platform that allows file
3574 sizes greater than the maximum off_t value. */
3575 if (end_offset < 0)
3576 buffer_overflow ();
3578 /* The file size returned from stat may be zero, but data
3579 may be readable nonetheless, for example when this is a
3580 file in the /proc filesystem. */
3581 if (end_offset == 0)
3582 end_offset = READ_BUF_SIZE;
3586 /* Check now whether the buffer will become too large,
3587 in the likely case where the file's length is not changing.
3588 This saves a lot of needless work before a buffer overflow. */
3589 if (! not_regular)
3591 /* The likely offset where we will stop reading. We could read
3592 more (or less), if the file grows (or shrinks) as we read it. */
3593 off_t likely_end = min (end_offset, st.st_size);
3595 if (beg_offset < likely_end)
3597 ptrdiff_t buf_bytes
3598 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3599 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3600 off_t likely_growth = likely_end - beg_offset;
3601 if (buf_growth_max < likely_growth)
3602 buffer_overflow ();
3606 /* Prevent redisplay optimizations. */
3607 current_buffer->clip_changed = true;
3609 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3611 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3612 setup_coding_system (coding_system, &coding);
3613 /* Ensure we set Vlast_coding_system_used. */
3614 set_coding_system = true;
3616 else if (BEG < Z)
3618 /* Decide the coding system to use for reading the file now
3619 because we can't use an optimized method for handling
3620 `coding:' tag if the current buffer is not empty. */
3621 if (!NILP (Vcoding_system_for_read))
3622 coding_system = Vcoding_system_for_read;
3623 else
3625 /* Don't try looking inside a file for a coding system
3626 specification if it is not seekable. */
3627 if (! not_regular && ! NILP (Vset_auto_coding_function))
3629 /* Find a coding system specified in the heading two
3630 lines or in the tailing several lines of the file.
3631 We assume that the 1K-byte and 3K-byte for heading
3632 and tailing respectively are sufficient for this
3633 purpose. */
3634 int nread;
3636 if (st.st_size <= (1024 * 4))
3637 nread = emacs_read (fd, read_buf, 1024 * 4);
3638 else
3640 nread = emacs_read (fd, read_buf, 1024);
3641 if (nread == 1024)
3643 int ntail;
3644 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3645 report_file_error ("Setting file position",
3646 orig_filename);
3647 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3648 nread = ntail < 0 ? ntail : nread + ntail;
3652 if (nread < 0)
3653 report_file_error ("Read error", orig_filename);
3654 else if (nread > 0)
3656 AUTO_STRING (name, " *code-converting-work*");
3657 struct buffer *prev = current_buffer;
3658 Lisp_Object workbuf;
3659 struct buffer *buf;
3661 record_unwind_current_buffer ();
3663 workbuf = Fget_buffer_create (name);
3664 buf = XBUFFER (workbuf);
3666 delete_all_overlays (buf);
3667 bset_directory (buf, BVAR (current_buffer, directory));
3668 bset_read_only (buf, Qnil);
3669 bset_filename (buf, Qnil);
3670 bset_undo_list (buf, Qt);
3671 eassert (buf->overlays_before == NULL);
3672 eassert (buf->overlays_after == NULL);
3674 set_buffer_internal (buf);
3675 Ferase_buffer ();
3676 bset_enable_multibyte_characters (buf, Qnil);
3678 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3679 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3680 coding_system = call2 (Vset_auto_coding_function,
3681 filename, make_number (nread));
3682 set_buffer_internal (prev);
3684 /* Discard the unwind protect for recovering the
3685 current buffer. */
3686 specpdl_ptr--;
3688 /* Rewind the file for the actual read done later. */
3689 if (lseek (fd, 0, SEEK_SET) < 0)
3690 report_file_error ("Setting file position", orig_filename);
3694 if (NILP (coding_system))
3696 /* If we have not yet decided a coding system, check
3697 file-coding-system-alist. */
3698 coding_system = CALLN (Ffind_operation_coding_system,
3699 Qinsert_file_contents, orig_filename,
3700 visit, beg, end, replace);
3701 if (CONSP (coding_system))
3702 coding_system = XCAR (coding_system);
3706 if (NILP (coding_system))
3707 coding_system = Qundecided;
3708 else
3709 CHECK_CODING_SYSTEM (coding_system);
3711 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3712 /* We must suppress all character code conversion except for
3713 end-of-line conversion. */
3714 coding_system = raw_text_coding_system (coding_system);
3716 setup_coding_system (coding_system, &coding);
3717 /* Ensure we set Vlast_coding_system_used. */
3718 set_coding_system = true;
3721 /* If requested, replace the accessible part of the buffer
3722 with the file contents. Avoid replacing text at the
3723 beginning or end of the buffer that matches the file contents;
3724 that preserves markers pointing to the unchanged parts.
3726 Here we implement this feature in an optimized way
3727 for the case where code conversion is NOT needed.
3728 The following if-statement handles the case of conversion
3729 in a less optimal way.
3731 If the code conversion is "automatic" then we try using this
3732 method and hope for the best.
3733 But if we discover the need for conversion, we give up on this method
3734 and let the following if-statement handle the replace job. */
3735 if (!NILP (replace)
3736 && BEGV < ZV
3737 && (NILP (coding_system)
3738 || ! CODING_REQUIRE_DECODING (&coding)))
3740 ptrdiff_t overlap;
3741 /* There is still a possibility we will find the need to do code
3742 conversion. If that happens, set this variable to
3743 give up on handling REPLACE in the optimized way. */
3744 bool giveup_match_end = false;
3746 if (beg_offset != 0)
3748 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3749 report_file_error ("Setting file position", orig_filename);
3752 immediate_quit = 1;
3753 QUIT;
3754 /* Count how many chars at the start of the file
3755 match the text at the beginning of the buffer. */
3756 while (1)
3758 int nread, bufpos;
3760 nread = emacs_read (fd, read_buf, sizeof read_buf);
3761 if (nread < 0)
3762 report_file_error ("Read error", orig_filename);
3763 else if (nread == 0)
3764 break;
3766 if (CODING_REQUIRE_DETECTION (&coding))
3768 coding_system = detect_coding_system ((unsigned char *) read_buf,
3769 nread, nread, 1, 0,
3770 coding_system);
3771 setup_coding_system (coding_system, &coding);
3774 if (CODING_REQUIRE_DECODING (&coding))
3775 /* We found that the file should be decoded somehow.
3776 Let's give up here. */
3778 giveup_match_end = true;
3779 break;
3782 bufpos = 0;
3783 while (bufpos < nread && same_at_start < ZV_BYTE
3784 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3785 same_at_start++, bufpos++;
3786 /* If we found a discrepancy, stop the scan.
3787 Otherwise loop around and scan the next bufferful. */
3788 if (bufpos != nread)
3789 break;
3791 immediate_quit = false;
3792 /* If the file matches the buffer completely,
3793 there's no need to replace anything. */
3794 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3796 emacs_close (fd);
3797 clear_unwind_protect (fd_index);
3799 /* Truncate the buffer to the size of the file. */
3800 del_range_1 (same_at_start, same_at_end, 0, 0);
3801 goto handled;
3803 immediate_quit = true;
3804 QUIT;
3805 /* Count how many chars at the end of the file
3806 match the text at the end of the buffer. But, if we have
3807 already found that decoding is necessary, don't waste time. */
3808 while (!giveup_match_end)
3810 int total_read, nread, bufpos, trial;
3811 off_t curpos;
3813 /* At what file position are we now scanning? */
3814 curpos = end_offset - (ZV_BYTE - same_at_end);
3815 /* If the entire file matches the buffer tail, stop the scan. */
3816 if (curpos == 0)
3817 break;
3818 /* How much can we scan in the next step? */
3819 trial = min (curpos, sizeof read_buf);
3820 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3821 report_file_error ("Setting file position", orig_filename);
3823 total_read = nread = 0;
3824 while (total_read < trial)
3826 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3827 if (nread < 0)
3828 report_file_error ("Read error", orig_filename);
3829 else if (nread == 0)
3830 break;
3831 total_read += nread;
3834 /* Scan this bufferful from the end, comparing with
3835 the Emacs buffer. */
3836 bufpos = total_read;
3838 /* Compare with same_at_start to avoid counting some buffer text
3839 as matching both at the file's beginning and at the end. */
3840 while (bufpos > 0 && same_at_end > same_at_start
3841 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3842 same_at_end--, bufpos--;
3844 /* If we found a discrepancy, stop the scan.
3845 Otherwise loop around and scan the preceding bufferful. */
3846 if (bufpos != 0)
3848 /* If this discrepancy is because of code conversion,
3849 we cannot use this method; giveup and try the other. */
3850 if (same_at_end > same_at_start
3851 && FETCH_BYTE (same_at_end - 1) >= 0200
3852 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3853 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3854 giveup_match_end = true;
3855 break;
3858 if (nread == 0)
3859 break;
3861 immediate_quit = 0;
3863 if (! giveup_match_end)
3865 ptrdiff_t temp;
3866 ptrdiff_t this_count = SPECPDL_INDEX ();
3868 /* We win! We can handle REPLACE the optimized way. */
3870 /* Extend the start of non-matching text area to multibyte
3871 character boundary. */
3872 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3873 while (same_at_start > BEGV_BYTE
3874 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3875 same_at_start--;
3877 /* Extend the end of non-matching text area to multibyte
3878 character boundary. */
3879 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3880 while (same_at_end < ZV_BYTE
3881 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3882 same_at_end++;
3884 /* Don't try to reuse the same piece of text twice. */
3885 overlap = (same_at_start - BEGV_BYTE
3886 - (same_at_end
3887 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3888 if (overlap > 0)
3889 same_at_end += overlap;
3890 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3892 /* Arrange to read only the nonmatching middle part of the file. */
3893 beg_offset += same_at_start - BEGV_BYTE;
3894 end_offset -= ZV_BYTE - same_at_end;
3896 /* This binding is to avoid ask-user-about-supersession-threat
3897 being called in insert_from_buffer or del_range_bytes (via
3898 prepare_to_modify_buffer).
3899 AFAICT we could avoid ask-user-about-supersession-threat by setting
3900 current_buffer->modtime earlier, but we could still end up calling
3901 ask-user-about-supersession-threat if the file is modified while
3902 we read it, so we bind buffer-file-name instead. */
3903 specbind (intern ("buffer-file-name"), Qnil);
3904 del_range_byte (same_at_start, same_at_end);
3905 /* Insert from the file at the proper position. */
3906 temp = BYTE_TO_CHAR (same_at_start);
3907 SET_PT_BOTH (temp, same_at_start);
3908 unbind_to (this_count, Qnil);
3910 /* If display currently starts at beginning of line,
3911 keep it that way. */
3912 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3913 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3915 replace_handled = true;
3919 /* If requested, replace the accessible part of the buffer
3920 with the file contents. Avoid replacing text at the
3921 beginning or end of the buffer that matches the file contents;
3922 that preserves markers pointing to the unchanged parts.
3924 Here we implement this feature for the case where code conversion
3925 is needed, in a simple way that needs a lot of memory.
3926 The preceding if-statement handles the case of no conversion
3927 in a more optimized way. */
3928 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3930 ptrdiff_t same_at_start_charpos;
3931 ptrdiff_t inserted_chars;
3932 ptrdiff_t overlap;
3933 ptrdiff_t bufpos;
3934 unsigned char *decoded;
3935 ptrdiff_t temp;
3936 ptrdiff_t this = 0;
3937 ptrdiff_t this_count = SPECPDL_INDEX ();
3938 bool multibyte
3939 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3940 Lisp_Object conversion_buffer;
3942 conversion_buffer = code_conversion_save (1, multibyte);
3944 /* First read the whole file, performing code conversion into
3945 CONVERSION_BUFFER. */
3947 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3948 report_file_error ("Setting file position", orig_filename);
3950 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3951 unprocessed = 0; /* Bytes not processed in previous loop. */
3953 while (1)
3955 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3956 quitting while reading a huge file. */
3958 /* Allow quitting out of the actual I/O. */
3959 immediate_quit = 1;
3960 QUIT;
3961 this = emacs_read (fd, read_buf + unprocessed,
3962 READ_BUF_SIZE - unprocessed);
3963 immediate_quit = 0;
3965 if (this <= 0)
3966 break;
3968 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3969 BUF_Z (XBUFFER (conversion_buffer)));
3970 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3971 unprocessed + this, conversion_buffer);
3972 unprocessed = coding.carryover_bytes;
3973 if (coding.carryover_bytes > 0)
3974 memcpy (read_buf, coding.carryover, unprocessed);
3977 if (this < 0)
3978 report_file_error ("Read error", orig_filename);
3979 emacs_close (fd);
3980 clear_unwind_protect (fd_index);
3982 if (unprocessed > 0)
3984 coding.mode |= CODING_MODE_LAST_BLOCK;
3985 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3986 unprocessed, conversion_buffer);
3987 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3990 coding_system = CODING_ID_NAME (coding.id);
3991 set_coding_system = true;
3992 maybe_move_gap (XBUFFER (conversion_buffer));
3993 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3994 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3995 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3997 /* Compare the beginning of the converted string with the buffer
3998 text. */
4000 bufpos = 0;
4001 while (bufpos < inserted && same_at_start < same_at_end
4002 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4003 same_at_start++, bufpos++;
4005 /* If the file matches the head of buffer completely,
4006 there's no need to replace anything. */
4008 if (bufpos == inserted)
4010 /* Truncate the buffer to the size of the file. */
4011 if (same_at_start != same_at_end)
4013 /* See previous specbind for the reason behind this. */
4014 specbind (intern ("buffer-file-name"), Qnil);
4015 del_range_byte (same_at_start, same_at_end);
4017 inserted = 0;
4019 unbind_to (this_count, Qnil);
4020 goto handled;
4023 /* Extend the start of non-matching text area to the previous
4024 multibyte character boundary. */
4025 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4026 while (same_at_start > BEGV_BYTE
4027 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4028 same_at_start--;
4030 /* Scan this bufferful from the end, comparing with
4031 the Emacs buffer. */
4032 bufpos = inserted;
4034 /* Compare with same_at_start to avoid counting some buffer text
4035 as matching both at the file's beginning and at the end. */
4036 while (bufpos > 0 && same_at_end > same_at_start
4037 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4038 same_at_end--, bufpos--;
4040 /* Extend the end of non-matching text area to the next
4041 multibyte character boundary. */
4042 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4043 while (same_at_end < ZV_BYTE
4044 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4045 same_at_end++;
4047 /* Don't try to reuse the same piece of text twice. */
4048 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4049 if (overlap > 0)
4050 same_at_end += overlap;
4051 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4053 /* If display currently starts at beginning of line,
4054 keep it that way. */
4055 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4056 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4058 /* Replace the chars that we need to replace,
4059 and update INSERTED to equal the number of bytes
4060 we are taking from the decoded string. */
4061 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4063 /* See previous specbind for the reason behind this. */
4064 specbind (intern ("buffer-file-name"), Qnil);
4065 if (same_at_end != same_at_start)
4067 del_range_byte (same_at_start, same_at_end);
4068 temp = GPT;
4069 eassert (same_at_start == GPT_BYTE);
4070 same_at_start = GPT_BYTE;
4072 else
4074 temp = same_at_end_charpos;
4076 /* Insert from the file at the proper position. */
4077 SET_PT_BOTH (temp, same_at_start);
4078 same_at_start_charpos
4079 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4080 same_at_start - BEGV_BYTE
4081 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4082 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4083 inserted_chars
4084 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4085 same_at_start + inserted - BEGV_BYTE
4086 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4087 - same_at_start_charpos);
4088 insert_from_buffer (XBUFFER (conversion_buffer),
4089 same_at_start_charpos, inserted_chars, 0);
4090 /* Set `inserted' to the number of inserted characters. */
4091 inserted = PT - temp;
4092 /* Set point before the inserted characters. */
4093 SET_PT_BOTH (temp, same_at_start);
4095 unbind_to (this_count, Qnil);
4097 goto handled;
4100 if (! not_regular)
4101 total = end_offset - beg_offset;
4102 else
4103 /* For a special file, all we can do is guess. */
4104 total = READ_BUF_SIZE;
4106 if (NILP (visit) && total > 0)
4108 if (!NILP (BVAR (current_buffer, file_truename))
4109 /* Make binding buffer-file-name to nil effective. */
4110 && !NILP (BVAR (current_buffer, filename))
4111 && SAVE_MODIFF >= MODIFF)
4112 we_locked_file = true;
4113 prepare_to_modify_buffer (PT, PT, NULL);
4116 move_gap_both (PT, PT_BYTE);
4117 if (GAP_SIZE < total)
4118 make_gap (total - GAP_SIZE);
4120 if (beg_offset != 0 || !NILP (replace))
4122 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4123 report_file_error ("Setting file position", orig_filename);
4126 /* In the following loop, HOW_MUCH contains the total bytes read so
4127 far for a regular file, and not changed for a special file. But,
4128 before exiting the loop, it is set to a negative value if I/O
4129 error occurs. */
4130 how_much = 0;
4132 /* Total bytes inserted. */
4133 inserted = 0;
4135 /* Here, we don't do code conversion in the loop. It is done by
4136 decode_coding_gap after all data are read into the buffer. */
4138 ptrdiff_t gap_size = GAP_SIZE;
4140 while (how_much < total)
4142 /* `try' is reserved in some compilers (Microsoft C). */
4143 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4144 ptrdiff_t this;
4146 if (not_regular)
4148 Lisp_Object nbytes;
4150 /* Maybe make more room. */
4151 if (gap_size < trytry)
4153 make_gap (trytry - gap_size);
4154 gap_size = GAP_SIZE - inserted;
4157 /* Read from the file, capturing `quit'. When an
4158 error occurs, end the loop, and arrange for a quit
4159 to be signaled after decoding the text we read. */
4160 nbytes = internal_condition_case_1
4161 (read_non_regular,
4162 make_save_int_int_int (fd, inserted, trytry),
4163 Qerror, read_non_regular_quit);
4165 if (NILP (nbytes))
4167 read_quit = true;
4168 break;
4171 this = XINT (nbytes);
4173 else
4175 /* Allow quitting out of the actual I/O. We don't make text
4176 part of the buffer until all the reading is done, so a C-g
4177 here doesn't do any harm. */
4178 immediate_quit = 1;
4179 QUIT;
4180 this = emacs_read (fd,
4181 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4182 + inserted),
4183 trytry);
4184 immediate_quit = 0;
4187 if (this <= 0)
4189 how_much = this;
4190 break;
4193 gap_size -= this;
4195 /* For a regular file, where TOTAL is the real size,
4196 count HOW_MUCH to compare with it.
4197 For a special file, where TOTAL is just a buffer size,
4198 so don't bother counting in HOW_MUCH.
4199 (INSERTED is where we count the number of characters inserted.) */
4200 if (! not_regular)
4201 how_much += this;
4202 inserted += this;
4206 /* Now we have either read all the file data into the gap,
4207 or stop reading on I/O error or quit. If nothing was
4208 read, undo marking the buffer modified. */
4210 if (inserted == 0)
4212 if (we_locked_file)
4213 unlock_file (BVAR (current_buffer, file_truename));
4214 Vdeactivate_mark = old_Vdeactivate_mark;
4216 else
4217 Fset (Qdeactivate_mark, Qt);
4219 emacs_close (fd);
4220 clear_unwind_protect (fd_index);
4222 if (how_much < 0)
4223 report_file_error ("Read error", orig_filename);
4225 /* Make the text read part of the buffer. */
4226 GAP_SIZE -= inserted;
4227 GPT += inserted;
4228 GPT_BYTE += inserted;
4229 ZV += inserted;
4230 ZV_BYTE += inserted;
4231 Z += inserted;
4232 Z_BYTE += inserted;
4234 if (GAP_SIZE > 0)
4235 /* Put an anchor to ensure multi-byte form ends at gap. */
4236 *GPT_ADDR = 0;
4238 notfound:
4240 if (NILP (coding_system))
4242 /* The coding system is not yet decided. Decide it by an
4243 optimized method for handling `coding:' tag.
4245 Note that we can get here only if the buffer was empty
4246 before the insertion. */
4248 if (!NILP (Vcoding_system_for_read))
4249 coding_system = Vcoding_system_for_read;
4250 else
4252 /* Since we are sure that the current buffer was empty
4253 before the insertion, we can toggle
4254 enable-multibyte-characters directly here without taking
4255 care of marker adjustment. By this way, we can run Lisp
4256 program safely before decoding the inserted text. */
4257 Lisp_Object unwind_data;
4258 ptrdiff_t count1 = SPECPDL_INDEX ();
4260 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4261 Fcons (BVAR (current_buffer, undo_list),
4262 Fcurrent_buffer ()));
4263 bset_enable_multibyte_characters (current_buffer, Qnil);
4264 bset_undo_list (current_buffer, Qt);
4265 record_unwind_protect (decide_coding_unwind, unwind_data);
4267 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4269 coding_system = call2 (Vset_auto_coding_function,
4270 filename, make_number (inserted));
4273 if (NILP (coding_system))
4275 /* If the coding system is not yet decided, check
4276 file-coding-system-alist. */
4277 coding_system = CALLN (Ffind_operation_coding_system,
4278 Qinsert_file_contents, orig_filename,
4279 visit, beg, end, Qnil);
4280 if (CONSP (coding_system))
4281 coding_system = XCAR (coding_system);
4283 unbind_to (count1, Qnil);
4284 inserted = Z_BYTE - BEG_BYTE;
4287 if (NILP (coding_system))
4288 coding_system = Qundecided;
4289 else
4290 CHECK_CODING_SYSTEM (coding_system);
4292 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4293 /* We must suppress all character code conversion except for
4294 end-of-line conversion. */
4295 coding_system = raw_text_coding_system (coding_system);
4296 setup_coding_system (coding_system, &coding);
4297 /* Ensure we set Vlast_coding_system_used. */
4298 set_coding_system = true;
4301 if (!NILP (visit))
4303 /* When we visit a file by raw-text, we change the buffer to
4304 unibyte. */
4305 if (CODING_FOR_UNIBYTE (&coding)
4306 /* Can't do this if part of the buffer might be preserved. */
4307 && NILP (replace))
4309 /* Visiting a file with these coding system makes the buffer
4310 unibyte. */
4311 if (inserted > 0)
4312 bset_enable_multibyte_characters (current_buffer, Qnil);
4313 else
4314 Fset_buffer_multibyte (Qnil);
4318 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4319 if (CODING_MAY_REQUIRE_DECODING (&coding)
4320 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4322 move_gap_both (PT, PT_BYTE);
4323 GAP_SIZE += inserted;
4324 ZV_BYTE -= inserted;
4325 Z_BYTE -= inserted;
4326 ZV -= inserted;
4327 Z -= inserted;
4328 decode_coding_gap (&coding, inserted, inserted);
4329 inserted = coding.produced_char;
4330 coding_system = CODING_ID_NAME (coding.id);
4332 else if (inserted > 0)
4334 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4335 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4336 inserted);
4339 /* Call after-change hooks for the inserted text, aside from the case
4340 of normal visiting (not with REPLACE), which is done in a new buffer
4341 "before" the buffer is changed. */
4342 if (inserted > 0 && total > 0
4343 && (NILP (visit) || !NILP (replace)))
4345 signal_after_change (PT, 0, inserted);
4346 update_compositions (PT, PT, CHECK_BORDER);
4349 /* Now INSERTED is measured in characters. */
4351 handled:
4353 if (inserted > 0)
4354 restore_window_points (window_markers, inserted,
4355 BYTE_TO_CHAR (same_at_start),
4356 same_at_end_charpos);
4358 if (!NILP (visit))
4360 if (empty_undo_list_p)
4361 bset_undo_list (current_buffer, Qnil);
4363 if (NILP (handler))
4365 current_buffer->modtime = mtime;
4366 current_buffer->modtime_size = st.st_size;
4367 bset_filename (current_buffer, orig_filename);
4370 SAVE_MODIFF = MODIFF;
4371 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4372 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4373 if (NILP (handler))
4375 if (!NILP (BVAR (current_buffer, file_truename)))
4376 unlock_file (BVAR (current_buffer, file_truename));
4377 unlock_file (filename);
4379 if (not_regular)
4380 xsignal2 (Qfile_error,
4381 build_string ("not a regular file"), orig_filename);
4384 if (set_coding_system)
4385 Vlast_coding_system_used = coding_system;
4387 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4389 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4390 visit);
4391 if (! NILP (insval))
4393 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4394 wrong_type_argument (intern ("inserted-chars"), insval);
4395 inserted = XFASTINT (insval);
4399 /* Decode file format. */
4400 if (inserted > 0)
4402 /* Don't run point motion or modification hooks when decoding. */
4403 ptrdiff_t count1 = SPECPDL_INDEX ();
4404 ptrdiff_t old_inserted = inserted;
4405 specbind (Qinhibit_point_motion_hooks, Qt);
4406 specbind (Qinhibit_modification_hooks, Qt);
4408 /* Save old undo list and don't record undo for decoding. */
4409 old_undo = BVAR (current_buffer, undo_list);
4410 bset_undo_list (current_buffer, Qt);
4412 if (NILP (replace))
4414 insval = call3 (Qformat_decode,
4415 Qnil, make_number (inserted), visit);
4416 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4417 wrong_type_argument (intern ("inserted-chars"), insval);
4418 inserted = XFASTINT (insval);
4420 else
4422 /* If REPLACE is non-nil and we succeeded in not replacing the
4423 beginning or end of the buffer text with the file's contents,
4424 call format-decode with `point' positioned at the beginning
4425 of the buffer and `inserted' equaling the number of
4426 characters in the buffer. Otherwise, format-decode might
4427 fail to correctly analyze the beginning or end of the buffer.
4428 Hence we temporarily save `point' and `inserted' here and
4429 restore `point' iff format-decode did not insert or delete
4430 any text. Otherwise we leave `point' at point-min. */
4431 ptrdiff_t opoint = PT;
4432 ptrdiff_t opoint_byte = PT_BYTE;
4433 ptrdiff_t oinserted = ZV - BEGV;
4434 EMACS_INT ochars_modiff = CHARS_MODIFF;
4436 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4437 insval = call3 (Qformat_decode,
4438 Qnil, make_number (oinserted), visit);
4439 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4440 wrong_type_argument (intern ("inserted-chars"), insval);
4441 if (ochars_modiff == CHARS_MODIFF)
4442 /* format_decode didn't modify buffer's characters => move
4443 point back to position before inserted text and leave
4444 value of inserted alone. */
4445 SET_PT_BOTH (opoint, opoint_byte);
4446 else
4447 /* format_decode modified buffer's characters => consider
4448 entire buffer changed and leave point at point-min. */
4449 inserted = XFASTINT (insval);
4452 /* For consistency with format-decode call these now iff inserted > 0
4453 (martin 2007-06-28). */
4454 p = Vafter_insert_file_functions;
4455 while (CONSP (p))
4457 if (NILP (replace))
4459 insval = call1 (XCAR (p), make_number (inserted));
4460 if (!NILP (insval))
4462 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4463 wrong_type_argument (intern ("inserted-chars"), insval);
4464 inserted = XFASTINT (insval);
4467 else
4469 /* For the rationale of this see the comment on
4470 format-decode above. */
4471 ptrdiff_t opoint = PT;
4472 ptrdiff_t opoint_byte = PT_BYTE;
4473 ptrdiff_t oinserted = ZV - BEGV;
4474 EMACS_INT ochars_modiff = CHARS_MODIFF;
4476 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4477 insval = call1 (XCAR (p), make_number (oinserted));
4478 if (!NILP (insval))
4480 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4481 wrong_type_argument (intern ("inserted-chars"), insval);
4482 if (ochars_modiff == CHARS_MODIFF)
4483 /* after_insert_file_functions didn't modify
4484 buffer's characters => move point back to
4485 position before inserted text and leave value of
4486 inserted alone. */
4487 SET_PT_BOTH (opoint, opoint_byte);
4488 else
4489 /* after_insert_file_functions did modify buffer's
4490 characters => consider entire buffer changed and
4491 leave point at point-min. */
4492 inserted = XFASTINT (insval);
4496 QUIT;
4497 p = XCDR (p);
4500 if (!empty_undo_list_p)
4502 bset_undo_list (current_buffer, old_undo);
4503 if (CONSP (old_undo) && inserted != old_inserted)
4505 /* Adjust the last undo record for the size change during
4506 the format conversion. */
4507 Lisp_Object tem = XCAR (old_undo);
4508 if (CONSP (tem) && INTEGERP (XCAR (tem))
4509 && INTEGERP (XCDR (tem))
4510 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4511 XSETCDR (tem, make_number (PT + inserted));
4514 else
4515 /* If undo_list was Qt before, keep it that way.
4516 Otherwise start with an empty undo_list. */
4517 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4519 unbind_to (count1, Qnil);
4522 if (!NILP (visit)
4523 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4525 /* If visiting nonexistent file, return nil. */
4526 report_file_errno ("Opening input file", orig_filename, save_errno);
4529 /* We made a lot of deletions and insertions above, so invalidate
4530 the newline cache for the entire region of the inserted
4531 characters. */
4532 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4533 invalidate_region_cache (current_buffer->base_buffer,
4534 current_buffer->base_buffer->newline_cache,
4535 PT - BEG, Z - PT - inserted);
4536 else if (current_buffer->newline_cache)
4537 invalidate_region_cache (current_buffer,
4538 current_buffer->newline_cache,
4539 PT - BEG, Z - PT - inserted);
4541 if (read_quit)
4542 quit ();
4544 /* Retval needs to be dealt with in all cases consistently. */
4545 if (NILP (val))
4546 val = list2 (orig_filename, make_number (inserted));
4548 return unbind_to (count, val);
4551 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4553 static void
4554 build_annotations_unwind (Lisp_Object arg)
4556 Vwrite_region_annotation_buffers = arg;
4559 /* Decide the coding-system to encode the data with. */
4561 static Lisp_Object
4562 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4563 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4564 struct coding_system *coding)
4566 Lisp_Object val;
4567 Lisp_Object eol_parent = Qnil;
4569 if (auto_saving
4570 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4571 BVAR (current_buffer, auto_save_file_name))))
4573 val = Qutf_8_emacs;
4574 eol_parent = Qunix;
4576 else if (!NILP (Vcoding_system_for_write))
4578 val = Vcoding_system_for_write;
4579 if (coding_system_require_warning
4580 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4581 /* Confirm that VAL can surely encode the current region. */
4582 val = call5 (Vselect_safe_coding_system_function,
4583 start, end, list2 (Qt, val),
4584 Qnil, filename);
4586 else
4588 /* If the variable `buffer-file-coding-system' is set locally,
4589 it means that the file was read with some kind of code
4590 conversion or the variable is explicitly set by users. We
4591 had better write it out with the same coding system even if
4592 `enable-multibyte-characters' is nil.
4594 If it is not set locally, we anyway have to convert EOL
4595 format if the default value of `buffer-file-coding-system'
4596 tells that it is not Unix-like (LF only) format. */
4597 bool using_default_coding = 0;
4598 bool force_raw_text = 0;
4600 val = BVAR (current_buffer, buffer_file_coding_system);
4601 if (NILP (val)
4602 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4604 val = Qnil;
4605 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4606 force_raw_text = 1;
4609 if (NILP (val))
4611 /* Check file-coding-system-alist. */
4612 Lisp_Object coding_systems
4613 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4614 filename, append, visit, lockname);
4615 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4616 val = XCDR (coding_systems);
4619 if (NILP (val))
4621 /* If we still have not decided a coding system, use the
4622 current buffer's value of buffer-file-coding-system. */
4623 val = BVAR (current_buffer, buffer_file_coding_system);
4624 using_default_coding = 1;
4627 if (! NILP (val) && ! force_raw_text)
4629 Lisp_Object spec, attrs;
4631 CHECK_CODING_SYSTEM (val);
4632 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4633 attrs = AREF (spec, 0);
4634 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4635 force_raw_text = 1;
4638 if (!force_raw_text
4639 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4641 /* Confirm that VAL can surely encode the current region. */
4642 val = call5 (Vselect_safe_coding_system_function,
4643 start, end, val, Qnil, filename);
4644 /* As the function specified by select-safe-coding-system-function
4645 is out of our control, make sure we are not fed by bogus
4646 values. */
4647 if (!NILP (val))
4648 CHECK_CODING_SYSTEM (val);
4651 /* If the decided coding-system doesn't specify end-of-line
4652 format, we use that of
4653 `default-buffer-file-coding-system'. */
4654 if (! using_default_coding)
4656 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4658 if (! NILP (dflt))
4659 val = coding_inherit_eol_type (val, dflt);
4662 /* If we decide not to encode text, use `raw-text' or one of its
4663 subsidiaries. */
4664 if (force_raw_text)
4665 val = raw_text_coding_system (val);
4668 val = coding_inherit_eol_type (val, eol_parent);
4669 setup_coding_system (val, coding);
4671 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4672 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4673 return val;
4676 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4677 "r\nFWrite region to file: \ni\ni\ni\np",
4678 doc: /* Write current region into specified file.
4679 When called from a program, requires three arguments:
4680 START, END and FILENAME. START and END are normally buffer positions
4681 specifying the part of the buffer to write.
4682 If START is nil, that means to use the entire buffer contents; END is
4683 ignored.
4684 If START is a string, then output that string to the file
4685 instead of any buffer contents; END is ignored.
4687 Optional fourth argument APPEND if non-nil means
4688 append to existing file contents (if any). If it is a number,
4689 seek to that offset in the file before writing.
4690 Optional fifth argument VISIT, if t or a string, means
4691 set the last-save-file-modtime of buffer to this file's modtime
4692 and mark buffer not modified.
4693 If VISIT is a string, it is a second file name;
4694 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4695 VISIT is also the file name to lock and unlock for clash detection.
4696 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4697 do not display the \"Wrote file\" message.
4698 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4699 use for locking and unlocking, overriding FILENAME and VISIT.
4700 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4701 for an existing file with the same name. If MUSTBENEW is `excl',
4702 that means to get an error if the file already exists; never overwrite.
4703 If MUSTBENEW is neither nil nor `excl', that means ask for
4704 confirmation before overwriting, but do go ahead and overwrite the file
4705 if the user confirms.
4707 This does code conversion according to the value of
4708 `coding-system-for-write', `buffer-file-coding-system', or
4709 `file-coding-system-alist', and sets the variable
4710 `last-coding-system-used' to the coding system actually used.
4712 This calls `write-region-annotate-functions' at the start, and
4713 `write-region-post-annotation-function' at the end. */)
4714 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4715 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4717 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4718 -1);
4721 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4722 descriptor for FILENAME, so do not open or close FILENAME. */
4724 Lisp_Object
4725 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4726 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4727 Lisp_Object mustbenew, int desc)
4729 int open_flags;
4730 int mode;
4731 off_t offset UNINIT;
4732 bool open_and_close_file = desc < 0;
4733 bool ok;
4734 int save_errno = 0;
4735 const char *fn;
4736 struct stat st;
4737 struct timespec modtime;
4738 ptrdiff_t count = SPECPDL_INDEX ();
4739 ptrdiff_t count1 UNINIT;
4740 Lisp_Object handler;
4741 Lisp_Object visit_file;
4742 Lisp_Object annotations;
4743 Lisp_Object encoded_filename;
4744 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4745 bool quietly = !NILP (visit);
4746 bool file_locked = 0;
4747 struct buffer *given_buffer;
4748 struct coding_system coding;
4750 if (current_buffer->base_buffer && visiting)
4751 error ("Cannot do file visiting in an indirect buffer");
4753 if (!NILP (start) && !STRINGP (start))
4754 validate_region (&start, &end);
4756 visit_file = Qnil;
4758 filename = Fexpand_file_name (filename, Qnil);
4760 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4761 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4763 if (STRINGP (visit))
4764 visit_file = Fexpand_file_name (visit, Qnil);
4765 else
4766 visit_file = filename;
4768 if (NILP (lockname))
4769 lockname = visit_file;
4771 annotations = Qnil;
4773 /* If the file name has special constructs in it,
4774 call the corresponding file handler. */
4775 handler = Ffind_file_name_handler (filename, Qwrite_region);
4776 /* If FILENAME has no handler, see if VISIT has one. */
4777 if (NILP (handler) && STRINGP (visit))
4778 handler = Ffind_file_name_handler (visit, Qwrite_region);
4780 if (!NILP (handler))
4782 Lisp_Object val;
4783 val = call6 (handler, Qwrite_region, start, end,
4784 filename, append, visit);
4786 if (visiting)
4788 SAVE_MODIFF = MODIFF;
4789 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4790 bset_filename (current_buffer, visit_file);
4793 return val;
4796 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4798 /* Special kludge to simplify auto-saving. */
4799 if (NILP (start))
4801 /* Do it later, so write-region-annotate-function can work differently
4802 if we save "the buffer" vs "a region".
4803 This is useful in tar-mode. --Stef
4804 XSETFASTINT (start, BEG);
4805 XSETFASTINT (end, Z); */
4806 Fwiden ();
4809 record_unwind_protect (build_annotations_unwind,
4810 Vwrite_region_annotation_buffers);
4811 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4813 given_buffer = current_buffer;
4815 if (!STRINGP (start))
4817 annotations = build_annotations (start, end);
4819 if (current_buffer != given_buffer)
4821 XSETFASTINT (start, BEGV);
4822 XSETFASTINT (end, ZV);
4826 if (NILP (start))
4828 XSETFASTINT (start, BEGV);
4829 XSETFASTINT (end, ZV);
4832 /* Decide the coding-system to encode the data with.
4833 We used to make this choice before calling build_annotations, but that
4834 leads to problems when a write-annotate-function takes care of
4835 unsavable chars (as was the case with X-Symbol). */
4836 Vlast_coding_system_used
4837 = choose_write_coding_system (start, end, filename,
4838 append, visit, lockname, &coding);
4840 if (open_and_close_file && !auto_saving)
4842 lock_file (lockname);
4843 file_locked = 1;
4846 encoded_filename = ENCODE_FILE (filename);
4847 fn = SSDATA (encoded_filename);
4848 open_flags = O_WRONLY | O_CREAT;
4849 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4850 if (NUMBERP (append))
4851 offset = file_offset (append);
4852 else if (!NILP (append))
4853 open_flags |= O_APPEND;
4854 #ifdef DOS_NT
4855 mode = S_IREAD | S_IWRITE;
4856 #else
4857 mode = auto_saving ? auto_save_mode_bits : 0666;
4858 #endif
4860 if (open_and_close_file)
4862 desc = emacs_open (fn, open_flags, mode);
4863 if (desc < 0)
4865 int open_errno = errno;
4866 if (file_locked)
4867 unlock_file (lockname);
4868 report_file_errno ("Opening output file", filename, open_errno);
4871 count1 = SPECPDL_INDEX ();
4872 record_unwind_protect_int (close_file_unwind, desc);
4875 if (NUMBERP (append))
4877 off_t ret = lseek (desc, offset, SEEK_SET);
4878 if (ret < 0)
4880 int lseek_errno = errno;
4881 if (file_locked)
4882 unlock_file (lockname);
4883 report_file_errno ("Lseek error", filename, lseek_errno);
4887 immediate_quit = 1;
4889 if (STRINGP (start))
4890 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4891 else if (XINT (start) != XINT (end))
4892 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4893 &annotations, &coding);
4894 else
4896 /* If file was empty, still need to write the annotations. */
4897 coding.mode |= CODING_MODE_LAST_BLOCK;
4898 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4900 save_errno = errno;
4902 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4903 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4905 /* We have to flush out a data. */
4906 coding.mode |= CODING_MODE_LAST_BLOCK;
4907 ok = e_write (desc, Qnil, 1, 1, &coding);
4908 save_errno = errno;
4911 immediate_quit = 0;
4913 /* fsync is not crucial for temporary files. Nor for auto-save
4914 files, since they might lose some work anyway. */
4915 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4917 /* Transfer data and metadata to disk, retrying if interrupted.
4918 fsync can report a write failure here, e.g., due to disk full
4919 under NFS. But ignore EINVAL, which means fsync is not
4920 supported on this file. */
4921 while (fsync (desc) != 0)
4922 if (errno != EINTR)
4924 if (errno != EINVAL)
4925 ok = 0, save_errno = errno;
4926 break;
4930 modtime = invalid_timespec ();
4931 if (visiting)
4933 if (fstat (desc, &st) == 0)
4934 modtime = get_stat_mtime (&st);
4935 else
4936 ok = 0, save_errno = errno;
4939 if (open_and_close_file)
4941 /* NFS can report a write failure now. */
4942 if (emacs_close (desc) < 0)
4943 ok = 0, save_errno = errno;
4945 /* Discard the unwind protect for close_file_unwind. */
4946 specpdl_ptr = specpdl + count1;
4949 /* Some file systems have a bug where st_mtime is not updated
4950 properly after a write. For example, CIFS might not see the
4951 st_mtime change until after the file is opened again.
4953 Attempt to detect this file system bug, and update MODTIME to the
4954 newer st_mtime if the bug appears to be present. This introduces
4955 a race condition, so to avoid most instances of the race condition
4956 on non-buggy file systems, skip this check if the most recently
4957 encountered non-buggy file system was the current file system.
4959 A race condition can occur if some other process modifies the
4960 file between the fstat above and the fstat below, but the race is
4961 unlikely and a similar race between the last write and the fstat
4962 above cannot possibly be closed anyway. */
4964 if (timespec_valid_p (modtime)
4965 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4967 int desc1 = emacs_open (fn, O_WRONLY, 0);
4968 if (desc1 >= 0)
4970 struct stat st1;
4971 if (fstat (desc1, &st1) == 0
4972 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4974 /* Use the heuristic if it appears to be valid. With neither
4975 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4976 file, the time stamp won't change. Also, some non-POSIX
4977 systems don't update an empty file's time stamp when
4978 truncating it. Finally, file systems with 100 ns or worse
4979 resolution sometimes seem to have bugs: on a system with ns
4980 resolution, checking ns % 100 incorrectly avoids the heuristic
4981 1% of the time, but the problem should be temporary as we will
4982 try again on the next time stamp. */
4983 bool use_heuristic
4984 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4985 && st.st_size != 0
4986 && modtime.tv_nsec % 100 != 0);
4988 struct timespec modtime1 = get_stat_mtime (&st1);
4989 if (use_heuristic
4990 && timespec_cmp (modtime, modtime1) == 0
4991 && st.st_size == st1.st_size)
4993 timestamp_file_system = st.st_dev;
4994 valid_timestamp_file_system = 1;
4996 else
4998 st.st_size = st1.st_size;
4999 modtime = modtime1;
5002 emacs_close (desc1);
5006 /* Call write-region-post-annotation-function. */
5007 while (CONSP (Vwrite_region_annotation_buffers))
5009 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5010 if (!NILP (Fbuffer_live_p (buf)))
5012 Fset_buffer (buf);
5013 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5014 call0 (Vwrite_region_post_annotation_function);
5016 Vwrite_region_annotation_buffers
5017 = XCDR (Vwrite_region_annotation_buffers);
5020 unbind_to (count, Qnil);
5022 if (file_locked)
5023 unlock_file (lockname);
5025 /* Do this before reporting IO error
5026 to avoid a "file has changed on disk" warning on
5027 next attempt to save. */
5028 if (timespec_valid_p (modtime))
5030 current_buffer->modtime = modtime;
5031 current_buffer->modtime_size = st.st_size;
5034 if (! ok)
5035 report_file_errno ("Write error", filename, save_errno);
5037 if (visiting)
5039 SAVE_MODIFF = MODIFF;
5040 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5041 bset_filename (current_buffer, visit_file);
5042 update_mode_lines = 14;
5044 else if (quietly)
5046 if (auto_saving
5047 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5048 BVAR (current_buffer, auto_save_file_name))))
5049 SAVE_MODIFF = MODIFF;
5051 return Qnil;
5054 if (!auto_saving && !noninteractive)
5055 message_with_string ((NUMBERP (append)
5056 ? "Updated %s"
5057 : ! NILP (append)
5058 ? "Added to %s"
5059 : "Wrote %s"),
5060 visit_file, 1);
5062 return Qnil;
5065 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5066 doc: /* Return t if (car A) is numerically less than (car B). */)
5067 (Lisp_Object a, Lisp_Object b)
5069 return CALLN (Flss, Fcar (a), Fcar (b));
5072 /* Build the complete list of annotations appropriate for writing out
5073 the text between START and END, by calling all the functions in
5074 write-region-annotate-functions and merging the lists they return.
5075 If one of these functions switches to a different buffer, we assume
5076 that buffer contains altered text. Therefore, the caller must
5077 make sure to restore the current buffer in all cases,
5078 as save-excursion would do. */
5080 static Lisp_Object
5081 build_annotations (Lisp_Object start, Lisp_Object end)
5083 Lisp_Object annotations;
5084 Lisp_Object p, res;
5085 Lisp_Object original_buffer;
5086 int i;
5087 bool used_global = false;
5089 XSETBUFFER (original_buffer, current_buffer);
5091 annotations = Qnil;
5092 p = Vwrite_region_annotate_functions;
5093 while (CONSP (p))
5095 struct buffer *given_buffer = current_buffer;
5096 if (EQ (Qt, XCAR (p)) && !used_global)
5097 { /* Use the global value of the hook. */
5098 used_global = true;
5099 p = CALLN (Fappend,
5100 Fdefault_value (Qwrite_region_annotate_functions),
5101 XCDR (p));
5102 continue;
5104 Vwrite_region_annotations_so_far = annotations;
5105 res = call2 (XCAR (p), start, end);
5106 /* If the function makes a different buffer current,
5107 assume that means this buffer contains altered text to be output.
5108 Reset START and END from the buffer bounds
5109 and discard all previous annotations because they should have
5110 been dealt with by this function. */
5111 if (current_buffer != given_buffer)
5113 Vwrite_region_annotation_buffers
5114 = Fcons (Fcurrent_buffer (),
5115 Vwrite_region_annotation_buffers);
5116 XSETFASTINT (start, BEGV);
5117 XSETFASTINT (end, ZV);
5118 annotations = Qnil;
5120 Flength (res); /* Check basic validity of return value */
5121 annotations = merge (annotations, res, Qcar_less_than_car);
5122 p = XCDR (p);
5125 /* Now do the same for annotation functions implied by the file-format */
5126 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5127 p = BVAR (current_buffer, auto_save_file_format);
5128 else
5129 p = BVAR (current_buffer, file_format);
5130 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5132 struct buffer *given_buffer = current_buffer;
5134 Vwrite_region_annotations_so_far = annotations;
5136 /* Value is either a list of annotations or nil if the function
5137 has written annotations to a temporary buffer, which is now
5138 current. */
5139 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5140 original_buffer, make_number (i));
5141 if (current_buffer != given_buffer)
5143 XSETFASTINT (start, BEGV);
5144 XSETFASTINT (end, ZV);
5145 annotations = Qnil;
5148 if (CONSP (res))
5149 annotations = merge (annotations, res, Qcar_less_than_car);
5152 return annotations;
5156 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5157 If STRING is nil, POS is the character position in the current buffer.
5158 Intersperse with them the annotations from *ANNOT
5159 which fall within the range of POS to POS + NCHARS,
5160 each at its appropriate position.
5162 We modify *ANNOT by discarding elements as we use them up.
5164 Return true if successful. */
5166 static bool
5167 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5168 ptrdiff_t nchars, Lisp_Object *annot,
5169 struct coding_system *coding)
5171 Lisp_Object tem;
5172 ptrdiff_t nextpos;
5173 ptrdiff_t lastpos = pos + nchars;
5175 while (NILP (*annot) || CONSP (*annot))
5177 tem = Fcar_safe (Fcar (*annot));
5178 nextpos = pos - 1;
5179 if (INTEGERP (tem))
5180 nextpos = XFASTINT (tem);
5182 /* If there are no more annotations in this range,
5183 output the rest of the range all at once. */
5184 if (! (nextpos >= pos && nextpos <= lastpos))
5185 return e_write (desc, string, pos, lastpos, coding);
5187 /* Output buffer text up to the next annotation's position. */
5188 if (nextpos > pos)
5190 if (!e_write (desc, string, pos, nextpos, coding))
5191 return 0;
5192 pos = nextpos;
5194 /* Output the annotation. */
5195 tem = Fcdr (Fcar (*annot));
5196 if (STRINGP (tem))
5198 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5199 return 0;
5201 *annot = Fcdr (*annot);
5203 return 1;
5206 /* Maximum number of characters that the next
5207 function encodes per one loop iteration. */
5209 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5211 /* Write text in the range START and END into descriptor DESC,
5212 encoding them with coding system CODING. If STRING is nil, START
5213 and END are character positions of the current buffer, else they
5214 are indexes to the string STRING. Return true if successful. */
5216 static bool
5217 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5218 struct coding_system *coding)
5220 if (STRINGP (string))
5222 start = 0;
5223 end = SCHARS (string);
5226 /* We used to have a code for handling selective display here. But,
5227 now it is handled within encode_coding. */
5229 while (start < end)
5231 if (STRINGP (string))
5233 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5234 if (CODING_REQUIRE_ENCODING (coding))
5236 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5238 /* Avoid creating huge Lisp string in encode_coding_object. */
5239 if (nchars == E_WRITE_MAX)
5240 coding->raw_destination = 1;
5242 encode_coding_object
5243 (coding, string, start, string_char_to_byte (string, start),
5244 start + nchars, string_char_to_byte (string, start + nchars),
5245 Qt);
5247 else
5249 coding->dst_object = string;
5250 coding->consumed_char = SCHARS (string);
5251 coding->produced = SBYTES (string);
5254 else
5256 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5257 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5259 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5260 if (CODING_REQUIRE_ENCODING (coding))
5262 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5264 /* Likewise. */
5265 if (nchars == E_WRITE_MAX)
5266 coding->raw_destination = 1;
5268 encode_coding_object
5269 (coding, Fcurrent_buffer (), start, start_byte,
5270 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5272 else
5274 coding->dst_object = Qnil;
5275 coding->dst_pos_byte = start_byte;
5276 if (start >= GPT || end <= GPT)
5278 coding->consumed_char = end - start;
5279 coding->produced = end_byte - start_byte;
5281 else
5283 coding->consumed_char = GPT - start;
5284 coding->produced = GPT_BYTE - start_byte;
5289 if (coding->produced > 0)
5291 char *buf = (coding->raw_destination ? (char *) coding->destination
5292 : (STRINGP (coding->dst_object)
5293 ? SSDATA (coding->dst_object)
5294 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5295 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5297 if (coding->raw_destination)
5299 /* We're responsible for freeing this, see
5300 encode_coding_object to check why. */
5301 xfree (coding->destination);
5302 coding->raw_destination = 0;
5304 if (coding->produced)
5305 return 0;
5307 start += coding->consumed_char;
5310 return 1;
5313 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5314 Sverify_visited_file_modtime, 0, 1, 0,
5315 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5316 This means that the file has not been changed since it was visited or saved.
5317 If BUF is omitted or nil, it defaults to the current buffer.
5318 See Info node `(elisp)Modification Time' for more details. */)
5319 (Lisp_Object buf)
5321 struct buffer *b = decode_buffer (buf);
5322 struct stat st;
5323 Lisp_Object handler;
5324 Lisp_Object filename;
5325 struct timespec mtime;
5327 if (!STRINGP (BVAR (b, filename))) return Qt;
5328 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5330 /* If the file name has special constructs in it,
5331 call the corresponding file handler. */
5332 handler = Ffind_file_name_handler (BVAR (b, filename),
5333 Qverify_visited_file_modtime);
5334 if (!NILP (handler))
5335 return call2 (handler, Qverify_visited_file_modtime, buf);
5337 filename = ENCODE_FILE (BVAR (b, filename));
5339 mtime = (stat (SSDATA (filename), &st) == 0
5340 ? get_stat_mtime (&st)
5341 : time_error_value (errno));
5342 if (timespec_cmp (mtime, b->modtime) == 0
5343 && (b->modtime_size < 0
5344 || st.st_size == b->modtime_size))
5345 return Qt;
5346 return Qnil;
5349 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5350 Svisited_file_modtime, 0, 0, 0,
5351 doc: /* Return the current buffer's recorded visited file modification time.
5352 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5353 `file-attributes' returns. If the current buffer has no recorded file
5354 modification time, this function returns 0. If the visited file
5355 doesn't exist, return -1.
5356 See Info node `(elisp)Modification Time' for more details. */)
5357 (void)
5359 int ns = current_buffer->modtime.tv_nsec;
5360 if (ns < 0)
5361 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5362 return make_lisp_time (current_buffer->modtime);
5365 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5366 Sset_visited_file_modtime, 0, 1, 0,
5367 doc: /* Update buffer's recorded modification time from the visited file's time.
5368 Useful if the buffer was not read from the file normally
5369 or if the file itself has been changed for some known benign reason.
5370 An argument specifies the modification time value to use
5371 \(instead of that of the visited file), in the form of a list
5372 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5373 `visited-file-modtime'. */)
5374 (Lisp_Object time_flag)
5376 if (!NILP (time_flag))
5378 struct timespec mtime;
5379 if (INTEGERP (time_flag))
5381 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5382 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5384 else
5385 mtime = lisp_time_argument (time_flag);
5387 current_buffer->modtime = mtime;
5388 current_buffer->modtime_size = -1;
5390 else
5392 register Lisp_Object filename;
5393 struct stat st;
5394 Lisp_Object handler;
5396 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5398 /* If the file name has special constructs in it,
5399 call the corresponding file handler. */
5400 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5401 if (!NILP (handler))
5402 /* The handler can find the file name the same way we did. */
5403 return call2 (handler, Qset_visited_file_modtime, Qnil);
5405 filename = ENCODE_FILE (filename);
5407 if (stat (SSDATA (filename), &st) >= 0)
5409 current_buffer->modtime = get_stat_mtime (&st);
5410 current_buffer->modtime_size = st.st_size;
5414 return Qnil;
5417 static Lisp_Object
5418 auto_save_error (Lisp_Object error_val)
5420 auto_save_error_occurred = 1;
5422 ring_bell (XFRAME (selected_frame));
5424 AUTO_STRING (format, "Auto-saving %s: %s");
5425 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5426 Ferror_message_string (error_val));
5427 call3 (intern ("display-warning"),
5428 intern ("auto-save"), msg, intern ("error"));
5430 return Qnil;
5433 static Lisp_Object
5434 auto_save_1 (void)
5436 struct stat st;
5437 Lisp_Object modes;
5439 auto_save_mode_bits = 0666;
5441 /* Get visited file's mode to become the auto save file's mode. */
5442 if (! NILP (BVAR (current_buffer, filename)))
5444 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5445 /* But make sure we can overwrite it later! */
5446 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5447 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5448 INTEGERP (modes))
5449 /* Remote files don't cooperate with stat. */
5450 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5453 return
5454 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5455 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5456 Qnil, Qnil);
5459 struct auto_save_unwind
5461 FILE *stream;
5462 bool auto_raise;
5465 static void
5466 do_auto_save_unwind (void *arg)
5468 struct auto_save_unwind *p = arg;
5469 FILE *stream = p->stream;
5470 minibuffer_auto_raise = p->auto_raise;
5471 auto_saving = 0;
5472 if (stream != NULL)
5474 block_input ();
5475 fclose (stream);
5476 unblock_input ();
5480 static Lisp_Object
5481 do_auto_save_make_dir (Lisp_Object dir)
5483 Lisp_Object result;
5485 auto_saving_dir_umask = 077;
5486 result = call2 (Qmake_directory, dir, Qt);
5487 auto_saving_dir_umask = 0;
5488 return result;
5491 static Lisp_Object
5492 do_auto_save_eh (Lisp_Object ignore)
5494 auto_saving_dir_umask = 0;
5495 return Qnil;
5498 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5499 doc: /* Auto-save all buffers that need it.
5500 This is all buffers that have auto-saving enabled
5501 and are changed since last auto-saved.
5502 Auto-saving writes the buffer into a file
5503 so that your editing is not lost if the system crashes.
5504 This file is not the file you visited; that changes only when you save.
5505 Normally we run the normal hook `auto-save-hook' before saving.
5507 A non-nil NO-MESSAGE argument means do not print any message if successful.
5508 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5509 (Lisp_Object no_message, Lisp_Object current_only)
5511 struct buffer *old = current_buffer, *b;
5512 Lisp_Object tail, buf, hook;
5513 bool auto_saved = 0;
5514 int do_handled_files;
5515 Lisp_Object oquit;
5516 FILE *stream = NULL;
5517 ptrdiff_t count = SPECPDL_INDEX ();
5518 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5519 bool old_message_p = 0;
5520 struct auto_save_unwind auto_save_unwind;
5522 if (max_specpdl_size < specpdl_size + 40)
5523 max_specpdl_size = specpdl_size + 40;
5525 if (minibuf_level)
5526 no_message = Qt;
5528 if (NILP (no_message))
5530 old_message_p = push_message ();
5531 record_unwind_protect_void (pop_message_unwind);
5534 /* Ordinarily don't quit within this function,
5535 but don't make it impossible to quit (in case we get hung in I/O). */
5536 oquit = Vquit_flag;
5537 Vquit_flag = Qnil;
5539 hook = intern ("auto-save-hook");
5540 safe_run_hooks (hook);
5542 if (STRINGP (Vauto_save_list_file_name))
5544 Lisp_Object listfile;
5546 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5548 /* Don't try to create the directory when shutting down Emacs,
5549 because creating the directory might signal an error, and
5550 that would leave Emacs in a strange state. */
5551 if (!NILP (Vrun_hooks))
5553 Lisp_Object dir;
5554 dir = Ffile_name_directory (listfile);
5555 if (NILP (Ffile_directory_p (dir)))
5556 internal_condition_case_1 (do_auto_save_make_dir,
5557 dir, Qt,
5558 do_auto_save_eh);
5561 stream = emacs_fopen (SSDATA (listfile), "w");
5564 auto_save_unwind.stream = stream;
5565 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5566 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5567 minibuffer_auto_raise = 0;
5568 auto_saving = 1;
5569 auto_save_error_occurred = 0;
5571 /* On first pass, save all files that don't have handlers.
5572 On second pass, save all files that do have handlers.
5574 If Emacs is crashing, the handlers may tweak what is causing
5575 Emacs to crash in the first place, and it would be a shame if
5576 Emacs failed to autosave perfectly ordinary files because it
5577 couldn't handle some ange-ftp'd file. */
5579 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5580 FOR_EACH_LIVE_BUFFER (tail, buf)
5582 b = XBUFFER (buf);
5584 /* Record all the buffers that have auto save mode
5585 in the special file that lists them. For each of these buffers,
5586 Record visited name (if any) and auto save name. */
5587 if (STRINGP (BVAR (b, auto_save_file_name))
5588 && stream != NULL && do_handled_files == 0)
5590 block_input ();
5591 if (!NILP (BVAR (b, filename)))
5593 fwrite (SDATA (BVAR (b, filename)), 1,
5594 SBYTES (BVAR (b, filename)), stream);
5596 putc ('\n', stream);
5597 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5598 SBYTES (BVAR (b, auto_save_file_name)), stream);
5599 putc ('\n', stream);
5600 unblock_input ();
5603 if (!NILP (current_only)
5604 && b != current_buffer)
5605 continue;
5607 /* Don't auto-save indirect buffers.
5608 The base buffer takes care of it. */
5609 if (b->base_buffer)
5610 continue;
5612 /* Check for auto save enabled
5613 and file changed since last auto save
5614 and file changed since last real save. */
5615 if (STRINGP (BVAR (b, auto_save_file_name))
5616 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5617 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5618 /* -1 means we've turned off autosaving for a while--see below. */
5619 && XINT (BVAR (b, save_length)) >= 0
5620 && (do_handled_files
5621 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5622 Qwrite_region))))
5624 struct timespec before_time = current_timespec ();
5625 struct timespec after_time;
5627 /* If we had a failure, don't try again for 20 minutes. */
5628 if (b->auto_save_failure_time > 0
5629 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5630 continue;
5632 set_buffer_internal (b);
5633 if (NILP (Vauto_save_include_big_deletions)
5634 && (XFASTINT (BVAR (b, save_length)) * 10
5635 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5636 /* A short file is likely to change a large fraction;
5637 spare the user annoying messages. */
5638 && XFASTINT (BVAR (b, save_length)) > 5000
5639 /* These messages are frequent and annoying for `*mail*'. */
5640 && !EQ (BVAR (b, filename), Qnil)
5641 && NILP (no_message))
5643 /* It has shrunk too much; turn off auto-saving here. */
5644 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5645 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5646 BVAR (b, name), 1);
5647 minibuffer_auto_raise = 0;
5648 /* Turn off auto-saving until there's a real save,
5649 and prevent any more warnings. */
5650 XSETINT (BVAR (b, save_length), -1);
5651 Fsleep_for (make_number (1), Qnil);
5652 continue;
5654 if (!auto_saved && NILP (no_message))
5655 message1 ("Auto-saving...");
5656 internal_condition_case (auto_save_1, Qt, auto_save_error);
5657 auto_saved = 1;
5658 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5659 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5660 set_buffer_internal (old);
5662 after_time = current_timespec ();
5664 /* If auto-save took more than 60 seconds,
5665 assume it was an NFS failure that got a timeout. */
5666 if (after_time.tv_sec - before_time.tv_sec > 60)
5667 b->auto_save_failure_time = after_time.tv_sec;
5671 /* Prevent another auto save till enough input events come in. */
5672 record_auto_save ();
5674 if (auto_saved && NILP (no_message))
5676 if (old_message_p)
5678 /* If we are going to restore an old message,
5679 give time to read ours. */
5680 sit_for (make_number (1), 0, 0);
5681 restore_message ();
5683 else if (!auto_save_error_occurred)
5684 /* Don't overwrite the error message if an error occurred.
5685 If we displayed a message and then restored a state
5686 with no message, leave a "done" message on the screen. */
5687 message1 ("Auto-saving...done");
5690 Vquit_flag = oquit;
5692 /* This restores the message-stack status. */
5693 unbind_to (count, Qnil);
5694 return Qnil;
5697 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5698 Sset_buffer_auto_saved, 0, 0, 0,
5699 doc: /* Mark current buffer as auto-saved with its current text.
5700 No auto-save file will be written until the buffer changes again. */)
5701 (void)
5703 /* FIXME: This should not be called in indirect buffers, since
5704 they're not autosaved. */
5705 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5706 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5707 current_buffer->auto_save_failure_time = 0;
5708 return Qnil;
5711 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5712 Sclear_buffer_auto_save_failure, 0, 0, 0,
5713 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5714 (void)
5716 current_buffer->auto_save_failure_time = 0;
5717 return Qnil;
5720 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5721 0, 0, 0,
5722 doc: /* Return t if current buffer has been auto-saved recently.
5723 More precisely, if it has been auto-saved since last read from or saved
5724 in the visited file. If the buffer has no visited file,
5725 then any auto-save counts as "recent". */)
5726 (void)
5728 /* FIXME: maybe we should return nil for indirect buffers since
5729 they're never autosaved. */
5730 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5733 /* Reading and completing file names. */
5735 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5736 Snext_read_file_uses_dialog_p, 0, 0, 0,
5737 doc: /* Return t if a call to `read-file-name' will use a dialog.
5738 The return value is only relevant for a call to `read-file-name' that happens
5739 before any other event (mouse or keypress) is handled. */)
5740 (void)
5742 #if (defined USE_GTK || defined USE_MOTIF \
5743 || defined HAVE_NS || defined HAVE_NTGUI)
5744 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5745 && use_dialog_box
5746 && use_file_dialog
5747 && window_system_available (SELECTED_FRAME ()))
5748 return Qt;
5749 #endif
5750 return Qnil;
5754 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5755 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5756 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5757 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5758 it to text mode.
5760 As a side effect, this function flushes any pending STREAM's data.
5762 Value is the previous value of STREAM's I/O mode, nil for text mode,
5763 non-nil for binary mode.
5765 On MS-Windows and MS-DOS, binary mode is needed to read or write
5766 arbitrary binary data, and for disabling translation between CR-LF
5767 pairs and a single newline character. Examples include generation
5768 of text files with Unix-style end-of-line format using `princ' in
5769 batch mode, with standard output redirected to a file.
5771 On Posix systems, this function always returns non-nil, and has no
5772 effect except for flushing STREAM's data. */)
5773 (Lisp_Object stream, Lisp_Object mode)
5775 FILE *fp = NULL;
5776 int binmode;
5778 CHECK_SYMBOL (stream);
5779 if (EQ (stream, Qstdin))
5780 fp = stdin;
5781 else if (EQ (stream, Qstdout))
5782 fp = stdout;
5783 else if (EQ (stream, Qstderr))
5784 fp = stderr;
5785 else
5786 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5788 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5789 if (fp != stdin)
5790 fflush (fp);
5792 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5795 void
5796 init_fileio (void)
5798 realmask = umask (0);
5799 umask (realmask);
5801 valid_timestamp_file_system = 0;
5803 /* fsync can be a significant performance hit. Often it doesn't
5804 suffice to make the file-save operation survive a crash. For
5805 batch scripts, which are typically part of larger shell commands
5806 that don't fsync other files, its effect on performance can be
5807 significant so its utility is particularly questionable.
5808 Hence, for now by default fsync is used only when interactive.
5810 For more on why fsync often fails to work on today's hardware, see:
5811 Zheng M et al. Understanding the robustness of SSDs under power fault.
5812 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5813 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5815 For more on why fsync does not suffice even if it works properly, see:
5816 Roche X. Necessary step(s) to synchronize filename operations on disk.
5817 Austin Group Defect 672, 2013-03-19
5818 http://austingroupbugs.net/view.php?id=672 */
5819 write_region_inhibit_fsync = noninteractive;
5822 void
5823 syms_of_fileio (void)
5825 /* Property name of a file name handler,
5826 which gives a list of operations it handles. */
5827 DEFSYM (Qoperations, "operations");
5829 DEFSYM (Qexpand_file_name, "expand-file-name");
5830 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5831 DEFSYM (Qdirectory_file_name, "directory-file-name");
5832 DEFSYM (Qfile_name_directory, "file-name-directory");
5833 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5834 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5835 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5836 DEFSYM (Qcopy_file, "copy-file");
5837 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5838 DEFSYM (Qmake_directory, "make-directory");
5839 DEFSYM (Qdelete_file, "delete-file");
5840 DEFSYM (Qrename_file, "rename-file");
5841 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5842 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5843 DEFSYM (Qfile_exists_p, "file-exists-p");
5844 DEFSYM (Qfile_executable_p, "file-executable-p");
5845 DEFSYM (Qfile_readable_p, "file-readable-p");
5846 DEFSYM (Qfile_writable_p, "file-writable-p");
5847 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5848 DEFSYM (Qaccess_file, "access-file");
5849 DEFSYM (Qfile_directory_p, "file-directory-p");
5850 DEFSYM (Qfile_regular_p, "file-regular-p");
5851 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5852 DEFSYM (Qfile_modes, "file-modes");
5853 DEFSYM (Qset_file_modes, "set-file-modes");
5854 DEFSYM (Qset_file_times, "set-file-times");
5855 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5856 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5857 DEFSYM (Qfile_acl, "file-acl");
5858 DEFSYM (Qset_file_acl, "set-file-acl");
5859 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5860 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5861 DEFSYM (Qwrite_region, "write-region");
5862 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5863 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5865 /* The symbol bound to coding-system-for-read when
5866 insert-file-contents is called for recovering a file. This is not
5867 an actual coding system name, but just an indicator to tell
5868 insert-file-contents to use `emacs-mule' with a special flag for
5869 auto saving and recovering a file. */
5870 DEFSYM (Qauto_save_coding, "auto-save-coding");
5872 DEFSYM (Qfile_name_history, "file-name-history");
5873 Fset (Qfile_name_history, Qnil);
5875 DEFSYM (Qfile_error, "file-error");
5876 DEFSYM (Qfile_already_exists, "file-already-exists");
5877 DEFSYM (Qfile_date_error, "file-date-error");
5878 DEFSYM (Qfile_missing, "file-missing");
5879 DEFSYM (Qfile_notify_error, "file-notify-error");
5880 DEFSYM (Qexcl, "excl");
5882 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5883 doc: /* Coding system for encoding file names.
5884 If it is nil, `default-file-name-coding-system' (which see) is used.
5886 On MS-Windows, the value of this variable is largely ignored if
5887 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5888 behaves as if file names were encoded in `utf-8'. */);
5889 Vfile_name_coding_system = Qnil;
5891 DEFVAR_LISP ("default-file-name-coding-system",
5892 Vdefault_file_name_coding_system,
5893 doc: /* Default coding system for encoding file names.
5894 This variable is used only when `file-name-coding-system' is nil.
5896 This variable is set/changed by the command `set-language-environment'.
5897 User should not set this variable manually,
5898 instead use `file-name-coding-system' to get a constant encoding
5899 of file names regardless of the current language environment.
5901 On MS-Windows, the value of this variable is largely ignored if
5902 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5903 behaves as if file names were encoded in `utf-8'. */);
5904 Vdefault_file_name_coding_system = Qnil;
5906 /* Lisp functions for translating file formats. */
5907 DEFSYM (Qformat_decode, "format-decode");
5908 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5910 /* Lisp function for setting buffer-file-coding-system and the
5911 multibyteness of the current buffer after inserting a file. */
5912 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5914 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5916 Fput (Qfile_error, Qerror_conditions,
5917 Fpurecopy (list2 (Qfile_error, Qerror)));
5918 Fput (Qfile_error, Qerror_message,
5919 build_pure_c_string ("File error"));
5921 Fput (Qfile_already_exists, Qerror_conditions,
5922 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5923 Fput (Qfile_already_exists, Qerror_message,
5924 build_pure_c_string ("File already exists"));
5926 Fput (Qfile_date_error, Qerror_conditions,
5927 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5928 Fput (Qfile_date_error, Qerror_message,
5929 build_pure_c_string ("Cannot set file date"));
5931 Fput (Qfile_missing, Qerror_conditions,
5932 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
5933 Fput (Qfile_missing, Qerror_message,
5934 build_pure_c_string ("File is missing"));
5936 Fput (Qfile_notify_error, Qerror_conditions,
5937 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5938 Fput (Qfile_notify_error, Qerror_message,
5939 build_pure_c_string ("File notification error"));
5941 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5942 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5943 If a file name matches REGEXP, all I/O on that file is done by calling
5944 HANDLER. If a file name matches more than one handler, the handler
5945 whose match starts last in the file name gets precedence. The
5946 function `find-file-name-handler' checks this list for a handler for
5947 its argument.
5949 HANDLER should be a function. The first argument given to it is the
5950 name of the I/O primitive to be handled; the remaining arguments are
5951 the arguments that were passed to that primitive. For example, if you
5952 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5953 HANDLER is called like this:
5955 (funcall HANDLER \\='file-exists-p FILENAME)
5957 Note that HANDLER must be able to handle all I/O primitives; if it has
5958 nothing special to do for a primitive, it should reinvoke the
5959 primitive to handle the operation \"the usual way\".
5960 See Info node `(elisp)Magic File Names' for more details. */);
5961 Vfile_name_handler_alist = Qnil;
5963 DEFVAR_LISP ("set-auto-coding-function",
5964 Vset_auto_coding_function,
5965 doc: /* If non-nil, a function to call to decide a coding system of file.
5966 Two arguments are passed to this function: the file name
5967 and the length of a file contents following the point.
5968 This function should return a coding system to decode the file contents.
5969 It should check the file name against `auto-coding-alist'.
5970 If no coding system is decided, it should check a coding system
5971 specified in the heading lines with the format:
5972 -*- ... coding: CODING-SYSTEM; ... -*-
5973 or local variable spec of the tailing lines with `coding:' tag. */);
5974 Vset_auto_coding_function = Qnil;
5976 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5977 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5978 Each is passed one argument, the number of characters inserted,
5979 with point at the start of the inserted text. Each function
5980 should leave point the same, and return the new character count.
5981 If `insert-file-contents' is intercepted by a handler from
5982 `file-name-handler-alist', that handler is responsible for calling the
5983 functions in `after-insert-file-functions' if appropriate. */);
5984 Vafter_insert_file_functions = Qnil;
5986 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5987 doc: /* A list of functions to be called at the start of `write-region'.
5988 Each is passed two arguments, START and END as for `write-region'.
5989 These are usually two numbers but not always; see the documentation
5990 for `write-region'. The function should return a list of pairs
5991 of the form (POSITION . STRING), consisting of strings to be effectively
5992 inserted at the specified positions of the file being written (1 means to
5993 insert before the first byte written). The POSITIONs must be sorted into
5994 increasing order.
5996 If there are several annotation functions, the lists returned by these
5997 functions are merged destructively. As each annotation function runs,
5998 the variable `write-region-annotations-so-far' contains a list of all
5999 annotations returned by previous annotation functions.
6001 An annotation function can return with a different buffer current.
6002 Doing so removes the annotations returned by previous functions, and
6003 resets START and END to `point-min' and `point-max' of the new buffer.
6005 After `write-region' completes, Emacs calls the function stored in
6006 `write-region-post-annotation-function', once for each buffer that was
6007 current when building the annotations (i.e., at least once), with that
6008 buffer current. */);
6009 Vwrite_region_annotate_functions = Qnil;
6010 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6012 DEFVAR_LISP ("write-region-post-annotation-function",
6013 Vwrite_region_post_annotation_function,
6014 doc: /* Function to call after `write-region' completes.
6015 The function is called with no arguments. If one or more of the
6016 annotation functions in `write-region-annotate-functions' changed the
6017 current buffer, the function stored in this variable is called for
6018 each of those additional buffers as well, in addition to the original
6019 buffer. The relevant buffer is current during each function call. */);
6020 Vwrite_region_post_annotation_function = Qnil;
6021 staticpro (&Vwrite_region_annotation_buffers);
6023 DEFVAR_LISP ("write-region-annotations-so-far",
6024 Vwrite_region_annotations_so_far,
6025 doc: /* When an annotation function is called, this holds the previous annotations.
6026 These are the annotations made by other annotation functions
6027 that were already called. See also `write-region-annotate-functions'. */);
6028 Vwrite_region_annotations_so_far = Qnil;
6030 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6031 doc: /* A list of file name handlers that temporarily should not be used.
6032 This applies only to the operation `inhibit-file-name-operation'. */);
6033 Vinhibit_file_name_handlers = Qnil;
6035 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6036 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6037 Vinhibit_file_name_operation = Qnil;
6039 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6040 doc: /* File name in which we write a list of all auto save file names.
6041 This variable is initialized automatically from `auto-save-list-file-prefix'
6042 shortly after Emacs reads your init file, if you have not yet given it
6043 a non-nil value. */);
6044 Vauto_save_list_file_name = Qnil;
6046 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6047 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6048 Normally auto-save files are written under other names. */);
6049 Vauto_save_visited_file_name = Qnil;
6051 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6052 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6053 If nil, deleting a substantial portion of the text disables auto-save
6054 in the buffer; this is the default behavior, because the auto-save
6055 file is usually more useful if it contains the deleted text. */);
6056 Vauto_save_include_big_deletions = Qnil;
6058 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6059 doc: /* Non-nil means don't call fsync in `write-region'.
6060 This variable affects calls to `write-region' as well as save commands.
6061 Setting this to nil may avoid data loss if the system loses power or
6062 the operating system crashes. By default, it is non-nil in batch mode. */);
6063 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6065 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6066 doc: /* Specifies whether to use the system's trash can.
6067 When non-nil, certain file deletion commands use the function
6068 `move-file-to-trash' instead of deleting files outright.
6069 This includes interactive calls to `delete-file' and
6070 `delete-directory' and the Dired deletion commands. */);
6071 delete_by_moving_to_trash = 0;
6072 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6074 /* Lisp function for moving files to trash. */
6075 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6077 /* Lisp function for recursively copying directories. */
6078 DEFSYM (Qcopy_directory, "copy-directory");
6080 /* Lisp function for recursively deleting directories. */
6081 DEFSYM (Qdelete_directory, "delete-directory");
6083 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6084 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6086 DEFSYM (Qstdin, "stdin");
6087 DEFSYM (Qstdout, "stdout");
6088 DEFSYM (Qstderr, "stderr");
6090 defsubr (&Sfind_file_name_handler);
6091 defsubr (&Sfile_name_directory);
6092 defsubr (&Sfile_name_nondirectory);
6093 defsubr (&Sunhandled_file_name_directory);
6094 defsubr (&Sfile_name_as_directory);
6095 defsubr (&Sdirectory_file_name);
6096 defsubr (&Smake_temp_name);
6097 defsubr (&Sexpand_file_name);
6098 defsubr (&Ssubstitute_in_file_name);
6099 defsubr (&Scopy_file);
6100 defsubr (&Smake_directory_internal);
6101 defsubr (&Sdelete_directory_internal);
6102 defsubr (&Sdelete_file);
6103 defsubr (&Srename_file);
6104 defsubr (&Sadd_name_to_file);
6105 defsubr (&Smake_symbolic_link);
6106 defsubr (&Sfile_name_absolute_p);
6107 defsubr (&Sfile_exists_p);
6108 defsubr (&Sfile_executable_p);
6109 defsubr (&Sfile_readable_p);
6110 defsubr (&Sfile_writable_p);
6111 defsubr (&Saccess_file);
6112 defsubr (&Sfile_symlink_p);
6113 defsubr (&Sfile_directory_p);
6114 defsubr (&Sfile_accessible_directory_p);
6115 defsubr (&Sfile_regular_p);
6116 defsubr (&Sfile_modes);
6117 defsubr (&Sset_file_modes);
6118 defsubr (&Sset_file_times);
6119 defsubr (&Sfile_selinux_context);
6120 defsubr (&Sfile_acl);
6121 defsubr (&Sset_file_acl);
6122 defsubr (&Sset_file_selinux_context);
6123 defsubr (&Sset_default_file_modes);
6124 defsubr (&Sdefault_file_modes);
6125 defsubr (&Sfile_newer_than_file_p);
6126 defsubr (&Sinsert_file_contents);
6127 defsubr (&Swrite_region);
6128 defsubr (&Scar_less_than_car);
6129 defsubr (&Sverify_visited_file_modtime);
6130 defsubr (&Svisited_file_modtime);
6131 defsubr (&Sset_visited_file_modtime);
6132 defsubr (&Sdo_auto_save);
6133 defsubr (&Sset_buffer_auto_saved);
6134 defsubr (&Sclear_buffer_auto_save_failure);
6135 defsubr (&Srecent_auto_save_p);
6137 defsubr (&Snext_read_file_uses_dialog_p);
6139 defsubr (&Sset_binary_mode);
6141 #ifdef HAVE_SYNC
6142 defsubr (&Sunix_sync);
6143 #endif