Document reserved keys
[emacs.git] / src / fileio.c
blobc4a10000bc3f306506a5879515ea4c53f7491d97
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2018 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 <https://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 DARWIN_OS
29 #include <sys/attr.h>
30 #endif
32 #ifdef HAVE_PWD_H
33 #include <pwd.h>
34 #endif
36 #include <errno.h>
38 #ifdef HAVE_LIBSELINUX
39 #include <selinux/selinux.h>
40 #include <selinux/context.h>
41 #endif
43 #if USE_ACL && defined HAVE_ACL_SET_FILE
44 #include <sys/acl.h>
45 #endif
47 #include <c-ctype.h>
49 #include "lisp.h"
50 #include "composite.h"
51 #include "character.h"
52 #include "buffer.h"
53 #include "coding.h"
54 #include "window.h"
55 #include "blockinput.h"
56 #include "region-cache.h"
57 #include "frame.h"
59 #ifdef HAVE_LINUX_FS_H
60 # include <sys/ioctl.h>
61 # include <linux/fs.h>
62 #endif
64 #ifdef WINDOWSNT
65 #define NOMINMAX 1
66 #include <windows.h>
67 /* The redundant #ifdef is to avoid compiler warning about unused macro. */
68 #ifdef NOMINMAX
69 #undef NOMINMAX
70 #endif
71 #include <sys/file.h>
72 #include "w32.h"
73 #endif /* not WINDOWSNT */
75 #ifdef MSDOS
76 #include "msdos.h"
77 #include <sys/param.h>
78 #endif
80 #ifdef DOS_NT
81 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
82 redirector allows the six letters between 'Z' and 'a' as well. */
83 #ifdef MSDOS
84 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
85 #endif
86 #ifdef WINDOWSNT
87 #define IS_DRIVE(x) c_isalpha (x)
88 #endif
89 /* Need to lower-case the drive letter, or else expanded
90 filenames will sometimes compare unequal, because
91 `expand-file-name' doesn't always down-case the drive letter. */
92 #define DRIVE_LETTER(x) c_tolower (x)
93 #endif
95 #include "systime.h"
96 #include <acl.h>
97 #include <allocator.h>
98 #include <careadlinkat.h>
99 #include <stat-time.h>
100 #include <tempname.h>
102 #include <binary-io.h>
104 #ifdef HPUX
105 #include <netio.h>
106 #endif
108 #include "commands.h"
110 /* True during writing of auto-save files. */
111 static bool auto_saving;
113 /* Emacs's real umask. */
114 static mode_t realmask;
116 /* Nonzero umask during creation of auto-save directories. */
117 static mode_t auto_saving_dir_umask;
119 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
120 a new file with the same mode as the original. */
121 static mode_t auto_save_mode_bits;
123 /* Set by auto_save_1 if an error occurred during the last auto-save. */
124 static bool auto_save_error_occurred;
126 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
127 number of a file system where time stamps were observed to work. */
128 static bool valid_timestamp_file_system;
129 static dev_t timestamp_file_system;
131 /* Each time an annotation function changes the buffer, the new buffer
132 is added here. */
133 static Lisp_Object Vwrite_region_annotation_buffers;
135 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
136 Lisp_Object *, struct coding_system *);
137 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
138 struct coding_system *);
141 /* Return true if FILENAME exists. */
143 static bool
144 check_existing (const char *filename)
146 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
149 /* Return true if file FILENAME exists and can be executed. */
151 static bool
152 check_executable (char *filename)
154 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
157 /* Return true if file FILENAME exists and can be accessed
158 according to AMODE, which should include W_OK.
159 On failure, return false and set errno. */
161 static bool
162 check_writable (const char *filename, int amode)
164 #ifdef MSDOS
165 /* FIXME: an faccessat implementation should be added to the
166 DOS/Windows ports and this #ifdef branch should be removed. */
167 struct stat st;
168 if (stat (filename, &st) < 0)
169 return 0;
170 errno = EPERM;
171 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
172 #else /* not MSDOS */
173 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
174 #ifdef CYGWIN
175 /* faccessat may have returned failure because Cygwin couldn't
176 determine the file's UID or GID; if so, we return success. */
177 if (!res)
179 int faccessat_errno = errno;
180 struct stat st;
181 if (stat (filename, &st) < 0)
182 return 0;
183 res = (st.st_uid == -1 || st.st_gid == -1);
184 errno = faccessat_errno;
186 #endif /* CYGWIN */
187 return res;
188 #endif /* not MSDOS */
191 /* Signal a file-access failure. STRING describes the failure,
192 NAME the file involved, and ERRORNO the errno value.
194 If NAME is neither null nor a pair, package it up as a singleton
195 list before reporting it; this saves report_file_errno's caller the
196 trouble of preserving errno before calling list1. */
198 void
199 report_file_errno (char const *string, Lisp_Object name, int errorno)
201 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
202 char *str = emacs_strerror (errorno);
203 AUTO_STRING (unibyte_str, str);
204 Lisp_Object errstring
205 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
206 Lisp_Object errdata = Fcons (errstring, data);
208 if (errorno == EEXIST)
209 xsignal (Qfile_already_exists, errdata);
210 else
211 xsignal (errorno == ENOENT ? Qfile_missing : Qfile_error,
212 Fcons (build_string (string), errdata));
215 /* Signal a file-access failure that set errno. STRING describes the
216 failure, NAME the file involved. When invoking this function, take
217 care to not use arguments such as build_string ("foo") that involve
218 side effects that may set errno. */
220 void
221 report_file_error (char const *string, Lisp_Object name)
223 report_file_errno (string, name, errno);
226 /* Like report_file_error, but reports a file-notify-error instead. */
228 void
229 report_file_notify_error (const char *string, Lisp_Object name)
231 char *str = emacs_strerror (errno);
232 AUTO_STRING (unibyte_str, str);
233 Lisp_Object errstring
234 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
235 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
236 Lisp_Object errdata = Fcons (errstring, data);
238 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
241 void
242 close_file_unwind (int fd)
244 emacs_close (fd);
247 void
248 fclose_unwind (void *arg)
250 FILE *stream = arg;
251 fclose (stream);
254 /* Restore point, having saved it as a marker. */
256 void
257 restore_point_unwind (Lisp_Object location)
259 Fgoto_char (location);
260 unchain_marker (XMARKER (location));
264 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
265 Sfind_file_name_handler, 2, 2, 0,
266 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
267 Otherwise, return nil.
268 A file name is handled if one of the regular expressions in
269 `file-name-handler-alist' matches it.
271 If OPERATION equals `inhibit-file-name-operation', then ignore
272 any handlers that are members of `inhibit-file-name-handlers',
273 but still do run any other handlers. This lets handlers
274 use the standard functions without calling themselves recursively. */)
275 (Lisp_Object filename, Lisp_Object operation)
277 /* This function must not munge the match data. */
278 Lisp_Object chain, inhibited_handlers, result;
279 ptrdiff_t pos = -1;
281 result = Qnil;
282 CHECK_STRING (filename);
284 if (EQ (operation, Vinhibit_file_name_operation))
285 inhibited_handlers = Vinhibit_file_name_handlers;
286 else
287 inhibited_handlers = Qnil;
289 for (chain = Vfile_name_handler_alist; CONSP (chain);
290 chain = XCDR (chain))
292 Lisp_Object elt;
293 elt = XCAR (chain);
294 if (CONSP (elt))
296 Lisp_Object string = XCAR (elt);
297 ptrdiff_t match_pos;
298 Lisp_Object handler = XCDR (elt);
299 Lisp_Object operations = Qnil;
301 if (SYMBOLP (handler))
302 operations = Fget (handler, Qoperations);
304 if (STRINGP (string)
305 && (match_pos = fast_string_match (string, filename)) > pos
306 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
308 Lisp_Object tem;
310 handler = XCDR (elt);
311 tem = Fmemq (handler, inhibited_handlers);
312 if (NILP (tem))
314 result = handler;
315 pos = match_pos;
320 maybe_quit ();
322 return result;
325 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
326 1, 1, 0,
327 doc: /* Return the directory component in file name FILENAME.
328 Return nil if FILENAME does not include a directory.
329 Otherwise return a directory name.
330 Given a Unix syntax file name, returns a string ending in slash. */)
331 (Lisp_Object filename)
333 Lisp_Object handler;
335 CHECK_STRING (filename);
337 /* If the file name has special constructs in it,
338 call the corresponding file handler. */
339 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
340 if (!NILP (handler))
342 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
343 filename);
344 return STRINGP (handled_name) ? handled_name : Qnil;
347 char *beg = SSDATA (filename);
348 char const *p = beg + SBYTES (filename);
350 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
351 #ifdef DOS_NT
352 /* only recognize drive specifier at the beginning */
353 && !(p[-1] == ':'
354 /* handle the "/:d:foo" and "/:foo" cases correctly */
355 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
356 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
357 #endif
358 ) p--;
360 if (p == beg)
361 return Qnil;
362 #ifdef DOS_NT
363 /* Expansion of "c:" to drive and default directory. */
364 Lisp_Object tem_fn;
365 USE_SAFE_ALLOCA;
366 SAFE_ALLOCA_STRING (beg, filename);
367 p = beg + (p - SSDATA (filename));
369 if (p[-1] == ':')
371 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
372 char *res = alloca (MAXPATHLEN + 1);
373 char *r = res;
375 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
377 memcpy (res, beg, 2);
378 beg += 2;
379 r += 2;
382 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
384 size_t l = strlen (res);
386 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
387 strcat (res, "/");
388 beg = res;
389 p = beg + strlen (beg);
390 dostounix_filename (beg);
391 tem_fn = make_specified_string (beg, -1, p - beg,
392 STRING_MULTIBYTE (filename));
394 else
395 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
396 STRING_MULTIBYTE (filename));
398 else if (STRING_MULTIBYTE (filename))
400 tem_fn = make_specified_string (beg, -1, p - beg, 1);
401 dostounix_filename (SSDATA (tem_fn));
402 #ifdef WINDOWSNT
403 if (!NILP (Vw32_downcase_file_names))
404 tem_fn = Fdowncase (tem_fn);
405 #endif
407 else
409 dostounix_filename (beg);
410 tem_fn = make_specified_string (beg, -1, p - beg, 0);
412 SAFE_FREE ();
413 return tem_fn;
414 #else /* DOS_NT */
415 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
416 #endif /* DOS_NT */
419 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
420 Sfile_name_nondirectory, 1, 1, 0,
421 doc: /* Return file name FILENAME sans its directory.
422 For example, in a Unix-syntax file name,
423 this is everything after the last slash,
424 or the entire name if it contains no slash. */)
425 (Lisp_Object filename)
427 register const char *beg, *p, *end;
428 Lisp_Object handler;
430 CHECK_STRING (filename);
432 /* If the file name has special constructs in it,
433 call the corresponding file handler. */
434 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
435 if (!NILP (handler))
437 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
438 filename);
439 if (STRINGP (handled_name))
440 return handled_name;
441 error ("Invalid handler in `file-name-handler-alist'");
444 beg = SSDATA (filename);
445 end = p = beg + SBYTES (filename);
447 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
448 #ifdef DOS_NT
449 /* only recognize drive specifier at beginning */
450 && !(p[-1] == ':'
451 /* handle the "/:d:foo" case correctly */
452 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
453 #endif
455 p--;
457 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
460 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
461 Sunhandled_file_name_directory, 1, 1, 0,
462 doc: /* Return a directly usable directory name somehow associated with FILENAME.
463 A `directly usable' directory name is one that may be used without the
464 intervention of any file handler.
465 If FILENAME is a directly usable file itself, return
466 \(file-name-as-directory FILENAME).
467 If FILENAME refers to a file which is not accessible from a local process,
468 then this should return nil.
469 The `call-process' and `start-process' functions use this function to
470 get a current directory to run processes in. */)
471 (Lisp_Object filename)
473 Lisp_Object handler;
475 /* If the file name has special constructs in it,
476 call the corresponding file handler. */
477 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
478 if (!NILP (handler))
480 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
481 filename);
482 return STRINGP (handled_name) ? handled_name : Qnil;
485 return Ffile_name_as_directory (filename);
488 /* Maximum number of bytes that DST will be longer than SRC
489 in file_name_as_directory. This occurs when SRCLEN == 0. */
490 enum { file_name_as_directory_slop = 2 };
492 /* Convert from file name SRC of length SRCLEN to directory name in
493 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
494 string. On UNIX, just make sure there is a terminating /. Return
495 the length of DST in bytes. */
497 static ptrdiff_t
498 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
499 bool multibyte)
501 if (srclen == 0)
503 dst[0] = '.';
504 dst[1] = '/';
505 dst[2] = '\0';
506 return 2;
509 memcpy (dst, src, srclen);
510 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
511 dst[srclen++] = DIRECTORY_SEP;
512 dst[srclen] = 0;
513 #ifdef DOS_NT
514 dostounix_filename (dst);
515 #endif
516 return srclen;
519 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
520 Sfile_name_as_directory, 1, 1, 0,
521 doc: /* Return a string representing the file name FILE interpreted as a directory.
522 This operation exists because a directory is also a file, but its name as
523 a directory is different from its name as a file.
524 The result can be used as the value of `default-directory'
525 or passed as second argument to `expand-file-name'.
526 For a Unix-syntax file name, just appends a slash unless a trailing slash
527 is already present. */)
528 (Lisp_Object file)
530 char *buf;
531 ptrdiff_t length;
532 Lisp_Object handler, val;
533 USE_SAFE_ALLOCA;
535 CHECK_STRING (file);
537 /* If the file name has special constructs in it,
538 call the corresponding file handler. */
539 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
540 if (!NILP (handler))
542 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
543 file);
544 if (STRINGP (handled_name))
545 return handled_name;
546 error ("Invalid handler in `file-name-handler-alist'");
549 #ifdef WINDOWSNT
550 if (!NILP (Vw32_downcase_file_names))
551 file = Fdowncase (file);
552 #endif
553 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
554 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
555 STRING_MULTIBYTE (file));
556 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
557 SAFE_FREE ();
558 return val;
561 /* Convert from directory name SRC of length SRCLEN to file name in
562 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
563 string. On UNIX, just make sure there isn't a terminating /.
564 Return the length of DST in bytes. */
566 static ptrdiff_t
567 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
569 /* In Unix-like systems, just remove any final slashes. However, if
570 they are all slashes, leave "/" and "//" alone, and treat "///"
571 and longer as if they were "/". */
572 if (! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
573 while (srclen > 1
574 #ifdef DOS_NT
575 && !(srclen > 2 && IS_DEVICE_SEP (src[srclen - 2]))
576 #endif
577 && IS_DIRECTORY_SEP (src[srclen - 1]))
578 srclen--;
580 memcpy (dst, src, srclen);
581 dst[srclen] = 0;
582 #ifdef DOS_NT
583 dostounix_filename (dst);
584 #endif
585 return srclen;
588 DEFUN ("directory-name-p", Fdirectory_name_p, Sdirectory_name_p, 1, 1, 0,
589 doc: /* Return non-nil if NAME ends with a directory separator character. */)
590 (Lisp_Object name)
592 CHECK_STRING (name);
593 ptrdiff_t namelen = SBYTES (name);
594 unsigned char c = namelen ? SREF (name, namelen - 1) : 0;
595 return IS_DIRECTORY_SEP (c) ? Qt : Qnil;
598 /* Return the expansion of NEWNAME, except that if NEWNAME is a
599 directory name then return the expansion of FILE's basename under
600 NEWNAME. This resembles how 'cp FILE NEWNAME' works, except that
601 it requires NEWNAME to be a directory name (typically, by ending in
602 "/"). */
604 static Lisp_Object
605 expand_cp_target (Lisp_Object file, Lisp_Object newname)
607 return (!NILP (Fdirectory_name_p (newname))
608 ? Fexpand_file_name (Ffile_name_nondirectory (file), newname)
609 : Fexpand_file_name (newname, Qnil));
612 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
613 1, 1, 0,
614 doc: /* Returns the file name of the directory named DIRECTORY.
615 This is the name of the file that holds the data for the directory DIRECTORY.
616 This operation exists because a directory is also a file, but its name as
617 a directory is different from its name as a file.
618 In Unix-syntax, this function just removes the final slash. */)
619 (Lisp_Object directory)
621 char *buf;
622 ptrdiff_t length;
623 Lisp_Object handler, val;
624 USE_SAFE_ALLOCA;
626 CHECK_STRING (directory);
628 /* If the file name has special constructs in it,
629 call the corresponding file handler. */
630 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
631 if (!NILP (handler))
633 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
634 directory);
635 if (STRINGP (handled_name))
636 return handled_name;
637 error ("Invalid handler in `file-name-handler-alist'");
640 #ifdef WINDOWSNT
641 if (!NILP (Vw32_downcase_file_names))
642 directory = Fdowncase (directory);
643 #endif
644 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
645 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
646 STRING_MULTIBYTE (directory));
647 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
648 SAFE_FREE ();
649 return val;
652 DEFUN ("make-temp-file-internal", Fmake_temp_file_internal,
653 Smake_temp_file_internal, 4, 4, 0,
654 doc: /* Generate a new file whose name starts with PREFIX, a string.
655 Return the name of the generated file. If DIR-FLAG is zero, do not
656 create the file, just its name. Otherwise, if DIR-FLAG is non-nil,
657 create an empty directory. The file name should end in SUFFIX.
658 Do not expand PREFIX; a non-absolute PREFIX is relative to the Emacs
659 working directory. If TEXT is a string, insert it into the newly
660 created file.
662 Signal an error if the file could not be created.
664 This function does not grok magic file names. */)
665 (Lisp_Object prefix, Lisp_Object dir_flag, Lisp_Object suffix,
666 Lisp_Object text)
668 CHECK_STRING (prefix);
669 CHECK_STRING (suffix);
670 Lisp_Object encoded_prefix = ENCODE_FILE (prefix);
671 Lisp_Object encoded_suffix = ENCODE_FILE (suffix);
672 ptrdiff_t prefix_len = SBYTES (encoded_prefix);
673 ptrdiff_t suffix_len = SBYTES (encoded_suffix);
674 if (INT_MAX < suffix_len)
675 args_out_of_range (prefix, suffix);
676 int nX = 6;
677 Lisp_Object val = make_uninit_string (prefix_len + nX + suffix_len);
678 char *data = SSDATA (val);
679 memcpy (data, SSDATA (encoded_prefix), prefix_len);
680 memset (data + prefix_len, 'X', nX);
681 memcpy (data + prefix_len + nX, SSDATA (encoded_suffix), suffix_len);
682 int kind = (NILP (dir_flag) ? GT_FILE
683 : EQ (dir_flag, make_number (0)) ? GT_NOCREATE
684 : GT_DIR);
685 int fd = gen_tempname (data, suffix_len, O_BINARY | O_CLOEXEC, kind);
686 bool failed = fd < 0;
687 if (!failed)
689 ptrdiff_t count = SPECPDL_INDEX ();
690 record_unwind_protect_int (close_file_unwind, fd);
691 val = DECODE_FILE (val);
692 if (STRINGP (text) && SBYTES (text) != 0)
693 write_region (text, Qnil, val, Qnil, Qnil, Qnil, Qnil, fd);
694 failed = NILP (dir_flag) && emacs_close (fd) != 0;
695 /* Discard the unwind protect. */
696 specpdl_ptr = specpdl + count;
698 if (failed)
700 static char const kind_message[][32] =
702 [GT_FILE] = "Creating file with prefix",
703 [GT_DIR] = "Creating directory with prefix",
704 [GT_NOCREATE] = "Creating file name with prefix"
706 report_file_error (kind_message[kind], prefix);
708 return val;
712 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
713 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
715 This function tries to choose a name that has no existing file.
716 For this to work, PREFIX should be an absolute file name, and PREFIX
717 and the returned string should both be non-magic.
719 There is a race condition between calling `make-temp-name' and
720 later creating the file, which opens all kinds of security holes.
721 For that reason, you should normally use `make-temp-file' instead. */)
722 (Lisp_Object prefix)
724 return Fmake_temp_file_internal (prefix, make_number (0),
725 empty_unibyte_string, Qnil);
728 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
729 doc: /* Convert filename NAME to absolute, and canonicalize it.
730 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
731 \(does not start with slash or tilde); both the directory name and
732 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
733 missing, the current buffer's value of `default-directory' is used.
734 NAME should be a string that is a valid file name for the underlying
735 filesystem.
736 File name components that are `.' are removed, and
737 so are file name components followed by `..', along with the `..' itself;
738 note that these simplifications are done without checking the resulting
739 file names in the file system.
740 Multiple consecutive slashes are collapsed into a single slash,
741 except at the beginning of the file name when they are significant (e.g.,
742 UNC file names on MS-Windows.)
743 An initial `~/' expands to your home directory.
744 An initial `~USER/' expands to USER's home directory.
745 See also the function `substitute-in-file-name'.
747 For technical reasons, this function can return correct but
748 non-intuitive results for the root directory; for instance,
749 \(expand-file-name ".." "/") returns "/..". For this reason, use
750 \(directory-file-name (file-name-directory dirname)) to traverse a
751 filesystem tree, not (expand-file-name ".." dirname). Note: make
752 sure DIRNAME in this example doesn't end in a slash, unless it's
753 the root directory. */)
754 (Lisp_Object name, Lisp_Object default_directory)
756 /* These point to SDATA and need to be careful with string-relocation
757 during GC (via DECODE_FILE). */
758 char *nm;
759 char *nmlim;
760 const char *newdir;
761 const char *newdirlim;
762 /* This should only point to alloca'd data. */
763 char *target;
765 ptrdiff_t tlen;
766 struct passwd *pw;
767 #ifdef DOS_NT
768 int drive = 0;
769 bool collapse_newdir = true;
770 bool is_escaped = 0;
771 #endif /* DOS_NT */
772 ptrdiff_t length, nbytes;
773 Lisp_Object handler, result, handled_name;
774 bool multibyte;
775 Lisp_Object hdir;
776 USE_SAFE_ALLOCA;
778 CHECK_STRING (name);
780 /* If the file name has special constructs in it,
781 call the corresponding file handler. */
782 handler = Ffind_file_name_handler (name, Qexpand_file_name);
783 if (!NILP (handler))
785 handled_name = call3 (handler, Qexpand_file_name,
786 name, default_directory);
787 if (STRINGP (handled_name))
788 return handled_name;
789 error ("Invalid handler in `file-name-handler-alist'");
793 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
794 if (NILP (default_directory))
795 default_directory = BVAR (current_buffer, directory);
796 if (! STRINGP (default_directory))
798 #ifdef DOS_NT
799 /* "/" is not considered a root directory on DOS_NT, so using "/"
800 here causes an infinite recursion in, e.g., the following:
802 (let (default-directory)
803 (expand-file-name "a"))
805 To avoid this, we set default_directory to the root of the
806 current drive. */
807 default_directory = build_string (emacs_root_dir ());
808 #else
809 default_directory = build_string ("/");
810 #endif
813 if (!NILP (default_directory))
815 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
816 if (!NILP (handler))
818 handled_name = call3 (handler, Qexpand_file_name,
819 name, default_directory);
820 if (STRINGP (handled_name))
821 return handled_name;
822 error ("Invalid handler in `file-name-handler-alist'");
827 char *o = SSDATA (default_directory);
829 /* Make sure DEFAULT_DIRECTORY is properly expanded.
830 It would be better to do this down below where we actually use
831 default_directory. Unfortunately, calling Fexpand_file_name recursively
832 could invoke GC, and the strings might be relocated. This would
833 be annoying because we have pointers into strings lying around
834 that would need adjusting, and people would add new pointers to
835 the code and forget to adjust them, resulting in intermittent bugs.
836 Putting this call here avoids all that crud.
838 The EQ test avoids infinite recursion. */
839 if (! NILP (default_directory) && !EQ (default_directory, name)
840 /* Save time in some common cases - as long as default_directory
841 is not relative, it can be canonicalized with name below (if it
842 is needed at all) without requiring it to be expanded now. */
843 #ifdef DOS_NT
844 /* Detect MSDOS file names with drive specifiers. */
845 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
846 && IS_DIRECTORY_SEP (o[2]))
847 /* Detect escaped file names without drive spec after "/:".
848 These should not be recursively expanded, to avoid
849 including the default directory twice in the expanded
850 result. */
851 && ! (o[0] == '/' && o[1] == ':')
852 #ifdef WINDOWSNT
853 /* Detect Windows file names in UNC format. */
854 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
855 #endif
856 #else /* not DOS_NT */
857 /* Detect Unix absolute file names (/... alone is not absolute on
858 DOS or Windows). */
859 && ! (IS_DIRECTORY_SEP (o[0]))
860 #endif /* not DOS_NT */
863 default_directory = Fexpand_file_name (default_directory, Qnil);
866 multibyte = STRING_MULTIBYTE (name);
867 if (multibyte != STRING_MULTIBYTE (default_directory))
869 if (multibyte)
871 unsigned char *p = SDATA (name);
873 while (*p && ASCII_CHAR_P (*p))
874 p++;
875 if (*p == '\0')
877 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
878 unibyte. Do not convert DEFAULT_DIRECTORY to
879 multibyte; instead, convert NAME to a unibyte string,
880 so that the result of this function is also a unibyte
881 string. This is needed during bootstrapping and
882 dumping, when Emacs cannot decode file names, because
883 the locale environment is not set up. */
884 name = make_unibyte_string (SSDATA (name), SBYTES (name));
885 multibyte = 0;
887 else
888 default_directory = string_to_multibyte (default_directory);
890 else
892 name = string_to_multibyte (name);
893 multibyte = 1;
897 #ifdef WINDOWSNT
898 if (!NILP (Vw32_downcase_file_names))
899 default_directory = Fdowncase (default_directory);
900 #endif
902 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
903 SAFE_ALLOCA_STRING (nm, name);
904 nmlim = nm + SBYTES (name);
906 #ifdef DOS_NT
907 /* Note if special escape prefix is present, but remove for now. */
908 if (nm[0] == '/' && nm[1] == ':')
910 is_escaped = 1;
911 nm += 2;
914 /* Find and remove drive specifier if present; this makes nm absolute
915 even if the rest of the name appears to be relative. Only look for
916 drive specifier at the beginning. */
917 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
919 drive = (unsigned char) nm[0];
920 nm += 2;
923 #ifdef WINDOWSNT
924 /* If we see "c://somedir", we want to strip the first slash after the
925 colon when stripping the drive letter. Otherwise, this expands to
926 "//somedir". */
927 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
928 nm++;
930 /* Discard any previous drive specifier if nm is now in UNC format. */
931 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
932 && !IS_DIRECTORY_SEP (nm[2]))
933 drive = 0;
934 #endif /* WINDOWSNT */
935 #endif /* DOS_NT */
937 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
938 none are found, we can probably return right away. We will avoid
939 allocating a new string if name is already fully expanded. */
940 if (
941 IS_DIRECTORY_SEP (nm[0])
942 #ifdef MSDOS
943 && drive && !is_escaped
944 #endif
945 #ifdef WINDOWSNT
946 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
947 #endif
950 /* If it turns out that the filename we want to return is just a
951 suffix of FILENAME, we don't need to go through and edit
952 things; we just need to construct a new string using data
953 starting at the middle of FILENAME. If we set LOSE, that
954 means we've discovered that we can't do that cool trick. */
955 bool lose = 0;
956 char *p = nm;
958 while (*p)
960 /* Since we know the name is absolute, we can assume that each
961 element starts with a "/". */
963 /* "." and ".." are hairy. */
964 if (IS_DIRECTORY_SEP (p[0])
965 && p[1] == '.'
966 && (IS_DIRECTORY_SEP (p[2])
967 || p[2] == 0
968 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
969 || p[3] == 0))))
970 lose = 1;
971 /* Replace multiple slashes with a single one, except
972 leave leading "//" alone. */
973 else if (IS_DIRECTORY_SEP (p[0])
974 && IS_DIRECTORY_SEP (p[1])
975 && (p != nm || IS_DIRECTORY_SEP (p[2])))
976 lose = 1;
977 p++;
979 if (!lose)
981 #ifdef DOS_NT
982 /* Make sure directories are all separated with /, but
983 avoid allocation of a new string when not required. */
984 dostounix_filename (nm);
985 #ifdef WINDOWSNT
986 if (IS_DIRECTORY_SEP (nm[1]))
988 if (strcmp (nm, SSDATA (name)) != 0)
989 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
991 else
992 #endif
993 /* Drive must be set, so this is okay. */
994 if (strcmp (nm - 2, SSDATA (name)) != 0)
996 name = make_specified_string (nm, -1, p - nm, multibyte);
997 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
998 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
999 name = concat2 (drive_prefix, name);
1001 #ifdef WINDOWSNT
1002 if (!NILP (Vw32_downcase_file_names))
1003 name = Fdowncase (name);
1004 #endif
1005 #else /* not DOS_NT */
1006 if (strcmp (nm, SSDATA (name)) != 0)
1007 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1008 #endif /* not DOS_NT */
1009 SAFE_FREE ();
1010 return name;
1014 /* At this point, nm might or might not be an absolute file name. We
1015 need to expand ~ or ~user if present, otherwise prefix nm with
1016 default_directory if nm is not absolute, and finally collapse /./
1017 and /foo/../ sequences.
1019 We set newdir to be the appropriate prefix if one is needed:
1020 - the relevant user directory if nm starts with ~ or ~user
1021 - the specified drive's working dir (DOS/NT only) if nm does not
1022 start with /
1023 - the value of default_directory.
1025 Note that these prefixes are not guaranteed to be absolute (except
1026 for the working dir of a drive). Therefore, to ensure we always
1027 return an absolute name, if the final prefix is not absolute we
1028 append it to the current working directory. */
1030 newdir = newdirlim = 0;
1032 if (nm[0] == '~' /* prefix ~ */
1033 #ifdef DOS_NT
1034 && !is_escaped /* don't expand ~ in escaped file names */
1035 #endif
1038 if (IS_DIRECTORY_SEP (nm[1])
1039 || nm[1] == 0) /* ~ by itself */
1041 Lisp_Object tem;
1043 if (!(newdir = egetenv ("HOME")))
1044 newdir = newdirlim = "";
1045 nm++;
1046 #ifdef WINDOWSNT
1047 if (newdir[0])
1049 char newdir_utf8[MAX_UTF8_PATH];
1051 filename_from_ansi (newdir, newdir_utf8);
1052 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1053 newdir = SSDATA (tem);
1055 else
1056 #endif
1057 tem = build_string (newdir);
1058 newdirlim = newdir + SBYTES (tem);
1059 /* `egetenv' may return a unibyte string, which will bite us
1060 if we expect the directory to be multibyte. */
1061 if (multibyte && !STRING_MULTIBYTE (tem))
1063 hdir = DECODE_FILE (tem);
1064 newdir = SSDATA (hdir);
1065 newdirlim = newdir + SBYTES (hdir);
1067 #ifdef DOS_NT
1068 collapse_newdir = false;
1069 #endif
1071 else /* ~user/filename */
1073 char *o, *p;
1074 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1075 continue;
1076 o = SAFE_ALLOCA (p - nm + 1);
1077 memcpy (o, nm, p - nm);
1078 o[p - nm] = 0;
1080 block_input ();
1081 pw = getpwnam (o + 1);
1082 unblock_input ();
1083 if (pw)
1085 Lisp_Object tem;
1087 newdir = pw->pw_dir;
1088 /* `getpwnam' may return a unibyte string, which will
1089 bite us when we expect the directory to be multibyte. */
1090 tem = make_unibyte_string (newdir, strlen (newdir));
1091 newdirlim = newdir + SBYTES (tem);
1092 if (multibyte && !STRING_MULTIBYTE (tem))
1094 hdir = DECODE_FILE (tem);
1095 newdir = SSDATA (hdir);
1096 newdirlim = newdir + SBYTES (hdir);
1098 nm = p;
1099 #ifdef DOS_NT
1100 collapse_newdir = false;
1101 #endif
1104 /* If we don't find a user of that name, leave the name
1105 unchanged; don't move nm forward to p. */
1109 #ifdef DOS_NT
1110 /* On DOS and Windows, nm is absolute if a drive name was specified;
1111 use the drive's current directory as the prefix if needed. */
1112 if (!newdir && drive)
1114 /* Get default directory if needed to make nm absolute. */
1115 char *adir = NULL;
1116 if (!IS_DIRECTORY_SEP (nm[0]))
1118 adir = alloca (MAXPATHLEN + 1);
1119 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1120 adir = NULL;
1121 else if (multibyte)
1123 Lisp_Object tem = build_string (adir);
1125 tem = DECODE_FILE (tem);
1126 newdirlim = adir + SBYTES (tem);
1127 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1129 else
1130 newdirlim = adir + strlen (adir);
1132 if (!adir)
1134 /* Either nm starts with /, or drive isn't mounted. */
1135 adir = alloca (4);
1136 adir[0] = DRIVE_LETTER (drive);
1137 adir[1] = ':';
1138 adir[2] = '/';
1139 adir[3] = 0;
1140 newdirlim = adir + 3;
1142 newdir = adir;
1144 #endif /* DOS_NT */
1146 /* Finally, if no prefix has been specified and nm is not absolute,
1147 then it must be expanded relative to default_directory. */
1149 if (1
1150 #ifndef DOS_NT
1151 /* /... alone is not absolute on DOS and Windows. */
1152 && !IS_DIRECTORY_SEP (nm[0])
1153 #endif
1154 #ifdef WINDOWSNT
1155 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1156 && !IS_DIRECTORY_SEP (nm[2]))
1157 #endif
1158 && !newdir)
1160 newdir = SSDATA (default_directory);
1161 newdirlim = newdir + SBYTES (default_directory);
1162 #ifdef DOS_NT
1163 /* Note if special escape prefix is present, but remove for now. */
1164 if (newdir[0] == '/' && newdir[1] == ':')
1166 is_escaped = 1;
1167 newdir += 2;
1169 #endif
1172 #ifdef DOS_NT
1173 if (newdir)
1175 /* First ensure newdir is an absolute name. */
1176 if (
1177 /* Detect MSDOS file names with drive specifiers. */
1178 ! (IS_DRIVE (newdir[0])
1179 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1180 #ifdef WINDOWSNT
1181 /* Detect Windows file names in UNC format. */
1182 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1183 && !IS_DIRECTORY_SEP (newdir[2]))
1184 #endif
1187 /* Effectively, let newdir be (expand-file-name newdir cwd).
1188 Because of the admonition against calling expand-file-name
1189 when we have pointers into lisp strings, we accomplish this
1190 indirectly by prepending newdir to nm if necessary, and using
1191 cwd (or the wd of newdir's drive) as the new newdir. */
1192 char *adir;
1193 #ifdef WINDOWSNT
1194 const int adir_size = MAX_UTF8_PATH;
1195 #else
1196 const int adir_size = MAXPATHLEN + 1;
1197 #endif
1199 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1201 drive = (unsigned char) newdir[0];
1202 newdir += 2;
1204 if (!IS_DIRECTORY_SEP (nm[0]))
1206 ptrdiff_t nmlen = nmlim - nm;
1207 ptrdiff_t newdirlen = newdirlim - newdir;
1208 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1209 + nmlen + 1);
1210 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1211 multibyte);
1212 memcpy (tmp + dlen, nm, nmlen + 1);
1213 nm = tmp;
1214 nmlim = nm + dlen + nmlen;
1216 adir = alloca (adir_size);
1217 if (drive)
1219 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1220 strcpy (adir, "/");
1222 else
1223 getcwd (adir, adir_size);
1224 if (multibyte)
1226 Lisp_Object tem = build_string (adir);
1228 tem = DECODE_FILE (tem);
1229 newdirlim = adir + SBYTES (tem);
1230 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1232 else
1233 newdirlim = adir + strlen (adir);
1234 newdir = adir;
1237 /* Strip off drive name from prefix, if present. */
1238 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1240 drive = newdir[0];
1241 newdir += 2;
1244 /* Keep only a prefix from newdir if nm starts with slash
1245 (//server/share for UNC, nothing otherwise). */
1246 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1248 #ifdef WINDOWSNT
1249 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1250 && !IS_DIRECTORY_SEP (newdir[2]))
1252 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1253 char *p = adir + 2;
1254 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1255 p++;
1256 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1257 *p = 0;
1258 newdir = adir;
1259 newdirlim = newdir + strlen (adir);
1261 else
1262 #endif
1263 newdir = newdirlim = "";
1266 #endif /* DOS_NT */
1268 /* Ignore any slash at the end of newdir, unless newdir is
1269 just "/" or "//". */
1270 length = newdirlim - newdir;
1271 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1272 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1273 length--;
1275 /* Now concatenate the directory and name to new space in the stack frame. */
1276 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1277 eassert (tlen > file_name_as_directory_slop + 1);
1278 #ifdef DOS_NT
1279 /* Reserve space for drive specifier and escape prefix, since either
1280 or both may need to be inserted. (The Microsoft x86 compiler
1281 produces incorrect code if the following two lines are combined.) */
1282 target = alloca (tlen + 4);
1283 target += 4;
1284 #else /* not DOS_NT */
1285 target = SAFE_ALLOCA (tlen);
1286 #endif /* not DOS_NT */
1287 *target = 0;
1288 nbytes = 0;
1290 if (newdir)
1292 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1294 #ifdef DOS_NT
1295 /* If newdir is effectively "C:/", then the drive letter will have
1296 been stripped and newdir will be "/". Concatenating with an
1297 absolute directory in nm produces "//", which will then be
1298 incorrectly treated as a network share. Ignore newdir in
1299 this case (keeping the drive letter). */
1300 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1301 && newdir[1] == '\0'))
1302 #endif
1304 memcpy (target, newdir, length);
1305 target[length] = 0;
1306 nbytes = length;
1309 else
1310 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1313 memcpy (target + nbytes, nm, nmlim - nm + 1);
1315 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1316 appear. */
1318 char *p = target;
1319 char *o = target;
1321 while (*p)
1323 if (!IS_DIRECTORY_SEP (*p))
1325 *o++ = *p++;
1327 else if (p[1] == '.'
1328 && (IS_DIRECTORY_SEP (p[2])
1329 || p[2] == 0))
1331 /* If "/." is the entire filename, keep the "/". Otherwise,
1332 just delete the whole "/.". */
1333 if (o == target && p[2] == '\0')
1334 *o++ = *p;
1335 p += 2;
1337 else if (p[1] == '.' && p[2] == '.'
1338 /* `/../' is the "superroot" on certain file systems.
1339 Turned off on DOS_NT systems because they have no
1340 "superroot" and because this causes us to produce
1341 file names like "d:/../foo" which fail file-related
1342 functions of the underlying OS. (To reproduce, try a
1343 long series of "../../" in default_directory, longer
1344 than the number of levels from the root.) */
1345 #ifndef DOS_NT
1346 && o != target
1347 #endif
1348 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1350 #ifdef WINDOWSNT
1351 char *prev_o = o;
1352 #endif
1353 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1354 continue;
1355 #ifdef WINDOWSNT
1356 /* Don't go below server level in UNC filenames. */
1357 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1358 && IS_DIRECTORY_SEP (*target))
1359 o = prev_o;
1360 else
1361 #endif
1362 /* Keep initial / only if this is the whole name. */
1363 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1364 ++o;
1365 p += 3;
1367 else if (IS_DIRECTORY_SEP (p[1])
1368 && (p != target || IS_DIRECTORY_SEP (p[2])))
1369 /* Collapse multiple "/", except leave leading "//" alone. */
1370 p++;
1371 else
1373 *o++ = *p++;
1377 #ifdef DOS_NT
1378 /* At last, set drive name. */
1379 #ifdef WINDOWSNT
1380 /* Except for network file name. */
1381 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1382 #endif /* WINDOWSNT */
1384 if (!drive) emacs_abort ();
1385 target -= 2;
1386 target[0] = DRIVE_LETTER (drive);
1387 target[1] = ':';
1389 /* Reinsert the escape prefix if required. */
1390 if (is_escaped)
1392 target -= 2;
1393 target[0] = '/';
1394 target[1] = ':';
1396 result = make_specified_string (target, -1, o - target, multibyte);
1397 dostounix_filename (SSDATA (result));
1398 #ifdef WINDOWSNT
1399 if (!NILP (Vw32_downcase_file_names))
1400 result = Fdowncase (result);
1401 #endif
1402 #else /* !DOS_NT */
1403 result = make_specified_string (target, -1, o - target, multibyte);
1404 #endif /* !DOS_NT */
1407 /* Again look to see if the file name has special constructs in it
1408 and perhaps call the corresponding file handler. This is needed
1409 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1410 the ".." component gives us "/user@host:/bar/../baz" which needs
1411 to be expanded again. */
1412 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1413 if (!NILP (handler))
1415 handled_name = call3 (handler, Qexpand_file_name,
1416 result, default_directory);
1417 if (! STRINGP (handled_name))
1418 error ("Invalid handler in `file-name-handler-alist'");
1419 result = handled_name;
1422 SAFE_FREE ();
1423 return result;
1426 #if 0
1427 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1428 This is the old version of expand-file-name, before it was thoroughly
1429 rewritten for Emacs 10.31. We leave this version here commented-out,
1430 because the code is very complex and likely to have subtle bugs. If
1431 bugs _are_ found, it might be of interest to look at the old code and
1432 see what did it do in the relevant situation.
1434 Don't remove this code: it's true that it will be accessible
1435 from the repository, but a few years from deletion, people will
1436 forget it is there. */
1438 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1439 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1440 "Convert FILENAME to absolute, and canonicalize it.\n\
1441 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1442 \(does not start with slash); if DEFAULT is nil or missing,\n\
1443 the current buffer's value of default-directory is used.\n\
1444 Filenames containing `.' or `..' as components are simplified;\n\
1445 initial `~/' expands to your home directory.\n\
1446 See also the function `substitute-in-file-name'.")
1447 (name, defalt)
1448 Lisp_Object name, defalt;
1450 unsigned char *nm;
1452 register unsigned char *newdir, *p, *o;
1453 ptrdiff_t tlen;
1454 unsigned char *target;
1455 struct passwd *pw;
1457 CHECK_STRING (name);
1458 nm = SDATA (name);
1460 /* If nm is absolute, flush ...// and detect /./ and /../.
1461 If no /./ or /../ we can return right away. */
1462 if (nm[0] == '/')
1464 bool lose = 0;
1465 p = nm;
1466 while (*p)
1468 if (p[0] == '/' && p[1] == '/')
1469 nm = p + 1;
1470 if (p[0] == '/' && p[1] == '~')
1471 nm = p + 1, lose = 1;
1472 if (p[0] == '/' && p[1] == '.'
1473 && (p[2] == '/' || p[2] == 0
1474 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1475 lose = 1;
1476 p++;
1478 if (!lose)
1480 if (nm == SDATA (name))
1481 return name;
1482 return build_string (nm);
1486 /* Now determine directory to start with and put it in NEWDIR. */
1488 newdir = 0;
1490 if (nm[0] == '~') /* prefix ~ */
1491 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1493 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1494 newdir = (unsigned char *) "";
1495 nm++;
1497 else /* ~user/filename */
1499 /* Get past ~ to user. */
1500 unsigned char *user = nm + 1;
1501 /* Find end of name. */
1502 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1503 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1504 /* Copy the user name into temp storage. */
1505 o = alloca (len + 1);
1506 memcpy (o, user, len);
1507 o[len] = 0;
1509 /* Look up the user name. */
1510 block_input ();
1511 pw = (struct passwd *) getpwnam (o + 1);
1512 unblock_input ();
1513 if (!pw)
1514 error ("\"%s\" isn't a registered user", o + 1);
1516 newdir = (unsigned char *) pw->pw_dir;
1518 /* Discard the user name from NM. */
1519 nm += len;
1522 if (nm[0] != '/' && !newdir)
1524 if (NILP (defalt))
1525 defalt = current_buffer->directory;
1526 CHECK_STRING (defalt);
1527 newdir = SDATA (defalt);
1530 /* Now concatenate the directory and name to new space in the stack frame. */
1532 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1533 target = alloca (tlen);
1534 *target = 0;
1536 if (newdir)
1538 if (nm[0] == 0 || nm[0] == '/')
1539 strcpy (target, newdir);
1540 else
1541 file_name_as_directory (target, newdir);
1544 strcat (target, nm);
1546 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1548 p = target;
1549 o = target;
1551 while (*p)
1553 if (*p != '/')
1555 *o++ = *p++;
1557 else if (!strncmp (p, "//", 2)
1560 o = target;
1561 p++;
1563 else if (p[0] == '/' && p[1] == '.'
1564 && (p[2] == '/' || p[2] == 0))
1565 p += 2;
1566 else if (!strncmp (p, "/..", 3)
1567 /* `/../' is the "superroot" on certain file systems. */
1568 && o != target
1569 && (p[3] == '/' || p[3] == 0))
1571 while (o != target && *--o != '/')
1573 if (o == target && *o == '/')
1574 ++o;
1575 p += 3;
1577 else
1579 *o++ = *p++;
1583 return make_string (target, o - target);
1585 #endif
1587 /* If /~ or // appears, discard everything through first slash. */
1588 static bool
1589 file_name_absolute_p (const char *filename)
1591 return
1592 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1593 #ifdef DOS_NT
1594 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1595 && IS_DIRECTORY_SEP (filename[2]))
1596 #endif
1600 static char *
1601 search_embedded_absfilename (char *nm, char *endp)
1603 char *p, *s;
1605 for (p = nm + 1; p < endp; p++)
1607 if (IS_DIRECTORY_SEP (p[-1])
1608 && file_name_absolute_p (p)
1609 #if defined (WINDOWSNT) || defined (CYGWIN)
1610 /* // at start of file name is meaningful in Apollo,
1611 WindowsNT and Cygwin systems. */
1612 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1613 #endif /* not (WINDOWSNT || CYGWIN) */
1616 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1617 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1619 USE_SAFE_ALLOCA;
1620 char *o = SAFE_ALLOCA (s - p + 1);
1621 struct passwd *pw;
1622 memcpy (o, p, s - p);
1623 o [s - p] = 0;
1625 /* If we have ~user and `user' exists, discard
1626 everything up to ~. But if `user' does not exist, leave
1627 ~user alone, it might be a literal file name. */
1628 block_input ();
1629 pw = getpwnam (o + 1);
1630 unblock_input ();
1631 SAFE_FREE ();
1632 if (pw)
1633 return p;
1635 else
1636 return p;
1639 return NULL;
1642 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1643 Ssubstitute_in_file_name, 1, 1, 0,
1644 doc: /* Substitute environment variables referred to in FILENAME.
1645 `$FOO' where FOO is an environment variable name means to substitute
1646 the value of that variable. The variable name should be terminated
1647 with a character not a letter, digit or underscore; otherwise, enclose
1648 the entire variable name in braces.
1650 If `/~' appears, all of FILENAME through that `/' is discarded.
1651 If `//' appears, everything up to and including the first of
1652 those `/' is discarded. */)
1653 (Lisp_Object filename)
1655 char *nm, *p, *x, *endp;
1656 bool substituted = false;
1657 bool multibyte;
1658 char *xnm;
1659 Lisp_Object handler;
1661 CHECK_STRING (filename);
1663 multibyte = STRING_MULTIBYTE (filename);
1665 /* If the file name has special constructs in it,
1666 call the corresponding file handler. */
1667 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1668 if (!NILP (handler))
1670 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1671 filename);
1672 if (STRINGP (handled_name))
1673 return handled_name;
1674 error ("Invalid handler in `file-name-handler-alist'");
1677 /* Always work on a copy of the string, in case GC happens during
1678 decode of environment variables, causing the original Lisp_String
1679 data to be relocated. */
1680 USE_SAFE_ALLOCA;
1681 SAFE_ALLOCA_STRING (nm, filename);
1683 #ifdef DOS_NT
1684 dostounix_filename (nm);
1685 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1686 #endif
1687 endp = nm + SBYTES (filename);
1689 /* If /~ or // appears, discard everything through first slash. */
1690 p = search_embedded_absfilename (nm, endp);
1691 if (p)
1692 /* Start over with the new string, so we check the file-name-handler
1693 again. Important with filenames like "/home/foo//:/hello///there"
1694 which would substitute to "/:/hello///there" rather than "/there". */
1696 Lisp_Object result
1697 = (Fsubstitute_in_file_name
1698 (make_specified_string (p, -1, endp - p, multibyte)));
1699 SAFE_FREE ();
1700 return result;
1703 /* See if any variables are substituted into the string. */
1705 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1707 Lisp_Object name
1708 = (!substituted ? filename
1709 : make_specified_string (nm, -1, endp - nm, multibyte));
1710 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1711 CHECK_STRING (tmp);
1712 if (!EQ (tmp, name))
1713 substituted = true;
1714 filename = tmp;
1717 if (!substituted)
1719 #ifdef WINDOWSNT
1720 if (!NILP (Vw32_downcase_file_names))
1721 filename = Fdowncase (filename);
1722 #endif
1723 SAFE_FREE ();
1724 return filename;
1727 xnm = SSDATA (filename);
1728 x = xnm + SBYTES (filename);
1730 /* If /~ or // appears, discard everything through first slash. */
1731 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1732 /* This time we do not start over because we've already expanded envvars
1733 and replaced $$ with $. Maybe we should start over as well, but we'd
1734 need to quote some $ to $$ first. */
1735 xnm = p;
1737 #ifdef WINDOWSNT
1738 if (!NILP (Vw32_downcase_file_names))
1740 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1742 filename = Fdowncase (xname);
1744 else
1745 #endif
1746 if (xnm != SSDATA (filename))
1747 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1748 SAFE_FREE ();
1749 return filename;
1752 /* A slightly faster and more convenient way to get
1753 (directory-file-name (expand-file-name FOO)). */
1755 Lisp_Object
1756 expand_and_dir_to_file (Lisp_Object filename)
1758 Lisp_Object absname = Fexpand_file_name (filename, Qnil);
1760 /* Remove final slash, if any (unless this is the root dir).
1761 stat behaves differently depending! */
1762 if (SCHARS (absname) > 1
1763 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1764 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1765 /* We cannot take shortcuts; they might be wrong for magic file names. */
1766 absname = Fdirectory_file_name (absname);
1767 return absname;
1770 /* Signal an error if the file ABSNAME already exists.
1771 If KNOWN_TO_EXIST, the file is known to exist.
1772 QUERYSTRING is a name for the action that is being considered
1773 to alter the file.
1774 If INTERACTIVE, ask the user whether to proceed,
1775 and bypass the error if the user says to go ahead.
1776 If QUICK, ask for y or n, not yes or no. */
1778 static void
1779 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1780 const char *querystring, bool interactive,
1781 bool quick)
1783 Lisp_Object tem, encoded_filename;
1784 struct stat statbuf;
1786 encoded_filename = ENCODE_FILE (absname);
1788 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1790 if (S_ISDIR (statbuf.st_mode))
1791 xsignal2 (Qfile_error,
1792 build_string ("File is a directory"), absname);
1793 known_to_exist = true;
1796 if (known_to_exist)
1798 if (! interactive)
1799 xsignal2 (Qfile_already_exists,
1800 build_string ("File already exists"), absname);
1801 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1802 tem = CALLN (Fformat, format, absname, build_string (querystring));
1803 if (quick)
1804 tem = call1 (intern ("y-or-n-p"), tem);
1805 else
1806 tem = do_yes_or_no_p (tem);
1807 if (NILP (tem))
1808 xsignal2 (Qfile_already_exists,
1809 build_string ("File already exists"), absname);
1813 #ifndef WINDOWSNT
1814 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1815 static bool
1816 clone_file (int dest, int source)
1818 #ifdef FICLONE
1819 return ioctl (dest, FICLONE, source) == 0;
1820 #endif
1821 return false;
1823 #endif
1825 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1826 "fCopy file: \nGCopy %s to file: \np\nP",
1827 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1828 If NEWNAME is a directory name, copy FILE to a like-named file under
1829 NEWNAME. For NEWNAME to be recognized as a directory name, it should
1830 end in a slash.
1832 This function always sets the file modes of the output file to match
1833 the input file.
1835 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1836 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1837 signal a `file-already-exists' error without overwriting. If
1838 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1839 about overwriting; this is what happens in interactive use with M-x.
1840 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1841 existing file.
1843 Fourth arg KEEP-TIME non-nil means give the output file the same
1844 last-modified time as the old one. (This works on only some systems.)
1846 A prefix arg makes KEEP-TIME non-nil.
1848 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1849 FILE to NEWNAME.
1851 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1852 this includes the file modes, along with ACL entries and SELinux
1853 context if present. Otherwise, if NEWNAME is created its file
1854 permission bits are those of FILE, masked by the default file
1855 permissions. */)
1856 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1857 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1858 Lisp_Object preserve_permissions)
1860 Lisp_Object handler;
1861 ptrdiff_t count = SPECPDL_INDEX ();
1862 Lisp_Object encoded_file, encoded_newname;
1863 #if HAVE_LIBSELINUX
1864 security_context_t con;
1865 int conlength = 0;
1866 #endif
1867 #ifdef WINDOWSNT
1868 int result;
1869 #else
1870 bool already_exists = false;
1871 mode_t new_mask;
1872 int ifd, ofd;
1873 struct stat st;
1874 #endif
1876 file = Fexpand_file_name (file, Qnil);
1877 newname = expand_cp_target (file, newname);
1879 /* If the input file name has special constructs in it,
1880 call the corresponding file handler. */
1881 handler = Ffind_file_name_handler (file, Qcopy_file);
1882 /* Likewise for output file name. */
1883 if (NILP (handler))
1884 handler = Ffind_file_name_handler (newname, Qcopy_file);
1885 if (!NILP (handler))
1886 return call7 (handler, Qcopy_file, file, newname,
1887 ok_if_already_exists, keep_time, preserve_uid_gid,
1888 preserve_permissions);
1890 encoded_file = ENCODE_FILE (file);
1891 encoded_newname = ENCODE_FILE (newname);
1893 #ifdef WINDOWSNT
1894 if (NILP (ok_if_already_exists)
1895 || INTEGERP (ok_if_already_exists))
1896 barf_or_query_if_file_exists (newname, false, "copy to it",
1897 INTEGERP (ok_if_already_exists), false);
1899 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1900 !NILP (keep_time), !NILP (preserve_uid_gid),
1901 !NILP (preserve_permissions));
1902 switch (result)
1904 case -1:
1905 report_file_error ("Copying file", list2 (file, newname));
1906 case -2:
1907 report_file_error ("Copying permissions from", file);
1908 case -3:
1909 xsignal2 (Qfile_date_error,
1910 build_string ("Resetting file times"), newname);
1911 case -4:
1912 report_file_error ("Copying permissions to", newname);
1914 #else /* not WINDOWSNT */
1915 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1917 if (ifd < 0)
1918 report_file_error ("Opening input file", file);
1920 record_unwind_protect_int (close_file_unwind, ifd);
1922 if (fstat (ifd, &st) != 0)
1923 report_file_error ("Input file status", file);
1925 if (!NILP (preserve_permissions))
1927 #if HAVE_LIBSELINUX
1928 if (is_selinux_enabled ())
1930 conlength = fgetfilecon (ifd, &con);
1931 if (conlength == -1)
1932 report_file_error ("Doing fgetfilecon", file);
1934 #endif
1937 /* We can copy only regular files. */
1938 if (!S_ISREG (st.st_mode))
1939 report_file_errno ("Non-regular file", file,
1940 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1942 #ifndef MSDOS
1943 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1944 #else
1945 new_mask = S_IREAD | S_IWRITE;
1946 #endif
1948 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1949 new_mask);
1950 if (ofd < 0 && errno == EEXIST)
1952 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1953 barf_or_query_if_file_exists (newname, true, "copy to it",
1954 INTEGERP (ok_if_already_exists), false);
1955 already_exists = true;
1956 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1958 if (ofd < 0)
1959 report_file_error ("Opening output file", newname);
1961 record_unwind_protect_int (close_file_unwind, ofd);
1963 off_t oldsize = 0, newsize;
1965 if (already_exists)
1967 struct stat out_st;
1968 if (fstat (ofd, &out_st) != 0)
1969 report_file_error ("Output file status", newname);
1970 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1971 report_file_errno ("Input and output files are the same",
1972 list2 (file, newname), 0);
1973 if (S_ISREG (out_st.st_mode))
1974 oldsize = out_st.st_size;
1977 maybe_quit ();
1979 if (clone_file (ofd, ifd))
1980 newsize = st.st_size;
1981 else
1983 char buf[MAX_ALLOCA];
1984 ptrdiff_t n;
1985 for (newsize = 0; 0 < (n = emacs_read_quit (ifd, buf, sizeof buf));
1986 newsize += n)
1987 if (emacs_write_quit (ofd, buf, n) != n)
1988 report_file_error ("Write error", newname);
1989 if (n < 0)
1990 report_file_error ("Read error", file);
1993 /* Truncate any existing output file after writing the data. This
1994 is more likely to work than truncation before writing, if the
1995 file system is out of space or the user is over disk quota. */
1996 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
1997 report_file_error ("Truncating output file", newname);
1999 #ifndef MSDOS
2000 /* Preserve the original file permissions, and if requested, also its
2001 owner and group. */
2003 mode_t preserved_permissions = st.st_mode & 07777;
2004 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2005 if (!NILP (preserve_uid_gid))
2007 /* Attempt to change owner and group. If that doesn't work
2008 attempt to change just the group, as that is sometimes allowed.
2009 Adjust the mode mask to eliminate setuid or setgid bits
2010 or group permissions bits that are inappropriate if the
2011 owner or group are wrong. */
2012 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2014 if (fchown (ofd, -1, st.st_gid) == 0)
2015 preserved_permissions &= ~04000;
2016 else
2018 preserved_permissions &= ~06000;
2020 /* Copy the other bits to the group bits, since the
2021 group is wrong. */
2022 preserved_permissions &= ~070;
2023 preserved_permissions |= (preserved_permissions & 7) << 3;
2024 default_permissions &= ~070;
2025 default_permissions |= (default_permissions & 7) << 3;
2030 switch (!NILP (preserve_permissions)
2031 ? qcopy_acl (SSDATA (encoded_file), ifd,
2032 SSDATA (encoded_newname), ofd,
2033 preserved_permissions)
2034 : (already_exists
2035 || (new_mask & ~realmask) == default_permissions)
2037 : fchmod (ofd, default_permissions))
2039 case -2: report_file_error ("Copying permissions from", file);
2040 case -1: report_file_error ("Copying permissions to", newname);
2043 #endif /* not MSDOS */
2045 #if HAVE_LIBSELINUX
2046 if (conlength > 0)
2048 /* Set the modified context back to the file. */
2049 bool fail = fsetfilecon (ofd, con) != 0;
2050 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
2051 if (fail && errno != ENOTSUP)
2052 report_file_error ("Doing fsetfilecon", newname);
2054 freecon (con);
2056 #endif
2058 if (!NILP (keep_time))
2060 struct timespec atime = get_stat_atime (&st);
2061 struct timespec mtime = get_stat_mtime (&st);
2062 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2063 xsignal2 (Qfile_date_error,
2064 build_string ("Cannot set file date"), newname);
2067 if (emacs_close (ofd) < 0)
2068 report_file_error ("Write error", newname);
2070 emacs_close (ifd);
2072 #ifdef MSDOS
2073 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2074 and if it can't, it tells so. Otherwise, under MSDOS we usually
2075 get only the READ bit, which will make the copied file read-only,
2076 so it's better not to chmod at all. */
2077 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2078 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2079 #endif /* MSDOS */
2080 #endif /* not WINDOWSNT */
2082 /* Discard the unwind protects. */
2083 specpdl_ptr = specpdl + count;
2085 return Qnil;
2088 DEFUN ("make-directory-internal", Fmake_directory_internal,
2089 Smake_directory_internal, 1, 1, 0,
2090 doc: /* Create a new directory named DIRECTORY. */)
2091 (Lisp_Object directory)
2093 const char *dir;
2094 Lisp_Object handler;
2095 Lisp_Object encoded_dir;
2097 CHECK_STRING (directory);
2098 directory = Fexpand_file_name (directory, Qnil);
2100 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2101 if (!NILP (handler))
2102 return call2 (handler, Qmake_directory_internal, directory);
2104 encoded_dir = ENCODE_FILE (directory);
2106 dir = SSDATA (encoded_dir);
2108 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2109 report_file_error ("Creating directory", directory);
2111 return Qnil;
2114 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2115 Sdelete_directory_internal, 1, 1, 0,
2116 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2117 (Lisp_Object directory)
2119 const char *dir;
2120 Lisp_Object encoded_dir;
2122 CHECK_STRING (directory);
2123 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2124 encoded_dir = ENCODE_FILE (directory);
2125 dir = SSDATA (encoded_dir);
2127 if (rmdir (dir) != 0)
2128 report_file_error ("Removing directory", directory);
2130 return Qnil;
2133 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2134 "(list (read-file-name \
2135 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2136 \"Move file to trash: \" \"Delete file: \") \
2137 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2138 (null current-prefix-arg))",
2139 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2140 If file has multiple names, it continues to exist with the other names.
2141 TRASH non-nil means to trash the file instead of deleting, provided
2142 `delete-by-moving-to-trash' is non-nil.
2144 When called interactively, TRASH is t if no prefix argument is given.
2145 With a prefix argument, TRASH is nil. */)
2146 (Lisp_Object filename, Lisp_Object trash)
2148 Lisp_Object handler;
2149 Lisp_Object encoded_file;
2151 if (!NILP (Ffile_directory_p (filename))
2152 && NILP (Ffile_symlink_p (filename)))
2153 xsignal2 (Qfile_error,
2154 build_string ("Removing old name: is a directory"),
2155 filename);
2156 filename = Fexpand_file_name (filename, Qnil);
2158 handler = Ffind_file_name_handler (filename, Qdelete_file);
2159 if (!NILP (handler))
2160 return call3 (handler, Qdelete_file, filename, trash);
2162 if (delete_by_moving_to_trash && !NILP (trash))
2163 return call1 (Qmove_file_to_trash, filename);
2165 encoded_file = ENCODE_FILE (filename);
2167 if (unlink (SSDATA (encoded_file)) != 0 && errno != ENOENT)
2168 report_file_error ("Removing old name", filename);
2169 return Qnil;
2172 static Lisp_Object
2173 internal_delete_file_1 (Lisp_Object ignore)
2175 return Qt;
2178 /* Delete file FILENAME, returning true if successful.
2179 This ignores `delete-by-moving-to-trash'. */
2181 bool
2182 internal_delete_file (Lisp_Object filename)
2184 Lisp_Object tem;
2186 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2187 Qt, internal_delete_file_1);
2188 return NILP (tem);
2191 /* Filesystems are case-sensitive on all supported systems except
2192 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2193 case-insensitive on the first two, but they may or may not be
2194 case-insensitive on Cygwin and OS X. The following function
2195 attempts to provide a runtime test on those two systems. If the
2196 test is not conclusive, we assume case-insensitivity on Cygwin and
2197 case-sensitivity on Mac OS X.
2199 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2200 NFS-mounted Windows volumes, might be case-insensitive. Can we
2201 detect this? */
2203 static bool
2204 file_name_case_insensitive_p (const char *filename)
2206 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2207 those flags are available. As of this writing (2017-05-20),
2208 Cygwin is the only platform known to support the former (starting
2209 with Cygwin-2.6.1), and macOS is the only platform known to
2210 support the latter. */
2212 #ifdef _PC_CASE_INSENSITIVE
2213 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2214 if (res >= 0)
2215 return res > 0;
2216 #elif defined _PC_CASE_SENSITIVE
2217 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2218 if (res >= 0)
2219 return res == 0;
2220 #endif
2222 #if defined CYGWIN || defined DOS_NT
2223 return true;
2224 #else
2225 return false;
2226 #endif
2229 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2230 Sfile_name_case_insensitive_p, 1, 1, 0,
2231 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2232 The arg must be a string. */)
2233 (Lisp_Object filename)
2235 Lisp_Object handler;
2237 CHECK_STRING (filename);
2238 filename = Fexpand_file_name (filename, Qnil);
2240 /* If the file name has special constructs in it,
2241 call the corresponding file handler. */
2242 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2243 if (!NILP (handler))
2244 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2246 filename = ENCODE_FILE (filename);
2247 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2250 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2251 "fRename file: \nGRename %s to file: \np",
2252 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2253 If file has names other than FILE, it continues to have those names.
2254 If NEWNAME is a directory name, rename FILE to a like-named file under
2255 NEWNAME. For NEWNAME to be recognized as a directory name, it should
2256 end in a slash.
2258 Signal a `file-already-exists' error if a file NEWNAME already exists
2259 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2260 An integer third arg means request confirmation if NEWNAME already exists.
2261 This is what happens in interactive use with M-x. */)
2262 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2264 Lisp_Object handler;
2265 Lisp_Object encoded_file, encoded_newname;
2267 file = Fexpand_file_name (file, Qnil);
2269 /* If the filesystem is case-insensitive and the file names are
2270 identical but for case, treat it as a change-case request, and do
2271 not worry whether NEWNAME exists or whether it is a directory, as
2272 it is already another name for FILE. */
2273 bool case_only_rename = false;
2274 #if defined CYGWIN || defined DOS_NT
2275 if (!NILP (Ffile_name_case_insensitive_p (file)))
2277 newname = Fexpand_file_name (newname, Qnil);
2278 case_only_rename = !NILP (Fstring_equal (Fdowncase (file),
2279 Fdowncase (newname)));
2281 #endif
2283 if (!case_only_rename)
2284 newname = expand_cp_target (Fdirectory_file_name (file), newname);
2286 /* If the file name has special constructs in it,
2287 call the corresponding file handler. */
2288 handler = Ffind_file_name_handler (file, Qrename_file);
2289 if (NILP (handler))
2290 handler = Ffind_file_name_handler (newname, Qrename_file);
2291 if (!NILP (handler))
2292 return call4 (handler, Qrename_file,
2293 file, newname, ok_if_already_exists);
2295 encoded_file = ENCODE_FILE (file);
2296 encoded_newname = ENCODE_FILE (newname);
2298 bool plain_rename = (case_only_rename
2299 || (!NILP (ok_if_already_exists)
2300 && !INTEGERP (ok_if_already_exists)));
2301 int rename_errno UNINIT;
2302 if (!plain_rename)
2304 if (renameat_noreplace (AT_FDCWD, SSDATA (encoded_file),
2305 AT_FDCWD, SSDATA (encoded_newname))
2306 == 0)
2307 return Qnil;
2309 rename_errno = errno;
2310 switch (rename_errno)
2312 case EEXIST: case EINVAL: case ENOSYS:
2313 #if ENOSYS != ENOTSUP
2314 case ENOTSUP:
2315 #endif
2316 barf_or_query_if_file_exists (newname, rename_errno == EEXIST,
2317 "rename to it",
2318 INTEGERP (ok_if_already_exists),
2319 false);
2320 plain_rename = true;
2321 break;
2325 if (plain_rename)
2327 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2328 return Qnil;
2329 rename_errno = errno;
2330 /* Don't prompt again. */
2331 ok_if_already_exists = Qt;
2333 else if (!NILP (ok_if_already_exists))
2334 ok_if_already_exists = Qt;
2336 if (rename_errno != EXDEV)
2337 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2339 struct stat file_st;
2340 bool dirp = !NILP (Fdirectory_name_p (file));
2341 if (!dirp)
2343 if (lstat (SSDATA (encoded_file), &file_st) != 0)
2344 report_file_error ("Renaming", list2 (file, newname));
2345 dirp = S_ISDIR (file_st.st_mode) != 0;
2347 if (dirp)
2348 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2349 else
2351 Lisp_Object symlink_target
2352 = (S_ISLNK (file_st.st_mode)
2353 ? emacs_readlinkat (AT_FDCWD, SSDATA (encoded_file))
2354 : Qnil);
2355 if (!NILP (symlink_target))
2356 Fmake_symbolic_link (symlink_target, newname, ok_if_already_exists);
2357 else
2358 Fcopy_file (file, newname, ok_if_already_exists, Qt, Qt, Qt);
2361 ptrdiff_t count = SPECPDL_INDEX ();
2362 specbind (Qdelete_by_moving_to_trash, Qnil);
2363 if (dirp)
2364 call2 (Qdelete_directory, file, Qt);
2365 else
2366 Fdelete_file (file, Qnil);
2367 return unbind_to (count, Qnil);
2370 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2371 "fAdd name to file: \nGName to add to %s: \np",
2372 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2373 If NEWNAME is a directory name, give FILE a like-named new name under
2374 NEWNAME.
2376 Signal a `file-already-exists' error if a file NEWNAME already exists
2377 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2378 An integer third arg means request confirmation if NEWNAME already exists.
2379 This is what happens in interactive use with M-x. */)
2380 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2382 Lisp_Object handler;
2383 Lisp_Object encoded_file, encoded_newname;
2385 file = Fexpand_file_name (file, Qnil);
2386 newname = expand_cp_target (file, newname);
2388 /* If the file name has special constructs in it,
2389 call the corresponding file handler. */
2390 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2391 if (!NILP (handler))
2392 return call4 (handler, Qadd_name_to_file, file,
2393 newname, ok_if_already_exists);
2395 /* If the new name has special constructs in it,
2396 call the corresponding file handler. */
2397 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2398 if (!NILP (handler))
2399 return call4 (handler, Qadd_name_to_file, file,
2400 newname, ok_if_already_exists);
2402 encoded_file = ENCODE_FILE (file);
2403 encoded_newname = ENCODE_FILE (newname);
2405 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2406 return Qnil;
2408 if (errno == EEXIST)
2410 if (NILP (ok_if_already_exists)
2411 || INTEGERP (ok_if_already_exists))
2412 barf_or_query_if_file_exists (newname, true, "make it a new name",
2413 INTEGERP (ok_if_already_exists), false);
2414 unlink (SSDATA (newname));
2415 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2416 return Qnil;
2419 report_file_error ("Adding new name", list2 (file, newname));
2422 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2423 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2424 doc: /* Make a symbolic link to TARGET, named NEWNAME.
2425 If NEWNAME is a directory name, make a like-named symbolic link under
2426 NEWNAME.
2428 Signal a `file-already-exists' error if a file NEWNAME already exists
2429 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2430 An integer third arg means request confirmation if NEWNAME already
2431 exists, and expand leading "~" or strip leading "/:" in TARGET.
2432 This happens for interactive use with M-x. */)
2433 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2435 Lisp_Object handler;
2436 Lisp_Object encoded_target, encoded_linkname;
2438 CHECK_STRING (target);
2439 if (INTEGERP (ok_if_already_exists))
2441 if (SREF (target, 0) == '~')
2442 target = Fexpand_file_name (target, Qnil);
2443 else if (SREF (target, 0) == '/' && SREF (target, 1) == ':')
2444 target = Fsubstring_no_properties (target, make_number (2), Qnil);
2446 linkname = expand_cp_target (target, linkname);
2448 /* If the new link name has special constructs in it,
2449 call the corresponding file handler. */
2450 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2451 if (!NILP (handler))
2452 return call4 (handler, Qmake_symbolic_link, target,
2453 linkname, ok_if_already_exists);
2455 encoded_target = ENCODE_FILE (target);
2456 encoded_linkname = ENCODE_FILE (linkname);
2458 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2459 return Qnil;
2461 if (errno == ENOSYS)
2462 xsignal1 (Qfile_error,
2463 build_string ("Symbolic links are not supported"));
2465 if (errno == EEXIST)
2467 if (NILP (ok_if_already_exists)
2468 || INTEGERP (ok_if_already_exists))
2469 barf_or_query_if_file_exists (linkname, true, "make it a link",
2470 INTEGERP (ok_if_already_exists), false);
2471 unlink (SSDATA (encoded_linkname));
2472 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2473 return Qnil;
2476 report_file_error ("Making symbolic link", list2 (target, linkname));
2480 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2481 1, 1, 0,
2482 doc: /* Return t if FILENAME is an absolute file name or starts with `~'.
2483 On Unix, absolute file names start with `/'. */)
2484 (Lisp_Object filename)
2486 CHECK_STRING (filename);
2487 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2490 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2491 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2492 See also `file-readable-p' and `file-attributes'.
2493 This returns nil for a symlink to a nonexistent file.
2494 Use `file-symlink-p' to test for such links. */)
2495 (Lisp_Object filename)
2497 Lisp_Object absname;
2498 Lisp_Object handler;
2500 CHECK_STRING (filename);
2501 absname = Fexpand_file_name (filename, Qnil);
2503 /* If the file name has special constructs in it,
2504 call the corresponding file handler. */
2505 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2506 if (!NILP (handler))
2508 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2509 errno = 0;
2510 return result;
2513 absname = ENCODE_FILE (absname);
2515 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2518 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2519 doc: /* Return t if FILENAME can be executed by you.
2520 For a directory, this means you can access files in that directory.
2521 \(It is generally better to use `file-accessible-directory-p' for that
2522 purpose, though.) */)
2523 (Lisp_Object filename)
2525 Lisp_Object absname;
2526 Lisp_Object handler;
2528 CHECK_STRING (filename);
2529 absname = Fexpand_file_name (filename, Qnil);
2531 /* If the file name has special constructs in it,
2532 call the corresponding file handler. */
2533 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2534 if (!NILP (handler))
2535 return call2 (handler, Qfile_executable_p, absname);
2537 absname = ENCODE_FILE (absname);
2539 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2542 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2543 doc: /* Return t if file FILENAME exists and you can read it.
2544 See also `file-exists-p' and `file-attributes'. */)
2545 (Lisp_Object filename)
2547 Lisp_Object absname;
2548 Lisp_Object handler;
2550 CHECK_STRING (filename);
2551 absname = Fexpand_file_name (filename, Qnil);
2553 /* If the file name has special constructs in it,
2554 call the corresponding file handler. */
2555 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2556 if (!NILP (handler))
2557 return call2 (handler, Qfile_readable_p, absname);
2559 absname = ENCODE_FILE (absname);
2560 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2561 ? Qt : Qnil);
2564 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2565 doc: /* Return t if file FILENAME can be written or created by you. */)
2566 (Lisp_Object filename)
2568 Lisp_Object absname, dir, encoded;
2569 Lisp_Object handler;
2571 CHECK_STRING (filename);
2572 absname = Fexpand_file_name (filename, Qnil);
2574 /* If the file name has special constructs in it,
2575 call the corresponding file handler. */
2576 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2577 if (!NILP (handler))
2578 return call2 (handler, Qfile_writable_p, absname);
2580 encoded = ENCODE_FILE (absname);
2581 if (check_writable (SSDATA (encoded), W_OK))
2582 return Qt;
2583 if (errno != ENOENT)
2584 return Qnil;
2586 dir = Ffile_name_directory (absname);
2587 eassert (!NILP (dir));
2588 #ifdef MSDOS
2589 dir = Fdirectory_file_name (dir);
2590 #endif /* MSDOS */
2592 dir = ENCODE_FILE (dir);
2593 #ifdef WINDOWSNT
2594 /* The read-only attribute of the parent directory doesn't affect
2595 whether a file or directory can be created within it. Some day we
2596 should check ACLs though, which do affect this. */
2597 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2598 #else
2599 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2600 #endif
2603 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2604 doc: /* Access file FILENAME, and get an error if that does not work.
2605 The second argument STRING is prepended to the error message.
2606 If there is no error, returns nil. */)
2607 (Lisp_Object filename, Lisp_Object string)
2609 Lisp_Object handler, encoded_filename, absname;
2611 CHECK_STRING (filename);
2612 absname = Fexpand_file_name (filename, Qnil);
2614 CHECK_STRING (string);
2616 /* If the file name has special constructs in it,
2617 call the corresponding file handler. */
2618 handler = Ffind_file_name_handler (absname, Qaccess_file);
2619 if (!NILP (handler))
2620 return call3 (handler, Qaccess_file, absname, string);
2622 encoded_filename = ENCODE_FILE (absname);
2624 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2625 report_file_error (SSDATA (string), filename);
2627 return Qnil;
2630 /* Relative to directory FD, return the symbolic link value of FILENAME.
2631 On failure, return nil. */
2632 Lisp_Object
2633 emacs_readlinkat (int fd, char const *filename)
2635 static struct allocator const emacs_norealloc_allocator =
2636 { xmalloc, NULL, xfree, memory_full };
2637 Lisp_Object val;
2638 char readlink_buf[1024];
2639 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2640 &emacs_norealloc_allocator, readlinkat);
2641 if (!buf)
2642 return Qnil;
2644 val = build_unibyte_string (buf);
2645 if (buf != readlink_buf)
2646 xfree (buf);
2647 val = DECODE_FILE (val);
2648 return val;
2651 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2652 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2653 The value is the link target, as a string.
2654 Otherwise it returns nil.
2656 This function does not check whether the link target exists. */)
2657 (Lisp_Object filename)
2659 Lisp_Object handler;
2661 CHECK_STRING (filename);
2662 filename = Fexpand_file_name (filename, Qnil);
2664 /* If the file name has special constructs in it,
2665 call the corresponding file handler. */
2666 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2667 if (!NILP (handler))
2668 return call2 (handler, Qfile_symlink_p, filename);
2670 filename = ENCODE_FILE (filename);
2672 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2675 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2676 doc: /* Return t if FILENAME names an existing directory.
2677 Symbolic links to directories count as directories.
2678 See `file-symlink-p' to distinguish symlinks. */)
2679 (Lisp_Object filename)
2681 Lisp_Object absname = expand_and_dir_to_file (filename);
2683 /* If the file name has special constructs in it,
2684 call the corresponding file handler. */
2685 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2686 if (!NILP (handler))
2687 return call2 (handler, Qfile_directory_p, absname);
2689 absname = ENCODE_FILE (absname);
2691 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2694 /* Return true if FILE is a directory or a symlink to a directory. */
2695 bool
2696 file_directory_p (char const *file)
2698 #ifdef WINDOWSNT
2699 /* This is cheaper than 'stat'. */
2700 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2701 #else
2702 struct stat st;
2703 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2704 #endif
2707 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2708 Sfile_accessible_directory_p, 1, 1, 0,
2709 doc: /* Return t if FILENAME names a directory you can open.
2710 For the value to be t, FILENAME must specify the name of a directory
2711 as a file, and the directory must allow you to open files in it. In
2712 order to use a directory as a buffer's current directory, this
2713 predicate must return true. A directory name spec may be given
2714 instead; then the value is t if the directory so specified exists and
2715 really is a readable and searchable directory. */)
2716 (Lisp_Object filename)
2718 Lisp_Object absname;
2719 Lisp_Object handler;
2721 CHECK_STRING (filename);
2722 absname = Fexpand_file_name (filename, Qnil);
2724 /* If the file name has special constructs in it,
2725 call the corresponding file handler. */
2726 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2727 if (!NILP (handler))
2729 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2731 /* Set errno in case the handler failed. EACCES might be a lie
2732 (e.g., the directory might not exist, or be a regular file),
2733 but at least it does TRT in the "usual" case of an existing
2734 directory that is not accessible by the current user, and
2735 avoids reporting "Success" for a failed operation. Perhaps
2736 someday we can fix this in a better way, by improving
2737 file-accessible-directory-p's API; see Bug#25419. */
2738 if (!EQ (r, Qt))
2739 errno = EACCES;
2741 return r;
2744 absname = ENCODE_FILE (absname);
2745 return file_accessible_directory_p (absname) ? Qt : Qnil;
2748 /* If FILE is a searchable directory or a symlink to a
2749 searchable directory, return true. Otherwise return
2750 false and set errno to an error number. */
2751 bool
2752 file_accessible_directory_p (Lisp_Object file)
2754 #ifdef DOS_NT
2755 # ifdef WINDOWSNT
2756 /* We need a special-purpose test because (a) NTFS security data is
2757 not reflected in Posix-style mode bits, and (b) the trick with
2758 accessing "DIR/.", used below on Posix hosts, doesn't work on
2759 Windows, because "DIR/." is normalized to just "DIR" before
2760 hitting the disk. */
2761 return (SBYTES (file) == 0
2762 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2763 # else /* MSDOS */
2764 return file_directory_p (SSDATA (file));
2765 # endif /* MSDOS */
2766 #else /* !DOS_NT */
2767 /* On POSIXish platforms, use just one system call; this avoids a
2768 race and is typically faster. */
2769 const char *data = SSDATA (file);
2770 ptrdiff_t len = SBYTES (file);
2771 char const *dir;
2772 bool ok;
2773 int saved_errno;
2774 USE_SAFE_ALLOCA;
2776 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2777 There are three exceptions: "", "/", and "//". Leave "" alone,
2778 as it's invalid. Append only "." to the other two exceptions as
2779 "/" and "//" are distinct on some platforms, whereas "/", "///",
2780 "////", etc. are all equivalent. */
2781 if (! len)
2782 dir = data;
2783 else
2785 /* Just check for trailing '/' when deciding whether to append '/'.
2786 That's simpler than testing the two special cases "/" and "//",
2787 and it's a safe optimization here. */
2788 char *buf = SAFE_ALLOCA (len + 3);
2789 memcpy (buf, data, len);
2790 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2791 dir = buf;
2794 ok = check_existing (dir);
2795 saved_errno = errno;
2796 SAFE_FREE ();
2797 errno = saved_errno;
2798 return ok;
2799 #endif /* !DOS_NT */
2802 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2803 doc: /* Return t if FILENAME names a regular file.
2804 This is the sort of file that holds an ordinary stream of data bytes.
2805 Symbolic links to regular files count as regular files.
2806 See `file-symlink-p' to distinguish symlinks. */)
2807 (Lisp_Object filename)
2809 struct stat st;
2810 Lisp_Object absname = expand_and_dir_to_file (filename);
2812 /* If the file name has special constructs in it,
2813 call the corresponding file handler. */
2814 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2815 if (!NILP (handler))
2816 return call2 (handler, Qfile_regular_p, absname);
2818 absname = ENCODE_FILE (absname);
2820 #ifdef WINDOWSNT
2822 int result;
2823 Lisp_Object tem = Vw32_get_true_file_attributes;
2825 /* Tell stat to use expensive method to get accurate info. */
2826 Vw32_get_true_file_attributes = Qt;
2827 result = stat (SSDATA (absname), &st);
2828 Vw32_get_true_file_attributes = tem;
2830 if (result < 0)
2831 return Qnil;
2832 return S_ISREG (st.st_mode) ? Qt : Qnil;
2834 #else
2835 if (stat (SSDATA (absname), &st) < 0)
2836 return Qnil;
2837 return S_ISREG (st.st_mode) ? Qt : Qnil;
2838 #endif
2841 DEFUN ("file-selinux-context", Ffile_selinux_context,
2842 Sfile_selinux_context, 1, 1, 0,
2843 doc: /* Return SELinux context of file named FILENAME.
2844 The return value is a list (USER ROLE TYPE RANGE), where the list
2845 elements are strings naming the user, role, type, and range of the
2846 file's SELinux security context.
2848 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2849 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2850 (Lisp_Object filename)
2852 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2853 Lisp_Object absname = expand_and_dir_to_file (filename);
2855 /* If the file name has special constructs in it,
2856 call the corresponding file handler. */
2857 Lisp_Object handler = Ffind_file_name_handler (absname,
2858 Qfile_selinux_context);
2859 if (!NILP (handler))
2860 return call2 (handler, Qfile_selinux_context, absname);
2862 absname = ENCODE_FILE (absname);
2864 #if HAVE_LIBSELINUX
2865 if (is_selinux_enabled ())
2867 security_context_t con;
2868 int conlength = lgetfilecon (SSDATA (absname), &con);
2869 if (conlength > 0)
2871 context_t context = context_new (con);
2872 if (context_user_get (context))
2873 user = build_string (context_user_get (context));
2874 if (context_role_get (context))
2875 role = build_string (context_role_get (context));
2876 if (context_type_get (context))
2877 type = build_string (context_type_get (context));
2878 if (context_range_get (context))
2879 range = build_string (context_range_get (context));
2880 context_free (context);
2881 freecon (con);
2884 #endif
2886 return list4 (user, role, type, range);
2889 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2890 Sset_file_selinux_context, 2, 2, 0,
2891 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2892 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2893 elements are strings naming the components of a SELinux context.
2895 Value is t if setting of SELinux context was successful, nil otherwise.
2897 This function does nothing and returns nil if SELinux is disabled,
2898 or if Emacs was not compiled with SELinux support. */)
2899 (Lisp_Object filename, Lisp_Object context)
2901 Lisp_Object absname;
2902 Lisp_Object handler;
2903 #if HAVE_LIBSELINUX
2904 Lisp_Object encoded_absname;
2905 Lisp_Object user = CAR_SAFE (context);
2906 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2907 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2908 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2909 security_context_t con;
2910 bool fail;
2911 int conlength;
2912 context_t parsed_con;
2913 #endif
2915 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2917 /* If the file name has special constructs in it,
2918 call the corresponding file handler. */
2919 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2920 if (!NILP (handler))
2921 return call3 (handler, Qset_file_selinux_context, absname, context);
2923 #if HAVE_LIBSELINUX
2924 if (is_selinux_enabled ())
2926 /* Get current file context. */
2927 encoded_absname = ENCODE_FILE (absname);
2928 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2929 if (conlength > 0)
2931 parsed_con = context_new (con);
2932 /* Change the parts defined in the parameter.*/
2933 if (STRINGP (user))
2935 if (context_user_set (parsed_con, SSDATA (user)))
2936 error ("Doing context_user_set");
2938 if (STRINGP (role))
2940 if (context_role_set (parsed_con, SSDATA (role)))
2941 error ("Doing context_role_set");
2943 if (STRINGP (type))
2945 if (context_type_set (parsed_con, SSDATA (type)))
2946 error ("Doing context_type_set");
2948 if (STRINGP (range))
2950 if (context_range_set (parsed_con, SSDATA (range)))
2951 error ("Doing context_range_set");
2954 /* Set the modified context back to the file. */
2955 fail = (lsetfilecon (SSDATA (encoded_absname),
2956 context_str (parsed_con))
2957 != 0);
2958 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
2959 if (fail && errno != ENOTSUP)
2960 report_file_error ("Doing lsetfilecon", absname);
2962 context_free (parsed_con);
2963 freecon (con);
2964 return fail ? Qnil : Qt;
2966 else
2967 report_file_error ("Doing lgetfilecon", absname);
2969 #endif
2971 return Qnil;
2974 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2975 doc: /* Return ACL entries of file named FILENAME.
2976 The entries are returned in a format suitable for use in `set-file-acl'
2977 but is otherwise undocumented and subject to change.
2978 Return nil if file does not exist or is not accessible, or if Emacs
2979 was unable to determine the ACL entries. */)
2980 (Lisp_Object filename)
2982 Lisp_Object acl_string = Qnil;
2984 #if USE_ACL
2985 Lisp_Object absname = expand_and_dir_to_file (filename);
2987 /* If the file name has special constructs in it,
2988 call the corresponding file handler. */
2989 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_acl);
2990 if (!NILP (handler))
2991 return call2 (handler, Qfile_acl, absname);
2993 # ifdef HAVE_ACL_SET_FILE
2994 absname = ENCODE_FILE (absname);
2996 # ifndef HAVE_ACL_TYPE_EXTENDED
2997 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2998 # endif
2999 acl_t acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3000 if (acl == NULL)
3001 return Qnil;
3003 char *str = acl_to_text (acl, NULL);
3004 if (str == NULL)
3006 acl_free (acl);
3007 return Qnil;
3010 acl_string = build_string (str);
3011 acl_free (str);
3012 acl_free (acl);
3013 # endif
3014 #endif
3016 return acl_string;
3019 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3020 2, 2, 0,
3021 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3022 ACL-STRING should contain the textual representation of the ACL
3023 entries in a format suitable for the platform.
3025 Value is t if setting of ACL was successful, nil otherwise.
3027 Setting ACL for local files requires Emacs to be built with ACL
3028 support. */)
3029 (Lisp_Object filename, Lisp_Object acl_string)
3031 #if USE_ACL
3032 Lisp_Object absname;
3033 Lisp_Object handler;
3034 # ifdef HAVE_ACL_SET_FILE
3035 Lisp_Object encoded_absname;
3036 acl_t acl;
3037 bool fail;
3038 # endif
3040 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3042 /* If the file name has special constructs in it,
3043 call the corresponding file handler. */
3044 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3045 if (!NILP (handler))
3046 return call3 (handler, Qset_file_acl, absname, acl_string);
3048 # ifdef HAVE_ACL_SET_FILE
3049 if (STRINGP (acl_string))
3051 acl = acl_from_text (SSDATA (acl_string));
3052 if (acl == NULL)
3054 if (acl_errno_valid (errno))
3055 report_file_error ("Converting ACL", absname);
3056 return Qnil;
3059 encoded_absname = ENCODE_FILE (absname);
3061 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3062 acl)
3063 != 0);
3064 if (fail && acl_errno_valid (errno))
3065 report_file_error ("Setting ACL", absname);
3067 acl_free (acl);
3068 return fail ? Qnil : Qt;
3070 # endif
3071 #endif
3073 return Qnil;
3076 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3077 doc: /* Return mode bits of file named FILENAME, as an integer.
3078 Return nil, if file does not exist or is not accessible. */)
3079 (Lisp_Object filename)
3081 struct stat st;
3082 Lisp_Object absname = expand_and_dir_to_file (filename);
3084 /* If the file name has special constructs in it,
3085 call the corresponding file handler. */
3086 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_modes);
3087 if (!NILP (handler))
3088 return call2 (handler, Qfile_modes, absname);
3090 absname = ENCODE_FILE (absname);
3092 if (stat (SSDATA (absname), &st) < 0)
3093 return Qnil;
3095 return make_number (st.st_mode & 07777);
3098 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3099 "(let ((file (read-file-name \"File: \"))) \
3100 (list file (read-file-modes nil file)))",
3101 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3102 Only the 12 low bits of MODE are used.
3104 Interactively, mode bits are read by `read-file-modes', which accepts
3105 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3106 (Lisp_Object filename, Lisp_Object mode)
3108 Lisp_Object absname, encoded_absname;
3109 Lisp_Object handler;
3111 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3112 CHECK_NUMBER (mode);
3114 /* If the file name has special constructs in it,
3115 call the corresponding file handler. */
3116 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3117 if (!NILP (handler))
3118 return call3 (handler, Qset_file_modes, absname, mode);
3120 encoded_absname = ENCODE_FILE (absname);
3122 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3123 report_file_error ("Doing chmod", absname);
3125 return Qnil;
3128 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3129 doc: /* Set the file permission bits for newly created files.
3130 The argument MODE should be an integer; only the low 9 bits are used.
3131 On Posix hosts, this setting is inherited by subprocesses.
3133 This function works by setting the Emacs's file mode creation mask.
3134 Each bit that is set in the mask means that the corresponding bit
3135 in the permissions of newly created files will be disabled.
3137 Note that when `write-region' creates a file, it resets the
3138 execute bit, even if the mask set by this function allows that bit
3139 by having the corresponding bit in the mask reset. */)
3140 (Lisp_Object mode)
3142 mode_t oldrealmask, oldumask, newumask;
3143 CHECK_NUMBER (mode);
3144 oldrealmask = realmask;
3145 newumask = ~ XINT (mode) & 0777;
3147 block_input ();
3148 realmask = newumask;
3149 oldumask = umask (newumask);
3150 unblock_input ();
3152 eassert (oldumask == oldrealmask);
3153 return Qnil;
3156 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3157 doc: /* Return the default file protection for created files.
3158 The value is an integer. */)
3159 (void)
3161 Lisp_Object value;
3162 XSETINT (value, (~ realmask) & 0777);
3163 return value;
3167 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3168 doc: /* Set times of file FILENAME to TIMESTAMP.
3169 Set both access and modification times.
3170 Return t on success, else nil.
3171 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3172 `current-time'. */)
3173 (Lisp_Object filename, Lisp_Object timestamp)
3175 Lisp_Object absname, encoded_absname;
3176 Lisp_Object handler;
3177 struct timespec t = lisp_time_argument (timestamp);
3179 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3181 /* If the file name has special constructs in it,
3182 call the corresponding file handler. */
3183 handler = Ffind_file_name_handler (absname, Qset_file_times);
3184 if (!NILP (handler))
3185 return call3 (handler, Qset_file_times, absname, timestamp);
3187 encoded_absname = ENCODE_FILE (absname);
3190 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3192 #ifdef MSDOS
3193 /* Setting times on a directory always fails. */
3194 if (file_directory_p (SSDATA (encoded_absname)))
3195 return Qnil;
3196 #endif
3197 report_file_error ("Setting file times", absname);
3201 return Qt;
3204 #ifdef HAVE_SYNC
3205 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3206 doc: /* Tell Unix to finish all pending disk updates. */)
3207 (void)
3209 sync ();
3210 return Qnil;
3213 #endif /* HAVE_SYNC */
3215 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3216 doc: /* Return t if file FILE1 is newer than file FILE2.
3217 If FILE1 does not exist, the answer is nil;
3218 otherwise, if FILE2 does not exist, the answer is t. */)
3219 (Lisp_Object file1, Lisp_Object file2)
3221 struct stat st1, st2;
3223 CHECK_STRING (file1);
3224 CHECK_STRING (file2);
3226 Lisp_Object absname1 = expand_and_dir_to_file (file1);
3227 Lisp_Object absname2 = expand_and_dir_to_file (file2);
3229 /* If the file name has special constructs in it,
3230 call the corresponding file handler. */
3231 Lisp_Object handler = Ffind_file_name_handler (absname1,
3232 Qfile_newer_than_file_p);
3233 if (NILP (handler))
3234 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3235 if (!NILP (handler))
3236 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3238 absname1 = ENCODE_FILE (absname1);
3239 absname2 = ENCODE_FILE (absname2);
3241 if (stat (SSDATA (absname1), &st1) < 0)
3242 return Qnil;
3244 if (stat (SSDATA (absname2), &st2) < 0)
3245 return Qt;
3247 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3248 ? Qt : Qnil);
3251 enum { READ_BUF_SIZE = MAX_ALLOCA };
3253 /* This function is called after Lisp functions to decide a coding
3254 system are called, or when they cause an error. Before they are
3255 called, the current buffer is set unibyte and it contains only a
3256 newly inserted text (thus the buffer was empty before the
3257 insertion).
3259 The functions may set markers, overlays, text properties, or even
3260 alter the buffer contents, change the current buffer.
3262 Here, we reset all those changes by:
3263 o set back the current buffer.
3264 o move all markers and overlays to BEG.
3265 o remove all text properties.
3266 o set back the buffer multibyteness. */
3268 static void
3269 decide_coding_unwind (Lisp_Object unwind_data)
3271 Lisp_Object multibyte, undo_list, buffer;
3273 multibyte = XCAR (unwind_data);
3274 unwind_data = XCDR (unwind_data);
3275 undo_list = XCAR (unwind_data);
3276 buffer = XCDR (unwind_data);
3278 set_buffer_internal (XBUFFER (buffer));
3279 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3280 adjust_overlays_for_delete (BEG, Z - BEG);
3281 set_buffer_intervals (current_buffer, NULL);
3282 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3284 /* Now we are safe to change the buffer's multibyteness directly. */
3285 bset_enable_multibyte_characters (current_buffer, multibyte);
3286 bset_undo_list (current_buffer, undo_list);
3289 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3290 object where slot 0 is the file descriptor, slot 1 specifies
3291 an offset to put the read bytes, and slot 2 is the maximum
3292 amount of bytes to read. Value is the number of bytes read. */
3294 static Lisp_Object
3295 read_non_regular (Lisp_Object state)
3297 int nbytes = emacs_read_quit (XSAVE_INTEGER (state, 0),
3298 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3299 + XSAVE_INTEGER (state, 1)),
3300 XSAVE_INTEGER (state, 2));
3301 /* Fast recycle this object for the likely next call. */
3302 free_misc (state);
3303 return make_number (nbytes);
3307 /* Condition-case handler used when reading from non-regular files
3308 in insert-file-contents. */
3310 static Lisp_Object
3311 read_non_regular_quit (Lisp_Object ignore)
3313 return Qnil;
3316 /* Return the file offset that VAL represents, checking for type
3317 errors and overflow. */
3318 static off_t
3319 file_offset (Lisp_Object val)
3321 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3322 return XINT (val);
3324 if (FLOATP (val))
3326 double v = XFLOAT_DATA (val);
3327 if (0 <= v && v < 1.0 + TYPE_MAXIMUM (off_t))
3329 off_t o = v;
3330 if (o == v)
3331 return o;
3335 wrong_type_argument (intern ("file-offset"), val);
3338 /* Return a special time value indicating the error number ERRNUM. */
3339 static struct timespec
3340 time_error_value (int errnum)
3342 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3343 ? NONEXISTENT_MODTIME_NSECS
3344 : UNKNOWN_MODTIME_NSECS);
3345 return make_timespec (0, ns);
3348 static Lisp_Object
3349 get_window_points_and_markers (void)
3351 Lisp_Object pt_marker = Fpoint_marker ();
3352 Lisp_Object windows
3353 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3354 Lisp_Object window_markers = windows;
3355 /* Window markers (and point) are handled specially: rather than move to
3356 just before or just after the modified text, we try to keep the
3357 markers at the same distance (bug#19161).
3358 In general, this is wrong, but for window-markers, this should be harmless
3359 and is convenient for the end user when most of the file is unmodified,
3360 except for a few minor details near the beginning and near the end. */
3361 for (; CONSP (windows); windows = XCDR (windows))
3362 if (WINDOWP (XCAR (windows)))
3364 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3365 XSETCAR (windows,
3366 Fcons (window_marker, Fmarker_position (window_marker)));
3368 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3371 static void
3372 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3373 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3375 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3376 if (CONSP (XCAR (window_markers)))
3378 Lisp_Object car = XCAR (window_markers);
3379 Lisp_Object marker = XCAR (car);
3380 Lisp_Object oldpos = XCDR (car);
3381 if (MARKERP (marker) && INTEGERP (oldpos)
3382 && XINT (oldpos) > same_at_start
3383 && XINT (oldpos) < same_at_end)
3385 ptrdiff_t oldsize = same_at_end - same_at_start;
3386 ptrdiff_t newsize = inserted;
3387 double growth = newsize / (double)oldsize;
3388 ptrdiff_t newpos
3389 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3390 Fset_marker (marker, make_number (newpos), Qnil);
3395 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3396 text as a linear C char array. */
3397 static void
3398 maybe_move_gap (struct buffer *b)
3400 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3402 struct buffer *cb = current_buffer;
3404 set_buffer_internal (b);
3405 move_gap_both (Z, Z_BYTE);
3406 set_buffer_internal (cb);
3410 /* FIXME: insert-file-contents should be split with the top-level moved to
3411 Elisp and only the core kept in C. */
3413 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3414 1, 5, 0,
3415 doc: /* Insert contents of file FILENAME after point.
3416 Returns list of absolute file name and number of characters inserted.
3417 If second argument VISIT is non-nil, the buffer's visited filename and
3418 last save file modtime are set, and it is marked unmodified. If
3419 visiting and the file does not exist, visiting is completed before the
3420 error is signaled.
3422 The optional third and fourth arguments BEG and END specify what portion
3423 of the file to insert. These arguments count bytes in the file, not
3424 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3426 If optional fifth argument REPLACE is non-nil, replace the current
3427 buffer contents (in the accessible portion) with the file contents.
3428 This is better than simply deleting and inserting the whole thing
3429 because (1) it preserves some marker positions and (2) it puts less data
3430 in the undo list. When REPLACE is non-nil, the second return value is
3431 the number of characters that replace previous buffer contents.
3433 This function does code conversion according to the value of
3434 `coding-system-for-read' or `file-coding-system-alist', and sets the
3435 variable `last-coding-system-used' to the coding system actually used.
3437 In addition, this function decodes the inserted text from known formats
3438 by calling `format-decode', which see. */)
3439 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3441 struct stat st;
3442 struct timespec mtime;
3443 int fd;
3444 ptrdiff_t inserted = 0;
3445 ptrdiff_t how_much;
3446 off_t beg_offset, end_offset;
3447 int unprocessed;
3448 ptrdiff_t count = SPECPDL_INDEX ();
3449 Lisp_Object handler, val, insval, orig_filename, old_undo;
3450 Lisp_Object p;
3451 ptrdiff_t total = 0;
3452 bool not_regular = 0;
3453 int save_errno = 0;
3454 char read_buf[READ_BUF_SIZE];
3455 struct coding_system coding;
3456 bool replace_handled = false;
3457 bool set_coding_system = false;
3458 Lisp_Object coding_system;
3459 bool read_quit = false;
3460 /* If the undo log only contains the insertion, there's no point
3461 keeping it. It's typically when we first fill a file-buffer. */
3462 bool empty_undo_list_p
3463 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3464 && BEG == Z);
3465 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3466 bool we_locked_file = false;
3467 ptrdiff_t fd_index;
3468 Lisp_Object window_markers = Qnil;
3469 /* same_at_start and same_at_end count bytes, because file access counts
3470 bytes and BEG and END count bytes. */
3471 ptrdiff_t same_at_start = BEGV_BYTE;
3472 ptrdiff_t same_at_end = ZV_BYTE;
3473 /* SAME_AT_END_CHARPOS counts characters, because
3474 restore_window_points needs the old character count. */
3475 ptrdiff_t same_at_end_charpos = ZV;
3477 if (current_buffer->base_buffer && ! NILP (visit))
3478 error ("Cannot do file visiting in an indirect buffer");
3480 if (!NILP (BVAR (current_buffer, read_only)))
3481 Fbarf_if_buffer_read_only (Qnil);
3483 val = Qnil;
3484 p = Qnil;
3485 orig_filename = Qnil;
3486 old_undo = Qnil;
3488 CHECK_STRING (filename);
3489 filename = Fexpand_file_name (filename, Qnil);
3491 /* The value Qnil means that the coding system is not yet
3492 decided. */
3493 coding_system = Qnil;
3495 /* If the file name has special constructs in it,
3496 call the corresponding file handler. */
3497 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3498 if (!NILP (handler))
3500 val = call6 (handler, Qinsert_file_contents, filename,
3501 visit, beg, end, replace);
3502 if (CONSP (val) && CONSP (XCDR (val))
3503 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3504 inserted = XINT (XCAR (XCDR (val)));
3505 goto handled;
3508 orig_filename = filename;
3509 filename = ENCODE_FILE (filename);
3511 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3512 if (fd < 0)
3514 save_errno = errno;
3515 if (NILP (visit))
3516 report_file_error ("Opening input file", orig_filename);
3517 mtime = time_error_value (save_errno);
3518 st.st_size = -1;
3519 if (!NILP (Vcoding_system_for_read))
3521 /* Don't let invalid values into buffer-file-coding-system. */
3522 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3523 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3525 goto notfound;
3528 fd_index = SPECPDL_INDEX ();
3529 record_unwind_protect_int (close_file_unwind, fd);
3531 /* Replacement should preserve point as it preserves markers. */
3532 if (!NILP (replace))
3534 window_markers = get_window_points_and_markers ();
3535 record_unwind_protect (restore_point_unwind,
3536 XCAR (XCAR (window_markers)));
3539 if (fstat (fd, &st) != 0)
3540 report_file_error ("Input file status", orig_filename);
3541 mtime = get_stat_mtime (&st);
3543 /* This code will need to be changed in order to work on named
3544 pipes, and it's probably just not worth it. So we should at
3545 least signal an error. */
3546 if (!S_ISREG (st.st_mode))
3548 not_regular = 1;
3550 if (! NILP (visit))
3551 goto notfound;
3553 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3554 xsignal2 (Qfile_error,
3555 build_string ("not a regular file"), orig_filename);
3558 if (!NILP (visit))
3560 if (!NILP (beg) || !NILP (end))
3561 error ("Attempt to visit less than an entire file");
3562 if (BEG < Z && NILP (replace))
3563 error ("Cannot do file visiting in a non-empty buffer");
3566 if (!NILP (beg))
3567 beg_offset = file_offset (beg);
3568 else
3569 beg_offset = 0;
3571 if (!NILP (end))
3572 end_offset = file_offset (end);
3573 else
3575 if (not_regular)
3576 end_offset = TYPE_MAXIMUM (off_t);
3577 else
3579 end_offset = st.st_size;
3581 /* A negative size can happen on a platform that allows file
3582 sizes greater than the maximum off_t value. */
3583 if (end_offset < 0)
3584 buffer_overflow ();
3586 /* The file size returned from stat may be zero, but data
3587 may be readable nonetheless, for example when this is a
3588 file in the /proc filesystem. */
3589 if (end_offset == 0)
3590 end_offset = READ_BUF_SIZE;
3594 /* Check now whether the buffer will become too large,
3595 in the likely case where the file's length is not changing.
3596 This saves a lot of needless work before a buffer overflow. */
3597 if (! not_regular)
3599 /* The likely offset where we will stop reading. We could read
3600 more (or less), if the file grows (or shrinks) as we read it. */
3601 off_t likely_end = min (end_offset, st.st_size);
3603 if (beg_offset < likely_end)
3605 ptrdiff_t buf_bytes
3606 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3607 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3608 off_t likely_growth = likely_end - beg_offset;
3609 if (buf_growth_max < likely_growth)
3610 buffer_overflow ();
3614 /* Prevent redisplay optimizations. */
3615 current_buffer->clip_changed = true;
3617 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3619 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3620 setup_coding_system (coding_system, &coding);
3621 /* Ensure we set Vlast_coding_system_used. */
3622 set_coding_system = true;
3624 else if (BEG < Z)
3626 /* Decide the coding system to use for reading the file now
3627 because we can't use an optimized method for handling
3628 `coding:' tag if the current buffer is not empty. */
3629 if (!NILP (Vcoding_system_for_read))
3630 coding_system = Vcoding_system_for_read;
3631 else
3633 /* Don't try looking inside a file for a coding system
3634 specification if it is not seekable. */
3635 if (! not_regular && ! NILP (Vset_auto_coding_function))
3637 /* Find a coding system specified in the heading two
3638 lines or in the tailing several lines of the file.
3639 We assume that the 1K-byte and 3K-byte for heading
3640 and tailing respectively are sufficient for this
3641 purpose. */
3642 int nread;
3644 if (st.st_size <= (1024 * 4))
3645 nread = emacs_read_quit (fd, read_buf, 1024 * 4);
3646 else
3648 nread = emacs_read_quit (fd, read_buf, 1024);
3649 if (nread == 1024)
3651 int ntail;
3652 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3653 report_file_error ("Setting file position",
3654 orig_filename);
3655 ntail = emacs_read_quit (fd, read_buf + nread, 1024 * 3);
3656 nread = ntail < 0 ? ntail : nread + ntail;
3660 if (nread < 0)
3661 report_file_error ("Read error", orig_filename);
3662 else if (nread > 0)
3664 AUTO_STRING (name, " *code-converting-work*");
3665 struct buffer *prev = current_buffer;
3666 Lisp_Object workbuf;
3667 struct buffer *buf;
3669 record_unwind_current_buffer ();
3671 workbuf = Fget_buffer_create (name);
3672 buf = XBUFFER (workbuf);
3674 delete_all_overlays (buf);
3675 bset_directory (buf, BVAR (current_buffer, directory));
3676 bset_read_only (buf, Qnil);
3677 bset_filename (buf, Qnil);
3678 bset_undo_list (buf, Qt);
3679 eassert (buf->overlays_before == NULL);
3680 eassert (buf->overlays_after == NULL);
3682 set_buffer_internal (buf);
3683 Ferase_buffer ();
3684 bset_enable_multibyte_characters (buf, Qnil);
3686 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3687 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3688 coding_system = call2 (Vset_auto_coding_function,
3689 filename, make_number (nread));
3690 set_buffer_internal (prev);
3692 /* Discard the unwind protect for recovering the
3693 current buffer. */
3694 specpdl_ptr--;
3696 /* Rewind the file for the actual read done later. */
3697 if (lseek (fd, 0, SEEK_SET) < 0)
3698 report_file_error ("Setting file position", orig_filename);
3702 if (NILP (coding_system))
3704 /* If we have not yet decided a coding system, check
3705 file-coding-system-alist. */
3706 coding_system = CALLN (Ffind_operation_coding_system,
3707 Qinsert_file_contents, orig_filename,
3708 visit, beg, end, replace);
3709 if (CONSP (coding_system))
3710 coding_system = XCAR (coding_system);
3714 if (NILP (coding_system))
3715 coding_system = Qundecided;
3716 else
3717 CHECK_CODING_SYSTEM (coding_system);
3719 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3720 /* We must suppress all character code conversion except for
3721 end-of-line conversion. */
3722 coding_system = raw_text_coding_system (coding_system);
3724 setup_coding_system (coding_system, &coding);
3725 /* Ensure we set Vlast_coding_system_used. */
3726 set_coding_system = true;
3729 /* If requested, replace the accessible part of the buffer
3730 with the file contents. Avoid replacing text at the
3731 beginning or end of the buffer that matches the file contents;
3732 that preserves markers pointing to the unchanged parts.
3734 Here we implement this feature in an optimized way
3735 for the case where code conversion is NOT needed.
3736 The following if-statement handles the case of conversion
3737 in a less optimal way.
3739 If the code conversion is "automatic" then we try using this
3740 method and hope for the best.
3741 But if we discover the need for conversion, we give up on this method
3742 and let the following if-statement handle the replace job. */
3743 if (!NILP (replace)
3744 && BEGV < ZV
3745 && (NILP (coding_system)
3746 || ! CODING_REQUIRE_DECODING (&coding)))
3748 ptrdiff_t overlap;
3749 /* There is still a possibility we will find the need to do code
3750 conversion. If that happens, set this variable to
3751 give up on handling REPLACE in the optimized way. */
3752 bool giveup_match_end = false;
3754 if (beg_offset != 0)
3756 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3757 report_file_error ("Setting file position", orig_filename);
3760 /* Count how many chars at the start of the file
3761 match the text at the beginning of the buffer. */
3762 while (true)
3764 int nread = emacs_read_quit (fd, read_buf, sizeof read_buf);
3765 if (nread < 0)
3766 report_file_error ("Read error", orig_filename);
3767 else if (nread == 0)
3768 break;
3770 if (CODING_REQUIRE_DETECTION (&coding))
3772 coding_system = detect_coding_system ((unsigned char *) read_buf,
3773 nread, nread, 1, 0,
3774 coding_system);
3775 setup_coding_system (coding_system, &coding);
3778 if (CODING_REQUIRE_DECODING (&coding))
3779 /* We found that the file should be decoded somehow.
3780 Let's give up here. */
3782 giveup_match_end = true;
3783 break;
3786 int bufpos = 0;
3787 while (bufpos < nread && same_at_start < ZV_BYTE
3788 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3789 same_at_start++, bufpos++;
3790 /* If we found a discrepancy, stop the scan.
3791 Otherwise loop around and scan the next bufferful. */
3792 if (bufpos != nread)
3793 break;
3795 /* If the file matches the buffer completely,
3796 there's no need to replace anything. */
3797 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3799 emacs_close (fd);
3800 clear_unwind_protect (fd_index);
3802 /* Truncate the buffer to the size of the file. */
3803 del_range_1 (same_at_start, same_at_end, 0, 0);
3804 goto handled;
3807 /* Count how many chars at the end of the file
3808 match the text at the end of the buffer. But, if we have
3809 already found that decoding is necessary, don't waste time. */
3810 while (!giveup_match_end)
3812 int total_read, nread, bufpos, trial;
3813 off_t curpos;
3815 /* At what file position are we now scanning? */
3816 curpos = end_offset - (ZV_BYTE - same_at_end);
3817 /* If the entire file matches the buffer tail, stop the scan. */
3818 if (curpos == 0)
3819 break;
3820 /* How much can we scan in the next step? */
3821 trial = min (curpos, sizeof read_buf);
3822 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3823 report_file_error ("Setting file position", orig_filename);
3825 total_read = nread = 0;
3826 while (total_read < trial)
3828 nread = emacs_read_quit (fd, read_buf + total_read,
3829 trial - total_read);
3830 if (nread < 0)
3831 report_file_error ("Read error", orig_filename);
3832 else if (nread == 0)
3833 break;
3834 total_read += nread;
3837 /* Scan this bufferful from the end, comparing with
3838 the Emacs buffer. */
3839 bufpos = total_read;
3841 /* Compare with same_at_start to avoid counting some buffer text
3842 as matching both at the file's beginning and at the end. */
3843 while (bufpos > 0 && same_at_end > same_at_start
3844 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3845 same_at_end--, bufpos--;
3847 /* If we found a discrepancy, stop the scan.
3848 Otherwise loop around and scan the preceding bufferful. */
3849 if (bufpos != 0)
3851 /* If this discrepancy is because of code conversion,
3852 we cannot use this method; giveup and try the other. */
3853 if (same_at_end > same_at_start
3854 && FETCH_BYTE (same_at_end - 1) >= 0200
3855 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3856 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3857 giveup_match_end = true;
3858 break;
3861 if (nread == 0)
3862 break;
3865 if (! giveup_match_end)
3867 ptrdiff_t temp;
3868 ptrdiff_t this_count = SPECPDL_INDEX ();
3870 /* We win! We can handle REPLACE the optimized way. */
3872 /* Extend the start of non-matching text area to multibyte
3873 character boundary. */
3874 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3875 while (same_at_start > BEGV_BYTE
3876 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3877 same_at_start--;
3879 /* Extend the end of non-matching text area to multibyte
3880 character boundary. */
3881 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3882 while (same_at_end < ZV_BYTE
3883 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3884 same_at_end++;
3886 /* Don't try to reuse the same piece of text twice. */
3887 overlap = (same_at_start - BEGV_BYTE
3888 - (same_at_end
3889 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3890 if (overlap > 0)
3891 same_at_end += overlap;
3892 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3894 /* Arrange to read only the nonmatching middle part of the file. */
3895 beg_offset += same_at_start - BEGV_BYTE;
3896 end_offset -= ZV_BYTE - same_at_end;
3898 /* This binding is to avoid ask-user-about-supersession-threat
3899 being called in insert_from_buffer or del_range_bytes (via
3900 prepare_to_modify_buffer).
3901 AFAICT we could avoid ask-user-about-supersession-threat by setting
3902 current_buffer->modtime earlier, but we could still end up calling
3903 ask-user-about-supersession-threat if the file is modified while
3904 we read it, so we bind buffer-file-name instead. */
3905 specbind (intern ("buffer-file-name"), Qnil);
3906 del_range_byte (same_at_start, same_at_end);
3907 /* Insert from the file at the proper position. */
3908 temp = BYTE_TO_CHAR (same_at_start);
3909 SET_PT_BOTH (temp, same_at_start);
3910 unbind_to (this_count, Qnil);
3912 /* If display currently starts at beginning of line,
3913 keep it that way. */
3914 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3915 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3917 replace_handled = true;
3921 /* If requested, replace the accessible part of the buffer
3922 with the file contents. Avoid replacing text at the
3923 beginning or end of the buffer that matches the file contents;
3924 that preserves markers pointing to the unchanged parts.
3926 Here we implement this feature for the case where code conversion
3927 is needed, in a simple way that needs a lot of memory.
3928 The preceding if-statement handles the case of no conversion
3929 in a more optimized way. */
3930 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3932 ptrdiff_t same_at_start_charpos;
3933 ptrdiff_t inserted_chars;
3934 ptrdiff_t overlap;
3935 ptrdiff_t bufpos;
3936 unsigned char *decoded;
3937 ptrdiff_t temp;
3938 ptrdiff_t this = 0;
3939 ptrdiff_t this_count = SPECPDL_INDEX ();
3940 bool multibyte
3941 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3942 Lisp_Object conversion_buffer;
3944 conversion_buffer = code_conversion_save (1, multibyte);
3946 /* First read the whole file, performing code conversion into
3947 CONVERSION_BUFFER. */
3949 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3950 report_file_error ("Setting file position", orig_filename);
3952 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3953 unprocessed = 0; /* Bytes not processed in previous loop. */
3955 while (true)
3957 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3958 quitting while reading a huge file. */
3960 this = emacs_read_quit (fd, read_buf + unprocessed,
3961 READ_BUF_SIZE - unprocessed);
3962 if (this <= 0)
3963 break;
3965 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3966 BUF_Z (XBUFFER (conversion_buffer)));
3967 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3968 unprocessed + this, conversion_buffer);
3969 unprocessed = coding.carryover_bytes;
3970 if (coding.carryover_bytes > 0)
3971 memcpy (read_buf, coding.carryover, unprocessed);
3974 if (this < 0)
3975 report_file_error ("Read error", orig_filename);
3976 emacs_close (fd);
3977 clear_unwind_protect (fd_index);
3979 if (unprocessed > 0)
3981 coding.mode |= CODING_MODE_LAST_BLOCK;
3982 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3983 unprocessed, conversion_buffer);
3984 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3987 coding_system = CODING_ID_NAME (coding.id);
3988 set_coding_system = true;
3989 maybe_move_gap (XBUFFER (conversion_buffer));
3990 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3991 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3992 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3994 /* Compare the beginning of the converted string with the buffer
3995 text. */
3997 bufpos = 0;
3998 while (bufpos < inserted && same_at_start < same_at_end
3999 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4000 same_at_start++, bufpos++;
4002 /* If the file matches the head of buffer completely,
4003 there's no need to replace anything. */
4005 if (bufpos == inserted)
4007 /* Truncate the buffer to the size of the file. */
4008 if (same_at_start != same_at_end)
4010 /* See previous specbind for the reason behind this. */
4011 specbind (intern ("buffer-file-name"), Qnil);
4012 del_range_byte (same_at_start, same_at_end);
4014 inserted = 0;
4016 unbind_to (this_count, Qnil);
4017 goto handled;
4020 /* Extend the start of non-matching text area to the previous
4021 multibyte character boundary. */
4022 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4023 while (same_at_start > BEGV_BYTE
4024 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4025 same_at_start--;
4027 /* Scan this bufferful from the end, comparing with
4028 the Emacs buffer. */
4029 bufpos = inserted;
4031 /* Compare with same_at_start to avoid counting some buffer text
4032 as matching both at the file's beginning and at the end. */
4033 while (bufpos > 0 && same_at_end > same_at_start
4034 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4035 same_at_end--, bufpos--;
4037 /* Extend the end of non-matching text area to the next
4038 multibyte character boundary. */
4039 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4040 while (same_at_end < ZV_BYTE
4041 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4042 same_at_end++;
4044 /* Don't try to reuse the same piece of text twice. */
4045 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4046 if (overlap > 0)
4047 same_at_end += overlap;
4048 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4050 /* If display currently starts at beginning of line,
4051 keep it that way. */
4052 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4053 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4055 /* Replace the chars that we need to replace,
4056 and update INSERTED to equal the number of bytes
4057 we are taking from the decoded string. */
4058 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4060 /* See previous specbind for the reason behind this. */
4061 specbind (intern ("buffer-file-name"), Qnil);
4062 if (same_at_end != same_at_start)
4064 del_range_byte (same_at_start, same_at_end);
4065 temp = GPT;
4066 eassert (same_at_start == GPT_BYTE);
4067 same_at_start = GPT_BYTE;
4069 else
4071 temp = same_at_end_charpos;
4073 /* Insert from the file at the proper position. */
4074 SET_PT_BOTH (temp, same_at_start);
4075 same_at_start_charpos
4076 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4077 same_at_start - BEGV_BYTE
4078 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4079 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4080 inserted_chars
4081 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4082 same_at_start + inserted - BEGV_BYTE
4083 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4084 - same_at_start_charpos);
4085 insert_from_buffer (XBUFFER (conversion_buffer),
4086 same_at_start_charpos, inserted_chars, 0);
4087 /* Set `inserted' to the number of inserted characters. */
4088 inserted = PT - temp;
4089 /* Set point before the inserted characters. */
4090 SET_PT_BOTH (temp, same_at_start);
4092 unbind_to (this_count, Qnil);
4094 goto handled;
4097 if (! not_regular)
4098 total = end_offset - beg_offset;
4099 else
4100 /* For a special file, all we can do is guess. */
4101 total = READ_BUF_SIZE;
4103 if (NILP (visit) && total > 0)
4105 if (!NILP (BVAR (current_buffer, file_truename))
4106 /* Make binding buffer-file-name to nil effective. */
4107 && !NILP (BVAR (current_buffer, filename))
4108 && SAVE_MODIFF >= MODIFF)
4109 we_locked_file = true;
4110 prepare_to_modify_buffer (PT, PT, NULL);
4113 move_gap_both (PT, PT_BYTE);
4114 if (GAP_SIZE < total)
4115 make_gap (total - GAP_SIZE);
4117 if (beg_offset != 0 || !NILP (replace))
4119 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4120 report_file_error ("Setting file position", orig_filename);
4123 /* In the following loop, HOW_MUCH contains the total bytes read so
4124 far for a regular file, and not changed for a special file. But,
4125 before exiting the loop, it is set to a negative value if I/O
4126 error occurs. */
4127 how_much = 0;
4129 /* Total bytes inserted. */
4130 inserted = 0;
4132 /* Here, we don't do code conversion in the loop. It is done by
4133 decode_coding_gap after all data are read into the buffer. */
4135 ptrdiff_t gap_size = GAP_SIZE;
4137 while (how_much < total)
4139 /* `try' is reserved in some compilers (Microsoft C). */
4140 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4141 ptrdiff_t this;
4143 if (not_regular)
4145 Lisp_Object nbytes;
4147 /* Maybe make more room. */
4148 if (gap_size < trytry)
4150 make_gap (trytry - gap_size);
4151 gap_size = GAP_SIZE - inserted;
4154 /* Read from the file, capturing `quit'. When an
4155 error occurs, end the loop, and arrange for a quit
4156 to be signaled after decoding the text we read. */
4157 nbytes = internal_condition_case_1
4158 (read_non_regular,
4159 make_save_int_int_int (fd, inserted, trytry),
4160 Qerror, read_non_regular_quit);
4162 if (NILP (nbytes))
4164 read_quit = true;
4165 break;
4168 this = XINT (nbytes);
4170 else
4172 /* Allow quitting out of the actual I/O. We don't make text
4173 part of the buffer until all the reading is done, so a C-g
4174 here doesn't do any harm. */
4175 this = emacs_read_quit (fd,
4176 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4177 + inserted),
4178 trytry);
4181 if (this <= 0)
4183 how_much = this;
4184 break;
4187 gap_size -= this;
4189 /* For a regular file, where TOTAL is the real size,
4190 count HOW_MUCH to compare with it.
4191 For a special file, where TOTAL is just a buffer size,
4192 so don't bother counting in HOW_MUCH.
4193 (INSERTED is where we count the number of characters inserted.) */
4194 if (! not_regular)
4195 how_much += this;
4196 inserted += this;
4200 /* Now we have either read all the file data into the gap,
4201 or stop reading on I/O error or quit. If nothing was
4202 read, undo marking the buffer modified. */
4204 if (inserted == 0)
4206 if (we_locked_file)
4207 unlock_file (BVAR (current_buffer, file_truename));
4208 Vdeactivate_mark = old_Vdeactivate_mark;
4210 else
4211 Fset (Qdeactivate_mark, Qt);
4213 emacs_close (fd);
4214 clear_unwind_protect (fd_index);
4216 if (how_much < 0)
4217 report_file_error ("Read error", orig_filename);
4219 /* Make the text read part of the buffer. */
4220 GAP_SIZE -= inserted;
4221 GPT += inserted;
4222 GPT_BYTE += inserted;
4223 ZV += inserted;
4224 ZV_BYTE += inserted;
4225 Z += inserted;
4226 Z_BYTE += inserted;
4228 if (GAP_SIZE > 0)
4229 /* Put an anchor to ensure multi-byte form ends at gap. */
4230 *GPT_ADDR = 0;
4232 notfound:
4234 if (NILP (coding_system))
4236 /* The coding system is not yet decided. Decide it by an
4237 optimized method for handling `coding:' tag.
4239 Note that we can get here only if the buffer was empty
4240 before the insertion. */
4242 if (!NILP (Vcoding_system_for_read))
4243 coding_system = Vcoding_system_for_read;
4244 else
4246 /* Since we are sure that the current buffer was empty
4247 before the insertion, we can toggle
4248 enable-multibyte-characters directly here without taking
4249 care of marker adjustment. By this way, we can run Lisp
4250 program safely before decoding the inserted text. */
4251 Lisp_Object unwind_data;
4252 ptrdiff_t count1 = SPECPDL_INDEX ();
4254 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4255 Fcons (BVAR (current_buffer, undo_list),
4256 Fcurrent_buffer ()));
4257 bset_enable_multibyte_characters (current_buffer, Qnil);
4258 bset_undo_list (current_buffer, Qt);
4259 record_unwind_protect (decide_coding_unwind, unwind_data);
4261 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4263 coding_system = call2 (Vset_auto_coding_function,
4264 filename, make_number (inserted));
4267 if (NILP (coding_system))
4269 /* If the coding system is not yet decided, check
4270 file-coding-system-alist. */
4271 coding_system = CALLN (Ffind_operation_coding_system,
4272 Qinsert_file_contents, orig_filename,
4273 visit, beg, end, Qnil);
4274 if (CONSP (coding_system))
4275 coding_system = XCAR (coding_system);
4277 unbind_to (count1, Qnil);
4278 inserted = Z_BYTE - BEG_BYTE;
4281 if (NILP (coding_system))
4282 coding_system = Qundecided;
4283 else
4284 CHECK_CODING_SYSTEM (coding_system);
4286 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4287 /* We must suppress all character code conversion except for
4288 end-of-line conversion. */
4289 coding_system = raw_text_coding_system (coding_system);
4290 setup_coding_system (coding_system, &coding);
4291 /* Ensure we set Vlast_coding_system_used. */
4292 set_coding_system = true;
4295 if (!NILP (visit))
4297 /* When we visit a file by raw-text, we change the buffer to
4298 unibyte. */
4299 if (CODING_FOR_UNIBYTE (&coding)
4300 /* Can't do this if part of the buffer might be preserved. */
4301 && NILP (replace))
4303 /* Visiting a file with these coding system makes the buffer
4304 unibyte. */
4305 if (inserted > 0)
4306 bset_enable_multibyte_characters (current_buffer, Qnil);
4307 else
4308 Fset_buffer_multibyte (Qnil);
4312 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4313 if (CODING_MAY_REQUIRE_DECODING (&coding)
4314 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4316 move_gap_both (PT, PT_BYTE);
4317 GAP_SIZE += inserted;
4318 ZV_BYTE -= inserted;
4319 Z_BYTE -= inserted;
4320 ZV -= inserted;
4321 Z -= inserted;
4322 decode_coding_gap (&coding, inserted, inserted);
4323 inserted = coding.produced_char;
4324 coding_system = CODING_ID_NAME (coding.id);
4326 else if (inserted > 0)
4328 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4329 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4330 inserted);
4333 /* Call after-change hooks for the inserted text, aside from the case
4334 of normal visiting (not with REPLACE), which is done in a new buffer
4335 "before" the buffer is changed. */
4336 if (inserted > 0 && total > 0
4337 && (NILP (visit) || !NILP (replace)))
4339 signal_after_change (PT, 0, inserted);
4340 update_compositions (PT, PT, CHECK_BORDER);
4343 /* Now INSERTED is measured in characters. */
4345 handled:
4347 if (inserted > 0)
4348 restore_window_points (window_markers, inserted,
4349 BYTE_TO_CHAR (same_at_start),
4350 same_at_end_charpos);
4352 if (!NILP (visit))
4354 if (empty_undo_list_p)
4355 bset_undo_list (current_buffer, Qnil);
4357 if (NILP (handler))
4359 current_buffer->modtime = mtime;
4360 current_buffer->modtime_size = st.st_size;
4361 bset_filename (current_buffer, orig_filename);
4364 SAVE_MODIFF = MODIFF;
4365 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4366 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4367 if (NILP (handler))
4369 if (!NILP (BVAR (current_buffer, file_truename)))
4370 unlock_file (BVAR (current_buffer, file_truename));
4371 unlock_file (filename);
4373 if (not_regular)
4374 xsignal2 (Qfile_error,
4375 build_string ("not a regular file"), orig_filename);
4378 if (set_coding_system)
4379 Vlast_coding_system_used = coding_system;
4381 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4383 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4384 visit);
4385 if (! NILP (insval))
4387 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4388 wrong_type_argument (intern ("inserted-chars"), insval);
4389 inserted = XFASTINT (insval);
4393 /* Decode file format. */
4394 if (inserted > 0)
4396 /* Don't run point motion or modification hooks when decoding. */
4397 ptrdiff_t count1 = SPECPDL_INDEX ();
4398 ptrdiff_t old_inserted = inserted;
4399 specbind (Qinhibit_point_motion_hooks, Qt);
4400 specbind (Qinhibit_modification_hooks, Qt);
4402 /* Save old undo list and don't record undo for decoding. */
4403 old_undo = BVAR (current_buffer, undo_list);
4404 bset_undo_list (current_buffer, Qt);
4406 if (NILP (replace))
4408 insval = call3 (Qformat_decode,
4409 Qnil, make_number (inserted), visit);
4410 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4411 wrong_type_argument (intern ("inserted-chars"), insval);
4412 inserted = XFASTINT (insval);
4414 else
4416 /* If REPLACE is non-nil and we succeeded in not replacing the
4417 beginning or end of the buffer text with the file's contents,
4418 call format-decode with `point' positioned at the beginning
4419 of the buffer and `inserted' equaling the number of
4420 characters in the buffer. Otherwise, format-decode might
4421 fail to correctly analyze the beginning or end of the buffer.
4422 Hence we temporarily save `point' and `inserted' here and
4423 restore `point' iff format-decode did not insert or delete
4424 any text. Otherwise we leave `point' at point-min. */
4425 ptrdiff_t opoint = PT;
4426 ptrdiff_t opoint_byte = PT_BYTE;
4427 ptrdiff_t oinserted = ZV - BEGV;
4428 EMACS_INT ochars_modiff = CHARS_MODIFF;
4430 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4431 insval = call3 (Qformat_decode,
4432 Qnil, make_number (oinserted), visit);
4433 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4434 wrong_type_argument (intern ("inserted-chars"), insval);
4435 if (ochars_modiff == CHARS_MODIFF)
4436 /* format_decode didn't modify buffer's characters => move
4437 point back to position before inserted text and leave
4438 value of inserted alone. */
4439 SET_PT_BOTH (opoint, opoint_byte);
4440 else
4441 /* format_decode modified buffer's characters => consider
4442 entire buffer changed and leave point at point-min. */
4443 inserted = XFASTINT (insval);
4446 /* For consistency with format-decode call these now iff inserted > 0
4447 (martin 2007-06-28). */
4448 p = Vafter_insert_file_functions;
4449 while (CONSP (p))
4451 if (NILP (replace))
4453 insval = call1 (XCAR (p), make_number (inserted));
4454 if (!NILP (insval))
4456 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4457 wrong_type_argument (intern ("inserted-chars"), insval);
4458 inserted = XFASTINT (insval);
4461 else
4463 /* For the rationale of this see the comment on
4464 format-decode above. */
4465 ptrdiff_t opoint = PT;
4466 ptrdiff_t opoint_byte = PT_BYTE;
4467 ptrdiff_t oinserted = ZV - BEGV;
4468 EMACS_INT ochars_modiff = CHARS_MODIFF;
4470 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4471 insval = call1 (XCAR (p), make_number (oinserted));
4472 if (!NILP (insval))
4474 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4475 wrong_type_argument (intern ("inserted-chars"), insval);
4476 if (ochars_modiff == CHARS_MODIFF)
4477 /* after_insert_file_functions didn't modify
4478 buffer's characters => move point back to
4479 position before inserted text and leave value of
4480 inserted alone. */
4481 SET_PT_BOTH (opoint, opoint_byte);
4482 else
4483 /* after_insert_file_functions did modify buffer's
4484 characters => consider entire buffer changed and
4485 leave point at point-min. */
4486 inserted = XFASTINT (insval);
4490 maybe_quit ();
4491 p = XCDR (p);
4494 if (!empty_undo_list_p)
4496 bset_undo_list (current_buffer, old_undo);
4497 if (CONSP (old_undo) && inserted != old_inserted)
4499 /* Adjust the last undo record for the size change during
4500 the format conversion. */
4501 Lisp_Object tem = XCAR (old_undo);
4502 if (CONSP (tem) && INTEGERP (XCAR (tem))
4503 && INTEGERP (XCDR (tem))
4504 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4505 XSETCDR (tem, make_number (PT + inserted));
4508 else
4509 /* If undo_list was Qt before, keep it that way.
4510 Otherwise start with an empty undo_list. */
4511 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4513 unbind_to (count1, Qnil);
4516 if (!NILP (visit)
4517 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4519 /* If visiting nonexistent file, return nil. */
4520 report_file_errno ("Opening input file", orig_filename, save_errno);
4523 /* We made a lot of deletions and insertions above, so invalidate
4524 the newline cache for the entire region of the inserted
4525 characters. */
4526 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4527 invalidate_region_cache (current_buffer->base_buffer,
4528 current_buffer->base_buffer->newline_cache,
4529 PT - BEG, Z - PT - inserted);
4530 else if (current_buffer->newline_cache)
4531 invalidate_region_cache (current_buffer,
4532 current_buffer->newline_cache,
4533 PT - BEG, Z - PT - inserted);
4535 if (read_quit)
4536 quit ();
4538 /* Retval needs to be dealt with in all cases consistently. */
4539 if (NILP (val))
4540 val = list2 (orig_filename, make_number (inserted));
4542 return unbind_to (count, val);
4545 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4547 static void
4548 build_annotations_unwind (Lisp_Object arg)
4550 Vwrite_region_annotation_buffers = arg;
4553 /* Decide the coding-system to encode the data with. */
4555 static Lisp_Object
4556 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4557 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4558 struct coding_system *coding)
4560 Lisp_Object val;
4561 Lisp_Object eol_parent = Qnil;
4563 if (auto_saving
4564 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4565 BVAR (current_buffer, auto_save_file_name))))
4567 val = Qutf_8_emacs;
4568 eol_parent = Qunix;
4570 else if (!NILP (Vcoding_system_for_write))
4572 val = Vcoding_system_for_write;
4573 if (coding_system_require_warning
4574 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4575 /* Confirm that VAL can surely encode the current region. */
4576 val = call5 (Vselect_safe_coding_system_function,
4577 start, end, list2 (Qt, val),
4578 Qnil, filename);
4580 else
4582 /* If the variable `buffer-file-coding-system' is set locally,
4583 it means that the file was read with some kind of code
4584 conversion or the variable is explicitly set by users. We
4585 had better write it out with the same coding system even if
4586 `enable-multibyte-characters' is nil.
4588 If it is not set locally, we anyway have to convert EOL
4589 format if the default value of `buffer-file-coding-system'
4590 tells that it is not Unix-like (LF only) format. */
4591 bool using_default_coding = 0;
4592 bool force_raw_text = 0;
4594 val = BVAR (current_buffer, buffer_file_coding_system);
4595 if (NILP (val)
4596 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4598 val = Qnil;
4599 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4600 force_raw_text = 1;
4603 if (NILP (val))
4605 /* Check file-coding-system-alist. */
4606 Lisp_Object coding_systems
4607 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4608 filename, append, visit, lockname);
4609 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4610 val = XCDR (coding_systems);
4613 if (NILP (val))
4615 /* If we still have not decided a coding system, use the
4616 current buffer's value of buffer-file-coding-system. */
4617 val = BVAR (current_buffer, buffer_file_coding_system);
4618 using_default_coding = 1;
4621 if (! NILP (val) && ! force_raw_text)
4623 Lisp_Object spec, attrs;
4625 CHECK_CODING_SYSTEM (val);
4626 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4627 attrs = AREF (spec, 0);
4628 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4629 force_raw_text = 1;
4632 if (!force_raw_text
4633 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4635 /* Confirm that VAL can surely encode the current region. */
4636 val = call5 (Vselect_safe_coding_system_function,
4637 start, end, val, Qnil, filename);
4638 /* As the function specified by select-safe-coding-system-function
4639 is out of our control, make sure we are not fed by bogus
4640 values. */
4641 if (!NILP (val))
4642 CHECK_CODING_SYSTEM (val);
4645 /* If the decided coding-system doesn't specify end-of-line
4646 format, we use that of `buffer-file-coding-system'. */
4647 if (! using_default_coding)
4649 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4651 if (! NILP (dflt))
4652 val = coding_inherit_eol_type (val, dflt);
4655 /* If we decide not to encode text, use `raw-text' or one of its
4656 subsidiaries. */
4657 if (force_raw_text)
4658 val = raw_text_coding_system (val);
4661 val = coding_inherit_eol_type (val, eol_parent);
4662 setup_coding_system (val, coding);
4664 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4665 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4666 return val;
4669 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4670 "r\nFWrite region to file: \ni\ni\ni\np",
4671 doc: /* Write current region into specified file.
4672 When called from a program, requires three arguments:
4673 START, END and FILENAME. START and END are normally buffer positions
4674 specifying the part of the buffer to write.
4675 If START is nil, that means to use the entire buffer contents; END is
4676 ignored.
4677 If START is a string, then output that string to the file
4678 instead of any buffer contents; END is ignored.
4680 Optional fourth argument APPEND if non-nil means
4681 append to existing file contents (if any). If it is a number,
4682 seek to that offset in the file before writing.
4683 Optional fifth argument VISIT, if t or a string, means
4684 set the last-save-file-modtime of buffer to this file's modtime
4685 and mark buffer not modified.
4686 If VISIT is a string, it is a second file name;
4687 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4688 VISIT is also the file name to lock and unlock for clash detection.
4689 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4690 do not display the \"Wrote file\" message.
4691 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4692 use for locking and unlocking, overriding FILENAME and VISIT.
4693 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4694 for an existing file with the same name. If MUSTBENEW is `excl',
4695 that means to get an error if the file already exists; never overwrite.
4696 If MUSTBENEW is neither nil nor `excl', that means ask for
4697 confirmation before overwriting, but do go ahead and overwrite the file
4698 if the user confirms.
4700 This does code conversion according to the value of
4701 `coding-system-for-write', `buffer-file-coding-system', or
4702 `file-coding-system-alist', and sets the variable
4703 `last-coding-system-used' to the coding system actually used.
4705 This calls `write-region-annotate-functions' at the start, and
4706 `write-region-post-annotation-function' at the end. */)
4707 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4708 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4710 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4711 -1);
4714 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4715 descriptor for FILENAME, so do not open or close FILENAME. */
4717 Lisp_Object
4718 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4719 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4720 Lisp_Object mustbenew, int desc)
4722 int open_flags;
4723 int mode;
4724 off_t offset UNINIT;
4725 bool open_and_close_file = desc < 0;
4726 bool ok;
4727 int save_errno = 0;
4728 const char *fn;
4729 struct stat st;
4730 struct timespec modtime;
4731 ptrdiff_t count = SPECPDL_INDEX ();
4732 ptrdiff_t count1 UNINIT;
4733 Lisp_Object handler;
4734 Lisp_Object visit_file;
4735 Lisp_Object annotations;
4736 Lisp_Object encoded_filename;
4737 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4738 bool quietly = !NILP (visit);
4739 bool file_locked = 0;
4740 struct buffer *given_buffer;
4741 struct coding_system coding;
4743 if (current_buffer->base_buffer && visiting)
4744 error ("Cannot do file visiting in an indirect buffer");
4746 if (!NILP (start) && !STRINGP (start))
4747 validate_region (&start, &end);
4749 visit_file = Qnil;
4751 filename = Fexpand_file_name (filename, Qnil);
4753 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4754 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4756 if (STRINGP (visit))
4757 visit_file = Fexpand_file_name (visit, Qnil);
4758 else
4759 visit_file = filename;
4761 if (NILP (lockname))
4762 lockname = visit_file;
4764 annotations = Qnil;
4766 /* If the file name has special constructs in it,
4767 call the corresponding file handler. */
4768 handler = Ffind_file_name_handler (filename, Qwrite_region);
4769 /* If FILENAME has no handler, see if VISIT has one. */
4770 if (NILP (handler) && STRINGP (visit))
4771 handler = Ffind_file_name_handler (visit, Qwrite_region);
4773 if (!NILP (handler))
4775 Lisp_Object val;
4776 val = call8 (handler, Qwrite_region, start, end,
4777 filename, append, visit, lockname, mustbenew);
4779 if (visiting)
4781 SAVE_MODIFF = MODIFF;
4782 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4783 bset_filename (current_buffer, visit_file);
4786 return val;
4789 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4791 /* Special kludge to simplify auto-saving. */
4792 if (NILP (start))
4794 /* Do it later, so write-region-annotate-function can work differently
4795 if we save "the buffer" vs "a region".
4796 This is useful in tar-mode. --Stef
4797 XSETFASTINT (start, BEG);
4798 XSETFASTINT (end, Z); */
4799 Fwiden ();
4802 record_unwind_protect (build_annotations_unwind,
4803 Vwrite_region_annotation_buffers);
4804 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4806 given_buffer = current_buffer;
4808 if (!STRINGP (start))
4810 annotations = build_annotations (start, end);
4812 if (current_buffer != given_buffer)
4814 XSETFASTINT (start, BEGV);
4815 XSETFASTINT (end, ZV);
4819 if (NILP (start))
4821 XSETFASTINT (start, BEGV);
4822 XSETFASTINT (end, ZV);
4825 /* Decide the coding-system to encode the data with.
4826 We used to make this choice before calling build_annotations, but that
4827 leads to problems when a write-annotate-function takes care of
4828 unsavable chars (as was the case with X-Symbol). */
4829 Vlast_coding_system_used
4830 = choose_write_coding_system (start, end, filename,
4831 append, visit, lockname, &coding);
4833 if (open_and_close_file && !auto_saving)
4835 lock_file (lockname);
4836 file_locked = 1;
4839 encoded_filename = ENCODE_FILE (filename);
4840 fn = SSDATA (encoded_filename);
4841 open_flags = O_WRONLY | O_CREAT;
4842 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4843 if (NUMBERP (append))
4844 offset = file_offset (append);
4845 else if (!NILP (append))
4846 open_flags |= O_APPEND;
4847 #ifdef DOS_NT
4848 mode = S_IREAD | S_IWRITE;
4849 #else
4850 mode = auto_saving ? auto_save_mode_bits : 0666;
4851 #endif
4853 if (open_and_close_file)
4855 desc = emacs_open (fn, open_flags, mode);
4856 if (desc < 0)
4858 int open_errno = errno;
4859 if (file_locked)
4860 unlock_file (lockname);
4861 report_file_errno ("Opening output file", filename, open_errno);
4864 count1 = SPECPDL_INDEX ();
4865 record_unwind_protect_int (close_file_unwind, desc);
4868 if (NUMBERP (append))
4870 off_t ret = lseek (desc, offset, SEEK_SET);
4871 if (ret < 0)
4873 int lseek_errno = errno;
4874 if (file_locked)
4875 unlock_file (lockname);
4876 report_file_errno ("Lseek error", filename, lseek_errno);
4880 if (STRINGP (start))
4881 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4882 else if (XINT (start) != XINT (end))
4883 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4884 &annotations, &coding);
4885 else
4887 /* If file was empty, still need to write the annotations. */
4888 coding.mode |= CODING_MODE_LAST_BLOCK;
4889 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4891 save_errno = errno;
4893 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4894 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4896 /* We have to flush out a data. */
4897 coding.mode |= CODING_MODE_LAST_BLOCK;
4898 ok = e_write (desc, Qnil, 1, 1, &coding);
4899 save_errno = errno;
4902 /* fsync is not crucial for temporary files. Nor for auto-save
4903 files, since they might lose some work anyway. */
4904 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4906 /* Transfer data and metadata to disk, retrying if interrupted.
4907 fsync can report a write failure here, e.g., due to disk full
4908 under NFS. But ignore EINVAL, which means fsync is not
4909 supported on this file. */
4910 while (fsync (desc) != 0)
4911 if (errno != EINTR)
4913 if (errno != EINVAL)
4914 ok = 0, save_errno = errno;
4915 break;
4919 modtime = invalid_timespec ();
4920 if (visiting)
4922 if (fstat (desc, &st) == 0)
4923 modtime = get_stat_mtime (&st);
4924 else
4925 ok = 0, save_errno = errno;
4928 if (open_and_close_file)
4930 /* NFS can report a write failure now. */
4931 if (emacs_close (desc) < 0)
4932 ok = 0, save_errno = errno;
4934 /* Discard the unwind protect for close_file_unwind. */
4935 specpdl_ptr = specpdl + count1;
4938 /* Some file systems have a bug where st_mtime is not updated
4939 properly after a write. For example, CIFS might not see the
4940 st_mtime change until after the file is opened again.
4942 Attempt to detect this file system bug, and update MODTIME to the
4943 newer st_mtime if the bug appears to be present. This introduces
4944 a race condition, so to avoid most instances of the race condition
4945 on non-buggy file systems, skip this check if the most recently
4946 encountered non-buggy file system was the current file system.
4948 A race condition can occur if some other process modifies the
4949 file between the fstat above and the fstat below, but the race is
4950 unlikely and a similar race between the last write and the fstat
4951 above cannot possibly be closed anyway. */
4953 if (timespec_valid_p (modtime)
4954 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4956 int desc1 = emacs_open (fn, O_WRONLY, 0);
4957 if (desc1 >= 0)
4959 struct stat st1;
4960 if (fstat (desc1, &st1) == 0
4961 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4963 /* Use the heuristic if it appears to be valid. With neither
4964 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4965 file, the time stamp won't change. Also, some non-POSIX
4966 systems don't update an empty file's time stamp when
4967 truncating it. Finally, file systems with 100 ns or worse
4968 resolution sometimes seem to have bugs: on a system with ns
4969 resolution, checking ns % 100 incorrectly avoids the heuristic
4970 1% of the time, but the problem should be temporary as we will
4971 try again on the next time stamp. */
4972 bool use_heuristic
4973 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4974 && st.st_size != 0
4975 && modtime.tv_nsec % 100 != 0);
4977 struct timespec modtime1 = get_stat_mtime (&st1);
4978 if (use_heuristic
4979 && timespec_cmp (modtime, modtime1) == 0
4980 && st.st_size == st1.st_size)
4982 timestamp_file_system = st.st_dev;
4983 valid_timestamp_file_system = 1;
4985 else
4987 st.st_size = st1.st_size;
4988 modtime = modtime1;
4991 emacs_close (desc1);
4995 /* Call write-region-post-annotation-function. */
4996 while (CONSP (Vwrite_region_annotation_buffers))
4998 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4999 if (!NILP (Fbuffer_live_p (buf)))
5001 Fset_buffer (buf);
5002 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5003 call0 (Vwrite_region_post_annotation_function);
5005 Vwrite_region_annotation_buffers
5006 = XCDR (Vwrite_region_annotation_buffers);
5009 unbind_to (count, Qnil);
5011 if (file_locked)
5012 unlock_file (lockname);
5014 /* Do this before reporting IO error
5015 to avoid a "file has changed on disk" warning on
5016 next attempt to save. */
5017 if (timespec_valid_p (modtime))
5019 current_buffer->modtime = modtime;
5020 current_buffer->modtime_size = st.st_size;
5023 if (! ok)
5024 report_file_errno ("Write error", filename, save_errno);
5026 bool auto_saving_into_visited_file =
5027 auto_saving
5028 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5029 BVAR (current_buffer, auto_save_file_name)));
5030 if (visiting)
5032 SAVE_MODIFF = MODIFF;
5033 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5034 bset_filename (current_buffer, visit_file);
5035 update_mode_lines = 14;
5036 if (auto_saving_into_visited_file)
5037 unlock_file (lockname);
5039 else if (quietly)
5041 if (auto_saving_into_visited_file)
5043 SAVE_MODIFF = MODIFF;
5044 unlock_file (lockname);
5047 return Qnil;
5050 if (!auto_saving && !noninteractive)
5051 message_with_string ((NUMBERP (append)
5052 ? "Updated %s"
5053 : ! NILP (append)
5054 ? "Added to %s"
5055 : "Wrote %s"),
5056 visit_file, 1);
5058 return Qnil;
5061 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5062 doc: /* Return t if (car A) is numerically less than (car B). */)
5063 (Lisp_Object a, Lisp_Object b)
5065 return arithcompare (Fcar (a), Fcar (b), ARITH_LESS);
5068 /* Build the complete list of annotations appropriate for writing out
5069 the text between START and END, by calling all the functions in
5070 write-region-annotate-functions and merging the lists they return.
5071 If one of these functions switches to a different buffer, we assume
5072 that buffer contains altered text. Therefore, the caller must
5073 make sure to restore the current buffer in all cases,
5074 as save-excursion would do. */
5076 static Lisp_Object
5077 build_annotations (Lisp_Object start, Lisp_Object end)
5079 Lisp_Object annotations;
5080 Lisp_Object p, res;
5081 Lisp_Object original_buffer;
5082 int i;
5083 bool used_global = false;
5085 XSETBUFFER (original_buffer, current_buffer);
5087 annotations = Qnil;
5088 p = Vwrite_region_annotate_functions;
5089 while (CONSP (p))
5091 struct buffer *given_buffer = current_buffer;
5092 if (EQ (Qt, XCAR (p)) && !used_global)
5093 { /* Use the global value of the hook. */
5094 used_global = true;
5095 p = CALLN (Fappend,
5096 Fdefault_value (Qwrite_region_annotate_functions),
5097 XCDR (p));
5098 continue;
5100 Vwrite_region_annotations_so_far = annotations;
5101 res = call2 (XCAR (p), start, end);
5102 /* If the function makes a different buffer current,
5103 assume that means this buffer contains altered text to be output.
5104 Reset START and END from the buffer bounds
5105 and discard all previous annotations because they should have
5106 been dealt with by this function. */
5107 if (current_buffer != given_buffer)
5109 Vwrite_region_annotation_buffers
5110 = Fcons (Fcurrent_buffer (),
5111 Vwrite_region_annotation_buffers);
5112 XSETFASTINT (start, BEGV);
5113 XSETFASTINT (end, ZV);
5114 annotations = Qnil;
5116 Flength (res); /* Check basic validity of return value */
5117 annotations = merge (annotations, res, Qcar_less_than_car);
5118 p = XCDR (p);
5121 /* Now do the same for annotation functions implied by the file-format */
5122 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5123 p = BVAR (current_buffer, auto_save_file_format);
5124 else
5125 p = BVAR (current_buffer, file_format);
5126 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5128 struct buffer *given_buffer = current_buffer;
5130 Vwrite_region_annotations_so_far = annotations;
5132 /* Value is either a list of annotations or nil if the function
5133 has written annotations to a temporary buffer, which is now
5134 current. */
5135 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5136 original_buffer, make_number (i));
5137 if (current_buffer != given_buffer)
5139 XSETFASTINT (start, BEGV);
5140 XSETFASTINT (end, ZV);
5141 annotations = Qnil;
5144 if (CONSP (res))
5145 annotations = merge (annotations, res, Qcar_less_than_car);
5148 return annotations;
5152 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5153 If STRING is nil, POS is the character position in the current buffer.
5154 Intersperse with them the annotations from *ANNOT
5155 which fall within the range of POS to POS + NCHARS,
5156 each at its appropriate position.
5158 We modify *ANNOT by discarding elements as we use them up.
5160 Return true if successful. */
5162 static bool
5163 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5164 ptrdiff_t nchars, Lisp_Object *annot,
5165 struct coding_system *coding)
5167 Lisp_Object tem;
5168 ptrdiff_t nextpos;
5169 ptrdiff_t lastpos = pos + nchars;
5171 while (NILP (*annot) || CONSP (*annot))
5173 tem = Fcar_safe (Fcar (*annot));
5174 nextpos = pos - 1;
5175 if (INTEGERP (tem))
5176 nextpos = XFASTINT (tem);
5178 /* If there are no more annotations in this range,
5179 output the rest of the range all at once. */
5180 if (! (nextpos >= pos && nextpos <= lastpos))
5181 return e_write (desc, string, pos, lastpos, coding);
5183 /* Output buffer text up to the next annotation's position. */
5184 if (nextpos > pos)
5186 if (!e_write (desc, string, pos, nextpos, coding))
5187 return 0;
5188 pos = nextpos;
5190 /* Output the annotation. */
5191 tem = Fcdr (Fcar (*annot));
5192 if (STRINGP (tem))
5194 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5195 return 0;
5197 *annot = Fcdr (*annot);
5199 return 1;
5202 /* Maximum number of characters that the next
5203 function encodes per one loop iteration. */
5205 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5207 /* Write text in the range START and END into descriptor DESC,
5208 encoding them with coding system CODING. If STRING is nil, START
5209 and END are character positions of the current buffer, else they
5210 are indexes to the string STRING. Return true if successful. */
5212 static bool
5213 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5214 struct coding_system *coding)
5216 if (STRINGP (string))
5218 start = 0;
5219 end = SCHARS (string);
5222 /* We used to have a code for handling selective display here. But,
5223 now it is handled within encode_coding. */
5225 while (start < end)
5227 if (STRINGP (string))
5229 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5230 if (CODING_REQUIRE_ENCODING (coding))
5232 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5234 /* Avoid creating huge Lisp string in encode_coding_object. */
5235 if (nchars == E_WRITE_MAX)
5236 coding->raw_destination = 1;
5238 encode_coding_object
5239 (coding, string, start, string_char_to_byte (string, start),
5240 start + nchars, string_char_to_byte (string, start + nchars),
5241 Qt);
5243 else
5245 coding->dst_object = string;
5246 coding->consumed_char = SCHARS (string);
5247 coding->produced = SBYTES (string);
5250 else
5252 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5253 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5255 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5256 if (CODING_REQUIRE_ENCODING (coding))
5258 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5260 /* Likewise. */
5261 if (nchars == E_WRITE_MAX)
5262 coding->raw_destination = 1;
5264 encode_coding_object
5265 (coding, Fcurrent_buffer (), start, start_byte,
5266 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5268 else
5270 coding->dst_object = Qnil;
5271 coding->dst_pos_byte = start_byte;
5272 if (start >= GPT || end <= GPT)
5274 coding->consumed_char = end - start;
5275 coding->produced = end_byte - start_byte;
5277 else
5279 coding->consumed_char = GPT - start;
5280 coding->produced = GPT_BYTE - start_byte;
5285 if (coding->produced > 0)
5287 char *buf = (coding->raw_destination ? (char *) coding->destination
5288 : (STRINGP (coding->dst_object)
5289 ? SSDATA (coding->dst_object)
5290 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5291 coding->produced -= emacs_write_quit (desc, buf, coding->produced);
5293 if (coding->raw_destination)
5295 /* We're responsible for freeing this, see
5296 encode_coding_object to check why. */
5297 xfree (coding->destination);
5298 coding->raw_destination = 0;
5300 if (coding->produced)
5301 return 0;
5303 start += coding->consumed_char;
5306 return 1;
5309 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5310 Sverify_visited_file_modtime, 0, 1, 0,
5311 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5312 This means that the file has not been changed since it was visited or saved.
5313 If BUF is omitted or nil, it defaults to the current buffer.
5314 See Info node `(elisp)Modification Time' for more details. */)
5315 (Lisp_Object buf)
5317 struct buffer *b = decode_buffer (buf);
5318 struct stat st;
5319 Lisp_Object handler;
5320 Lisp_Object filename;
5321 struct timespec mtime;
5323 if (!STRINGP (BVAR (b, filename))) return Qt;
5324 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5326 /* If the file name has special constructs in it,
5327 call the corresponding file handler. */
5328 handler = Ffind_file_name_handler (BVAR (b, filename),
5329 Qverify_visited_file_modtime);
5330 if (!NILP (handler))
5331 return call2 (handler, Qverify_visited_file_modtime, buf);
5333 filename = ENCODE_FILE (BVAR (b, filename));
5335 mtime = (stat (SSDATA (filename), &st) == 0
5336 ? get_stat_mtime (&st)
5337 : time_error_value (errno));
5338 if (timespec_cmp (mtime, b->modtime) == 0
5339 && (b->modtime_size < 0
5340 || st.st_size == b->modtime_size))
5341 return Qt;
5342 return Qnil;
5345 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5346 Svisited_file_modtime, 0, 0, 0,
5347 doc: /* Return the current buffer's recorded visited file modification time.
5348 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5349 `file-attributes' returns. If the current buffer has no recorded file
5350 modification time, this function returns 0. If the visited file
5351 doesn't exist, return -1.
5352 See Info node `(elisp)Modification Time' for more details. */)
5353 (void)
5355 int ns = current_buffer->modtime.tv_nsec;
5356 if (ns < 0)
5357 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5358 return make_lisp_time (current_buffer->modtime);
5361 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5362 Sset_visited_file_modtime, 0, 1, 0,
5363 doc: /* Update buffer's recorded modification time from the visited file's time.
5364 Useful if the buffer was not read from the file normally
5365 or if the file itself has been changed for some known benign reason.
5366 An argument specifies the modification time value to use
5367 \(instead of that of the visited file), in the form of a list
5368 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5369 `visited-file-modtime'. */)
5370 (Lisp_Object time_flag)
5372 if (!NILP (time_flag))
5374 struct timespec mtime;
5375 if (INTEGERP (time_flag))
5377 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5378 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5380 else
5381 mtime = lisp_time_argument (time_flag);
5383 current_buffer->modtime = mtime;
5384 current_buffer->modtime_size = -1;
5386 else
5388 register Lisp_Object filename;
5389 struct stat st;
5390 Lisp_Object handler;
5392 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5394 /* If the file name has special constructs in it,
5395 call the corresponding file handler. */
5396 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5397 if (!NILP (handler))
5398 /* The handler can find the file name the same way we did. */
5399 return call2 (handler, Qset_visited_file_modtime, Qnil);
5401 filename = ENCODE_FILE (filename);
5403 if (stat (SSDATA (filename), &st) >= 0)
5405 current_buffer->modtime = get_stat_mtime (&st);
5406 current_buffer->modtime_size = st.st_size;
5410 return Qnil;
5413 static Lisp_Object
5414 auto_save_error (Lisp_Object error_val)
5416 auto_save_error_occurred = 1;
5418 ring_bell (XFRAME (selected_frame));
5420 AUTO_STRING (format, "Auto-saving %s: %s");
5421 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5422 Ferror_message_string (error_val));
5423 call3 (intern ("display-warning"),
5424 intern ("auto-save"), msg, intern ("error"));
5426 return Qnil;
5429 static Lisp_Object
5430 auto_save_1 (void)
5432 struct stat st;
5433 Lisp_Object modes;
5435 auto_save_mode_bits = 0666;
5437 /* Get visited file's mode to become the auto save file's mode. */
5438 if (! NILP (BVAR (current_buffer, filename)))
5440 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5441 /* But make sure we can overwrite it later! */
5442 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5443 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5444 INTEGERP (modes))
5445 /* Remote files don't cooperate with stat. */
5446 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5449 return
5450 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5451 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5452 Qnil, Qnil);
5455 struct auto_save_unwind
5457 FILE *stream;
5458 bool auto_raise;
5461 static void
5462 do_auto_save_unwind (void *arg)
5464 struct auto_save_unwind *p = arg;
5465 FILE *stream = p->stream;
5466 minibuffer_auto_raise = p->auto_raise;
5467 auto_saving = 0;
5468 if (stream != NULL)
5470 block_input ();
5471 fclose (stream);
5472 unblock_input ();
5476 static Lisp_Object
5477 do_auto_save_make_dir (Lisp_Object dir)
5479 Lisp_Object result;
5481 auto_saving_dir_umask = 077;
5482 result = call2 (Qmake_directory, dir, Qt);
5483 auto_saving_dir_umask = 0;
5484 return result;
5487 static Lisp_Object
5488 do_auto_save_eh (Lisp_Object ignore)
5490 auto_saving_dir_umask = 0;
5491 return Qnil;
5494 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5495 doc: /* Auto-save all buffers that need it.
5496 This is all buffers that have auto-saving enabled
5497 and are changed since last auto-saved.
5498 Auto-saving writes the buffer into a file
5499 so that your editing is not lost if the system crashes.
5500 This file is not the file you visited; that changes only when you save.
5501 Normally, run the normal hook `auto-save-hook' before saving.
5503 A non-nil NO-MESSAGE argument means do not print any message if successful.
5504 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5505 (Lisp_Object no_message, Lisp_Object current_only)
5507 struct buffer *old = current_buffer, *b;
5508 Lisp_Object tail, buf, hook;
5509 bool auto_saved = 0;
5510 int do_handled_files;
5511 Lisp_Object oquit;
5512 FILE *stream = NULL;
5513 ptrdiff_t count = SPECPDL_INDEX ();
5514 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5515 bool old_message_p = 0;
5516 struct auto_save_unwind auto_save_unwind;
5518 if (max_specpdl_size < specpdl_size + 40)
5519 max_specpdl_size = specpdl_size + 40;
5521 if (minibuf_level)
5522 no_message = Qt;
5524 if (NILP (no_message))
5526 old_message_p = push_message ();
5527 record_unwind_protect_void (pop_message_unwind);
5530 /* Ordinarily don't quit within this function,
5531 but don't make it impossible to quit (in case we get hung in I/O). */
5532 oquit = Vquit_flag;
5533 Vquit_flag = Qnil;
5535 hook = intern ("auto-save-hook");
5536 safe_run_hooks (hook);
5538 if (STRINGP (Vauto_save_list_file_name))
5540 Lisp_Object listfile;
5542 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5544 /* Don't try to create the directory when shutting down Emacs,
5545 because creating the directory might signal an error, and
5546 that would leave Emacs in a strange state. */
5547 if (!NILP (Vrun_hooks))
5549 Lisp_Object dir;
5550 dir = Ffile_name_directory (listfile);
5551 if (NILP (Ffile_directory_p (dir)))
5552 internal_condition_case_1 (do_auto_save_make_dir,
5553 dir, Qt,
5554 do_auto_save_eh);
5557 stream = emacs_fopen (SSDATA (listfile), "w");
5560 auto_save_unwind.stream = stream;
5561 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5562 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5563 minibuffer_auto_raise = 0;
5564 auto_saving = 1;
5565 auto_save_error_occurred = 0;
5567 /* On first pass, save all files that don't have handlers.
5568 On second pass, save all files that do have handlers.
5570 If Emacs is crashing, the handlers may tweak what is causing
5571 Emacs to crash in the first place, and it would be a shame if
5572 Emacs failed to autosave perfectly ordinary files because it
5573 couldn't handle some ange-ftp'd file. */
5575 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5576 FOR_EACH_LIVE_BUFFER (tail, buf)
5578 b = XBUFFER (buf);
5580 /* Record all the buffers that have auto save mode
5581 in the special file that lists them. For each of these buffers,
5582 Record visited name (if any) and auto save name. */
5583 if (STRINGP (BVAR (b, auto_save_file_name))
5584 && stream != NULL && do_handled_files == 0)
5586 block_input ();
5587 if (!NILP (BVAR (b, filename)))
5588 fwrite_unlocked (SDATA (BVAR (b, filename)), 1,
5589 SBYTES (BVAR (b, filename)), stream);
5590 putc_unlocked ('\n', stream);
5591 fwrite_unlocked (SDATA (BVAR (b, auto_save_file_name)), 1,
5592 SBYTES (BVAR (b, auto_save_file_name)), stream);
5593 putc_unlocked ('\n', stream);
5594 unblock_input ();
5597 if (!NILP (current_only)
5598 && b != current_buffer)
5599 continue;
5601 /* Don't auto-save indirect buffers.
5602 The base buffer takes care of it. */
5603 if (b->base_buffer)
5604 continue;
5606 /* Check for auto save enabled
5607 and file changed since last auto save
5608 and file changed since last real save. */
5609 if (STRINGP (BVAR (b, auto_save_file_name))
5610 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5611 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5612 /* -1 means we've turned off autosaving for a while--see below. */
5613 && XINT (BVAR (b, save_length)) >= 0
5614 && (do_handled_files
5615 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5616 Qwrite_region))))
5618 struct timespec before_time = current_timespec ();
5619 struct timespec after_time;
5621 /* If we had a failure, don't try again for 20 minutes. */
5622 if (b->auto_save_failure_time > 0
5623 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5624 continue;
5626 set_buffer_internal (b);
5627 if (NILP (Vauto_save_include_big_deletions)
5628 && (XFASTINT (BVAR (b, save_length)) * 10
5629 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5630 /* A short file is likely to change a large fraction;
5631 spare the user annoying messages. */
5632 && XFASTINT (BVAR (b, save_length)) > 5000
5633 /* These messages are frequent and annoying for `*mail*'. */
5634 && !EQ (BVAR (b, filename), Qnil)
5635 && NILP (no_message))
5637 /* It has shrunk too much; turn off auto-saving here. */
5638 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5639 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5640 BVAR (b, name), 1);
5641 minibuffer_auto_raise = 0;
5642 /* Turn off auto-saving until there's a real save,
5643 and prevent any more warnings. */
5644 XSETINT (BVAR (b, save_length), -1);
5645 Fsleep_for (make_number (1), Qnil);
5646 continue;
5648 if (!auto_saved && NILP (no_message))
5649 message1 ("Auto-saving...");
5650 internal_condition_case (auto_save_1, Qt, auto_save_error);
5651 auto_saved = 1;
5652 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5653 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5654 set_buffer_internal (old);
5656 after_time = current_timespec ();
5658 /* If auto-save took more than 60 seconds,
5659 assume it was an NFS failure that got a timeout. */
5660 if (after_time.tv_sec - before_time.tv_sec > 60)
5661 b->auto_save_failure_time = after_time.tv_sec;
5665 /* Prevent another auto save till enough input events come in. */
5666 record_auto_save ();
5668 if (auto_saved && NILP (no_message))
5670 if (old_message_p)
5672 /* If we are going to restore an old message,
5673 give time to read ours. */
5674 sit_for (make_number (1), 0, 0);
5675 restore_message ();
5677 else if (!auto_save_error_occurred)
5678 /* Don't overwrite the error message if an error occurred.
5679 If we displayed a message and then restored a state
5680 with no message, leave a "done" message on the screen. */
5681 message1 ("Auto-saving...done");
5684 Vquit_flag = oquit;
5686 /* This restores the message-stack status. */
5687 unbind_to (count, Qnil);
5688 return Qnil;
5691 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5692 Sset_buffer_auto_saved, 0, 0, 0,
5693 doc: /* Mark current buffer as auto-saved with its current text.
5694 No auto-save file will be written until the buffer changes again. */)
5695 (void)
5697 /* FIXME: This should not be called in indirect buffers, since
5698 they're not autosaved. */
5699 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5700 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5701 current_buffer->auto_save_failure_time = 0;
5702 return Qnil;
5705 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5706 Sclear_buffer_auto_save_failure, 0, 0, 0,
5707 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5708 (void)
5710 current_buffer->auto_save_failure_time = 0;
5711 return Qnil;
5714 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5715 0, 0, 0,
5716 doc: /* Return t if current buffer has been auto-saved recently.
5717 More precisely, if it has been auto-saved since last read from or saved
5718 in the visited file. If the buffer has no visited file,
5719 then any auto-save counts as "recent". */)
5720 (void)
5722 /* FIXME: maybe we should return nil for indirect buffers since
5723 they're never autosaved. */
5724 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5727 /* Reading and completing file names. */
5729 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5730 Snext_read_file_uses_dialog_p, 0, 0, 0,
5731 doc: /* Return t if a call to `read-file-name' will use a dialog.
5732 The return value is only relevant for a call to `read-file-name' that happens
5733 before any other event (mouse or keypress) is handled. */)
5734 (void)
5736 #if (defined USE_GTK || defined USE_MOTIF \
5737 || defined HAVE_NS || defined HAVE_NTGUI)
5738 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5739 && use_dialog_box
5740 && use_file_dialog
5741 && window_system_available (SELECTED_FRAME ()))
5742 return Qt;
5743 #endif
5744 return Qnil;
5748 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5749 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5750 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5751 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5752 it to text mode.
5754 As a side effect, this function flushes any pending STREAM's data.
5756 Value is the previous value of STREAM's I/O mode, nil for text mode,
5757 non-nil for binary mode.
5759 On MS-Windows and MS-DOS, binary mode is needed to read or write
5760 arbitrary binary data, and for disabling translation between CR-LF
5761 pairs and a single newline character. Examples include generation
5762 of text files with Unix-style end-of-line format using `princ' in
5763 batch mode, with standard output redirected to a file.
5765 On Posix systems, this function always returns non-nil, and has no
5766 effect except for flushing STREAM's data. */)
5767 (Lisp_Object stream, Lisp_Object mode)
5769 FILE *fp = NULL;
5770 int binmode;
5772 CHECK_SYMBOL (stream);
5773 if (EQ (stream, Qstdin))
5774 fp = stdin;
5775 else if (EQ (stream, Qstdout))
5776 fp = stdout;
5777 else if (EQ (stream, Qstderr))
5778 fp = stderr;
5779 else
5780 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5782 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5783 if (fp != stdin)
5784 fflush_unlocked (fp);
5786 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5789 void
5790 init_fileio (void)
5792 realmask = umask (0);
5793 umask (realmask);
5795 valid_timestamp_file_system = 0;
5797 /* fsync can be a significant performance hit. Often it doesn't
5798 suffice to make the file-save operation survive a crash. For
5799 batch scripts, which are typically part of larger shell commands
5800 that don't fsync other files, its effect on performance can be
5801 significant so its utility is particularly questionable.
5802 Hence, for now by default fsync is used only when interactive.
5804 For more on why fsync often fails to work on today's hardware, see:
5805 Zheng M et al. Understanding the robustness of SSDs under power fault.
5806 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5807 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5809 For more on why fsync does not suffice even if it works properly, see:
5810 Roche X. Necessary step(s) to synchronize filename operations on disk.
5811 Austin Group Defect 672, 2013-03-19
5812 http://austingroupbugs.net/view.php?id=672 */
5813 write_region_inhibit_fsync = noninteractive;
5816 void
5817 syms_of_fileio (void)
5819 /* Property name of a file name handler,
5820 which gives a list of operations it handles. */
5821 DEFSYM (Qoperations, "operations");
5823 DEFSYM (Qexpand_file_name, "expand-file-name");
5824 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5825 DEFSYM (Qdirectory_file_name, "directory-file-name");
5826 DEFSYM (Qfile_name_directory, "file-name-directory");
5827 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5828 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5829 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5830 DEFSYM (Qcopy_file, "copy-file");
5831 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5832 DEFSYM (Qmake_directory, "make-directory");
5833 DEFSYM (Qdelete_file, "delete-file");
5834 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5835 DEFSYM (Qrename_file, "rename-file");
5836 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5837 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5838 DEFSYM (Qfile_exists_p, "file-exists-p");
5839 DEFSYM (Qfile_executable_p, "file-executable-p");
5840 DEFSYM (Qfile_readable_p, "file-readable-p");
5841 DEFSYM (Qfile_writable_p, "file-writable-p");
5842 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5843 DEFSYM (Qaccess_file, "access-file");
5844 DEFSYM (Qfile_directory_p, "file-directory-p");
5845 DEFSYM (Qfile_regular_p, "file-regular-p");
5846 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5847 DEFSYM (Qfile_modes, "file-modes");
5848 DEFSYM (Qset_file_modes, "set-file-modes");
5849 DEFSYM (Qset_file_times, "set-file-times");
5850 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5851 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5852 DEFSYM (Qfile_acl, "file-acl");
5853 DEFSYM (Qset_file_acl, "set-file-acl");
5854 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5855 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5856 DEFSYM (Qwrite_region, "write-region");
5857 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5858 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5860 /* The symbol bound to coding-system-for-read when
5861 insert-file-contents is called for recovering a file. This is not
5862 an actual coding system name, but just an indicator to tell
5863 insert-file-contents to use `emacs-mule' with a special flag for
5864 auto saving and recovering a file. */
5865 DEFSYM (Qauto_save_coding, "auto-save-coding");
5867 DEFSYM (Qfile_name_history, "file-name-history");
5868 Fset (Qfile_name_history, Qnil);
5870 DEFSYM (Qfile_error, "file-error");
5871 DEFSYM (Qfile_already_exists, "file-already-exists");
5872 DEFSYM (Qfile_date_error, "file-date-error");
5873 DEFSYM (Qfile_missing, "file-missing");
5874 DEFSYM (Qfile_notify_error, "file-notify-error");
5875 DEFSYM (Qexcl, "excl");
5877 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5878 doc: /* Coding system for encoding file names.
5879 If it is nil, `default-file-name-coding-system' (which see) is used.
5881 On MS-Windows, the value of this variable is largely ignored if
5882 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5883 behaves as if file names were encoded in `utf-8'. */);
5884 Vfile_name_coding_system = Qnil;
5886 DEFVAR_LISP ("default-file-name-coding-system",
5887 Vdefault_file_name_coding_system,
5888 doc: /* Default coding system for encoding file names.
5889 This variable is used only when `file-name-coding-system' is nil.
5891 This variable is set/changed by the command `set-language-environment'.
5892 User should not set this variable manually,
5893 instead use `file-name-coding-system' to get a constant encoding
5894 of file names regardless of the current language environment.
5896 On MS-Windows, the value of this variable is largely ignored if
5897 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5898 behaves as if file names were encoded in `utf-8'. */);
5899 Vdefault_file_name_coding_system = Qnil;
5901 /* Lisp functions for translating file formats. */
5902 DEFSYM (Qformat_decode, "format-decode");
5903 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5905 /* Lisp function for setting buffer-file-coding-system and the
5906 multibyteness of the current buffer after inserting a file. */
5907 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5909 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5911 Fput (Qfile_error, Qerror_conditions,
5912 Fpurecopy (list2 (Qfile_error, Qerror)));
5913 Fput (Qfile_error, Qerror_message,
5914 build_pure_c_string ("File error"));
5916 Fput (Qfile_already_exists, Qerror_conditions,
5917 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5918 Fput (Qfile_already_exists, Qerror_message,
5919 build_pure_c_string ("File already exists"));
5921 Fput (Qfile_date_error, Qerror_conditions,
5922 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5923 Fput (Qfile_date_error, Qerror_message,
5924 build_pure_c_string ("Cannot set file date"));
5926 Fput (Qfile_missing, Qerror_conditions,
5927 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
5928 Fput (Qfile_missing, Qerror_message,
5929 build_pure_c_string ("File is missing"));
5931 Fput (Qfile_notify_error, Qerror_conditions,
5932 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5933 Fput (Qfile_notify_error, Qerror_message,
5934 build_pure_c_string ("File notification error"));
5936 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5937 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5938 If a file name matches REGEXP, all I/O on that file is done by calling
5939 HANDLER. If a file name matches more than one handler, the handler
5940 whose match starts last in the file name gets precedence. The
5941 function `find-file-name-handler' checks this list for a handler for
5942 its argument.
5944 HANDLER should be a function. The first argument given to it is the
5945 name of the I/O primitive to be handled; the remaining arguments are
5946 the arguments that were passed to that primitive. For example, if you
5947 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5948 HANDLER is called like this:
5950 (funcall HANDLER \\='file-exists-p FILENAME)
5952 Note that HANDLER must be able to handle all I/O primitives; if it has
5953 nothing special to do for a primitive, it should reinvoke the
5954 primitive to handle the operation \"the usual way\".
5955 See Info node `(elisp)Magic File Names' for more details. */);
5956 Vfile_name_handler_alist = Qnil;
5958 DEFVAR_LISP ("set-auto-coding-function",
5959 Vset_auto_coding_function,
5960 doc: /* If non-nil, a function to call to decide a coding system of file.
5961 Two arguments are passed to this function: the file name
5962 and the length of a file contents following the point.
5963 This function should return a coding system to decode the file contents.
5964 It should check the file name against `auto-coding-alist'.
5965 If no coding system is decided, it should check a coding system
5966 specified in the heading lines with the format:
5967 -*- ... coding: CODING-SYSTEM; ... -*-
5968 or local variable spec of the tailing lines with `coding:' tag. */);
5969 Vset_auto_coding_function = Qnil;
5971 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5972 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5973 Each is passed one argument, the number of characters inserted,
5974 with point at the start of the inserted text. Each function
5975 should leave point the same, and return the new character count.
5976 If `insert-file-contents' is intercepted by a handler from
5977 `file-name-handler-alist', that handler is responsible for calling the
5978 functions in `after-insert-file-functions' if appropriate. */);
5979 Vafter_insert_file_functions = Qnil;
5981 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5982 doc: /* A list of functions to be called at the start of `write-region'.
5983 Each is passed two arguments, START and END as for `write-region'.
5984 These are usually two numbers but not always; see the documentation
5985 for `write-region'. The function should return a list of pairs
5986 of the form (POSITION . STRING), consisting of strings to be effectively
5987 inserted at the specified positions of the file being written (1 means to
5988 insert before the first byte written). The POSITIONs must be sorted into
5989 increasing order.
5991 If there are several annotation functions, the lists returned by these
5992 functions are merged destructively. As each annotation function runs,
5993 the variable `write-region-annotations-so-far' contains a list of all
5994 annotations returned by previous annotation functions.
5996 An annotation function can return with a different buffer current.
5997 Doing so removes the annotations returned by previous functions, and
5998 resets START and END to `point-min' and `point-max' of the new buffer.
6000 After `write-region' completes, Emacs calls the function stored in
6001 `write-region-post-annotation-function', once for each buffer that was
6002 current when building the annotations (i.e., at least once), with that
6003 buffer current. */);
6004 Vwrite_region_annotate_functions = Qnil;
6005 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6007 DEFVAR_LISP ("write-region-post-annotation-function",
6008 Vwrite_region_post_annotation_function,
6009 doc: /* Function to call after `write-region' completes.
6010 The function is called with no arguments. If one or more of the
6011 annotation functions in `write-region-annotate-functions' changed the
6012 current buffer, the function stored in this variable is called for
6013 each of those additional buffers as well, in addition to the original
6014 buffer. The relevant buffer is current during each function call. */);
6015 Vwrite_region_post_annotation_function = Qnil;
6016 staticpro (&Vwrite_region_annotation_buffers);
6018 DEFVAR_LISP ("write-region-annotations-so-far",
6019 Vwrite_region_annotations_so_far,
6020 doc: /* When an annotation function is called, this holds the previous annotations.
6021 These are the annotations made by other annotation functions
6022 that were already called. See also `write-region-annotate-functions'. */);
6023 Vwrite_region_annotations_so_far = Qnil;
6025 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6026 doc: /* A list of file name handlers that temporarily should not be used.
6027 This applies only to the operation `inhibit-file-name-operation'. */);
6028 Vinhibit_file_name_handlers = Qnil;
6030 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6031 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6032 Vinhibit_file_name_operation = Qnil;
6034 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6035 doc: /* File name in which to write a list of all auto save file names.
6036 This variable is initialized automatically from `auto-save-list-file-prefix'
6037 shortly after Emacs reads your init file, if you have not yet given it
6038 a non-nil value. */);
6039 Vauto_save_list_file_name = Qnil;
6041 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6042 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6043 Normally auto-save files are written under other names. */);
6044 Vauto_save_visited_file_name = Qnil;
6046 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6047 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6048 If nil, deleting a substantial portion of the text disables auto-save
6049 in the buffer; this is the default behavior, because the auto-save
6050 file is usually more useful if it contains the deleted text. */);
6051 Vauto_save_include_big_deletions = Qnil;
6053 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6054 doc: /* Non-nil means don't call fsync in `write-region'.
6055 This variable affects calls to `write-region' as well as save commands.
6056 Setting this to nil may avoid data loss if the system loses power or
6057 the operating system crashes. By default, it is non-nil in batch mode. */);
6058 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6060 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6061 doc: /* Specifies whether to use the system's trash can.
6062 When non-nil, certain file deletion commands use the function
6063 `move-file-to-trash' instead of deleting files outright.
6064 This includes interactive calls to `delete-file' and
6065 `delete-directory' and the Dired deletion commands. */);
6066 delete_by_moving_to_trash = 0;
6067 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6069 /* Lisp function for moving files to trash. */
6070 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6072 /* Lisp function for recursively copying directories. */
6073 DEFSYM (Qcopy_directory, "copy-directory");
6075 /* Lisp function for recursively deleting directories. */
6076 DEFSYM (Qdelete_directory, "delete-directory");
6078 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6079 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6081 DEFSYM (Qstdin, "stdin");
6082 DEFSYM (Qstdout, "stdout");
6083 DEFSYM (Qstderr, "stderr");
6085 defsubr (&Sfind_file_name_handler);
6086 defsubr (&Sfile_name_directory);
6087 defsubr (&Sfile_name_nondirectory);
6088 defsubr (&Sunhandled_file_name_directory);
6089 defsubr (&Sfile_name_as_directory);
6090 defsubr (&Sdirectory_name_p);
6091 defsubr (&Sdirectory_file_name);
6092 defsubr (&Smake_temp_file_internal);
6093 defsubr (&Smake_temp_name);
6094 defsubr (&Sexpand_file_name);
6095 defsubr (&Ssubstitute_in_file_name);
6096 defsubr (&Scopy_file);
6097 defsubr (&Smake_directory_internal);
6098 defsubr (&Sdelete_directory_internal);
6099 defsubr (&Sdelete_file);
6100 defsubr (&Sfile_name_case_insensitive_p);
6101 defsubr (&Srename_file);
6102 defsubr (&Sadd_name_to_file);
6103 defsubr (&Smake_symbolic_link);
6104 defsubr (&Sfile_name_absolute_p);
6105 defsubr (&Sfile_exists_p);
6106 defsubr (&Sfile_executable_p);
6107 defsubr (&Sfile_readable_p);
6108 defsubr (&Sfile_writable_p);
6109 defsubr (&Saccess_file);
6110 defsubr (&Sfile_symlink_p);
6111 defsubr (&Sfile_directory_p);
6112 defsubr (&Sfile_accessible_directory_p);
6113 defsubr (&Sfile_regular_p);
6114 defsubr (&Sfile_modes);
6115 defsubr (&Sset_file_modes);
6116 defsubr (&Sset_file_times);
6117 defsubr (&Sfile_selinux_context);
6118 defsubr (&Sfile_acl);
6119 defsubr (&Sset_file_acl);
6120 defsubr (&Sset_file_selinux_context);
6121 defsubr (&Sset_default_file_modes);
6122 defsubr (&Sdefault_file_modes);
6123 defsubr (&Sfile_newer_than_file_p);
6124 defsubr (&Sinsert_file_contents);
6125 defsubr (&Swrite_region);
6126 defsubr (&Scar_less_than_car);
6127 defsubr (&Sverify_visited_file_modtime);
6128 defsubr (&Svisited_file_modtime);
6129 defsubr (&Sset_visited_file_modtime);
6130 defsubr (&Sdo_auto_save);
6131 defsubr (&Sset_buffer_auto_saved);
6132 defsubr (&Sclear_buffer_auto_save_failure);
6133 defsubr (&Srecent_auto_save_p);
6135 defsubr (&Snext_read_file_uses_dialog_p);
6137 defsubr (&Sset_binary_mode);
6139 #ifdef HAVE_SYNC
6140 defsubr (&Sunix_sync);
6141 #endif