Tell user about read-integer-overflow-as-float
[emacs.git] / src / fileio.c
blob2f8358f01b552fc5804f3dfef89c472df6ddd2fc
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 <fsusage.h>
100 #include <stat-time.h>
101 #include <tempname.h>
103 #include <binary-io.h>
105 #ifdef HPUX
106 #include <netio.h>
107 #endif
109 #include "commands.h"
111 /* True during writing of auto-save files. */
112 static bool auto_saving;
114 /* Emacs's real umask. */
115 static mode_t realmask;
117 /* Nonzero umask during creation of auto-save directories. */
118 static mode_t auto_saving_dir_umask;
120 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
121 a new file with the same mode as the original. */
122 static mode_t auto_save_mode_bits;
124 /* Set by auto_save_1 if an error occurred during the last auto-save. */
125 static bool auto_save_error_occurred;
127 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
128 number of a file system where time stamps were observed to work. */
129 static bool valid_timestamp_file_system;
130 static dev_t timestamp_file_system;
132 /* Each time an annotation function changes the buffer, the new buffer
133 is added here. */
134 static Lisp_Object Vwrite_region_annotation_buffers;
136 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
137 Lisp_Object *, struct coding_system *);
138 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
139 struct coding_system *);
142 /* Return true if FILENAME exists, otherwise return false and set errno. */
144 static bool
145 check_existing (const char *filename)
147 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
150 /* Return true if file FILENAME exists and can be executed. */
152 static bool
153 check_executable (char *filename)
155 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
158 /* Return true if file FILENAME exists and can be accessed
159 according to AMODE, which should include W_OK.
160 On failure, return false and set errno. */
162 static bool
163 check_writable (const char *filename, int amode)
165 #ifdef MSDOS
166 /* FIXME: an faccessat implementation should be added to the
167 DOS/Windows ports and this #ifdef branch should be removed. */
168 struct stat st;
169 if (stat (filename, &st) < 0)
170 return 0;
171 errno = EPERM;
172 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
173 #else /* not MSDOS */
174 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
175 #ifdef CYGWIN
176 /* faccessat may have returned failure because Cygwin couldn't
177 determine the file's UID or GID; if so, we return success. */
178 if (!res)
180 int faccessat_errno = errno;
181 struct stat st;
182 if (stat (filename, &st) < 0)
183 return 0;
184 res = (st.st_uid == -1 || st.st_gid == -1);
185 errno = faccessat_errno;
187 #endif /* CYGWIN */
188 return res;
189 #endif /* not MSDOS */
192 /* Signal a file-access failure. STRING describes the failure,
193 NAME the file involved, and ERRORNO the errno value.
195 If NAME is neither null nor a pair, package it up as a singleton
196 list before reporting it; this saves report_file_errno's caller the
197 trouble of preserving errno before calling list1. */
199 void
200 report_file_errno (char const *string, Lisp_Object name, int errorno)
202 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
203 char *str = emacs_strerror (errorno);
204 AUTO_STRING (unibyte_str, str);
205 Lisp_Object errstring
206 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
207 Lisp_Object errdata = Fcons (errstring, data);
209 if (errorno == EEXIST)
210 xsignal (Qfile_already_exists, errdata);
211 else
212 xsignal (errorno == ENOENT ? Qfile_missing : Qfile_error,
213 Fcons (build_string (string), errdata));
216 /* Signal a file-access failure that set errno. STRING describes the
217 failure, NAME the file involved. When invoking this function, take
218 care to not use arguments such as build_string ("foo") that involve
219 side effects that may set errno. */
221 void
222 report_file_error (char const *string, Lisp_Object name)
224 report_file_errno (string, name, errno);
227 #ifdef USE_FILE_NOTIFY
228 /* Like report_file_error, but reports a file-notify-error instead. */
230 void
231 report_file_notify_error (const char *string, Lisp_Object name)
233 char *str = emacs_strerror (errno);
234 AUTO_STRING (unibyte_str, str);
235 Lisp_Object errstring
236 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
237 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
238 Lisp_Object errdata = Fcons (errstring, data);
240 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
242 #endif
244 void
245 close_file_unwind (int fd)
247 emacs_close (fd);
250 void
251 fclose_unwind (void *arg)
253 FILE *stream = arg;
254 fclose (stream);
257 /* Restore point, having saved it as a marker. */
259 void
260 restore_point_unwind (Lisp_Object location)
262 Fgoto_char (location);
263 unchain_marker (XMARKER (location));
267 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
268 Sfind_file_name_handler, 2, 2, 0,
269 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
270 Otherwise, return nil.
271 A file name is handled if one of the regular expressions in
272 `file-name-handler-alist' matches it.
274 If OPERATION equals `inhibit-file-name-operation', then ignore
275 any handlers that are members of `inhibit-file-name-handlers',
276 but still do run any other handlers. This lets handlers
277 use the standard functions without calling themselves recursively. */)
278 (Lisp_Object filename, Lisp_Object operation)
280 /* This function must not munge the match data. */
281 Lisp_Object chain, inhibited_handlers, result;
282 ptrdiff_t pos = -1;
284 result = Qnil;
285 CHECK_STRING (filename);
287 if (EQ (operation, Vinhibit_file_name_operation))
288 inhibited_handlers = Vinhibit_file_name_handlers;
289 else
290 inhibited_handlers = Qnil;
292 for (chain = Vfile_name_handler_alist; CONSP (chain);
293 chain = XCDR (chain))
295 Lisp_Object elt;
296 elt = XCAR (chain);
297 if (CONSP (elt))
299 Lisp_Object string = XCAR (elt);
300 ptrdiff_t match_pos;
301 Lisp_Object handler = XCDR (elt);
302 Lisp_Object operations = Qnil;
304 if (SYMBOLP (handler))
305 operations = Fget (handler, Qoperations);
307 if (STRINGP (string)
308 && (match_pos = fast_string_match (string, filename)) > pos
309 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
311 Lisp_Object tem;
313 handler = XCDR (elt);
314 tem = Fmemq (handler, inhibited_handlers);
315 if (NILP (tem))
317 result = handler;
318 pos = match_pos;
323 maybe_quit ();
325 return result;
328 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
329 1, 1, 0,
330 doc: /* Return the directory component in file name FILENAME.
331 Return nil if FILENAME does not include a directory.
332 Otherwise return a directory name.
333 Given a Unix syntax file name, returns a string ending in slash. */)
334 (Lisp_Object filename)
336 Lisp_Object handler;
338 CHECK_STRING (filename);
340 /* If the file name has special constructs in it,
341 call the corresponding file handler. */
342 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
343 if (!NILP (handler))
345 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
346 filename);
347 return STRINGP (handled_name) ? handled_name : Qnil;
350 char *beg = SSDATA (filename);
351 char const *p = beg + SBYTES (filename);
353 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
354 #ifdef DOS_NT
355 /* only recognize drive specifier at the beginning */
356 && !(p[-1] == ':'
357 /* handle the "/:d:foo" and "/:foo" cases correctly */
358 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
359 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
360 #endif
361 ) p--;
363 if (p == beg)
364 return Qnil;
365 #ifdef DOS_NT
366 /* Expansion of "c:" to drive and default directory. */
367 Lisp_Object tem_fn;
368 USE_SAFE_ALLOCA;
369 SAFE_ALLOCA_STRING (beg, filename);
370 p = beg + (p - SSDATA (filename));
372 if (p[-1] == ':')
374 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
375 char *res = alloca (MAXPATHLEN + 1);
376 char *r = res;
378 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
380 memcpy (res, beg, 2);
381 beg += 2;
382 r += 2;
385 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
387 size_t l = strlen (res);
389 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
390 strcat (res, "/");
391 beg = res;
392 p = beg + strlen (beg);
393 dostounix_filename (beg);
394 tem_fn = make_specified_string (beg, -1, p - beg,
395 STRING_MULTIBYTE (filename));
397 else
398 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
399 STRING_MULTIBYTE (filename));
401 else if (STRING_MULTIBYTE (filename))
403 tem_fn = make_specified_string (beg, -1, p - beg, 1);
404 dostounix_filename (SSDATA (tem_fn));
405 #ifdef WINDOWSNT
406 if (!NILP (Vw32_downcase_file_names))
407 tem_fn = Fdowncase (tem_fn);
408 #endif
410 else
412 dostounix_filename (beg);
413 tem_fn = make_specified_string (beg, -1, p - beg, 0);
415 SAFE_FREE ();
416 return tem_fn;
417 #else /* DOS_NT */
418 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
419 #endif /* DOS_NT */
422 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
423 Sfile_name_nondirectory, 1, 1, 0,
424 doc: /* Return file name FILENAME sans its directory.
425 For example, in a Unix-syntax file name,
426 this is everything after the last slash,
427 or the entire name if it contains no slash. */)
428 (Lisp_Object filename)
430 register const char *beg, *p, *end;
431 Lisp_Object handler;
433 CHECK_STRING (filename);
435 /* If the file name has special constructs in it,
436 call the corresponding file handler. */
437 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
438 if (!NILP (handler))
440 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
441 filename);
442 if (STRINGP (handled_name))
443 return handled_name;
444 error ("Invalid handler in `file-name-handler-alist'");
447 beg = SSDATA (filename);
448 end = p = beg + SBYTES (filename);
450 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
451 #ifdef DOS_NT
452 /* only recognize drive specifier at beginning */
453 && !(p[-1] == ':'
454 /* handle the "/:d:foo" case correctly */
455 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
456 #endif
458 p--;
460 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
463 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
464 Sunhandled_file_name_directory, 1, 1, 0,
465 doc: /* Return a directly usable directory name somehow associated with FILENAME.
466 A `directly usable' directory name is one that may be used without the
467 intervention of any file handler.
468 If FILENAME is a directly usable file itself, return
469 \(file-name-as-directory FILENAME).
470 If FILENAME refers to a file which is not accessible from a local process,
471 then this should return nil.
472 The `call-process' and `start-process' functions use this function to
473 get a current directory to run processes in. */)
474 (Lisp_Object filename)
476 Lisp_Object handler;
478 /* If the file name has special constructs in it,
479 call the corresponding file handler. */
480 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
481 if (!NILP (handler))
483 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
484 filename);
485 return STRINGP (handled_name) ? handled_name : Qnil;
488 return Ffile_name_as_directory (filename);
491 /* Maximum number of bytes that DST will be longer than SRC
492 in file_name_as_directory. This occurs when SRCLEN == 0. */
493 enum { file_name_as_directory_slop = 2 };
495 /* Convert from file name SRC of length SRCLEN to directory name in
496 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
497 string. On UNIX, just make sure there is a terminating /. Return
498 the length of DST in bytes. */
500 static ptrdiff_t
501 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
502 bool multibyte)
504 if (srclen == 0)
506 dst[0] = '.';
507 dst[1] = '/';
508 dst[2] = '\0';
509 return 2;
512 memcpy (dst, src, srclen);
513 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
514 dst[srclen++] = DIRECTORY_SEP;
515 dst[srclen] = 0;
516 #ifdef DOS_NT
517 dostounix_filename (dst);
518 #endif
519 return srclen;
522 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
523 Sfile_name_as_directory, 1, 1, 0,
524 doc: /* Return a string representing the file name FILE interpreted as a directory.
525 This operation exists because a directory is also a file, but its name as
526 a directory is different from its name as a file.
527 The result can be used as the value of `default-directory'
528 or passed as second argument to `expand-file-name'.
529 For a Unix-syntax file name, just appends a slash unless a trailing slash
530 is already present. */)
531 (Lisp_Object file)
533 char *buf;
534 ptrdiff_t length;
535 Lisp_Object handler, val;
536 USE_SAFE_ALLOCA;
538 CHECK_STRING (file);
540 /* If the file name has special constructs in it,
541 call the corresponding file handler. */
542 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
543 if (!NILP (handler))
545 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
546 file);
547 if (STRINGP (handled_name))
548 return handled_name;
549 error ("Invalid handler in `file-name-handler-alist'");
552 #ifdef WINDOWSNT
553 if (!NILP (Vw32_downcase_file_names))
554 file = Fdowncase (file);
555 #endif
556 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
557 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
558 STRING_MULTIBYTE (file));
559 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
560 SAFE_FREE ();
561 return val;
564 /* Convert from directory name SRC of length SRCLEN to file name in
565 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
566 string. On UNIX, just make sure there isn't a terminating /.
567 Return the length of DST in bytes. */
569 static ptrdiff_t
570 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
572 /* In Unix-like systems, just remove any final slashes. However, if
573 they are all slashes, leave "/" and "//" alone, and treat "///"
574 and longer as if they were "/". */
575 if (! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
576 while (srclen > 1
577 #ifdef DOS_NT
578 && !(srclen > 2 && IS_DEVICE_SEP (src[srclen - 2]))
579 #endif
580 && IS_DIRECTORY_SEP (src[srclen - 1]))
581 srclen--;
583 memcpy (dst, src, srclen);
584 dst[srclen] = 0;
585 #ifdef DOS_NT
586 dostounix_filename (dst);
587 #endif
588 return srclen;
591 DEFUN ("directory-name-p", Fdirectory_name_p, Sdirectory_name_p, 1, 1, 0,
592 doc: /* Return non-nil if NAME ends with a directory separator character. */)
593 (Lisp_Object name)
595 CHECK_STRING (name);
596 ptrdiff_t namelen = SBYTES (name);
597 unsigned char c = namelen ? SREF (name, namelen - 1) : 0;
598 return IS_DIRECTORY_SEP (c) ? Qt : Qnil;
601 /* Return the expansion of NEWNAME, except that if NEWNAME is a
602 directory name then return the expansion of FILE's basename under
603 NEWNAME. This resembles how 'cp FILE NEWNAME' works, except that
604 it requires NEWNAME to be a directory name (typically, by ending in
605 "/"). */
607 static Lisp_Object
608 expand_cp_target (Lisp_Object file, Lisp_Object newname)
610 return (!NILP (Fdirectory_name_p (newname))
611 ? Fexpand_file_name (Ffile_name_nondirectory (file), newname)
612 : Fexpand_file_name (newname, Qnil));
615 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
616 1, 1, 0,
617 doc: /* Returns the file name of the directory named DIRECTORY.
618 This is the name of the file that holds the data for the directory DIRECTORY.
619 This operation exists because a directory is also a file, but its name as
620 a directory is different from its name as a file.
621 In Unix-syntax, this function just removes the final slash. */)
622 (Lisp_Object directory)
624 char *buf;
625 ptrdiff_t length;
626 Lisp_Object handler, val;
627 USE_SAFE_ALLOCA;
629 CHECK_STRING (directory);
631 /* If the file name has special constructs in it,
632 call the corresponding file handler. */
633 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
634 if (!NILP (handler))
636 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
637 directory);
638 if (STRINGP (handled_name))
639 return handled_name;
640 error ("Invalid handler in `file-name-handler-alist'");
643 #ifdef WINDOWSNT
644 if (!NILP (Vw32_downcase_file_names))
645 directory = Fdowncase (directory);
646 #endif
647 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
648 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
649 STRING_MULTIBYTE (directory));
650 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
651 SAFE_FREE ();
652 return val;
655 DEFUN ("make-temp-file-internal", Fmake_temp_file_internal,
656 Smake_temp_file_internal, 4, 4, 0,
657 doc: /* Generate a new file whose name starts with PREFIX, a string.
658 Return the name of the generated file. If DIR-FLAG is zero, do not
659 create the file, just its name. Otherwise, if DIR-FLAG is non-nil,
660 create an empty directory. The file name should end in SUFFIX.
661 Do not expand PREFIX; a non-absolute PREFIX is relative to the Emacs
662 working directory. If TEXT is a string, insert it into the newly
663 created file.
665 Signal an error if the file could not be created.
667 This function does not grok magic file names. */)
668 (Lisp_Object prefix, Lisp_Object dir_flag, Lisp_Object suffix,
669 Lisp_Object text)
671 CHECK_STRING (prefix);
672 CHECK_STRING (suffix);
673 Lisp_Object encoded_prefix = ENCODE_FILE (prefix);
674 Lisp_Object encoded_suffix = ENCODE_FILE (suffix);
675 ptrdiff_t prefix_len = SBYTES (encoded_prefix);
676 ptrdiff_t suffix_len = SBYTES (encoded_suffix);
677 if (INT_MAX < suffix_len)
678 args_out_of_range (prefix, suffix);
679 int nX = 6;
680 Lisp_Object val = make_uninit_string (prefix_len + nX + suffix_len);
681 char *data = SSDATA (val);
682 memcpy (data, SSDATA (encoded_prefix), prefix_len);
683 memset (data + prefix_len, 'X', nX);
684 memcpy (data + prefix_len + nX, SSDATA (encoded_suffix), suffix_len);
685 int kind = (NILP (dir_flag) ? GT_FILE
686 : EQ (dir_flag, make_number (0)) ? GT_NOCREATE
687 : GT_DIR);
688 int fd = gen_tempname (data, suffix_len, O_BINARY | O_CLOEXEC, kind);
689 bool failed = fd < 0;
690 if (!failed)
692 ptrdiff_t count = SPECPDL_INDEX ();
693 record_unwind_protect_int (close_file_unwind, fd);
694 val = DECODE_FILE (val);
695 if (STRINGP (text) && SBYTES (text) != 0)
696 write_region (text, Qnil, val, Qnil, Qnil, Qnil, Qnil, fd);
697 failed = NILP (dir_flag) && emacs_close (fd) != 0;
698 /* Discard the unwind protect. */
699 specpdl_ptr = specpdl + count;
701 if (failed)
703 static char const kind_message[][32] =
705 [GT_FILE] = "Creating file with prefix",
706 [GT_DIR] = "Creating directory with prefix",
707 [GT_NOCREATE] = "Creating file name with prefix"
709 report_file_error (kind_message[kind], prefix);
711 return val;
715 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
716 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
718 This function tries to choose a name that has no existing file.
719 For this to work, PREFIX should be an absolute file name, and PREFIX
720 and the returned string should both be non-magic.
722 There is a race condition between calling `make-temp-name' and
723 later creating the file, which opens all kinds of security holes.
724 For that reason, you should normally use `make-temp-file' instead. */)
725 (Lisp_Object prefix)
727 return Fmake_temp_file_internal (prefix, make_number (0),
728 empty_unibyte_string, Qnil);
731 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
732 doc: /* Convert filename NAME to absolute, and canonicalize it.
733 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
734 \(does not start with slash or tilde); both the directory name and
735 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
736 missing, the current buffer's value of `default-directory' is used.
737 NAME should be a string that is a valid file name for the underlying
738 filesystem.
739 File name components that are `.' are removed, and
740 so are file name components followed by `..', along with the `..' itself;
741 note that these simplifications are done without checking the resulting
742 file names in the file system.
743 Multiple consecutive slashes are collapsed into a single slash,
744 except at the beginning of the file name when they are significant (e.g.,
745 UNC file names on MS-Windows.)
746 An initial `~/' expands to your home directory.
747 An initial `~USER/' expands to USER's home directory.
748 See also the function `substitute-in-file-name'.
750 For technical reasons, this function can return correct but
751 non-intuitive results for the root directory; for instance,
752 \(expand-file-name ".." "/") returns "/..". For this reason, use
753 \(directory-file-name (file-name-directory dirname)) to traverse a
754 filesystem tree, not (expand-file-name ".." dirname). Note: make
755 sure DIRNAME in this example doesn't end in a slash, unless it's
756 the root directory. */)
757 (Lisp_Object name, Lisp_Object default_directory)
759 /* These point to SDATA and need to be careful with string-relocation
760 during GC (via DECODE_FILE). */
761 char *nm;
762 char *nmlim;
763 const char *newdir;
764 const char *newdirlim;
765 /* This should only point to alloca'd data. */
766 char *target;
768 ptrdiff_t tlen;
769 struct passwd *pw;
770 #ifdef DOS_NT
771 int drive = 0;
772 bool collapse_newdir = true;
773 bool is_escaped = 0;
774 #endif /* DOS_NT */
775 ptrdiff_t length, nbytes;
776 Lisp_Object handler, result, handled_name;
777 bool multibyte;
778 Lisp_Object hdir;
779 USE_SAFE_ALLOCA;
781 CHECK_STRING (name);
783 /* If the file name has special constructs in it,
784 call the corresponding file handler. */
785 handler = Ffind_file_name_handler (name, Qexpand_file_name);
786 if (!NILP (handler))
788 handled_name = call3 (handler, Qexpand_file_name,
789 name, default_directory);
790 if (STRINGP (handled_name))
791 return handled_name;
792 error ("Invalid handler in `file-name-handler-alist'");
796 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
797 if (NILP (default_directory))
798 default_directory = BVAR (current_buffer, directory);
799 if (! STRINGP (default_directory))
801 #ifdef DOS_NT
802 /* "/" is not considered a root directory on DOS_NT, so using "/"
803 here causes an infinite recursion in, e.g., the following:
805 (let (default-directory)
806 (expand-file-name "a"))
808 To avoid this, we set default_directory to the root of the
809 current drive. */
810 default_directory = build_string (emacs_root_dir ());
811 #else
812 default_directory = build_string ("/");
813 #endif
816 if (!NILP (default_directory))
818 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
819 if (!NILP (handler))
821 handled_name = call3 (handler, Qexpand_file_name,
822 name, default_directory);
823 if (STRINGP (handled_name))
824 return handled_name;
825 error ("Invalid handler in `file-name-handler-alist'");
830 char *o = SSDATA (default_directory);
832 /* Make sure DEFAULT_DIRECTORY is properly expanded.
833 It would be better to do this down below where we actually use
834 default_directory. Unfortunately, calling Fexpand_file_name recursively
835 could invoke GC, and the strings might be relocated. This would
836 be annoying because we have pointers into strings lying around
837 that would need adjusting, and people would add new pointers to
838 the code and forget to adjust them, resulting in intermittent bugs.
839 Putting this call here avoids all that crud.
841 The EQ test avoids infinite recursion. */
842 if (! NILP (default_directory) && !EQ (default_directory, name)
843 /* Save time in some common cases - as long as default_directory
844 is not relative, it can be canonicalized with name below (if it
845 is needed at all) without requiring it to be expanded now. */
846 #ifdef DOS_NT
847 /* Detect MSDOS file names with drive specifiers. */
848 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
849 && IS_DIRECTORY_SEP (o[2]))
850 /* Detect escaped file names without drive spec after "/:".
851 These should not be recursively expanded, to avoid
852 including the default directory twice in the expanded
853 result. */
854 && ! (o[0] == '/' && o[1] == ':')
855 #ifdef WINDOWSNT
856 /* Detect Windows file names in UNC format. */
857 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
858 #endif
859 #else /* not DOS_NT */
860 /* Detect Unix absolute file names (/... alone is not absolute on
861 DOS or Windows). */
862 && ! (IS_DIRECTORY_SEP (o[0]))
863 #endif /* not DOS_NT */
866 default_directory = Fexpand_file_name (default_directory, Qnil);
869 multibyte = STRING_MULTIBYTE (name);
870 if (multibyte != STRING_MULTIBYTE (default_directory))
872 if (multibyte)
874 unsigned char *p = SDATA (name);
876 while (*p && ASCII_CHAR_P (*p))
877 p++;
878 if (*p == '\0')
880 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
881 unibyte. Do not convert DEFAULT_DIRECTORY to
882 multibyte; instead, convert NAME to a unibyte string,
883 so that the result of this function is also a unibyte
884 string. This is needed during bootstrapping and
885 dumping, when Emacs cannot decode file names, because
886 the locale environment is not set up. */
887 name = make_unibyte_string (SSDATA (name), SBYTES (name));
888 multibyte = 0;
890 else
891 default_directory = string_to_multibyte (default_directory);
893 else
895 name = string_to_multibyte (name);
896 multibyte = 1;
900 #ifdef WINDOWSNT
901 if (!NILP (Vw32_downcase_file_names))
902 default_directory = Fdowncase (default_directory);
903 #endif
905 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
906 SAFE_ALLOCA_STRING (nm, name);
907 nmlim = nm + SBYTES (name);
909 #ifdef DOS_NT
910 /* Note if special escape prefix is present, but remove for now. */
911 if (nm[0] == '/' && nm[1] == ':')
913 is_escaped = 1;
914 nm += 2;
917 /* Find and remove drive specifier if present; this makes nm absolute
918 even if the rest of the name appears to be relative. Only look for
919 drive specifier at the beginning. */
920 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
922 drive = (unsigned char) nm[0];
923 nm += 2;
926 #ifdef WINDOWSNT
927 /* If we see "c://somedir", we want to strip the first slash after the
928 colon when stripping the drive letter. Otherwise, this expands to
929 "//somedir". */
930 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
931 nm++;
933 /* Discard any previous drive specifier if nm is now in UNC format. */
934 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
935 && !IS_DIRECTORY_SEP (nm[2]))
936 drive = 0;
937 #endif /* WINDOWSNT */
938 #endif /* DOS_NT */
940 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
941 none are found, we can probably return right away. We will avoid
942 allocating a new string if name is already fully expanded. */
943 if (
944 IS_DIRECTORY_SEP (nm[0])
945 #ifdef MSDOS
946 && drive && !is_escaped
947 #endif
948 #ifdef WINDOWSNT
949 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
950 #endif
953 /* If it turns out that the filename we want to return is just a
954 suffix of FILENAME, we don't need to go through and edit
955 things; we just need to construct a new string using data
956 starting at the middle of FILENAME. If we set LOSE, that
957 means we've discovered that we can't do that cool trick. */
958 bool lose = 0;
959 char *p = nm;
961 while (*p)
963 /* Since we know the name is absolute, we can assume that each
964 element starts with a "/". */
966 /* "." and ".." are hairy. */
967 if (IS_DIRECTORY_SEP (p[0])
968 && p[1] == '.'
969 && (IS_DIRECTORY_SEP (p[2])
970 || p[2] == 0
971 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
972 || p[3] == 0))))
973 lose = 1;
974 /* Replace multiple slashes with a single one, except
975 leave leading "//" alone. */
976 else if (IS_DIRECTORY_SEP (p[0])
977 && IS_DIRECTORY_SEP (p[1])
978 && (p != nm || IS_DIRECTORY_SEP (p[2])))
979 lose = 1;
980 p++;
982 if (!lose)
984 #ifdef DOS_NT
985 /* Make sure directories are all separated with /, but
986 avoid allocation of a new string when not required. */
987 dostounix_filename (nm);
988 #ifdef WINDOWSNT
989 if (IS_DIRECTORY_SEP (nm[1]))
991 if (strcmp (nm, SSDATA (name)) != 0)
992 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
994 else
995 #endif
996 /* Drive must be set, so this is okay. */
997 if (strcmp (nm - 2, SSDATA (name)) != 0)
999 name = make_specified_string (nm, -1, p - nm, multibyte);
1000 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1001 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1002 name = concat2 (drive_prefix, name);
1004 #ifdef WINDOWSNT
1005 if (!NILP (Vw32_downcase_file_names))
1006 name = Fdowncase (name);
1007 #endif
1008 #else /* not DOS_NT */
1009 if (strcmp (nm, SSDATA (name)) != 0)
1010 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1011 #endif /* not DOS_NT */
1012 SAFE_FREE ();
1013 return name;
1017 /* At this point, nm might or might not be an absolute file name. We
1018 need to expand ~ or ~user if present, otherwise prefix nm with
1019 default_directory if nm is not absolute, and finally collapse /./
1020 and /foo/../ sequences.
1022 We set newdir to be the appropriate prefix if one is needed:
1023 - the relevant user directory if nm starts with ~ or ~user
1024 - the specified drive's working dir (DOS/NT only) if nm does not
1025 start with /
1026 - the value of default_directory.
1028 Note that these prefixes are not guaranteed to be absolute (except
1029 for the working dir of a drive). Therefore, to ensure we always
1030 return an absolute name, if the final prefix is not absolute we
1031 append it to the current working directory. */
1033 newdir = newdirlim = 0;
1035 if (nm[0] == '~' /* prefix ~ */
1036 #ifdef DOS_NT
1037 && !is_escaped /* don't expand ~ in escaped file names */
1038 #endif
1041 if (IS_DIRECTORY_SEP (nm[1])
1042 || nm[1] == 0) /* ~ by itself */
1044 Lisp_Object tem;
1046 if (!(newdir = egetenv ("HOME")))
1047 newdir = newdirlim = "";
1048 nm++;
1049 #ifdef WINDOWSNT
1050 if (newdir[0])
1052 char newdir_utf8[MAX_UTF8_PATH];
1054 filename_from_ansi (newdir, newdir_utf8);
1055 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1056 newdir = SSDATA (tem);
1058 else
1059 #endif
1060 tem = build_string (newdir);
1061 newdirlim = newdir + SBYTES (tem);
1062 /* `egetenv' may return a unibyte string, which will bite us
1063 if we expect the directory to be multibyte. */
1064 if (multibyte && !STRING_MULTIBYTE (tem))
1066 hdir = DECODE_FILE (tem);
1067 newdir = SSDATA (hdir);
1068 newdirlim = newdir + SBYTES (hdir);
1070 #ifdef DOS_NT
1071 collapse_newdir = false;
1072 #endif
1074 else /* ~user/filename */
1076 char *o, *p;
1077 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1078 continue;
1079 o = SAFE_ALLOCA (p - nm + 1);
1080 memcpy (o, nm, p - nm);
1081 o[p - nm] = 0;
1083 block_input ();
1084 pw = getpwnam (o + 1);
1085 unblock_input ();
1086 if (pw)
1088 Lisp_Object tem;
1090 newdir = pw->pw_dir;
1091 /* `getpwnam' may return a unibyte string, which will
1092 bite us when we expect the directory to be multibyte. */
1093 tem = make_unibyte_string (newdir, strlen (newdir));
1094 newdirlim = newdir + SBYTES (tem);
1095 if (multibyte && !STRING_MULTIBYTE (tem))
1097 hdir = DECODE_FILE (tem);
1098 newdir = SSDATA (hdir);
1099 newdirlim = newdir + SBYTES (hdir);
1101 nm = p;
1102 #ifdef DOS_NT
1103 collapse_newdir = false;
1104 #endif
1107 /* If we don't find a user of that name, leave the name
1108 unchanged; don't move nm forward to p. */
1112 #ifdef DOS_NT
1113 /* On DOS and Windows, nm is absolute if a drive name was specified;
1114 use the drive's current directory as the prefix if needed. */
1115 if (!newdir && drive)
1117 /* Get default directory if needed to make nm absolute. */
1118 char *adir = NULL;
1119 if (!IS_DIRECTORY_SEP (nm[0]))
1121 adir = alloca (MAXPATHLEN + 1);
1122 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1123 adir = NULL;
1124 else if (multibyte)
1126 Lisp_Object tem = build_string (adir);
1128 tem = DECODE_FILE (tem);
1129 newdirlim = adir + SBYTES (tem);
1130 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1132 else
1133 newdirlim = adir + strlen (adir);
1135 if (!adir)
1137 /* Either nm starts with /, or drive isn't mounted. */
1138 adir = alloca (4);
1139 adir[0] = DRIVE_LETTER (drive);
1140 adir[1] = ':';
1141 adir[2] = '/';
1142 adir[3] = 0;
1143 newdirlim = adir + 3;
1145 newdir = adir;
1147 #endif /* DOS_NT */
1149 /* Finally, if no prefix has been specified and nm is not absolute,
1150 then it must be expanded relative to default_directory. */
1152 if (1
1153 #ifndef DOS_NT
1154 /* /... alone is not absolute on DOS and Windows. */
1155 && !IS_DIRECTORY_SEP (nm[0])
1156 #endif
1157 #ifdef WINDOWSNT
1158 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1159 && !IS_DIRECTORY_SEP (nm[2]))
1160 #endif
1161 && !newdir)
1163 newdir = SSDATA (default_directory);
1164 newdirlim = newdir + SBYTES (default_directory);
1165 #ifdef DOS_NT
1166 /* Note if special escape prefix is present, but remove for now. */
1167 if (newdir[0] == '/' && newdir[1] == ':')
1169 is_escaped = 1;
1170 newdir += 2;
1172 #endif
1175 #ifdef DOS_NT
1176 if (newdir)
1178 /* First ensure newdir is an absolute name. */
1179 if (
1180 /* Detect MSDOS file names with drive specifiers. */
1181 ! (IS_DRIVE (newdir[0])
1182 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1183 #ifdef WINDOWSNT
1184 /* Detect Windows file names in UNC format. */
1185 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1186 && !IS_DIRECTORY_SEP (newdir[2]))
1187 #endif
1190 /* Effectively, let newdir be (expand-file-name newdir cwd).
1191 Because of the admonition against calling expand-file-name
1192 when we have pointers into lisp strings, we accomplish this
1193 indirectly by prepending newdir to nm if necessary, and using
1194 cwd (or the wd of newdir's drive) as the new newdir. */
1195 char *adir;
1196 #ifdef WINDOWSNT
1197 const int adir_size = MAX_UTF8_PATH;
1198 #else
1199 const int adir_size = MAXPATHLEN + 1;
1200 #endif
1202 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1204 drive = (unsigned char) newdir[0];
1205 newdir += 2;
1207 if (!IS_DIRECTORY_SEP (nm[0]))
1209 ptrdiff_t nmlen = nmlim - nm;
1210 ptrdiff_t newdirlen = newdirlim - newdir;
1211 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1212 + nmlen + 1);
1213 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1214 multibyte);
1215 memcpy (tmp + dlen, nm, nmlen + 1);
1216 nm = tmp;
1217 nmlim = nm + dlen + nmlen;
1219 adir = alloca (adir_size);
1220 if (drive)
1222 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1223 strcpy (adir, "/");
1225 else
1226 getcwd (adir, adir_size);
1227 if (multibyte)
1229 Lisp_Object tem = build_string (adir);
1231 tem = DECODE_FILE (tem);
1232 newdirlim = adir + SBYTES (tem);
1233 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1235 else
1236 newdirlim = adir + strlen (adir);
1237 newdir = adir;
1240 /* Strip off drive name from prefix, if present. */
1241 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1243 drive = newdir[0];
1244 newdir += 2;
1247 /* Keep only a prefix from newdir if nm starts with slash
1248 (//server/share for UNC, nothing otherwise). */
1249 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1251 #ifdef WINDOWSNT
1252 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1253 && !IS_DIRECTORY_SEP (newdir[2]))
1255 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1256 char *p = adir + 2;
1257 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1258 p++;
1259 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1260 *p = 0;
1261 newdir = adir;
1262 newdirlim = newdir + strlen (adir);
1264 else
1265 #endif
1266 newdir = newdirlim = "";
1269 #endif /* DOS_NT */
1271 /* Ignore any slash at the end of newdir, unless newdir is
1272 just "/" or "//". */
1273 length = newdirlim - newdir;
1274 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1275 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1276 length--;
1278 /* Now concatenate the directory and name to new space in the stack frame. */
1279 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1280 eassert (tlen > file_name_as_directory_slop + 1);
1281 #ifdef DOS_NT
1282 /* Reserve space for drive specifier and escape prefix, since either
1283 or both may need to be inserted. (The Microsoft x86 compiler
1284 produces incorrect code if the following two lines are combined.) */
1285 target = alloca (tlen + 4);
1286 target += 4;
1287 #else /* not DOS_NT */
1288 target = SAFE_ALLOCA (tlen);
1289 #endif /* not DOS_NT */
1290 *target = 0;
1291 nbytes = 0;
1293 if (newdir)
1295 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1297 #ifdef DOS_NT
1298 /* If newdir is effectively "C:/", then the drive letter will have
1299 been stripped and newdir will be "/". Concatenating with an
1300 absolute directory in nm produces "//", which will then be
1301 incorrectly treated as a network share. Ignore newdir in
1302 this case (keeping the drive letter). */
1303 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1304 && newdir[1] == '\0'))
1305 #endif
1307 memcpy (target, newdir, length);
1308 target[length] = 0;
1309 nbytes = length;
1312 else
1313 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1316 memcpy (target + nbytes, nm, nmlim - nm + 1);
1318 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1319 appear. */
1321 char *p = target;
1322 char *o = target;
1324 while (*p)
1326 if (!IS_DIRECTORY_SEP (*p))
1328 *o++ = *p++;
1330 else if (p[1] == '.'
1331 && (IS_DIRECTORY_SEP (p[2])
1332 || p[2] == 0))
1334 /* If "/." is the entire filename, keep the "/". Otherwise,
1335 just delete the whole "/.". */
1336 if (o == target && p[2] == '\0')
1337 *o++ = *p;
1338 p += 2;
1340 else if (p[1] == '.' && p[2] == '.'
1341 /* `/../' is the "superroot" on certain file systems.
1342 Turned off on DOS_NT systems because they have no
1343 "superroot" and because this causes us to produce
1344 file names like "d:/../foo" which fail file-related
1345 functions of the underlying OS. (To reproduce, try a
1346 long series of "../../" in default_directory, longer
1347 than the number of levels from the root.) */
1348 #ifndef DOS_NT
1349 && o != target
1350 #endif
1351 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1353 #ifdef WINDOWSNT
1354 char *prev_o = o;
1355 #endif
1356 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1357 continue;
1358 #ifdef WINDOWSNT
1359 /* Don't go below server level in UNC filenames. */
1360 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1361 && IS_DIRECTORY_SEP (*target))
1362 o = prev_o;
1363 else
1364 #endif
1365 /* Keep initial / only if this is the whole name. */
1366 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1367 ++o;
1368 p += 3;
1370 else if (IS_DIRECTORY_SEP (p[1])
1371 && (p != target || IS_DIRECTORY_SEP (p[2])))
1372 /* Collapse multiple "/", except leave leading "//" alone. */
1373 p++;
1374 else
1376 *o++ = *p++;
1380 #ifdef DOS_NT
1381 /* At last, set drive name. */
1382 #ifdef WINDOWSNT
1383 /* Except for network file name. */
1384 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1385 #endif /* WINDOWSNT */
1387 if (!drive) emacs_abort ();
1388 target -= 2;
1389 target[0] = DRIVE_LETTER (drive);
1390 target[1] = ':';
1392 /* Reinsert the escape prefix if required. */
1393 if (is_escaped)
1395 target -= 2;
1396 target[0] = '/';
1397 target[1] = ':';
1399 result = make_specified_string (target, -1, o - target, multibyte);
1400 dostounix_filename (SSDATA (result));
1401 #ifdef WINDOWSNT
1402 if (!NILP (Vw32_downcase_file_names))
1403 result = Fdowncase (result);
1404 #endif
1405 #else /* !DOS_NT */
1406 result = make_specified_string (target, -1, o - target, multibyte);
1407 #endif /* !DOS_NT */
1410 /* Again look to see if the file name has special constructs in it
1411 and perhaps call the corresponding file handler. This is needed
1412 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1413 the ".." component gives us "/user@host:/bar/../baz" which needs
1414 to be expanded again. */
1415 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1416 if (!NILP (handler))
1418 handled_name = call3 (handler, Qexpand_file_name,
1419 result, default_directory);
1420 if (! STRINGP (handled_name))
1421 error ("Invalid handler in `file-name-handler-alist'");
1422 result = handled_name;
1425 SAFE_FREE ();
1426 return result;
1429 #if 0
1430 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1431 This is the old version of expand-file-name, before it was thoroughly
1432 rewritten for Emacs 10.31. We leave this version here commented-out,
1433 because the code is very complex and likely to have subtle bugs. If
1434 bugs _are_ found, it might be of interest to look at the old code and
1435 see what did it do in the relevant situation.
1437 Don't remove this code: it's true that it will be accessible
1438 from the repository, but a few years from deletion, people will
1439 forget it is there. */
1441 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1442 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1443 "Convert FILENAME to absolute, and canonicalize it.\n\
1444 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1445 \(does not start with slash); if DEFAULT is nil or missing,\n\
1446 the current buffer's value of default-directory is used.\n\
1447 Filenames containing `.' or `..' as components are simplified;\n\
1448 initial `~/' expands to your home directory.\n\
1449 See also the function `substitute-in-file-name'.")
1450 (name, defalt)
1451 Lisp_Object name, defalt;
1453 unsigned char *nm;
1455 register unsigned char *newdir, *p, *o;
1456 ptrdiff_t tlen;
1457 unsigned char *target;
1458 struct passwd *pw;
1460 CHECK_STRING (name);
1461 nm = SDATA (name);
1463 /* If nm is absolute, flush ...// and detect /./ and /../.
1464 If no /./ or /../ we can return right away. */
1465 if (nm[0] == '/')
1467 bool lose = 0;
1468 p = nm;
1469 while (*p)
1471 if (p[0] == '/' && p[1] == '/')
1472 nm = p + 1;
1473 if (p[0] == '/' && p[1] == '~')
1474 nm = p + 1, lose = 1;
1475 if (p[0] == '/' && p[1] == '.'
1476 && (p[2] == '/' || p[2] == 0
1477 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1478 lose = 1;
1479 p++;
1481 if (!lose)
1483 if (nm == SDATA (name))
1484 return name;
1485 return build_string (nm);
1489 /* Now determine directory to start with and put it in NEWDIR. */
1491 newdir = 0;
1493 if (nm[0] == '~') /* prefix ~ */
1494 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1496 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1497 newdir = (unsigned char *) "";
1498 nm++;
1500 else /* ~user/filename */
1502 /* Get past ~ to user. */
1503 unsigned char *user = nm + 1;
1504 /* Find end of name. */
1505 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1506 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1507 /* Copy the user name into temp storage. */
1508 o = alloca (len + 1);
1509 memcpy (o, user, len);
1510 o[len] = 0;
1512 /* Look up the user name. */
1513 block_input ();
1514 pw = (struct passwd *) getpwnam (o + 1);
1515 unblock_input ();
1516 if (!pw)
1517 error ("\"%s\" isn't a registered user", o + 1);
1519 newdir = (unsigned char *) pw->pw_dir;
1521 /* Discard the user name from NM. */
1522 nm += len;
1525 if (nm[0] != '/' && !newdir)
1527 if (NILP (defalt))
1528 defalt = current_buffer->directory;
1529 CHECK_STRING (defalt);
1530 newdir = SDATA (defalt);
1533 /* Now concatenate the directory and name to new space in the stack frame. */
1535 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1536 target = alloca (tlen);
1537 *target = 0;
1539 if (newdir)
1541 if (nm[0] == 0 || nm[0] == '/')
1542 strcpy (target, newdir);
1543 else
1544 file_name_as_directory (target, newdir);
1547 strcat (target, nm);
1549 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1551 p = target;
1552 o = target;
1554 while (*p)
1556 if (*p != '/')
1558 *o++ = *p++;
1560 else if (!strncmp (p, "//", 2)
1563 o = target;
1564 p++;
1566 else if (p[0] == '/' && p[1] == '.'
1567 && (p[2] == '/' || p[2] == 0))
1568 p += 2;
1569 else if (!strncmp (p, "/..", 3)
1570 /* `/../' is the "superroot" on certain file systems. */
1571 && o != target
1572 && (p[3] == '/' || p[3] == 0))
1574 while (o != target && *--o != '/')
1576 if (o == target && *o == '/')
1577 ++o;
1578 p += 3;
1580 else
1582 *o++ = *p++;
1586 return make_string (target, o - target);
1588 #endif
1590 /* If /~ or // appears, discard everything through first slash. */
1591 static bool
1592 file_name_absolute_p (const char *filename)
1594 return
1595 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1596 #ifdef DOS_NT
1597 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1598 && IS_DIRECTORY_SEP (filename[2]))
1599 #endif
1603 static char *
1604 search_embedded_absfilename (char *nm, char *endp)
1606 char *p, *s;
1608 for (p = nm + 1; p < endp; p++)
1610 if (IS_DIRECTORY_SEP (p[-1])
1611 && file_name_absolute_p (p)
1612 #if defined (WINDOWSNT) || defined (CYGWIN)
1613 /* // at start of file name is meaningful in Apollo,
1614 WindowsNT and Cygwin systems. */
1615 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1616 #endif /* not (WINDOWSNT || CYGWIN) */
1619 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1620 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1622 USE_SAFE_ALLOCA;
1623 char *o = SAFE_ALLOCA (s - p + 1);
1624 struct passwd *pw;
1625 memcpy (o, p, s - p);
1626 o [s - p] = 0;
1628 /* If we have ~user and `user' exists, discard
1629 everything up to ~. But if `user' does not exist, leave
1630 ~user alone, it might be a literal file name. */
1631 block_input ();
1632 pw = getpwnam (o + 1);
1633 unblock_input ();
1634 SAFE_FREE ();
1635 if (pw)
1636 return p;
1638 else
1639 return p;
1642 return NULL;
1645 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1646 Ssubstitute_in_file_name, 1, 1, 0,
1647 doc: /* Substitute environment variables referred to in FILENAME.
1648 `$FOO' where FOO is an environment variable name means to substitute
1649 the value of that variable. The variable name should be terminated
1650 with a character not a letter, digit or underscore; otherwise, enclose
1651 the entire variable name in braces.
1653 If `/~' appears, all of FILENAME through that `/' is discarded.
1654 If `//' appears, everything up to and including the first of
1655 those `/' is discarded. */)
1656 (Lisp_Object filename)
1658 char *nm, *p, *x, *endp;
1659 bool substituted = false;
1660 bool multibyte;
1661 char *xnm;
1662 Lisp_Object handler;
1664 CHECK_STRING (filename);
1666 multibyte = STRING_MULTIBYTE (filename);
1668 /* If the file name has special constructs in it,
1669 call the corresponding file handler. */
1670 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1671 if (!NILP (handler))
1673 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1674 filename);
1675 if (STRINGP (handled_name))
1676 return handled_name;
1677 error ("Invalid handler in `file-name-handler-alist'");
1680 /* Always work on a copy of the string, in case GC happens during
1681 decode of environment variables, causing the original Lisp_String
1682 data to be relocated. */
1683 USE_SAFE_ALLOCA;
1684 SAFE_ALLOCA_STRING (nm, filename);
1686 #ifdef DOS_NT
1687 dostounix_filename (nm);
1688 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1689 #endif
1690 endp = nm + SBYTES (filename);
1692 /* If /~ or // appears, discard everything through first slash. */
1693 p = search_embedded_absfilename (nm, endp);
1694 if (p)
1695 /* Start over with the new string, so we check the file-name-handler
1696 again. Important with filenames like "/home/foo//:/hello///there"
1697 which would substitute to "/:/hello///there" rather than "/there". */
1699 Lisp_Object result
1700 = (Fsubstitute_in_file_name
1701 (make_specified_string (p, -1, endp - p, multibyte)));
1702 SAFE_FREE ();
1703 return result;
1706 /* See if any variables are substituted into the string. */
1708 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1710 Lisp_Object name
1711 = (!substituted ? filename
1712 : make_specified_string (nm, -1, endp - nm, multibyte));
1713 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1714 CHECK_STRING (tmp);
1715 if (!EQ (tmp, name))
1716 substituted = true;
1717 filename = tmp;
1720 if (!substituted)
1722 #ifdef WINDOWSNT
1723 if (!NILP (Vw32_downcase_file_names))
1724 filename = Fdowncase (filename);
1725 #endif
1726 SAFE_FREE ();
1727 return filename;
1730 xnm = SSDATA (filename);
1731 x = xnm + SBYTES (filename);
1733 /* If /~ or // appears, discard everything through first slash. */
1734 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1735 /* This time we do not start over because we've already expanded envvars
1736 and replaced $$ with $. Maybe we should start over as well, but we'd
1737 need to quote some $ to $$ first. */
1738 xnm = p;
1740 #ifdef WINDOWSNT
1741 if (!NILP (Vw32_downcase_file_names))
1743 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1745 filename = Fdowncase (xname);
1747 else
1748 #endif
1749 if (xnm != SSDATA (filename))
1750 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1751 SAFE_FREE ();
1752 return filename;
1755 /* A slightly faster and more convenient way to get
1756 (directory-file-name (expand-file-name FOO)). */
1758 Lisp_Object
1759 expand_and_dir_to_file (Lisp_Object filename)
1761 Lisp_Object absname = Fexpand_file_name (filename, Qnil);
1763 /* Remove final slash, if any (unless this is the root dir).
1764 stat behaves differently depending! */
1765 if (SCHARS (absname) > 1
1766 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1767 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1768 /* We cannot take shortcuts; they might be wrong for magic file names. */
1769 absname = Fdirectory_file_name (absname);
1770 return absname;
1773 /* Signal an error if the file ABSNAME already exists.
1774 If KNOWN_TO_EXIST, the file is known to exist.
1775 QUERYSTRING is a name for the action that is being considered
1776 to alter the file.
1777 If INTERACTIVE, ask the user whether to proceed,
1778 and bypass the error if the user says to go ahead.
1779 If QUICK, ask for y or n, not yes or no. */
1781 static void
1782 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1783 const char *querystring, bool interactive,
1784 bool quick)
1786 Lisp_Object tem, encoded_filename;
1787 struct stat statbuf;
1789 encoded_filename = ENCODE_FILE (absname);
1791 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1793 if (S_ISDIR (statbuf.st_mode))
1794 xsignal2 (Qfile_error,
1795 build_string ("File is a directory"), absname);
1796 known_to_exist = true;
1799 if (known_to_exist)
1801 if (! interactive)
1802 xsignal2 (Qfile_already_exists,
1803 build_string ("File already exists"), absname);
1804 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1805 tem = CALLN (Fformat, format, absname, build_string (querystring));
1806 if (quick)
1807 tem = call1 (intern ("y-or-n-p"), tem);
1808 else
1809 tem = do_yes_or_no_p (tem);
1810 if (NILP (tem))
1811 xsignal2 (Qfile_already_exists,
1812 build_string ("File already exists"), absname);
1816 #ifndef WINDOWSNT
1817 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1818 static bool
1819 clone_file (int dest, int source)
1821 #ifdef FICLONE
1822 return ioctl (dest, FICLONE, source) == 0;
1823 #endif
1824 return false;
1826 #endif
1828 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1829 "fCopy file: \nGCopy %s to file: \np\nP",
1830 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1831 If NEWNAME is a directory name, copy FILE to a like-named file under
1832 NEWNAME. For NEWNAME to be recognized as a directory name, it should
1833 end in a slash.
1835 This function always sets the file modes of the output file to match
1836 the input file.
1838 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1839 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1840 signal a `file-already-exists' error without overwriting. If
1841 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1842 about overwriting; this is what happens in interactive use with M-x.
1843 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1844 existing file.
1846 Fourth arg KEEP-TIME non-nil means give the output file the same
1847 last-modified time as the old one. (This works on only some systems.)
1849 A prefix arg makes KEEP-TIME non-nil.
1851 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1852 FILE to NEWNAME.
1854 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1855 this includes the file modes, along with ACL entries and SELinux
1856 context if present. Otherwise, if NEWNAME is created its file
1857 permission bits are those of FILE, masked by the default file
1858 permissions. */)
1859 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1860 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1861 Lisp_Object preserve_permissions)
1863 Lisp_Object handler;
1864 ptrdiff_t count = SPECPDL_INDEX ();
1865 Lisp_Object encoded_file, encoded_newname;
1866 #if HAVE_LIBSELINUX
1867 security_context_t con;
1868 int conlength = 0;
1869 #endif
1870 #ifdef WINDOWSNT
1871 int result;
1872 #else
1873 bool already_exists = false;
1874 mode_t new_mask;
1875 int ifd, ofd;
1876 struct stat st;
1877 #endif
1879 file = Fexpand_file_name (file, Qnil);
1880 newname = expand_cp_target (file, newname);
1882 /* If the input file name has special constructs in it,
1883 call the corresponding file handler. */
1884 handler = Ffind_file_name_handler (file, Qcopy_file);
1885 /* Likewise for output file name. */
1886 if (NILP (handler))
1887 handler = Ffind_file_name_handler (newname, Qcopy_file);
1888 if (!NILP (handler))
1889 return call7 (handler, Qcopy_file, file, newname,
1890 ok_if_already_exists, keep_time, preserve_uid_gid,
1891 preserve_permissions);
1893 encoded_file = ENCODE_FILE (file);
1894 encoded_newname = ENCODE_FILE (newname);
1896 #ifdef WINDOWSNT
1897 if (NILP (ok_if_already_exists)
1898 || INTEGERP (ok_if_already_exists))
1899 barf_or_query_if_file_exists (newname, false, "copy to it",
1900 INTEGERP (ok_if_already_exists), false);
1902 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1903 !NILP (keep_time), !NILP (preserve_uid_gid),
1904 !NILP (preserve_permissions));
1905 switch (result)
1907 case -1:
1908 report_file_error ("Copying file", list2 (file, newname));
1909 case -2:
1910 report_file_error ("Copying permissions from", file);
1911 case -3:
1912 xsignal2 (Qfile_date_error,
1913 build_string ("Resetting file times"), newname);
1914 case -4:
1915 report_file_error ("Copying permissions to", newname);
1917 #else /* not WINDOWSNT */
1918 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1920 if (ifd < 0)
1921 report_file_error ("Opening input file", file);
1923 record_unwind_protect_int (close_file_unwind, ifd);
1925 if (fstat (ifd, &st) != 0)
1926 report_file_error ("Input file status", file);
1928 if (!NILP (preserve_permissions))
1930 #if HAVE_LIBSELINUX
1931 if (is_selinux_enabled ())
1933 conlength = fgetfilecon (ifd, &con);
1934 if (conlength == -1)
1935 report_file_error ("Doing fgetfilecon", file);
1937 #endif
1940 /* We can copy only regular files. */
1941 if (!S_ISREG (st.st_mode))
1942 report_file_errno ("Non-regular file", file,
1943 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1945 #ifndef MSDOS
1946 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1947 #else
1948 new_mask = S_IREAD | S_IWRITE;
1949 #endif
1951 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1952 new_mask);
1953 if (ofd < 0 && errno == EEXIST)
1955 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1956 barf_or_query_if_file_exists (newname, true, "copy to it",
1957 INTEGERP (ok_if_already_exists), false);
1958 already_exists = true;
1959 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1961 if (ofd < 0)
1962 report_file_error ("Opening output file", newname);
1964 record_unwind_protect_int (close_file_unwind, ofd);
1966 off_t oldsize = 0, newsize;
1968 if (already_exists)
1970 struct stat out_st;
1971 if (fstat (ofd, &out_st) != 0)
1972 report_file_error ("Output file status", newname);
1973 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1974 report_file_errno ("Input and output files are the same",
1975 list2 (file, newname), 0);
1976 if (S_ISREG (out_st.st_mode))
1977 oldsize = out_st.st_size;
1980 maybe_quit ();
1982 if (clone_file (ofd, ifd))
1983 newsize = st.st_size;
1984 else
1986 char buf[MAX_ALLOCA];
1987 ptrdiff_t n;
1988 for (newsize = 0; 0 < (n = emacs_read_quit (ifd, buf, sizeof buf));
1989 newsize += n)
1990 if (emacs_write_quit (ofd, buf, n) != n)
1991 report_file_error ("Write error", newname);
1992 if (n < 0)
1993 report_file_error ("Read error", file);
1996 /* Truncate any existing output file after writing the data. This
1997 is more likely to work than truncation before writing, if the
1998 file system is out of space or the user is over disk quota. */
1999 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2000 report_file_error ("Truncating output file", newname);
2002 #ifndef MSDOS
2003 /* Preserve the original file permissions, and if requested, also its
2004 owner and group. */
2006 mode_t preserved_permissions = st.st_mode & 07777;
2007 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2008 if (!NILP (preserve_uid_gid))
2010 /* Attempt to change owner and group. If that doesn't work
2011 attempt to change just the group, as that is sometimes allowed.
2012 Adjust the mode mask to eliminate setuid or setgid bits
2013 or group permissions bits that are inappropriate if the
2014 owner or group are wrong. */
2015 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2017 if (fchown (ofd, -1, st.st_gid) == 0)
2018 preserved_permissions &= ~04000;
2019 else
2021 preserved_permissions &= ~06000;
2023 /* Copy the other bits to the group bits, since the
2024 group is wrong. */
2025 preserved_permissions &= ~070;
2026 preserved_permissions |= (preserved_permissions & 7) << 3;
2027 default_permissions &= ~070;
2028 default_permissions |= (default_permissions & 7) << 3;
2033 switch (!NILP (preserve_permissions)
2034 ? qcopy_acl (SSDATA (encoded_file), ifd,
2035 SSDATA (encoded_newname), ofd,
2036 preserved_permissions)
2037 : (already_exists
2038 || (new_mask & ~realmask) == default_permissions)
2040 : fchmod (ofd, default_permissions))
2042 case -2: report_file_error ("Copying permissions from", file);
2043 case -1: report_file_error ("Copying permissions to", newname);
2046 #endif /* not MSDOS */
2048 #if HAVE_LIBSELINUX
2049 if (conlength > 0)
2051 /* Set the modified context back to the file. */
2052 bool fail = fsetfilecon (ofd, con) != 0;
2053 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
2054 if (fail && errno != ENOTSUP)
2055 report_file_error ("Doing fsetfilecon", newname);
2057 freecon (con);
2059 #endif
2061 if (!NILP (keep_time))
2063 struct timespec atime = get_stat_atime (&st);
2064 struct timespec mtime = get_stat_mtime (&st);
2065 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2066 xsignal2 (Qfile_date_error,
2067 build_string ("Cannot set file date"), newname);
2070 if (emacs_close (ofd) < 0)
2071 report_file_error ("Write error", newname);
2073 emacs_close (ifd);
2075 #ifdef MSDOS
2076 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2077 and if it can't, it tells so. Otherwise, under MSDOS we usually
2078 get only the READ bit, which will make the copied file read-only,
2079 so it's better not to chmod at all. */
2080 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2081 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2082 #endif /* MSDOS */
2083 #endif /* not WINDOWSNT */
2085 /* Discard the unwind protects. */
2086 specpdl_ptr = specpdl + count;
2088 return Qnil;
2091 DEFUN ("make-directory-internal", Fmake_directory_internal,
2092 Smake_directory_internal, 1, 1, 0,
2093 doc: /* Create a new directory named DIRECTORY. */)
2094 (Lisp_Object directory)
2096 const char *dir;
2097 Lisp_Object handler;
2098 Lisp_Object encoded_dir;
2100 CHECK_STRING (directory);
2101 directory = Fexpand_file_name (directory, Qnil);
2103 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2104 if (!NILP (handler))
2105 return call2 (handler, Qmake_directory_internal, directory);
2107 encoded_dir = ENCODE_FILE (directory);
2109 dir = SSDATA (encoded_dir);
2111 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2112 report_file_error ("Creating directory", directory);
2114 return Qnil;
2117 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2118 Sdelete_directory_internal, 1, 1, 0,
2119 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2120 (Lisp_Object directory)
2122 const char *dir;
2123 Lisp_Object encoded_dir;
2125 CHECK_STRING (directory);
2126 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2127 encoded_dir = ENCODE_FILE (directory);
2128 dir = SSDATA (encoded_dir);
2130 if (rmdir (dir) != 0)
2131 report_file_error ("Removing directory", directory);
2133 return Qnil;
2136 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2137 "(list (read-file-name \
2138 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2139 \"Move file to trash: \" \"Delete file: \") \
2140 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2141 (null current-prefix-arg))",
2142 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2143 If file has multiple names, it continues to exist with the other names.
2144 TRASH non-nil means to trash the file instead of deleting, provided
2145 `delete-by-moving-to-trash' is non-nil.
2147 When called interactively, TRASH is t if no prefix argument is given.
2148 With a prefix argument, TRASH is nil. */)
2149 (Lisp_Object filename, Lisp_Object trash)
2151 Lisp_Object handler;
2152 Lisp_Object encoded_file;
2154 if (!NILP (Ffile_directory_p (filename))
2155 && NILP (Ffile_symlink_p (filename)))
2156 xsignal2 (Qfile_error,
2157 build_string ("Removing old name: is a directory"),
2158 filename);
2159 filename = Fexpand_file_name (filename, Qnil);
2161 handler = Ffind_file_name_handler (filename, Qdelete_file);
2162 if (!NILP (handler))
2163 return call3 (handler, Qdelete_file, filename, trash);
2165 if (delete_by_moving_to_trash && !NILP (trash))
2166 return call1 (Qmove_file_to_trash, filename);
2168 encoded_file = ENCODE_FILE (filename);
2170 if (unlink (SSDATA (encoded_file)) != 0 && errno != ENOENT)
2171 report_file_error ("Removing old name", filename);
2172 return Qnil;
2175 static Lisp_Object
2176 internal_delete_file_1 (Lisp_Object ignore)
2178 return Qt;
2181 /* Delete file FILENAME, returning true if successful.
2182 This ignores `delete-by-moving-to-trash'. */
2184 bool
2185 internal_delete_file (Lisp_Object filename)
2187 Lisp_Object tem;
2189 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2190 Qt, internal_delete_file_1);
2191 return NILP (tem);
2194 /* Filesystems are case-sensitive on all supported systems except
2195 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2196 case-insensitive on the first two, but they may or may not be
2197 case-insensitive on Cygwin and OS X. The following function
2198 attempts to provide a runtime test on those two systems. If the
2199 test is not conclusive, we assume case-insensitivity on Cygwin and
2200 case-sensitivity on Mac OS X.
2202 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2203 NFS-mounted Windows volumes, might be case-insensitive. Can we
2204 detect this? */
2206 static bool
2207 file_name_case_insensitive_p (const char *filename)
2209 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2210 those flags are available. As of this writing (2017-05-20),
2211 Cygwin is the only platform known to support the former (starting
2212 with Cygwin-2.6.1), and macOS is the only platform known to
2213 support the latter. */
2215 #ifdef _PC_CASE_INSENSITIVE
2216 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2217 if (res >= 0)
2218 return res > 0;
2219 #elif defined _PC_CASE_SENSITIVE
2220 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2221 if (res >= 0)
2222 return res == 0;
2223 #endif
2225 #if defined CYGWIN || defined DOS_NT
2226 return true;
2227 #else
2228 return false;
2229 #endif
2232 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2233 Sfile_name_case_insensitive_p, 1, 1, 0,
2234 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2235 The arg must be a string. */)
2236 (Lisp_Object filename)
2238 Lisp_Object handler;
2240 CHECK_STRING (filename);
2241 filename = Fexpand_file_name (filename, Qnil);
2243 /* If the file name has special constructs in it,
2244 call the corresponding file handler. */
2245 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2246 if (!NILP (handler))
2247 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2249 filename = ENCODE_FILE (filename);
2250 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2253 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2254 "fRename file: \nGRename %s to file: \np",
2255 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2256 If file has names other than FILE, it continues to have those names.
2257 If NEWNAME is a directory name, rename FILE to a like-named file under
2258 NEWNAME. For NEWNAME to be recognized as a directory name, it should
2259 end in a slash.
2261 Signal a `file-already-exists' error if a file NEWNAME already exists
2262 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2263 An integer third arg means request confirmation if NEWNAME already exists.
2264 This is what happens in interactive use with M-x. */)
2265 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2267 Lisp_Object handler;
2268 Lisp_Object encoded_file, encoded_newname;
2270 file = Fexpand_file_name (file, Qnil);
2272 /* If the filesystem is case-insensitive and the file names are
2273 identical but for case, treat it as a change-case request, and do
2274 not worry whether NEWNAME exists or whether it is a directory, as
2275 it is already another name for FILE. */
2276 bool case_only_rename = false;
2277 #if defined CYGWIN || defined DOS_NT
2278 if (!NILP (Ffile_name_case_insensitive_p (file)))
2280 newname = Fexpand_file_name (newname, Qnil);
2281 case_only_rename = !NILP (Fstring_equal (Fdowncase (file),
2282 Fdowncase (newname)));
2284 #endif
2286 if (!case_only_rename)
2287 newname = expand_cp_target (Fdirectory_file_name (file), newname);
2289 /* If the file name has special constructs in it,
2290 call the corresponding file handler. */
2291 handler = Ffind_file_name_handler (file, Qrename_file);
2292 if (NILP (handler))
2293 handler = Ffind_file_name_handler (newname, Qrename_file);
2294 if (!NILP (handler))
2295 return call4 (handler, Qrename_file,
2296 file, newname, ok_if_already_exists);
2298 encoded_file = ENCODE_FILE (file);
2299 encoded_newname = ENCODE_FILE (newname);
2301 bool plain_rename = (case_only_rename
2302 || (!NILP (ok_if_already_exists)
2303 && !INTEGERP (ok_if_already_exists)));
2304 int rename_errno UNINIT;
2305 if (!plain_rename)
2307 if (renameat_noreplace (AT_FDCWD, SSDATA (encoded_file),
2308 AT_FDCWD, SSDATA (encoded_newname))
2309 == 0)
2310 return Qnil;
2312 rename_errno = errno;
2313 switch (rename_errno)
2315 case EEXIST: case EINVAL: case ENOSYS:
2316 #if ENOSYS != ENOTSUP
2317 case ENOTSUP:
2318 #endif
2319 barf_or_query_if_file_exists (newname, rename_errno == EEXIST,
2320 "rename to it",
2321 INTEGERP (ok_if_already_exists),
2322 false);
2323 plain_rename = true;
2324 break;
2328 if (plain_rename)
2330 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2331 return Qnil;
2332 rename_errno = errno;
2333 /* Don't prompt again. */
2334 ok_if_already_exists = Qt;
2336 else if (!NILP (ok_if_already_exists))
2337 ok_if_already_exists = Qt;
2339 if (rename_errno != EXDEV)
2340 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2342 struct stat file_st;
2343 bool dirp = !NILP (Fdirectory_name_p (file));
2344 if (!dirp)
2346 if (lstat (SSDATA (encoded_file), &file_st) != 0)
2347 report_file_error ("Renaming", list2 (file, newname));
2348 dirp = S_ISDIR (file_st.st_mode) != 0;
2350 if (dirp)
2351 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2352 else
2354 Lisp_Object symlink_target
2355 = (S_ISLNK (file_st.st_mode)
2356 ? emacs_readlinkat (AT_FDCWD, SSDATA (encoded_file))
2357 : Qnil);
2358 if (!NILP (symlink_target))
2359 Fmake_symbolic_link (symlink_target, newname, ok_if_already_exists);
2360 else
2361 Fcopy_file (file, newname, ok_if_already_exists, Qt, Qt, Qt);
2364 ptrdiff_t count = SPECPDL_INDEX ();
2365 specbind (Qdelete_by_moving_to_trash, Qnil);
2366 if (dirp)
2367 call2 (Qdelete_directory, file, Qt);
2368 else
2369 Fdelete_file (file, Qnil);
2370 return unbind_to (count, Qnil);
2373 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2374 "fAdd name to file: \nGName to add to %s: \np",
2375 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2376 If NEWNAME is a directory name, give FILE a like-named new name under
2377 NEWNAME.
2379 Signal a `file-already-exists' error if a file NEWNAME already exists
2380 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2381 An integer third arg means request confirmation if NEWNAME already exists.
2382 This is what happens in interactive use with M-x. */)
2383 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2385 Lisp_Object handler;
2386 Lisp_Object encoded_file, encoded_newname;
2388 file = Fexpand_file_name (file, Qnil);
2389 newname = expand_cp_target (file, newname);
2391 /* If the file name has special constructs in it,
2392 call the corresponding file handler. */
2393 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2394 if (!NILP (handler))
2395 return call4 (handler, Qadd_name_to_file, file,
2396 newname, ok_if_already_exists);
2398 /* If the new name has special constructs in it,
2399 call the corresponding file handler. */
2400 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2401 if (!NILP (handler))
2402 return call4 (handler, Qadd_name_to_file, file,
2403 newname, ok_if_already_exists);
2405 encoded_file = ENCODE_FILE (file);
2406 encoded_newname = ENCODE_FILE (newname);
2408 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2409 return Qnil;
2411 if (errno == EEXIST)
2413 if (NILP (ok_if_already_exists)
2414 || INTEGERP (ok_if_already_exists))
2415 barf_or_query_if_file_exists (newname, true, "make it a new name",
2416 INTEGERP (ok_if_already_exists), false);
2417 unlink (SSDATA (newname));
2418 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2419 return Qnil;
2422 report_file_error ("Adding new name", list2 (file, newname));
2425 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2426 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2427 doc: /* Make a symbolic link to TARGET, named NEWNAME.
2428 If NEWNAME is a directory name, make a like-named symbolic link under
2429 NEWNAME.
2431 Signal a `file-already-exists' error if a file NEWNAME already exists
2432 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2433 An integer third arg means request confirmation if NEWNAME already
2434 exists, and expand leading "~" or strip leading "/:" in TARGET.
2435 This happens for interactive use with M-x. */)
2436 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2438 Lisp_Object handler;
2439 Lisp_Object encoded_target, encoded_linkname;
2441 CHECK_STRING (target);
2442 if (INTEGERP (ok_if_already_exists))
2444 if (SREF (target, 0) == '~')
2445 target = Fexpand_file_name (target, Qnil);
2446 else if (SREF (target, 0) == '/' && SREF (target, 1) == ':')
2447 target = Fsubstring_no_properties (target, make_number (2), Qnil);
2449 linkname = expand_cp_target (target, linkname);
2451 /* If the new link name has special constructs in it,
2452 call the corresponding file handler. */
2453 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2454 if (!NILP (handler))
2455 return call4 (handler, Qmake_symbolic_link, target,
2456 linkname, ok_if_already_exists);
2458 encoded_target = ENCODE_FILE (target);
2459 encoded_linkname = ENCODE_FILE (linkname);
2461 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2462 return Qnil;
2464 if (errno == ENOSYS)
2465 xsignal1 (Qfile_error,
2466 build_string ("Symbolic links are not supported"));
2468 if (errno == EEXIST)
2470 if (NILP (ok_if_already_exists)
2471 || INTEGERP (ok_if_already_exists))
2472 barf_or_query_if_file_exists (linkname, true, "make it a link",
2473 INTEGERP (ok_if_already_exists), false);
2474 unlink (SSDATA (encoded_linkname));
2475 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2476 return Qnil;
2479 report_file_error ("Making symbolic link", list2 (target, linkname));
2483 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2484 1, 1, 0,
2485 doc: /* Return t if FILENAME is an absolute file name or starts with `~'.
2486 On Unix, absolute file names start with `/'. */)
2487 (Lisp_Object filename)
2489 CHECK_STRING (filename);
2490 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2493 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2494 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2495 See also `file-readable-p' and `file-attributes'.
2496 This returns nil for a symlink to a nonexistent file.
2497 Use `file-symlink-p' to test for such links. */)
2498 (Lisp_Object filename)
2500 Lisp_Object absname;
2501 Lisp_Object handler;
2503 CHECK_STRING (filename);
2504 absname = Fexpand_file_name (filename, Qnil);
2506 /* If the file name has special constructs in it,
2507 call the corresponding file handler. */
2508 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2509 if (!NILP (handler))
2511 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2512 errno = 0;
2513 return result;
2516 absname = ENCODE_FILE (absname);
2518 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2521 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2522 doc: /* Return t if FILENAME can be executed by you.
2523 For a directory, this means you can access files in that directory.
2524 \(It is generally better to use `file-accessible-directory-p' for that
2525 purpose, though.) */)
2526 (Lisp_Object filename)
2528 Lisp_Object absname;
2529 Lisp_Object handler;
2531 CHECK_STRING (filename);
2532 absname = Fexpand_file_name (filename, Qnil);
2534 /* If the file name has special constructs in it,
2535 call the corresponding file handler. */
2536 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2537 if (!NILP (handler))
2538 return call2 (handler, Qfile_executable_p, absname);
2540 absname = ENCODE_FILE (absname);
2542 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2545 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2546 doc: /* Return t if file FILENAME exists and you can read it.
2547 See also `file-exists-p' and `file-attributes'. */)
2548 (Lisp_Object filename)
2550 Lisp_Object absname;
2551 Lisp_Object handler;
2553 CHECK_STRING (filename);
2554 absname = Fexpand_file_name (filename, Qnil);
2556 /* If the file name has special constructs in it,
2557 call the corresponding file handler. */
2558 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2559 if (!NILP (handler))
2560 return call2 (handler, Qfile_readable_p, absname);
2562 absname = ENCODE_FILE (absname);
2563 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2564 ? Qt : Qnil);
2567 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2568 doc: /* Return t if file FILENAME can be written or created by you. */)
2569 (Lisp_Object filename)
2571 Lisp_Object absname, dir, encoded;
2572 Lisp_Object handler;
2574 CHECK_STRING (filename);
2575 absname = Fexpand_file_name (filename, Qnil);
2577 /* If the file name has special constructs in it,
2578 call the corresponding file handler. */
2579 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2580 if (!NILP (handler))
2581 return call2 (handler, Qfile_writable_p, absname);
2583 encoded = ENCODE_FILE (absname);
2584 if (check_writable (SSDATA (encoded), W_OK))
2585 return Qt;
2586 if (errno != ENOENT)
2587 return Qnil;
2589 dir = Ffile_name_directory (absname);
2590 eassert (!NILP (dir));
2591 #ifdef MSDOS
2592 dir = Fdirectory_file_name (dir);
2593 #endif /* MSDOS */
2595 dir = ENCODE_FILE (dir);
2596 #ifdef WINDOWSNT
2597 /* The read-only attribute of the parent directory doesn't affect
2598 whether a file or directory can be created within it. Some day we
2599 should check ACLs though, which do affect this. */
2600 return file_directory_p (dir) ? Qt : Qnil;
2601 #else
2602 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2603 #endif
2606 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2607 doc: /* Access file FILENAME, and get an error if that does not work.
2608 The second argument STRING is prepended to the error message.
2609 If there is no error, returns nil. */)
2610 (Lisp_Object filename, Lisp_Object string)
2612 Lisp_Object handler, encoded_filename, absname;
2614 CHECK_STRING (filename);
2615 absname = Fexpand_file_name (filename, Qnil);
2617 CHECK_STRING (string);
2619 /* If the file name has special constructs in it,
2620 call the corresponding file handler. */
2621 handler = Ffind_file_name_handler (absname, Qaccess_file);
2622 if (!NILP (handler))
2623 return call3 (handler, Qaccess_file, absname, string);
2625 encoded_filename = ENCODE_FILE (absname);
2627 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2628 report_file_error (SSDATA (string), filename);
2630 return Qnil;
2633 /* Relative to directory FD, return the symbolic link value of FILENAME.
2634 On failure, return nil. */
2635 Lisp_Object
2636 emacs_readlinkat (int fd, char const *filename)
2638 static struct allocator const emacs_norealloc_allocator =
2639 { xmalloc, NULL, xfree, memory_full };
2640 Lisp_Object val;
2641 char readlink_buf[1024];
2642 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2643 &emacs_norealloc_allocator, readlinkat);
2644 if (!buf)
2645 return Qnil;
2647 val = build_unibyte_string (buf);
2648 if (buf != readlink_buf)
2649 xfree (buf);
2650 val = DECODE_FILE (val);
2651 return val;
2654 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2655 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2656 The value is the link target, as a string.
2657 Otherwise it returns nil.
2659 This function does not check whether the link target exists. */)
2660 (Lisp_Object filename)
2662 Lisp_Object handler;
2664 CHECK_STRING (filename);
2665 filename = Fexpand_file_name (filename, Qnil);
2667 /* If the file name has special constructs in it,
2668 call the corresponding file handler. */
2669 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2670 if (!NILP (handler))
2671 return call2 (handler, Qfile_symlink_p, filename);
2673 filename = ENCODE_FILE (filename);
2675 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2678 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2679 doc: /* Return t if FILENAME names an existing directory.
2680 Symbolic links to directories count as directories.
2681 See `file-symlink-p' to distinguish symlinks. */)
2682 (Lisp_Object filename)
2684 Lisp_Object absname = expand_and_dir_to_file (filename);
2686 /* If the file name has special constructs in it,
2687 call the corresponding file handler. */
2688 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2689 if (!NILP (handler))
2690 return call2 (handler, Qfile_directory_p, absname);
2692 absname = ENCODE_FILE (absname);
2694 return file_directory_p (absname) ? Qt : Qnil;
2697 /* Return true if FILE is a directory or a symlink to a directory.
2698 Otherwise return false and set errno. */
2699 bool
2700 file_directory_p (Lisp_Object file)
2702 #ifdef DOS_NT
2703 /* This is cheaper than 'stat'. */
2704 return faccessat (AT_FDCWD, SSDATA (file), D_OK, AT_EACCESS) == 0;
2705 #else
2706 # ifdef O_PATH
2707 /* Use O_PATH if available, as it avoids races and EOVERFLOW issues. */
2708 int fd = openat (AT_FDCWD, SSDATA (file), O_PATH | O_CLOEXEC | O_DIRECTORY);
2709 if (0 <= fd)
2711 emacs_close (fd);
2712 return true;
2714 if (errno != EINVAL)
2715 return false;
2716 /* O_PATH is defined but evidently this Linux kernel predates 2.6.39.
2717 Fall back on generic POSIX code. */
2718 # endif
2719 /* Use file_accessible_directory, as it avoids stat EOVERFLOW
2720 problems and could be cheaper. However, if it fails because FILE
2721 is inaccessible, fall back on stat; if the latter fails with
2722 EOVERFLOW then FILE must have been a directory unless a race
2723 condition occurred (a problem hard to work around portably). */
2724 if (file_accessible_directory_p (file))
2725 return true;
2726 if (errno != EACCES)
2727 return false;
2728 struct stat st;
2729 if (stat (SSDATA (file), &st) != 0)
2730 return errno == EOVERFLOW;
2731 if (S_ISDIR (st.st_mode))
2732 return true;
2733 errno = ENOTDIR;
2734 return false;
2735 #endif
2738 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2739 Sfile_accessible_directory_p, 1, 1, 0,
2740 doc: /* Return t if FILENAME names a directory you can open.
2741 For the value to be t, FILENAME must specify the name of a directory
2742 as a file, and the directory must allow you to open files in it. In
2743 order to use a directory as a buffer's current directory, this
2744 predicate must return true. A directory name spec may be given
2745 instead; then the value is t if the directory so specified exists and
2746 really is a readable and searchable directory. */)
2747 (Lisp_Object filename)
2749 Lisp_Object absname;
2750 Lisp_Object handler;
2752 CHECK_STRING (filename);
2753 absname = Fexpand_file_name (filename, Qnil);
2755 /* If the file name has special constructs in it,
2756 call the corresponding file handler. */
2757 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2758 if (!NILP (handler))
2760 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2762 /* Set errno in case the handler failed. EACCES might be a lie
2763 (e.g., the directory might not exist, or be a regular file),
2764 but at least it does TRT in the "usual" case of an existing
2765 directory that is not accessible by the current user, and
2766 avoids reporting "Success" for a failed operation. Perhaps
2767 someday we can fix this in a better way, by improving
2768 file-accessible-directory-p's API; see Bug#25419. */
2769 if (!EQ (r, Qt))
2770 errno = EACCES;
2772 return r;
2775 absname = ENCODE_FILE (absname);
2776 return file_accessible_directory_p (absname) ? Qt : Qnil;
2779 /* If FILE is a searchable directory or a symlink to a
2780 searchable directory, return true. Otherwise return
2781 false and set errno to an error number. */
2782 bool
2783 file_accessible_directory_p (Lisp_Object file)
2785 #ifdef DOS_NT
2786 # ifdef WINDOWSNT
2787 /* We need a special-purpose test because (a) NTFS security data is
2788 not reflected in Posix-style mode bits, and (b) the trick with
2789 accessing "DIR/.", used below on Posix hosts, doesn't work on
2790 Windows, because "DIR/." is normalized to just "DIR" before
2791 hitting the disk. */
2792 return (SBYTES (file) == 0
2793 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2794 # else /* MSDOS */
2795 return file_directory_p (file);
2796 # endif /* MSDOS */
2797 #else /* !DOS_NT */
2798 /* On POSIXish platforms, use just one system call; this avoids a
2799 race and is typically faster. */
2800 const char *data = SSDATA (file);
2801 ptrdiff_t len = SBYTES (file);
2802 char const *dir;
2803 bool ok;
2804 int saved_errno;
2805 USE_SAFE_ALLOCA;
2807 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2808 There are three exceptions: "", "/", and "//". Leave "" alone,
2809 as it's invalid. Append only "." to the other two exceptions as
2810 "/" and "//" are distinct on some platforms, whereas "/", "///",
2811 "////", etc. are all equivalent. */
2812 if (! len)
2813 dir = data;
2814 else
2816 /* Just check for trailing '/' when deciding whether append '/'
2817 before appending '.'. That's simpler than testing the two
2818 special cases "/" and "//", and it's a safe optimization
2819 here. After appending '.', append another '/' to work around
2820 a macOS bug (Bug#30350). */
2821 static char const appended[] = "/./";
2822 char *buf = SAFE_ALLOCA (len + sizeof appended);
2823 memcpy (buf, data, len);
2824 strcpy (buf + len, &appended[data[len - 1] == '/']);
2825 dir = buf;
2828 ok = check_existing (dir);
2829 saved_errno = errno;
2830 SAFE_FREE ();
2831 errno = saved_errno;
2832 return ok;
2833 #endif /* !DOS_NT */
2836 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2837 doc: /* Return t if FILENAME names a regular file.
2838 This is the sort of file that holds an ordinary stream of data bytes.
2839 Symbolic links to regular files count as regular files.
2840 See `file-symlink-p' to distinguish symlinks. */)
2841 (Lisp_Object filename)
2843 struct stat st;
2844 Lisp_Object absname = expand_and_dir_to_file (filename);
2846 /* If the file name has special constructs in it,
2847 call the corresponding file handler. */
2848 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2849 if (!NILP (handler))
2850 return call2 (handler, Qfile_regular_p, absname);
2852 absname = ENCODE_FILE (absname);
2854 #ifdef WINDOWSNT
2856 int result;
2857 Lisp_Object tem = Vw32_get_true_file_attributes;
2859 /* Tell stat to use expensive method to get accurate info. */
2860 Vw32_get_true_file_attributes = Qt;
2861 result = stat (SSDATA (absname), &st);
2862 Vw32_get_true_file_attributes = tem;
2864 if (result < 0)
2865 return Qnil;
2866 return S_ISREG (st.st_mode) ? Qt : Qnil;
2868 #else
2869 if (stat (SSDATA (absname), &st) < 0)
2870 return Qnil;
2871 return S_ISREG (st.st_mode) ? Qt : Qnil;
2872 #endif
2875 DEFUN ("file-selinux-context", Ffile_selinux_context,
2876 Sfile_selinux_context, 1, 1, 0,
2877 doc: /* Return SELinux context of file named FILENAME.
2878 The return value is a list (USER ROLE TYPE RANGE), where the list
2879 elements are strings naming the user, role, type, and range of the
2880 file's SELinux security context.
2882 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2883 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2884 (Lisp_Object filename)
2886 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2887 Lisp_Object absname = expand_and_dir_to_file (filename);
2889 /* If the file name has special constructs in it,
2890 call the corresponding file handler. */
2891 Lisp_Object handler = Ffind_file_name_handler (absname,
2892 Qfile_selinux_context);
2893 if (!NILP (handler))
2894 return call2 (handler, Qfile_selinux_context, absname);
2896 absname = ENCODE_FILE (absname);
2898 #if HAVE_LIBSELINUX
2899 if (is_selinux_enabled ())
2901 security_context_t con;
2902 int conlength = lgetfilecon (SSDATA (absname), &con);
2903 if (conlength > 0)
2905 context_t context = context_new (con);
2906 if (context_user_get (context))
2907 user = build_string (context_user_get (context));
2908 if (context_role_get (context))
2909 role = build_string (context_role_get (context));
2910 if (context_type_get (context))
2911 type = build_string (context_type_get (context));
2912 if (context_range_get (context))
2913 range = build_string (context_range_get (context));
2914 context_free (context);
2915 freecon (con);
2918 #endif
2920 return list4 (user, role, type, range);
2923 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2924 Sset_file_selinux_context, 2, 2, 0,
2925 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2926 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2927 elements are strings naming the components of a SELinux context.
2929 Value is t if setting of SELinux context was successful, nil otherwise.
2931 This function does nothing and returns nil if SELinux is disabled,
2932 or if Emacs was not compiled with SELinux support. */)
2933 (Lisp_Object filename, Lisp_Object context)
2935 Lisp_Object absname;
2936 Lisp_Object handler;
2937 #if HAVE_LIBSELINUX
2938 Lisp_Object encoded_absname;
2939 Lisp_Object user = CAR_SAFE (context);
2940 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2941 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2942 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2943 security_context_t con;
2944 bool fail;
2945 int conlength;
2946 context_t parsed_con;
2947 #endif
2949 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2951 /* If the file name has special constructs in it,
2952 call the corresponding file handler. */
2953 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2954 if (!NILP (handler))
2955 return call3 (handler, Qset_file_selinux_context, absname, context);
2957 #if HAVE_LIBSELINUX
2958 if (is_selinux_enabled ())
2960 /* Get current file context. */
2961 encoded_absname = ENCODE_FILE (absname);
2962 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2963 if (conlength > 0)
2965 parsed_con = context_new (con);
2966 /* Change the parts defined in the parameter.*/
2967 if (STRINGP (user))
2969 if (context_user_set (parsed_con, SSDATA (user)))
2970 error ("Doing context_user_set");
2972 if (STRINGP (role))
2974 if (context_role_set (parsed_con, SSDATA (role)))
2975 error ("Doing context_role_set");
2977 if (STRINGP (type))
2979 if (context_type_set (parsed_con, SSDATA (type)))
2980 error ("Doing context_type_set");
2982 if (STRINGP (range))
2984 if (context_range_set (parsed_con, SSDATA (range)))
2985 error ("Doing context_range_set");
2988 /* Set the modified context back to the file. */
2989 fail = (lsetfilecon (SSDATA (encoded_absname),
2990 context_str (parsed_con))
2991 != 0);
2992 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
2993 if (fail && errno != ENOTSUP)
2994 report_file_error ("Doing lsetfilecon", absname);
2996 context_free (parsed_con);
2997 freecon (con);
2998 return fail ? Qnil : Qt;
3000 else
3001 report_file_error ("Doing lgetfilecon", absname);
3003 #endif
3005 return Qnil;
3008 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
3009 doc: /* Return ACL entries of file named FILENAME.
3010 The entries are returned in a format suitable for use in `set-file-acl'
3011 but is otherwise undocumented and subject to change.
3012 Return nil if file does not exist or is not accessible, or if Emacs
3013 was unable to determine the ACL entries. */)
3014 (Lisp_Object filename)
3016 Lisp_Object acl_string = Qnil;
3018 #if USE_ACL
3019 Lisp_Object absname = expand_and_dir_to_file (filename);
3021 /* If the file name has special constructs in it,
3022 call the corresponding file handler. */
3023 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_acl);
3024 if (!NILP (handler))
3025 return call2 (handler, Qfile_acl, absname);
3027 # ifdef HAVE_ACL_SET_FILE
3028 absname = ENCODE_FILE (absname);
3030 # ifndef HAVE_ACL_TYPE_EXTENDED
3031 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
3032 # endif
3033 acl_t acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3034 if (acl == NULL)
3035 return Qnil;
3037 char *str = acl_to_text (acl, NULL);
3038 if (str == NULL)
3040 acl_free (acl);
3041 return Qnil;
3044 acl_string = build_string (str);
3045 acl_free (str);
3046 acl_free (acl);
3047 # endif
3048 #endif
3050 return acl_string;
3053 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3054 2, 2, 0,
3055 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3056 ACL-STRING should contain the textual representation of the ACL
3057 entries in a format suitable for the platform.
3059 Value is t if setting of ACL was successful, nil otherwise.
3061 Setting ACL for local files requires Emacs to be built with ACL
3062 support. */)
3063 (Lisp_Object filename, Lisp_Object acl_string)
3065 #if USE_ACL
3066 Lisp_Object absname;
3067 Lisp_Object handler;
3068 # ifdef HAVE_ACL_SET_FILE
3069 Lisp_Object encoded_absname;
3070 acl_t acl;
3071 bool fail;
3072 # endif
3074 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3076 /* If the file name has special constructs in it,
3077 call the corresponding file handler. */
3078 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3079 if (!NILP (handler))
3080 return call3 (handler, Qset_file_acl, absname, acl_string);
3082 # ifdef HAVE_ACL_SET_FILE
3083 if (STRINGP (acl_string))
3085 acl = acl_from_text (SSDATA (acl_string));
3086 if (acl == NULL)
3088 if (acl_errno_valid (errno))
3089 report_file_error ("Converting ACL", absname);
3090 return Qnil;
3093 encoded_absname = ENCODE_FILE (absname);
3095 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3096 acl)
3097 != 0);
3098 if (fail && acl_errno_valid (errno))
3099 report_file_error ("Setting ACL", absname);
3101 acl_free (acl);
3102 return fail ? Qnil : Qt;
3104 # endif
3105 #endif
3107 return Qnil;
3110 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3111 doc: /* Return mode bits of file named FILENAME, as an integer.
3112 Return nil, if file does not exist or is not accessible. */)
3113 (Lisp_Object filename)
3115 struct stat st;
3116 Lisp_Object absname = expand_and_dir_to_file (filename);
3118 /* If the file name has special constructs in it,
3119 call the corresponding file handler. */
3120 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_modes);
3121 if (!NILP (handler))
3122 return call2 (handler, Qfile_modes, absname);
3124 absname = ENCODE_FILE (absname);
3126 if (stat (SSDATA (absname), &st) < 0)
3127 return Qnil;
3129 return make_number (st.st_mode & 07777);
3132 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3133 "(let ((file (read-file-name \"File: \"))) \
3134 (list file (read-file-modes nil file)))",
3135 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3136 Only the 12 low bits of MODE are used.
3138 Interactively, mode bits are read by `read-file-modes', which accepts
3139 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3140 (Lisp_Object filename, Lisp_Object mode)
3142 Lisp_Object absname, encoded_absname;
3143 Lisp_Object handler;
3145 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3146 CHECK_NUMBER (mode);
3148 /* If the file name has special constructs in it,
3149 call the corresponding file handler. */
3150 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3151 if (!NILP (handler))
3152 return call3 (handler, Qset_file_modes, absname, mode);
3154 encoded_absname = ENCODE_FILE (absname);
3156 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3157 report_file_error ("Doing chmod", absname);
3159 return Qnil;
3162 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3163 doc: /* Set the file permission bits for newly created files.
3164 The argument MODE should be an integer; only the low 9 bits are used.
3165 On Posix hosts, this setting is inherited by subprocesses.
3167 This function works by setting the Emacs's file mode creation mask.
3168 Each bit that is set in the mask means that the corresponding bit
3169 in the permissions of newly created files will be disabled.
3171 Note that when `write-region' creates a file, it resets the
3172 execute bit, even if the mask set by this function allows that bit
3173 by having the corresponding bit in the mask reset. */)
3174 (Lisp_Object mode)
3176 mode_t oldrealmask, oldumask, newumask;
3177 CHECK_NUMBER (mode);
3178 oldrealmask = realmask;
3179 newumask = ~ XINT (mode) & 0777;
3181 block_input ();
3182 realmask = newumask;
3183 oldumask = umask (newumask);
3184 unblock_input ();
3186 eassert (oldumask == oldrealmask);
3187 return Qnil;
3190 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3191 doc: /* Return the default file protection for created files.
3192 The value is an integer. */)
3193 (void)
3195 Lisp_Object value;
3196 XSETINT (value, (~ realmask) & 0777);
3197 return value;
3201 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3202 doc: /* Set times of file FILENAME to TIMESTAMP.
3203 Set both access and modification times.
3204 Return t on success, else nil.
3205 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3206 `current-time'. */)
3207 (Lisp_Object filename, Lisp_Object timestamp)
3209 Lisp_Object absname, encoded_absname;
3210 Lisp_Object handler;
3211 struct timespec t = lisp_time_argument (timestamp);
3213 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3215 /* If the file name has special constructs in it,
3216 call the corresponding file handler. */
3217 handler = Ffind_file_name_handler (absname, Qset_file_times);
3218 if (!NILP (handler))
3219 return call3 (handler, Qset_file_times, absname, timestamp);
3221 encoded_absname = ENCODE_FILE (absname);
3224 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3226 #ifdef MSDOS
3227 /* Setting times on a directory always fails. */
3228 if (file_directory_p (encoded_absname))
3229 return Qnil;
3230 #endif
3231 report_file_error ("Setting file times", absname);
3235 return Qt;
3238 #ifdef HAVE_SYNC
3239 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3240 doc: /* Tell Unix to finish all pending disk updates. */)
3241 (void)
3243 sync ();
3244 return Qnil;
3247 #endif /* HAVE_SYNC */
3249 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3250 doc: /* Return t if file FILE1 is newer than file FILE2.
3251 If FILE1 does not exist, the answer is nil;
3252 otherwise, if FILE2 does not exist, the answer is t. */)
3253 (Lisp_Object file1, Lisp_Object file2)
3255 struct stat st1, st2;
3257 CHECK_STRING (file1);
3258 CHECK_STRING (file2);
3260 Lisp_Object absname1 = expand_and_dir_to_file (file1);
3261 Lisp_Object absname2 = expand_and_dir_to_file (file2);
3263 /* If the file name has special constructs in it,
3264 call the corresponding file handler. */
3265 Lisp_Object handler = Ffind_file_name_handler (absname1,
3266 Qfile_newer_than_file_p);
3267 if (NILP (handler))
3268 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3269 if (!NILP (handler))
3270 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3272 absname1 = ENCODE_FILE (absname1);
3273 absname2 = ENCODE_FILE (absname2);
3275 if (stat (SSDATA (absname1), &st1) < 0)
3276 return Qnil;
3278 if (stat (SSDATA (absname2), &st2) < 0)
3279 return Qt;
3281 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3282 ? Qt : Qnil);
3285 enum { READ_BUF_SIZE = MAX_ALLOCA };
3287 /* This function is called after Lisp functions to decide a coding
3288 system are called, or when they cause an error. Before they are
3289 called, the current buffer is set unibyte and it contains only a
3290 newly inserted text (thus the buffer was empty before the
3291 insertion).
3293 The functions may set markers, overlays, text properties, or even
3294 alter the buffer contents, change the current buffer.
3296 Here, we reset all those changes by:
3297 o set back the current buffer.
3298 o move all markers and overlays to BEG.
3299 o remove all text properties.
3300 o set back the buffer multibyteness. */
3302 static void
3303 decide_coding_unwind (Lisp_Object unwind_data)
3305 Lisp_Object multibyte, undo_list, buffer;
3307 multibyte = XCAR (unwind_data);
3308 unwind_data = XCDR (unwind_data);
3309 undo_list = XCAR (unwind_data);
3310 buffer = XCDR (unwind_data);
3312 set_buffer_internal (XBUFFER (buffer));
3313 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3314 adjust_overlays_for_delete (BEG, Z - BEG);
3315 set_buffer_intervals (current_buffer, NULL);
3316 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3318 /* Now we are safe to change the buffer's multibyteness directly. */
3319 bset_enable_multibyte_characters (current_buffer, multibyte);
3320 bset_undo_list (current_buffer, undo_list);
3323 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3324 object where slot 0 is the file descriptor, slot 1 specifies
3325 an offset to put the read bytes, and slot 2 is the maximum
3326 amount of bytes to read. Value is the number of bytes read. */
3328 static Lisp_Object
3329 read_non_regular (Lisp_Object state)
3331 int nbytes = emacs_read_quit (XSAVE_INTEGER (state, 0),
3332 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3333 + XSAVE_INTEGER (state, 1)),
3334 XSAVE_INTEGER (state, 2));
3335 /* Fast recycle this object for the likely next call. */
3336 free_misc (state);
3337 return make_number (nbytes);
3341 /* Condition-case handler used when reading from non-regular files
3342 in insert-file-contents. */
3344 static Lisp_Object
3345 read_non_regular_quit (Lisp_Object ignore)
3347 return Qnil;
3350 /* Return the file offset that VAL represents, checking for type
3351 errors and overflow. */
3352 static off_t
3353 file_offset (Lisp_Object val)
3355 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3356 return XINT (val);
3358 if (FLOATP (val))
3360 double v = XFLOAT_DATA (val);
3361 if (0 <= v && v < 1.0 + TYPE_MAXIMUM (off_t))
3363 off_t o = v;
3364 if (o == v)
3365 return o;
3369 wrong_type_argument (intern ("file-offset"), val);
3372 /* Return a special time value indicating the error number ERRNUM. */
3373 static struct timespec
3374 time_error_value (int errnum)
3376 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3377 ? NONEXISTENT_MODTIME_NSECS
3378 : UNKNOWN_MODTIME_NSECS);
3379 return make_timespec (0, ns);
3382 static Lisp_Object
3383 get_window_points_and_markers (void)
3385 Lisp_Object pt_marker = Fpoint_marker ();
3386 Lisp_Object windows
3387 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3388 Lisp_Object window_markers = windows;
3389 /* Window markers (and point) are handled specially: rather than move to
3390 just before or just after the modified text, we try to keep the
3391 markers at the same distance (bug#19161).
3392 In general, this is wrong, but for window-markers, this should be harmless
3393 and is convenient for the end user when most of the file is unmodified,
3394 except for a few minor details near the beginning and near the end. */
3395 for (; CONSP (windows); windows = XCDR (windows))
3396 if (WINDOWP (XCAR (windows)))
3398 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3399 XSETCAR (windows,
3400 Fcons (window_marker, Fmarker_position (window_marker)));
3402 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3405 static void
3406 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3407 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3409 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3410 if (CONSP (XCAR (window_markers)))
3412 Lisp_Object car = XCAR (window_markers);
3413 Lisp_Object marker = XCAR (car);
3414 Lisp_Object oldpos = XCDR (car);
3415 if (MARKERP (marker) && INTEGERP (oldpos)
3416 && XINT (oldpos) > same_at_start
3417 && XINT (oldpos) < same_at_end)
3419 ptrdiff_t oldsize = same_at_end - same_at_start;
3420 ptrdiff_t newsize = inserted;
3421 double growth = newsize / (double)oldsize;
3422 ptrdiff_t newpos
3423 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3424 Fset_marker (marker, make_number (newpos), Qnil);
3429 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3430 text as a linear C char array. */
3431 static void
3432 maybe_move_gap (struct buffer *b)
3434 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3436 struct buffer *cb = current_buffer;
3438 set_buffer_internal (b);
3439 move_gap_both (Z, Z_BYTE);
3440 set_buffer_internal (cb);
3444 /* FIXME: insert-file-contents should be split with the top-level moved to
3445 Elisp and only the core kept in C. */
3447 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3448 1, 5, 0,
3449 doc: /* Insert contents of file FILENAME after point.
3450 Returns list of absolute file name and number of characters inserted.
3451 If second argument VISIT is non-nil, the buffer's visited filename and
3452 last save file modtime are set, and it is marked unmodified. If
3453 visiting and the file does not exist, visiting is completed before the
3454 error is signaled.
3456 The optional third and fourth arguments BEG and END specify what portion
3457 of the file to insert. These arguments count bytes in the file, not
3458 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3460 If optional fifth argument REPLACE is non-nil, replace the current
3461 buffer contents (in the accessible portion) with the file contents.
3462 This is better than simply deleting and inserting the whole thing
3463 because (1) it preserves some marker positions and (2) it puts less data
3464 in the undo list. When REPLACE is non-nil, the second return value is
3465 the number of characters that replace previous buffer contents.
3467 This function does code conversion according to the value of
3468 `coding-system-for-read' or `file-coding-system-alist', and sets the
3469 variable `last-coding-system-used' to the coding system actually used.
3471 In addition, this function decodes the inserted text from known formats
3472 by calling `format-decode', which see. */)
3473 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3475 struct stat st;
3476 struct timespec mtime;
3477 int fd;
3478 ptrdiff_t inserted = 0;
3479 ptrdiff_t how_much;
3480 off_t beg_offset, end_offset;
3481 int unprocessed;
3482 ptrdiff_t count = SPECPDL_INDEX ();
3483 Lisp_Object handler, val, insval, orig_filename, old_undo;
3484 Lisp_Object p;
3485 ptrdiff_t total = 0;
3486 bool not_regular = 0;
3487 int save_errno = 0;
3488 char read_buf[READ_BUF_SIZE];
3489 struct coding_system coding;
3490 bool replace_handled = false;
3491 bool set_coding_system = false;
3492 Lisp_Object coding_system;
3493 bool read_quit = false;
3494 /* If the undo log only contains the insertion, there's no point
3495 keeping it. It's typically when we first fill a file-buffer. */
3496 bool empty_undo_list_p
3497 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3498 && BEG == Z);
3499 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3500 bool we_locked_file = false;
3501 ptrdiff_t fd_index;
3502 Lisp_Object window_markers = Qnil;
3503 /* same_at_start and same_at_end count bytes, because file access counts
3504 bytes and BEG and END count bytes. */
3505 ptrdiff_t same_at_start = BEGV_BYTE;
3506 ptrdiff_t same_at_end = ZV_BYTE;
3507 /* SAME_AT_END_CHARPOS counts characters, because
3508 restore_window_points needs the old character count. */
3509 ptrdiff_t same_at_end_charpos = ZV;
3511 if (current_buffer->base_buffer && ! NILP (visit))
3512 error ("Cannot do file visiting in an indirect buffer");
3514 if (!NILP (BVAR (current_buffer, read_only)))
3515 Fbarf_if_buffer_read_only (Qnil);
3517 val = Qnil;
3518 p = Qnil;
3519 orig_filename = Qnil;
3520 old_undo = Qnil;
3522 CHECK_STRING (filename);
3523 filename = Fexpand_file_name (filename, Qnil);
3525 /* The value Qnil means that the coding system is not yet
3526 decided. */
3527 coding_system = Qnil;
3529 /* If the file name has special constructs in it,
3530 call the corresponding file handler. */
3531 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3532 if (!NILP (handler))
3534 val = call6 (handler, Qinsert_file_contents, filename,
3535 visit, beg, end, replace);
3536 if (CONSP (val) && CONSP (XCDR (val))
3537 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3538 inserted = XINT (XCAR (XCDR (val)));
3539 goto handled;
3542 orig_filename = filename;
3543 filename = ENCODE_FILE (filename);
3545 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3546 if (fd < 0)
3548 save_errno = errno;
3549 if (NILP (visit))
3550 report_file_error ("Opening input file", orig_filename);
3551 mtime = time_error_value (save_errno);
3552 st.st_size = -1;
3553 if (!NILP (Vcoding_system_for_read))
3555 /* Don't let invalid values into buffer-file-coding-system. */
3556 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3557 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3559 goto notfound;
3562 fd_index = SPECPDL_INDEX ();
3563 record_unwind_protect_int (close_file_unwind, fd);
3565 /* Replacement should preserve point as it preserves markers. */
3566 if (!NILP (replace))
3568 window_markers = get_window_points_and_markers ();
3569 record_unwind_protect (restore_point_unwind,
3570 XCAR (XCAR (window_markers)));
3573 if (fstat (fd, &st) != 0)
3574 report_file_error ("Input file status", orig_filename);
3575 mtime = get_stat_mtime (&st);
3577 /* This code will need to be changed in order to work on named
3578 pipes, and it's probably just not worth it. So we should at
3579 least signal an error. */
3580 if (!S_ISREG (st.st_mode))
3582 not_regular = 1;
3584 if (! NILP (visit))
3585 goto notfound;
3587 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3588 xsignal2 (Qfile_error,
3589 build_string ("not a regular file"), orig_filename);
3592 if (!NILP (visit))
3594 if (!NILP (beg) || !NILP (end))
3595 error ("Attempt to visit less than an entire file");
3596 if (BEG < Z && NILP (replace))
3597 error ("Cannot do file visiting in a non-empty buffer");
3600 if (!NILP (beg))
3601 beg_offset = file_offset (beg);
3602 else
3603 beg_offset = 0;
3605 if (!NILP (end))
3606 end_offset = file_offset (end);
3607 else
3609 if (not_regular)
3610 end_offset = TYPE_MAXIMUM (off_t);
3611 else
3613 end_offset = st.st_size;
3615 /* A negative size can happen on a platform that allows file
3616 sizes greater than the maximum off_t value. */
3617 if (end_offset < 0)
3618 buffer_overflow ();
3620 /* The file size returned from stat may be zero, but data
3621 may be readable nonetheless, for example when this is a
3622 file in the /proc filesystem. */
3623 if (end_offset == 0)
3624 end_offset = READ_BUF_SIZE;
3628 /* Check now whether the buffer will become too large,
3629 in the likely case where the file's length is not changing.
3630 This saves a lot of needless work before a buffer overflow. */
3631 if (! not_regular)
3633 /* The likely offset where we will stop reading. We could read
3634 more (or less), if the file grows (or shrinks) as we read it. */
3635 off_t likely_end = min (end_offset, st.st_size);
3637 if (beg_offset < likely_end)
3639 ptrdiff_t buf_bytes
3640 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3641 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3642 off_t likely_growth = likely_end - beg_offset;
3643 if (buf_growth_max < likely_growth)
3644 buffer_overflow ();
3648 /* Prevent redisplay optimizations. */
3649 current_buffer->clip_changed = true;
3651 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3653 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3654 setup_coding_system (coding_system, &coding);
3655 /* Ensure we set Vlast_coding_system_used. */
3656 set_coding_system = true;
3658 else if (BEG < Z)
3660 /* Decide the coding system to use for reading the file now
3661 because we can't use an optimized method for handling
3662 `coding:' tag if the current buffer is not empty. */
3663 if (!NILP (Vcoding_system_for_read))
3664 coding_system = Vcoding_system_for_read;
3665 else
3667 /* Don't try looking inside a file for a coding system
3668 specification if it is not seekable. */
3669 if (! not_regular && ! NILP (Vset_auto_coding_function))
3671 /* Find a coding system specified in the heading two
3672 lines or in the tailing several lines of the file.
3673 We assume that the 1K-byte and 3K-byte for heading
3674 and tailing respectively are sufficient for this
3675 purpose. */
3676 int nread;
3678 if (st.st_size <= (1024 * 4))
3679 nread = emacs_read_quit (fd, read_buf, 1024 * 4);
3680 else
3682 nread = emacs_read_quit (fd, read_buf, 1024);
3683 if (nread == 1024)
3685 int ntail;
3686 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3687 report_file_error ("Setting file position",
3688 orig_filename);
3689 ntail = emacs_read_quit (fd, read_buf + nread, 1024 * 3);
3690 nread = ntail < 0 ? ntail : nread + ntail;
3694 if (nread < 0)
3695 report_file_error ("Read error", orig_filename);
3696 else if (nread > 0)
3698 AUTO_STRING (name, " *code-converting-work*");
3699 struct buffer *prev = current_buffer;
3700 Lisp_Object workbuf;
3701 struct buffer *buf;
3703 record_unwind_current_buffer ();
3705 workbuf = Fget_buffer_create (name);
3706 buf = XBUFFER (workbuf);
3708 delete_all_overlays (buf);
3709 bset_directory (buf, BVAR (current_buffer, directory));
3710 bset_read_only (buf, Qnil);
3711 bset_filename (buf, Qnil);
3712 bset_undo_list (buf, Qt);
3713 eassert (buf->overlays_before == NULL);
3714 eassert (buf->overlays_after == NULL);
3716 set_buffer_internal (buf);
3717 Ferase_buffer ();
3718 bset_enable_multibyte_characters (buf, Qnil);
3720 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3721 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3722 coding_system = call2 (Vset_auto_coding_function,
3723 filename, make_number (nread));
3724 set_buffer_internal (prev);
3726 /* Discard the unwind protect for recovering the
3727 current buffer. */
3728 specpdl_ptr--;
3730 /* Rewind the file for the actual read done later. */
3731 if (lseek (fd, 0, SEEK_SET) < 0)
3732 report_file_error ("Setting file position", orig_filename);
3736 if (NILP (coding_system))
3738 /* If we have not yet decided a coding system, check
3739 file-coding-system-alist. */
3740 coding_system = CALLN (Ffind_operation_coding_system,
3741 Qinsert_file_contents, orig_filename,
3742 visit, beg, end, replace);
3743 if (CONSP (coding_system))
3744 coding_system = XCAR (coding_system);
3748 if (NILP (coding_system))
3749 coding_system = Qundecided;
3750 else
3751 CHECK_CODING_SYSTEM (coding_system);
3753 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3754 /* We must suppress all character code conversion except for
3755 end-of-line conversion. */
3756 coding_system = raw_text_coding_system (coding_system);
3758 setup_coding_system (coding_system, &coding);
3759 /* Ensure we set Vlast_coding_system_used. */
3760 set_coding_system = true;
3763 /* If requested, replace the accessible part of the buffer
3764 with the file contents. Avoid replacing text at the
3765 beginning or end of the buffer that matches the file contents;
3766 that preserves markers pointing to the unchanged parts.
3768 Here we implement this feature in an optimized way
3769 for the case where code conversion is NOT needed.
3770 The following if-statement handles the case of conversion
3771 in a less optimal way.
3773 If the code conversion is "automatic" then we try using this
3774 method and hope for the best.
3775 But if we discover the need for conversion, we give up on this method
3776 and let the following if-statement handle the replace job. */
3777 if (!NILP (replace)
3778 && BEGV < ZV
3779 && (NILP (coding_system)
3780 || ! CODING_REQUIRE_DECODING (&coding)))
3782 ptrdiff_t overlap;
3783 /* There is still a possibility we will find the need to do code
3784 conversion. If that happens, set this variable to
3785 give up on handling REPLACE in the optimized way. */
3786 bool giveup_match_end = false;
3788 if (beg_offset != 0)
3790 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3791 report_file_error ("Setting file position", orig_filename);
3794 /* Count how many chars at the start of the file
3795 match the text at the beginning of the buffer. */
3796 while (true)
3798 int nread = emacs_read_quit (fd, read_buf, sizeof read_buf);
3799 if (nread < 0)
3800 report_file_error ("Read error", orig_filename);
3801 else if (nread == 0)
3802 break;
3804 if (CODING_REQUIRE_DETECTION (&coding))
3806 coding_system = detect_coding_system ((unsigned char *) read_buf,
3807 nread, nread, 1, 0,
3808 coding_system);
3809 setup_coding_system (coding_system, &coding);
3812 if (CODING_REQUIRE_DECODING (&coding))
3813 /* We found that the file should be decoded somehow.
3814 Let's give up here. */
3816 giveup_match_end = true;
3817 break;
3820 int bufpos = 0;
3821 while (bufpos < nread && same_at_start < ZV_BYTE
3822 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3823 same_at_start++, bufpos++;
3824 /* If we found a discrepancy, stop the scan.
3825 Otherwise loop around and scan the next bufferful. */
3826 if (bufpos != nread)
3827 break;
3829 /* If the file matches the buffer completely,
3830 there's no need to replace anything. */
3831 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3833 emacs_close (fd);
3834 clear_unwind_protect (fd_index);
3836 /* Truncate the buffer to the size of the file. */
3837 del_range_1 (same_at_start, same_at_end, 0, 0);
3838 goto handled;
3841 /* Count how many chars at the end of the file
3842 match the text at the end of the buffer. But, if we have
3843 already found that decoding is necessary, don't waste time. */
3844 while (!giveup_match_end)
3846 int total_read, nread, bufpos, trial;
3847 off_t curpos;
3849 /* At what file position are we now scanning? */
3850 curpos = end_offset - (ZV_BYTE - same_at_end);
3851 /* If the entire file matches the buffer tail, stop the scan. */
3852 if (curpos == 0)
3853 break;
3854 /* How much can we scan in the next step? */
3855 trial = min (curpos, sizeof read_buf);
3856 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3857 report_file_error ("Setting file position", orig_filename);
3859 total_read = nread = 0;
3860 while (total_read < trial)
3862 nread = emacs_read_quit (fd, read_buf + total_read,
3863 trial - total_read);
3864 if (nread < 0)
3865 report_file_error ("Read error", orig_filename);
3866 else if (nread == 0)
3867 break;
3868 total_read += nread;
3871 /* Scan this bufferful from the end, comparing with
3872 the Emacs buffer. */
3873 bufpos = total_read;
3875 /* Compare with same_at_start to avoid counting some buffer text
3876 as matching both at the file's beginning and at the end. */
3877 while (bufpos > 0 && same_at_end > same_at_start
3878 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3879 same_at_end--, bufpos--;
3881 /* If we found a discrepancy, stop the scan.
3882 Otherwise loop around and scan the preceding bufferful. */
3883 if (bufpos != 0)
3885 /* If this discrepancy is because of code conversion,
3886 we cannot use this method; giveup and try the other. */
3887 if (same_at_end > same_at_start
3888 && FETCH_BYTE (same_at_end - 1) >= 0200
3889 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3890 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3891 giveup_match_end = true;
3892 break;
3895 if (nread == 0)
3896 break;
3899 if (! giveup_match_end)
3901 ptrdiff_t temp;
3902 ptrdiff_t this_count = SPECPDL_INDEX ();
3904 /* We win! We can handle REPLACE the optimized way. */
3906 /* Extend the start of non-matching text area to multibyte
3907 character boundary. */
3908 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3909 while (same_at_start > BEGV_BYTE
3910 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3911 same_at_start--;
3913 /* Extend the end of non-matching text area to multibyte
3914 character boundary. */
3915 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3916 while (same_at_end < ZV_BYTE
3917 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3918 same_at_end++;
3920 /* Don't try to reuse the same piece of text twice. */
3921 overlap = (same_at_start - BEGV_BYTE
3922 - (same_at_end
3923 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3924 if (overlap > 0)
3925 same_at_end += overlap;
3926 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3928 /* Arrange to read only the nonmatching middle part of the file. */
3929 beg_offset += same_at_start - BEGV_BYTE;
3930 end_offset -= ZV_BYTE - same_at_end;
3932 /* This binding is to avoid ask-user-about-supersession-threat
3933 being called in insert_from_buffer or del_range_bytes (via
3934 prepare_to_modify_buffer).
3935 AFAICT we could avoid ask-user-about-supersession-threat by setting
3936 current_buffer->modtime earlier, but we could still end up calling
3937 ask-user-about-supersession-threat if the file is modified while
3938 we read it, so we bind buffer-file-name instead. */
3939 specbind (intern ("buffer-file-name"), Qnil);
3940 del_range_byte (same_at_start, same_at_end);
3941 /* Insert from the file at the proper position. */
3942 temp = BYTE_TO_CHAR (same_at_start);
3943 SET_PT_BOTH (temp, same_at_start);
3944 unbind_to (this_count, Qnil);
3946 /* If display currently starts at beginning of line,
3947 keep it that way. */
3948 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3949 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3951 replace_handled = true;
3955 /* If requested, replace the accessible part of the buffer
3956 with the file contents. Avoid replacing text at the
3957 beginning or end of the buffer that matches the file contents;
3958 that preserves markers pointing to the unchanged parts.
3960 Here we implement this feature for the case where code conversion
3961 is needed, in a simple way that needs a lot of memory.
3962 The preceding if-statement handles the case of no conversion
3963 in a more optimized way. */
3964 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3966 ptrdiff_t same_at_start_charpos;
3967 ptrdiff_t inserted_chars;
3968 ptrdiff_t overlap;
3969 ptrdiff_t bufpos;
3970 unsigned char *decoded;
3971 ptrdiff_t temp;
3972 ptrdiff_t this = 0;
3973 ptrdiff_t this_count = SPECPDL_INDEX ();
3974 bool multibyte
3975 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3976 Lisp_Object conversion_buffer;
3978 conversion_buffer = code_conversion_save (1, multibyte);
3980 /* First read the whole file, performing code conversion into
3981 CONVERSION_BUFFER. */
3983 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3984 report_file_error ("Setting file position", orig_filename);
3986 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3987 unprocessed = 0; /* Bytes not processed in previous loop. */
3989 while (true)
3991 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3992 quitting while reading a huge file. */
3994 this = emacs_read_quit (fd, read_buf + unprocessed,
3995 READ_BUF_SIZE - unprocessed);
3996 if (this <= 0)
3997 break;
3999 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
4000 BUF_Z (XBUFFER (conversion_buffer)));
4001 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4002 unprocessed + this, conversion_buffer);
4003 unprocessed = coding.carryover_bytes;
4004 if (coding.carryover_bytes > 0)
4005 memcpy (read_buf, coding.carryover, unprocessed);
4008 if (this < 0)
4009 report_file_error ("Read error", orig_filename);
4010 emacs_close (fd);
4011 clear_unwind_protect (fd_index);
4013 if (unprocessed > 0)
4015 coding.mode |= CODING_MODE_LAST_BLOCK;
4016 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4017 unprocessed, conversion_buffer);
4018 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4021 coding_system = CODING_ID_NAME (coding.id);
4022 set_coding_system = true;
4023 maybe_move_gap (XBUFFER (conversion_buffer));
4024 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
4025 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4026 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4028 /* Compare the beginning of the converted string with the buffer
4029 text. */
4031 bufpos = 0;
4032 while (bufpos < inserted && same_at_start < same_at_end
4033 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4034 same_at_start++, bufpos++;
4036 /* If the file matches the head of buffer completely,
4037 there's no need to replace anything. */
4039 if (bufpos == inserted)
4041 /* Truncate the buffer to the size of the file. */
4042 if (same_at_start != same_at_end)
4044 /* See previous specbind for the reason behind this. */
4045 specbind (intern ("buffer-file-name"), Qnil);
4046 del_range_byte (same_at_start, same_at_end);
4048 inserted = 0;
4050 unbind_to (this_count, Qnil);
4051 goto handled;
4054 /* Extend the start of non-matching text area to the previous
4055 multibyte character boundary. */
4056 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4057 while (same_at_start > BEGV_BYTE
4058 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4059 same_at_start--;
4061 /* Scan this bufferful from the end, comparing with
4062 the Emacs buffer. */
4063 bufpos = inserted;
4065 /* Compare with same_at_start to avoid counting some buffer text
4066 as matching both at the file's beginning and at the end. */
4067 while (bufpos > 0 && same_at_end > same_at_start
4068 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4069 same_at_end--, bufpos--;
4071 /* Extend the end of non-matching text area to the next
4072 multibyte character boundary. */
4073 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4074 while (same_at_end < ZV_BYTE
4075 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4076 same_at_end++;
4078 /* Don't try to reuse the same piece of text twice. */
4079 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4080 if (overlap > 0)
4081 same_at_end += overlap;
4082 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4084 /* If display currently starts at beginning of line,
4085 keep it that way. */
4086 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4087 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4089 /* Replace the chars that we need to replace,
4090 and update INSERTED to equal the number of bytes
4091 we are taking from the decoded string. */
4092 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4094 /* See previous specbind for the reason behind this. */
4095 specbind (intern ("buffer-file-name"), Qnil);
4096 if (same_at_end != same_at_start)
4098 del_range_byte (same_at_start, same_at_end);
4099 temp = GPT;
4100 eassert (same_at_start == GPT_BYTE);
4101 same_at_start = GPT_BYTE;
4103 else
4105 temp = same_at_end_charpos;
4107 /* Insert from the file at the proper position. */
4108 SET_PT_BOTH (temp, same_at_start);
4109 same_at_start_charpos
4110 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4111 same_at_start - BEGV_BYTE
4112 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4113 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4114 inserted_chars
4115 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4116 same_at_start + inserted - BEGV_BYTE
4117 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4118 - same_at_start_charpos);
4119 insert_from_buffer (XBUFFER (conversion_buffer),
4120 same_at_start_charpos, inserted_chars, 0);
4121 /* Set `inserted' to the number of inserted characters. */
4122 inserted = PT - temp;
4123 /* Set point before the inserted characters. */
4124 SET_PT_BOTH (temp, same_at_start);
4126 unbind_to (this_count, Qnil);
4128 goto handled;
4131 if (! not_regular)
4132 total = end_offset - beg_offset;
4133 else
4134 /* For a special file, all we can do is guess. */
4135 total = READ_BUF_SIZE;
4137 if (NILP (visit) && total > 0)
4139 if (!NILP (BVAR (current_buffer, file_truename))
4140 /* Make binding buffer-file-name to nil effective. */
4141 && !NILP (BVAR (current_buffer, filename))
4142 && SAVE_MODIFF >= MODIFF)
4143 we_locked_file = true;
4144 prepare_to_modify_buffer (PT, PT, NULL);
4147 move_gap_both (PT, PT_BYTE);
4148 if (GAP_SIZE < total)
4149 make_gap (total - GAP_SIZE);
4151 if (beg_offset != 0 || !NILP (replace))
4153 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4154 report_file_error ("Setting file position", orig_filename);
4157 /* In the following loop, HOW_MUCH contains the total bytes read so
4158 far for a regular file, and not changed for a special file. But,
4159 before exiting the loop, it is set to a negative value if I/O
4160 error occurs. */
4161 how_much = 0;
4163 /* Total bytes inserted. */
4164 inserted = 0;
4166 /* Here, we don't do code conversion in the loop. It is done by
4167 decode_coding_gap after all data are read into the buffer. */
4169 ptrdiff_t gap_size = GAP_SIZE;
4171 while (how_much < total)
4173 /* `try' is reserved in some compilers (Microsoft C). */
4174 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4175 ptrdiff_t this;
4177 if (not_regular)
4179 Lisp_Object nbytes;
4181 /* Maybe make more room. */
4182 if (gap_size < trytry)
4184 make_gap (trytry - gap_size);
4185 gap_size = GAP_SIZE - inserted;
4188 /* Read from the file, capturing `quit'. When an
4189 error occurs, end the loop, and arrange for a quit
4190 to be signaled after decoding the text we read. */
4191 nbytes = internal_condition_case_1
4192 (read_non_regular,
4193 make_save_int_int_int (fd, inserted, trytry),
4194 Qerror, read_non_regular_quit);
4196 if (NILP (nbytes))
4198 read_quit = true;
4199 break;
4202 this = XINT (nbytes);
4204 else
4206 /* Allow quitting out of the actual I/O. We don't make text
4207 part of the buffer until all the reading is done, so a C-g
4208 here doesn't do any harm. */
4209 this = emacs_read_quit (fd,
4210 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4211 + inserted),
4212 trytry);
4215 if (this <= 0)
4217 how_much = this;
4218 break;
4221 gap_size -= this;
4223 /* For a regular file, where TOTAL is the real size,
4224 count HOW_MUCH to compare with it.
4225 For a special file, where TOTAL is just a buffer size,
4226 so don't bother counting in HOW_MUCH.
4227 (INSERTED is where we count the number of characters inserted.) */
4228 if (! not_regular)
4229 how_much += this;
4230 inserted += this;
4234 /* Now we have either read all the file data into the gap,
4235 or stop reading on I/O error or quit. If nothing was
4236 read, undo marking the buffer modified. */
4238 if (inserted == 0)
4240 if (we_locked_file)
4241 unlock_file (BVAR (current_buffer, file_truename));
4242 Vdeactivate_mark = old_Vdeactivate_mark;
4244 else
4245 Fset (Qdeactivate_mark, Qt);
4247 emacs_close (fd);
4248 clear_unwind_protect (fd_index);
4250 if (how_much < 0)
4251 report_file_error ("Read error", orig_filename);
4253 /* Make the text read part of the buffer. */
4254 GAP_SIZE -= inserted;
4255 GPT += inserted;
4256 GPT_BYTE += inserted;
4257 ZV += inserted;
4258 ZV_BYTE += inserted;
4259 Z += inserted;
4260 Z_BYTE += inserted;
4262 if (GAP_SIZE > 0)
4263 /* Put an anchor to ensure multi-byte form ends at gap. */
4264 *GPT_ADDR = 0;
4266 notfound:
4268 if (NILP (coding_system))
4270 /* The coding system is not yet decided. Decide it by an
4271 optimized method for handling `coding:' tag.
4273 Note that we can get here only if the buffer was empty
4274 before the insertion. */
4276 if (!NILP (Vcoding_system_for_read))
4277 coding_system = Vcoding_system_for_read;
4278 else
4280 /* Since we are sure that the current buffer was empty
4281 before the insertion, we can toggle
4282 enable-multibyte-characters directly here without taking
4283 care of marker adjustment. By this way, we can run Lisp
4284 program safely before decoding the inserted text. */
4285 Lisp_Object unwind_data;
4286 ptrdiff_t count1 = SPECPDL_INDEX ();
4288 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4289 Fcons (BVAR (current_buffer, undo_list),
4290 Fcurrent_buffer ()));
4291 bset_enable_multibyte_characters (current_buffer, Qnil);
4292 bset_undo_list (current_buffer, Qt);
4293 record_unwind_protect (decide_coding_unwind, unwind_data);
4295 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4297 coding_system = call2 (Vset_auto_coding_function,
4298 filename, make_number (inserted));
4301 if (NILP (coding_system))
4303 /* If the coding system is not yet decided, check
4304 file-coding-system-alist. */
4305 coding_system = CALLN (Ffind_operation_coding_system,
4306 Qinsert_file_contents, orig_filename,
4307 visit, beg, end, Qnil);
4308 if (CONSP (coding_system))
4309 coding_system = XCAR (coding_system);
4311 unbind_to (count1, Qnil);
4312 inserted = Z_BYTE - BEG_BYTE;
4315 if (NILP (coding_system))
4316 coding_system = Qundecided;
4317 else
4318 CHECK_CODING_SYSTEM (coding_system);
4320 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4321 /* We must suppress all character code conversion except for
4322 end-of-line conversion. */
4323 coding_system = raw_text_coding_system (coding_system);
4324 setup_coding_system (coding_system, &coding);
4325 /* Ensure we set Vlast_coding_system_used. */
4326 set_coding_system = true;
4329 if (!NILP (visit))
4331 /* When we visit a file by raw-text, we change the buffer to
4332 unibyte. */
4333 if (CODING_FOR_UNIBYTE (&coding)
4334 /* Can't do this if part of the buffer might be preserved. */
4335 && NILP (replace))
4337 /* Visiting a file with these coding system makes the buffer
4338 unibyte. */
4339 if (inserted > 0)
4340 bset_enable_multibyte_characters (current_buffer, Qnil);
4341 else
4342 Fset_buffer_multibyte (Qnil);
4346 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4347 if (CODING_MAY_REQUIRE_DECODING (&coding)
4348 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4350 move_gap_both (PT, PT_BYTE);
4351 GAP_SIZE += inserted;
4352 ZV_BYTE -= inserted;
4353 Z_BYTE -= inserted;
4354 ZV -= inserted;
4355 Z -= inserted;
4356 decode_coding_gap (&coding, inserted, inserted);
4357 inserted = coding.produced_char;
4358 coding_system = CODING_ID_NAME (coding.id);
4360 else if (inserted > 0)
4362 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4363 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4364 inserted);
4367 /* Call after-change hooks for the inserted text, aside from the case
4368 of normal visiting (not with REPLACE), which is done in a new buffer
4369 "before" the buffer is changed. */
4370 if (inserted > 0 && total > 0
4371 && (NILP (visit) || !NILP (replace)))
4373 signal_after_change (PT, 0, inserted);
4374 update_compositions (PT, PT, CHECK_BORDER);
4377 /* Now INSERTED is measured in characters. */
4379 handled:
4381 if (inserted > 0)
4382 restore_window_points (window_markers, inserted,
4383 BYTE_TO_CHAR (same_at_start),
4384 same_at_end_charpos);
4386 if (!NILP (visit))
4388 if (empty_undo_list_p)
4389 bset_undo_list (current_buffer, Qnil);
4391 if (NILP (handler))
4393 current_buffer->modtime = mtime;
4394 current_buffer->modtime_size = st.st_size;
4395 bset_filename (current_buffer, orig_filename);
4398 SAVE_MODIFF = MODIFF;
4399 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4400 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4401 if (NILP (handler))
4403 if (!NILP (BVAR (current_buffer, file_truename)))
4404 unlock_file (BVAR (current_buffer, file_truename));
4405 unlock_file (filename);
4407 if (not_regular)
4408 xsignal2 (Qfile_error,
4409 build_string ("not a regular file"), orig_filename);
4412 if (set_coding_system)
4413 Vlast_coding_system_used = coding_system;
4415 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4417 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4418 visit);
4419 if (! NILP (insval))
4421 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4422 wrong_type_argument (intern ("inserted-chars"), insval);
4423 inserted = XFASTINT (insval);
4427 /* Decode file format. */
4428 if (inserted > 0)
4430 /* Don't run point motion or modification hooks when decoding. */
4431 ptrdiff_t count1 = SPECPDL_INDEX ();
4432 ptrdiff_t old_inserted = inserted;
4433 specbind (Qinhibit_point_motion_hooks, Qt);
4434 specbind (Qinhibit_modification_hooks, Qt);
4436 /* Save old undo list and don't record undo for decoding. */
4437 old_undo = BVAR (current_buffer, undo_list);
4438 bset_undo_list (current_buffer, Qt);
4440 if (NILP (replace))
4442 insval = call3 (Qformat_decode,
4443 Qnil, make_number (inserted), visit);
4444 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4445 wrong_type_argument (intern ("inserted-chars"), insval);
4446 inserted = XFASTINT (insval);
4448 else
4450 /* If REPLACE is non-nil and we succeeded in not replacing the
4451 beginning or end of the buffer text with the file's contents,
4452 call format-decode with `point' positioned at the beginning
4453 of the buffer and `inserted' equaling the number of
4454 characters in the buffer. Otherwise, format-decode might
4455 fail to correctly analyze the beginning or end of the buffer.
4456 Hence we temporarily save `point' and `inserted' here and
4457 restore `point' iff format-decode did not insert or delete
4458 any text. Otherwise we leave `point' at point-min. */
4459 ptrdiff_t opoint = PT;
4460 ptrdiff_t opoint_byte = PT_BYTE;
4461 ptrdiff_t oinserted = ZV - BEGV;
4462 EMACS_INT ochars_modiff = CHARS_MODIFF;
4464 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4465 insval = call3 (Qformat_decode,
4466 Qnil, make_number (oinserted), visit);
4467 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4468 wrong_type_argument (intern ("inserted-chars"), insval);
4469 if (ochars_modiff == CHARS_MODIFF)
4470 /* format_decode didn't modify buffer's characters => move
4471 point back to position before inserted text and leave
4472 value of inserted alone. */
4473 SET_PT_BOTH (opoint, opoint_byte);
4474 else
4475 /* format_decode modified buffer's characters => consider
4476 entire buffer changed and leave point at point-min. */
4477 inserted = XFASTINT (insval);
4480 /* For consistency with format-decode call these now iff inserted > 0
4481 (martin 2007-06-28). */
4482 p = Vafter_insert_file_functions;
4483 while (CONSP (p))
4485 if (NILP (replace))
4487 insval = call1 (XCAR (p), make_number (inserted));
4488 if (!NILP (insval))
4490 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4491 wrong_type_argument (intern ("inserted-chars"), insval);
4492 inserted = XFASTINT (insval);
4495 else
4497 /* For the rationale of this see the comment on
4498 format-decode above. */
4499 ptrdiff_t opoint = PT;
4500 ptrdiff_t opoint_byte = PT_BYTE;
4501 ptrdiff_t oinserted = ZV - BEGV;
4502 EMACS_INT ochars_modiff = CHARS_MODIFF;
4504 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4505 insval = call1 (XCAR (p), make_number (oinserted));
4506 if (!NILP (insval))
4508 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4509 wrong_type_argument (intern ("inserted-chars"), insval);
4510 if (ochars_modiff == CHARS_MODIFF)
4511 /* after_insert_file_functions didn't modify
4512 buffer's characters => move point back to
4513 position before inserted text and leave value of
4514 inserted alone. */
4515 SET_PT_BOTH (opoint, opoint_byte);
4516 else
4517 /* after_insert_file_functions did modify buffer's
4518 characters => consider entire buffer changed and
4519 leave point at point-min. */
4520 inserted = XFASTINT (insval);
4524 maybe_quit ();
4525 p = XCDR (p);
4528 if (!empty_undo_list_p)
4530 bset_undo_list (current_buffer, old_undo);
4531 if (CONSP (old_undo) && inserted != old_inserted)
4533 /* Adjust the last undo record for the size change during
4534 the format conversion. */
4535 Lisp_Object tem = XCAR (old_undo);
4536 if (CONSP (tem) && INTEGERP (XCAR (tem))
4537 && INTEGERP (XCDR (tem))
4538 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4539 XSETCDR (tem, make_number (PT + inserted));
4542 else
4543 /* If undo_list was Qt before, keep it that way.
4544 Otherwise start with an empty undo_list. */
4545 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4547 unbind_to (count1, Qnil);
4550 if (!NILP (visit)
4551 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4553 /* If visiting nonexistent file, return nil. */
4554 report_file_errno ("Opening input file", orig_filename, save_errno);
4557 /* We made a lot of deletions and insertions above, so invalidate
4558 the newline cache for the entire region of the inserted
4559 characters. */
4560 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4561 invalidate_region_cache (current_buffer->base_buffer,
4562 current_buffer->base_buffer->newline_cache,
4563 PT - BEG, Z - PT - inserted);
4564 else if (current_buffer->newline_cache)
4565 invalidate_region_cache (current_buffer,
4566 current_buffer->newline_cache,
4567 PT - BEG, Z - PT - inserted);
4569 if (read_quit)
4570 quit ();
4572 /* Retval needs to be dealt with in all cases consistently. */
4573 if (NILP (val))
4574 val = list2 (orig_filename, make_number (inserted));
4576 return unbind_to (count, val);
4579 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4581 static void
4582 build_annotations_unwind (Lisp_Object arg)
4584 Vwrite_region_annotation_buffers = arg;
4587 /* Decide the coding-system to encode the data with. */
4589 static Lisp_Object
4590 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4591 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4592 struct coding_system *coding)
4594 Lisp_Object val;
4595 Lisp_Object eol_parent = Qnil;
4597 if (auto_saving
4598 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4599 BVAR (current_buffer, auto_save_file_name))))
4601 val = Qutf_8_emacs;
4602 eol_parent = Qunix;
4604 else if (!NILP (Vcoding_system_for_write))
4606 val = Vcoding_system_for_write;
4607 if (coding_system_require_warning
4608 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4609 /* Confirm that VAL can surely encode the current region. */
4610 val = call5 (Vselect_safe_coding_system_function,
4611 start, end, list2 (Qt, val),
4612 Qnil, filename);
4614 else
4616 /* If the variable `buffer-file-coding-system' is set locally,
4617 it means that the file was read with some kind of code
4618 conversion or the variable is explicitly set by users. We
4619 had better write it out with the same coding system even if
4620 `enable-multibyte-characters' is nil.
4622 If it is not set locally, we anyway have to convert EOL
4623 format if the default value of `buffer-file-coding-system'
4624 tells that it is not Unix-like (LF only) format. */
4625 bool using_default_coding = 0;
4626 bool force_raw_text = 0;
4628 val = BVAR (current_buffer, buffer_file_coding_system);
4629 if (NILP (val)
4630 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4632 val = Qnil;
4633 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4634 force_raw_text = 1;
4637 if (NILP (val))
4639 /* Check file-coding-system-alist. */
4640 Lisp_Object coding_systems
4641 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4642 filename, append, visit, lockname);
4643 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4644 val = XCDR (coding_systems);
4647 if (NILP (val))
4649 /* If we still have not decided a coding system, use the
4650 current buffer's value of buffer-file-coding-system. */
4651 val = BVAR (current_buffer, buffer_file_coding_system);
4652 using_default_coding = 1;
4655 if (! NILP (val) && ! force_raw_text)
4657 Lisp_Object spec, attrs;
4659 CHECK_CODING_SYSTEM (val);
4660 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4661 attrs = AREF (spec, 0);
4662 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4663 force_raw_text = 1;
4666 if (!force_raw_text
4667 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4669 /* Confirm that VAL can surely encode the current region. */
4670 val = call5 (Vselect_safe_coding_system_function,
4671 start, end, val, Qnil, filename);
4672 /* As the function specified by select-safe-coding-system-function
4673 is out of our control, make sure we are not fed by bogus
4674 values. */
4675 if (!NILP (val))
4676 CHECK_CODING_SYSTEM (val);
4679 /* If the decided coding-system doesn't specify end-of-line
4680 format, we use that of `buffer-file-coding-system'. */
4681 if (! using_default_coding)
4683 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4685 if (! NILP (dflt))
4686 val = coding_inherit_eol_type (val, dflt);
4689 /* If we decide not to encode text, use `raw-text' or one of its
4690 subsidiaries. */
4691 if (force_raw_text)
4692 val = raw_text_coding_system (val);
4695 val = coding_inherit_eol_type (val, eol_parent);
4696 setup_coding_system (val, coding);
4698 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4699 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4700 return val;
4703 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4704 "r\nFWrite region to file: \ni\ni\ni\np",
4705 doc: /* Write current region into specified file.
4706 When called from a program, requires three arguments:
4707 START, END and FILENAME. START and END are normally buffer positions
4708 specifying the part of the buffer to write.
4709 If START is nil, that means to use the entire buffer contents; END is
4710 ignored.
4711 If START is a string, then output that string to the file
4712 instead of any buffer contents; END is ignored.
4714 Optional fourth argument APPEND if non-nil means
4715 append to existing file contents (if any). If it is a number,
4716 seek to that offset in the file before writing.
4717 Optional fifth argument VISIT, if t or a string, means
4718 set the last-save-file-modtime of buffer to this file's modtime
4719 and mark buffer not modified.
4720 If VISIT is a string, it is a second file name;
4721 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4722 VISIT is also the file name to lock and unlock for clash detection.
4723 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4724 do not display the \"Wrote file\" message.
4725 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4726 use for locking and unlocking, overriding FILENAME and VISIT.
4727 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4728 for an existing file with the same name. If MUSTBENEW is `excl',
4729 that means to get an error if the file already exists; never overwrite.
4730 If MUSTBENEW is neither nil nor `excl', that means ask for
4731 confirmation before overwriting, but do go ahead and overwrite the file
4732 if the user confirms.
4734 This does code conversion according to the value of
4735 `coding-system-for-write', `buffer-file-coding-system', or
4736 `file-coding-system-alist', and sets the variable
4737 `last-coding-system-used' to the coding system actually used.
4739 This calls `write-region-annotate-functions' at the start, and
4740 `write-region-post-annotation-function' at the end. */)
4741 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4742 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4744 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4745 -1);
4748 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4749 descriptor for FILENAME, so do not open or close FILENAME. */
4751 Lisp_Object
4752 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4753 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4754 Lisp_Object mustbenew, int desc)
4756 int open_flags;
4757 int mode;
4758 off_t offset UNINIT;
4759 bool open_and_close_file = desc < 0;
4760 bool ok;
4761 int save_errno = 0;
4762 const char *fn;
4763 struct stat st;
4764 struct timespec modtime;
4765 ptrdiff_t count = SPECPDL_INDEX ();
4766 ptrdiff_t count1 UNINIT;
4767 Lisp_Object handler;
4768 Lisp_Object visit_file;
4769 Lisp_Object annotations;
4770 Lisp_Object encoded_filename;
4771 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4772 bool quietly = !NILP (visit);
4773 bool file_locked = 0;
4774 struct buffer *given_buffer;
4775 struct coding_system coding;
4777 if (current_buffer->base_buffer && visiting)
4778 error ("Cannot do file visiting in an indirect buffer");
4780 if (!NILP (start) && !STRINGP (start))
4781 validate_region (&start, &end);
4783 visit_file = Qnil;
4785 filename = Fexpand_file_name (filename, Qnil);
4787 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4788 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4790 if (STRINGP (visit))
4791 visit_file = Fexpand_file_name (visit, Qnil);
4792 else
4793 visit_file = filename;
4795 if (NILP (lockname))
4796 lockname = visit_file;
4798 annotations = Qnil;
4800 /* If the file name has special constructs in it,
4801 call the corresponding file handler. */
4802 handler = Ffind_file_name_handler (filename, Qwrite_region);
4803 /* If FILENAME has no handler, see if VISIT has one. */
4804 if (NILP (handler) && STRINGP (visit))
4805 handler = Ffind_file_name_handler (visit, Qwrite_region);
4807 if (!NILP (handler))
4809 Lisp_Object val;
4810 val = call8 (handler, Qwrite_region, start, end,
4811 filename, append, visit, lockname, mustbenew);
4813 if (visiting)
4815 SAVE_MODIFF = MODIFF;
4816 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4817 bset_filename (current_buffer, visit_file);
4820 return val;
4823 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4825 /* Special kludge to simplify auto-saving. */
4826 if (NILP (start))
4828 /* Do it later, so write-region-annotate-function can work differently
4829 if we save "the buffer" vs "a region".
4830 This is useful in tar-mode. --Stef
4831 XSETFASTINT (start, BEG);
4832 XSETFASTINT (end, Z); */
4833 Fwiden ();
4836 record_unwind_protect (build_annotations_unwind,
4837 Vwrite_region_annotation_buffers);
4838 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4840 given_buffer = current_buffer;
4842 if (!STRINGP (start))
4844 annotations = build_annotations (start, end);
4846 if (current_buffer != given_buffer)
4848 XSETFASTINT (start, BEGV);
4849 XSETFASTINT (end, ZV);
4853 if (NILP (start))
4855 XSETFASTINT (start, BEGV);
4856 XSETFASTINT (end, ZV);
4859 /* Decide the coding-system to encode the data with.
4860 We used to make this choice before calling build_annotations, but that
4861 leads to problems when a write-annotate-function takes care of
4862 unsavable chars (as was the case with X-Symbol). */
4863 Vlast_coding_system_used
4864 = choose_write_coding_system (start, end, filename,
4865 append, visit, lockname, &coding);
4867 if (open_and_close_file && !auto_saving)
4869 lock_file (lockname);
4870 file_locked = 1;
4873 encoded_filename = ENCODE_FILE (filename);
4874 fn = SSDATA (encoded_filename);
4875 open_flags = O_WRONLY | O_CREAT;
4876 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4877 if (NUMBERP (append))
4878 offset = file_offset (append);
4879 else if (!NILP (append))
4880 open_flags |= O_APPEND;
4881 #ifdef DOS_NT
4882 mode = S_IREAD | S_IWRITE;
4883 #else
4884 mode = auto_saving ? auto_save_mode_bits : 0666;
4885 #endif
4887 if (open_and_close_file)
4889 desc = emacs_open (fn, open_flags, mode);
4890 if (desc < 0)
4892 int open_errno = errno;
4893 if (file_locked)
4894 unlock_file (lockname);
4895 report_file_errno ("Opening output file", filename, open_errno);
4898 count1 = SPECPDL_INDEX ();
4899 record_unwind_protect_int (close_file_unwind, desc);
4902 if (NUMBERP (append))
4904 off_t ret = lseek (desc, offset, SEEK_SET);
4905 if (ret < 0)
4907 int lseek_errno = errno;
4908 if (file_locked)
4909 unlock_file (lockname);
4910 report_file_errno ("Lseek error", filename, lseek_errno);
4914 if (STRINGP (start))
4915 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4916 else if (XINT (start) != XINT (end))
4917 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4918 &annotations, &coding);
4919 else
4921 /* If file was empty, still need to write the annotations. */
4922 coding.mode |= CODING_MODE_LAST_BLOCK;
4923 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4925 save_errno = errno;
4927 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4928 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4930 /* We have to flush out a data. */
4931 coding.mode |= CODING_MODE_LAST_BLOCK;
4932 ok = e_write (desc, Qnil, 1, 1, &coding);
4933 save_errno = errno;
4936 /* fsync is not crucial for temporary files. Nor for auto-save
4937 files, since they might lose some work anyway. */
4938 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4940 /* Transfer data and metadata to disk, retrying if interrupted.
4941 fsync can report a write failure here, e.g., due to disk full
4942 under NFS. But ignore EINVAL, which means fsync is not
4943 supported on this file. */
4944 while (fsync (desc) != 0)
4945 if (errno != EINTR)
4947 if (errno != EINVAL)
4948 ok = 0, save_errno = errno;
4949 break;
4953 modtime = invalid_timespec ();
4954 if (visiting)
4956 if (fstat (desc, &st) == 0)
4957 modtime = get_stat_mtime (&st);
4958 else
4959 ok = 0, save_errno = errno;
4962 if (open_and_close_file)
4964 /* NFS can report a write failure now. */
4965 if (emacs_close (desc) < 0)
4966 ok = 0, save_errno = errno;
4968 /* Discard the unwind protect for close_file_unwind. */
4969 specpdl_ptr = specpdl + count1;
4972 /* Some file systems have a bug where st_mtime is not updated
4973 properly after a write. For example, CIFS might not see the
4974 st_mtime change until after the file is opened again.
4976 Attempt to detect this file system bug, and update MODTIME to the
4977 newer st_mtime if the bug appears to be present. This introduces
4978 a race condition, so to avoid most instances of the race condition
4979 on non-buggy file systems, skip this check if the most recently
4980 encountered non-buggy file system was the current file system.
4982 A race condition can occur if some other process modifies the
4983 file between the fstat above and the fstat below, but the race is
4984 unlikely and a similar race between the last write and the fstat
4985 above cannot possibly be closed anyway. */
4987 if (timespec_valid_p (modtime)
4988 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4990 int desc1 = emacs_open (fn, O_WRONLY, 0);
4991 if (desc1 >= 0)
4993 struct stat st1;
4994 if (fstat (desc1, &st1) == 0
4995 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4997 /* Use the heuristic if it appears to be valid. With neither
4998 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4999 file, the time stamp won't change. Also, some non-POSIX
5000 systems don't update an empty file's time stamp when
5001 truncating it. Finally, file systems with 100 ns or worse
5002 resolution sometimes seem to have bugs: on a system with ns
5003 resolution, checking ns % 100 incorrectly avoids the heuristic
5004 1% of the time, but the problem should be temporary as we will
5005 try again on the next time stamp. */
5006 bool use_heuristic
5007 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
5008 && st.st_size != 0
5009 && modtime.tv_nsec % 100 != 0);
5011 struct timespec modtime1 = get_stat_mtime (&st1);
5012 if (use_heuristic
5013 && timespec_cmp (modtime, modtime1) == 0
5014 && st.st_size == st1.st_size)
5016 timestamp_file_system = st.st_dev;
5017 valid_timestamp_file_system = 1;
5019 else
5021 st.st_size = st1.st_size;
5022 modtime = modtime1;
5025 emacs_close (desc1);
5029 /* Call write-region-post-annotation-function. */
5030 while (CONSP (Vwrite_region_annotation_buffers))
5032 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5033 if (!NILP (Fbuffer_live_p (buf)))
5035 Fset_buffer (buf);
5036 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5037 call0 (Vwrite_region_post_annotation_function);
5039 Vwrite_region_annotation_buffers
5040 = XCDR (Vwrite_region_annotation_buffers);
5043 unbind_to (count, Qnil);
5045 if (file_locked)
5046 unlock_file (lockname);
5048 /* Do this before reporting IO error
5049 to avoid a "file has changed on disk" warning on
5050 next attempt to save. */
5051 if (timespec_valid_p (modtime))
5053 current_buffer->modtime = modtime;
5054 current_buffer->modtime_size = st.st_size;
5057 if (! ok)
5058 report_file_errno ("Write error", filename, save_errno);
5060 bool auto_saving_into_visited_file =
5061 auto_saving
5062 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5063 BVAR (current_buffer, auto_save_file_name)));
5064 if (visiting)
5066 SAVE_MODIFF = MODIFF;
5067 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5068 bset_filename (current_buffer, visit_file);
5069 update_mode_lines = 14;
5070 if (auto_saving_into_visited_file)
5071 unlock_file (lockname);
5073 else if (quietly)
5075 if (auto_saving_into_visited_file)
5077 SAVE_MODIFF = MODIFF;
5078 unlock_file (lockname);
5081 return Qnil;
5084 if (!auto_saving && !noninteractive)
5085 message_with_string ((NUMBERP (append)
5086 ? "Updated %s"
5087 : ! NILP (append)
5088 ? "Added to %s"
5089 : "Wrote %s"),
5090 visit_file, 1);
5092 return Qnil;
5095 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5096 doc: /* Return t if (car A) is numerically less than (car B). */)
5097 (Lisp_Object a, Lisp_Object b)
5099 return arithcompare (Fcar (a), Fcar (b), ARITH_LESS);
5102 /* Build the complete list of annotations appropriate for writing out
5103 the text between START and END, by calling all the functions in
5104 write-region-annotate-functions and merging the lists they return.
5105 If one of these functions switches to a different buffer, we assume
5106 that buffer contains altered text. Therefore, the caller must
5107 make sure to restore the current buffer in all cases,
5108 as save-excursion would do. */
5110 static Lisp_Object
5111 build_annotations (Lisp_Object start, Lisp_Object end)
5113 Lisp_Object annotations;
5114 Lisp_Object p, res;
5115 Lisp_Object original_buffer;
5116 int i;
5117 bool used_global = false;
5119 XSETBUFFER (original_buffer, current_buffer);
5121 annotations = Qnil;
5122 p = Vwrite_region_annotate_functions;
5123 while (CONSP (p))
5125 struct buffer *given_buffer = current_buffer;
5126 if (EQ (Qt, XCAR (p)) && !used_global)
5127 { /* Use the global value of the hook. */
5128 used_global = true;
5129 p = CALLN (Fappend,
5130 Fdefault_value (Qwrite_region_annotate_functions),
5131 XCDR (p));
5132 continue;
5134 Vwrite_region_annotations_so_far = annotations;
5135 res = call2 (XCAR (p), start, end);
5136 /* If the function makes a different buffer current,
5137 assume that means this buffer contains altered text to be output.
5138 Reset START and END from the buffer bounds
5139 and discard all previous annotations because they should have
5140 been dealt with by this function. */
5141 if (current_buffer != given_buffer)
5143 Vwrite_region_annotation_buffers
5144 = Fcons (Fcurrent_buffer (),
5145 Vwrite_region_annotation_buffers);
5146 XSETFASTINT (start, BEGV);
5147 XSETFASTINT (end, ZV);
5148 annotations = Qnil;
5150 Flength (res); /* Check basic validity of return value */
5151 annotations = merge (annotations, res, Qcar_less_than_car);
5152 p = XCDR (p);
5155 /* Now do the same for annotation functions implied by the file-format */
5156 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5157 p = BVAR (current_buffer, auto_save_file_format);
5158 else
5159 p = BVAR (current_buffer, file_format);
5160 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5162 struct buffer *given_buffer = current_buffer;
5164 Vwrite_region_annotations_so_far = annotations;
5166 /* Value is either a list of annotations or nil if the function
5167 has written annotations to a temporary buffer, which is now
5168 current. */
5169 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5170 original_buffer, make_number (i));
5171 if (current_buffer != given_buffer)
5173 XSETFASTINT (start, BEGV);
5174 XSETFASTINT (end, ZV);
5175 annotations = Qnil;
5178 if (CONSP (res))
5179 annotations = merge (annotations, res, Qcar_less_than_car);
5182 return annotations;
5186 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5187 If STRING is nil, POS is the character position in the current buffer.
5188 Intersperse with them the annotations from *ANNOT
5189 which fall within the range of POS to POS + NCHARS,
5190 each at its appropriate position.
5192 We modify *ANNOT by discarding elements as we use them up.
5194 Return true if successful. */
5196 static bool
5197 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5198 ptrdiff_t nchars, Lisp_Object *annot,
5199 struct coding_system *coding)
5201 Lisp_Object tem;
5202 ptrdiff_t nextpos;
5203 ptrdiff_t lastpos = pos + nchars;
5205 while (NILP (*annot) || CONSP (*annot))
5207 tem = Fcar_safe (Fcar (*annot));
5208 nextpos = pos - 1;
5209 if (INTEGERP (tem))
5210 nextpos = XFASTINT (tem);
5212 /* If there are no more annotations in this range,
5213 output the rest of the range all at once. */
5214 if (! (nextpos >= pos && nextpos <= lastpos))
5215 return e_write (desc, string, pos, lastpos, coding);
5217 /* Output buffer text up to the next annotation's position. */
5218 if (nextpos > pos)
5220 if (!e_write (desc, string, pos, nextpos, coding))
5221 return 0;
5222 pos = nextpos;
5224 /* Output the annotation. */
5225 tem = Fcdr (Fcar (*annot));
5226 if (STRINGP (tem))
5228 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5229 return 0;
5231 *annot = Fcdr (*annot);
5233 return 1;
5236 /* Maximum number of characters that the next
5237 function encodes per one loop iteration. */
5239 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5241 /* Write text in the range START and END into descriptor DESC,
5242 encoding them with coding system CODING. If STRING is nil, START
5243 and END are character positions of the current buffer, else they
5244 are indexes to the string STRING. Return true if successful. */
5246 static bool
5247 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5248 struct coding_system *coding)
5250 if (STRINGP (string))
5252 start = 0;
5253 end = SCHARS (string);
5256 /* We used to have a code for handling selective display here. But,
5257 now it is handled within encode_coding. */
5259 while (start < end)
5261 if (STRINGP (string))
5263 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5264 if (CODING_REQUIRE_ENCODING (coding))
5266 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5268 /* Avoid creating huge Lisp string in encode_coding_object. */
5269 if (nchars == E_WRITE_MAX)
5270 coding->raw_destination = 1;
5272 encode_coding_object
5273 (coding, string, start, string_char_to_byte (string, start),
5274 start + nchars, string_char_to_byte (string, start + nchars),
5275 Qt);
5277 else
5279 coding->dst_object = string;
5280 coding->consumed_char = SCHARS (string);
5281 coding->produced = SBYTES (string);
5284 else
5286 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5287 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5289 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5290 if (CODING_REQUIRE_ENCODING (coding))
5292 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5294 /* Likewise. */
5295 if (nchars == E_WRITE_MAX)
5296 coding->raw_destination = 1;
5298 encode_coding_object
5299 (coding, Fcurrent_buffer (), start, start_byte,
5300 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5302 else
5304 coding->dst_object = Qnil;
5305 coding->dst_pos_byte = start_byte;
5306 if (start >= GPT || end <= GPT)
5308 coding->consumed_char = end - start;
5309 coding->produced = end_byte - start_byte;
5311 else
5313 coding->consumed_char = GPT - start;
5314 coding->produced = GPT_BYTE - start_byte;
5319 if (coding->produced > 0)
5321 char *buf = (coding->raw_destination ? (char *) coding->destination
5322 : (STRINGP (coding->dst_object)
5323 ? SSDATA (coding->dst_object)
5324 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5325 coding->produced -= emacs_write_quit (desc, buf, coding->produced);
5327 if (coding->raw_destination)
5329 /* We're responsible for freeing this, see
5330 encode_coding_object to check why. */
5331 xfree (coding->destination);
5332 coding->raw_destination = 0;
5334 if (coding->produced)
5335 return 0;
5337 start += coding->consumed_char;
5340 return 1;
5343 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5344 Sverify_visited_file_modtime, 0, 1, 0,
5345 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5346 This means that the file has not been changed since it was visited or saved.
5347 If BUF is omitted or nil, it defaults to the current buffer.
5348 See Info node `(elisp)Modification Time' for more details. */)
5349 (Lisp_Object buf)
5351 struct buffer *b = decode_buffer (buf);
5352 struct stat st;
5353 Lisp_Object handler;
5354 Lisp_Object filename;
5355 struct timespec mtime;
5357 if (!STRINGP (BVAR (b, filename))) return Qt;
5358 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5360 /* If the file name has special constructs in it,
5361 call the corresponding file handler. */
5362 handler = Ffind_file_name_handler (BVAR (b, filename),
5363 Qverify_visited_file_modtime);
5364 if (!NILP (handler))
5365 return call2 (handler, Qverify_visited_file_modtime, buf);
5367 filename = ENCODE_FILE (BVAR (b, filename));
5369 mtime = (stat (SSDATA (filename), &st) == 0
5370 ? get_stat_mtime (&st)
5371 : time_error_value (errno));
5372 if (timespec_cmp (mtime, b->modtime) == 0
5373 && (b->modtime_size < 0
5374 || st.st_size == b->modtime_size))
5375 return Qt;
5376 return Qnil;
5379 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5380 Svisited_file_modtime, 0, 0, 0,
5381 doc: /* Return the current buffer's recorded visited file modification time.
5382 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5383 `file-attributes' returns. If the current buffer has no recorded file
5384 modification time, this function returns 0. If the visited file
5385 doesn't exist, return -1.
5386 See Info node `(elisp)Modification Time' for more details. */)
5387 (void)
5389 int ns = current_buffer->modtime.tv_nsec;
5390 if (ns < 0)
5391 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5392 return make_lisp_time (current_buffer->modtime);
5395 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5396 Sset_visited_file_modtime, 0, 1, 0,
5397 doc: /* Update buffer's recorded modification time from the visited file's time.
5398 Useful if the buffer was not read from the file normally
5399 or if the file itself has been changed for some known benign reason.
5400 An argument specifies the modification time value to use
5401 \(instead of that of the visited file), in the form of a list
5402 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5403 `visited-file-modtime'. */)
5404 (Lisp_Object time_flag)
5406 if (!NILP (time_flag))
5408 struct timespec mtime;
5409 if (INTEGERP (time_flag))
5411 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5412 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5414 else
5415 mtime = lisp_time_argument (time_flag);
5417 current_buffer->modtime = mtime;
5418 current_buffer->modtime_size = -1;
5420 else
5422 register Lisp_Object filename;
5423 struct stat st;
5424 Lisp_Object handler;
5426 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5428 /* If the file name has special constructs in it,
5429 call the corresponding file handler. */
5430 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5431 if (!NILP (handler))
5432 /* The handler can find the file name the same way we did. */
5433 return call2 (handler, Qset_visited_file_modtime, Qnil);
5435 filename = ENCODE_FILE (filename);
5437 if (stat (SSDATA (filename), &st) >= 0)
5439 current_buffer->modtime = get_stat_mtime (&st);
5440 current_buffer->modtime_size = st.st_size;
5444 return Qnil;
5447 static Lisp_Object
5448 auto_save_error (Lisp_Object error_val)
5450 auto_save_error_occurred = 1;
5452 ring_bell (XFRAME (selected_frame));
5454 AUTO_STRING (format, "Auto-saving %s: %s");
5455 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5456 Ferror_message_string (error_val));
5457 call3 (intern ("display-warning"),
5458 intern ("auto-save"), msg, intern ("error"));
5460 return Qnil;
5463 static Lisp_Object
5464 auto_save_1 (void)
5466 struct stat st;
5467 Lisp_Object modes;
5469 auto_save_mode_bits = 0666;
5471 /* Get visited file's mode to become the auto save file's mode. */
5472 if (! NILP (BVAR (current_buffer, filename)))
5474 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5475 /* But make sure we can overwrite it later! */
5476 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5477 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5478 INTEGERP (modes))
5479 /* Remote files don't cooperate with stat. */
5480 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5483 return
5484 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5485 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5486 Qnil, Qnil);
5489 struct auto_save_unwind
5491 FILE *stream;
5492 bool auto_raise;
5495 static void
5496 do_auto_save_unwind (void *arg)
5498 struct auto_save_unwind *p = arg;
5499 FILE *stream = p->stream;
5500 minibuffer_auto_raise = p->auto_raise;
5501 auto_saving = 0;
5502 if (stream != NULL)
5504 block_input ();
5505 fclose (stream);
5506 unblock_input ();
5510 static Lisp_Object
5511 do_auto_save_make_dir (Lisp_Object dir)
5513 Lisp_Object result;
5515 auto_saving_dir_umask = 077;
5516 result = call2 (Qmake_directory, dir, Qt);
5517 auto_saving_dir_umask = 0;
5518 return result;
5521 static Lisp_Object
5522 do_auto_save_eh (Lisp_Object ignore)
5524 auto_saving_dir_umask = 0;
5525 return Qnil;
5528 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5529 doc: /* Auto-save all buffers that need it.
5530 This is all buffers that have auto-saving enabled
5531 and are changed since last auto-saved.
5532 Auto-saving writes the buffer into a file
5533 so that your editing is not lost if the system crashes.
5534 This file is not the file you visited; that changes only when you save.
5535 Normally, run the normal hook `auto-save-hook' before saving.
5537 A non-nil NO-MESSAGE argument means do not print any message if successful.
5538 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5539 (Lisp_Object no_message, Lisp_Object current_only)
5541 struct buffer *old = current_buffer, *b;
5542 Lisp_Object tail, buf, hook;
5543 bool auto_saved = 0;
5544 int do_handled_files;
5545 Lisp_Object oquit;
5546 FILE *stream = NULL;
5547 ptrdiff_t count = SPECPDL_INDEX ();
5548 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5549 bool old_message_p = 0;
5550 struct auto_save_unwind auto_save_unwind;
5552 if (max_specpdl_size < specpdl_size + 40)
5553 max_specpdl_size = specpdl_size + 40;
5555 if (minibuf_level)
5556 no_message = Qt;
5558 if (NILP (no_message))
5560 old_message_p = push_message ();
5561 record_unwind_protect_void (pop_message_unwind);
5564 /* Ordinarily don't quit within this function,
5565 but don't make it impossible to quit (in case we get hung in I/O). */
5566 oquit = Vquit_flag;
5567 Vquit_flag = Qnil;
5569 hook = intern ("auto-save-hook");
5570 safe_run_hooks (hook);
5572 if (STRINGP (Vauto_save_list_file_name))
5574 Lisp_Object listfile;
5576 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5578 /* Don't try to create the directory when shutting down Emacs,
5579 because creating the directory might signal an error, and
5580 that would leave Emacs in a strange state. */
5581 if (!NILP (Vrun_hooks))
5583 Lisp_Object dir;
5584 dir = Ffile_name_directory (listfile);
5585 if (NILP (Ffile_directory_p (dir)))
5586 internal_condition_case_1 (do_auto_save_make_dir,
5587 dir, Qt,
5588 do_auto_save_eh);
5591 stream = emacs_fopen (SSDATA (listfile), "w");
5594 auto_save_unwind.stream = stream;
5595 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5596 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5597 minibuffer_auto_raise = 0;
5598 auto_saving = 1;
5599 auto_save_error_occurred = 0;
5601 /* On first pass, save all files that don't have handlers.
5602 On second pass, save all files that do have handlers.
5604 If Emacs is crashing, the handlers may tweak what is causing
5605 Emacs to crash in the first place, and it would be a shame if
5606 Emacs failed to autosave perfectly ordinary files because it
5607 couldn't handle some ange-ftp'd file. */
5609 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5610 FOR_EACH_LIVE_BUFFER (tail, buf)
5612 b = XBUFFER (buf);
5614 /* Record all the buffers that have auto save mode
5615 in the special file that lists them. For each of these buffers,
5616 Record visited name (if any) and auto save name. */
5617 if (STRINGP (BVAR (b, auto_save_file_name))
5618 && stream != NULL && do_handled_files == 0)
5620 block_input ();
5621 if (!NILP (BVAR (b, filename)))
5622 fwrite_unlocked (SDATA (BVAR (b, filename)), 1,
5623 SBYTES (BVAR (b, filename)), stream);
5624 putc_unlocked ('\n', stream);
5625 fwrite_unlocked (SDATA (BVAR (b, auto_save_file_name)), 1,
5626 SBYTES (BVAR (b, auto_save_file_name)), stream);
5627 putc_unlocked ('\n', stream);
5628 unblock_input ();
5631 if (!NILP (current_only)
5632 && b != current_buffer)
5633 continue;
5635 /* Don't auto-save indirect buffers.
5636 The base buffer takes care of it. */
5637 if (b->base_buffer)
5638 continue;
5640 /* Check for auto save enabled
5641 and file changed since last auto save
5642 and file changed since last real save. */
5643 if (STRINGP (BVAR (b, auto_save_file_name))
5644 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5645 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5646 /* -1 means we've turned off autosaving for a while--see below. */
5647 && XINT (BVAR (b, save_length)) >= 0
5648 && (do_handled_files
5649 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5650 Qwrite_region))))
5652 struct timespec before_time = current_timespec ();
5653 struct timespec after_time;
5655 /* If we had a failure, don't try again for 20 minutes. */
5656 if (b->auto_save_failure_time > 0
5657 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5658 continue;
5660 set_buffer_internal (b);
5661 if (NILP (Vauto_save_include_big_deletions)
5662 && (XFASTINT (BVAR (b, save_length)) * 10
5663 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5664 /* A short file is likely to change a large fraction;
5665 spare the user annoying messages. */
5666 && XFASTINT (BVAR (b, save_length)) > 5000
5667 /* These messages are frequent and annoying for `*mail*'. */
5668 && !EQ (BVAR (b, filename), Qnil)
5669 && NILP (no_message))
5671 /* It has shrunk too much; turn off auto-saving here. */
5672 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5673 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5674 BVAR (b, name), 1);
5675 minibuffer_auto_raise = 0;
5676 /* Turn off auto-saving until there's a real save,
5677 and prevent any more warnings. */
5678 XSETINT (BVAR (b, save_length), -1);
5679 Fsleep_for (make_number (1), Qnil);
5680 continue;
5682 if (!auto_saved && NILP (no_message))
5683 message1 ("Auto-saving...");
5684 internal_condition_case (auto_save_1, Qt, auto_save_error);
5685 auto_saved = 1;
5686 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5687 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5688 set_buffer_internal (old);
5690 after_time = current_timespec ();
5692 /* If auto-save took more than 60 seconds,
5693 assume it was an NFS failure that got a timeout. */
5694 if (after_time.tv_sec - before_time.tv_sec > 60)
5695 b->auto_save_failure_time = after_time.tv_sec;
5699 /* Prevent another auto save till enough input events come in. */
5700 record_auto_save ();
5702 if (auto_saved && NILP (no_message))
5704 if (old_message_p)
5706 /* If we are going to restore an old message,
5707 give time to read ours. */
5708 sit_for (make_number (1), 0, 0);
5709 restore_message ();
5711 else if (!auto_save_error_occurred)
5712 /* Don't overwrite the error message if an error occurred.
5713 If we displayed a message and then restored a state
5714 with no message, leave a "done" message on the screen. */
5715 message1 ("Auto-saving...done");
5718 Vquit_flag = oquit;
5720 /* This restores the message-stack status. */
5721 unbind_to (count, Qnil);
5722 return Qnil;
5725 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5726 Sset_buffer_auto_saved, 0, 0, 0,
5727 doc: /* Mark current buffer as auto-saved with its current text.
5728 No auto-save file will be written until the buffer changes again. */)
5729 (void)
5731 /* FIXME: This should not be called in indirect buffers, since
5732 they're not autosaved. */
5733 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5734 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5735 current_buffer->auto_save_failure_time = 0;
5736 return Qnil;
5739 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5740 Sclear_buffer_auto_save_failure, 0, 0, 0,
5741 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5742 (void)
5744 current_buffer->auto_save_failure_time = 0;
5745 return Qnil;
5748 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5749 0, 0, 0,
5750 doc: /* Return t if current buffer has been auto-saved recently.
5751 More precisely, if it has been auto-saved since last read from or saved
5752 in the visited file. If the buffer has no visited file,
5753 then any auto-save counts as "recent". */)
5754 (void)
5756 /* FIXME: maybe we should return nil for indirect buffers since
5757 they're never autosaved. */
5758 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5761 /* Reading and completing file names. */
5763 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5764 Snext_read_file_uses_dialog_p, 0, 0, 0,
5765 doc: /* Return t if a call to `read-file-name' will use a dialog.
5766 The return value is only relevant for a call to `read-file-name' that happens
5767 before any other event (mouse or keypress) is handled. */)
5768 (void)
5770 #if (defined USE_GTK || defined USE_MOTIF \
5771 || defined HAVE_NS || defined HAVE_NTGUI)
5772 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5773 && use_dialog_box
5774 && use_file_dialog
5775 && window_system_available (SELECTED_FRAME ()))
5776 return Qt;
5777 #endif
5778 return Qnil;
5782 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5783 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5784 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5785 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5786 it to text mode.
5788 As a side effect, this function flushes any pending STREAM's data.
5790 Value is the previous value of STREAM's I/O mode, nil for text mode,
5791 non-nil for binary mode.
5793 On MS-Windows and MS-DOS, binary mode is needed to read or write
5794 arbitrary binary data, and for disabling translation between CR-LF
5795 pairs and a single newline character. Examples include generation
5796 of text files with Unix-style end-of-line format using `princ' in
5797 batch mode, with standard output redirected to a file.
5799 On Posix systems, this function always returns non-nil, and has no
5800 effect except for flushing STREAM's data. */)
5801 (Lisp_Object stream, Lisp_Object mode)
5803 FILE *fp = NULL;
5804 int binmode;
5806 CHECK_SYMBOL (stream);
5807 if (EQ (stream, Qstdin))
5808 fp = stdin;
5809 else if (EQ (stream, Qstdout))
5810 fp = stdout;
5811 else if (EQ (stream, Qstderr))
5812 fp = stderr;
5813 else
5814 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5816 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5817 if (fp != stdin)
5818 fflush_unlocked (fp);
5820 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5823 #ifndef DOS_NT
5825 /* Yield a Lisp float as close as possible to BLOCKSIZE * BLOCKS, with
5826 the result negated if NEGATE. */
5827 static Lisp_Object
5828 blocks_to_bytes (uintmax_t blocksize, uintmax_t blocks, bool negate)
5830 /* On typical platforms the following code is accurate to 53 bits,
5831 which is close enough. BLOCKSIZE is invariably a power of 2, so
5832 converting it to double does not lose information. */
5833 double bs = blocksize;
5834 return make_float (negate ? -bs * -blocks : bs * blocks);
5837 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
5838 doc: /* Return storage information about the file system FILENAME is on.
5839 Value is a list of numbers (TOTAL FREE AVAIL), where TOTAL is the total
5840 storage of the file system, FREE is the free storage, and AVAIL is the
5841 storage available to a non-superuser. All 3 numbers are in bytes.
5842 If the underlying system call fails, value is nil. */)
5843 (Lisp_Object filename)
5845 Lisp_Object encoded = ENCODE_FILE (Fexpand_file_name (filename, Qnil));
5847 /* If the file name has special constructs in it,
5848 call the corresponding file handler. */
5849 Lisp_Object handler = Ffind_file_name_handler (encoded, Qfile_system_info);
5850 if (!NILP (handler))
5852 Lisp_Object result = call2 (handler, Qfile_system_info, encoded);
5853 if (CONSP (result) || NILP (result))
5854 return result;
5855 error ("Invalid handler in `file-name-handler-alist'");
5858 struct fs_usage u;
5859 if (get_fs_usage (SSDATA (encoded), NULL, &u) != 0)
5860 return Qnil;
5861 return list3 (blocks_to_bytes (u.fsu_blocksize, u.fsu_blocks, false),
5862 blocks_to_bytes (u.fsu_blocksize, u.fsu_bfree, false),
5863 blocks_to_bytes (u.fsu_blocksize, u.fsu_bavail,
5864 u.fsu_bavail_top_bit_set));
5867 #endif /* !DOS_NT */
5869 void
5870 init_fileio (void)
5872 realmask = umask (0);
5873 umask (realmask);
5875 valid_timestamp_file_system = 0;
5877 /* fsync can be a significant performance hit. Often it doesn't
5878 suffice to make the file-save operation survive a crash. For
5879 batch scripts, which are typically part of larger shell commands
5880 that don't fsync other files, its effect on performance can be
5881 significant so its utility is particularly questionable.
5882 Hence, for now by default fsync is used only when interactive.
5884 For more on why fsync often fails to work on today's hardware, see:
5885 Zheng M et al. Understanding the robustness of SSDs under power fault.
5886 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5887 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5889 For more on why fsync does not suffice even if it works properly, see:
5890 Roche X. Necessary step(s) to synchronize filename operations on disk.
5891 Austin Group Defect 672, 2013-03-19
5892 http://austingroupbugs.net/view.php?id=672 */
5893 write_region_inhibit_fsync = noninteractive;
5896 void
5897 syms_of_fileio (void)
5899 /* Property name of a file name handler,
5900 which gives a list of operations it handles. */
5901 DEFSYM (Qoperations, "operations");
5903 DEFSYM (Qexpand_file_name, "expand-file-name");
5904 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5905 DEFSYM (Qdirectory_file_name, "directory-file-name");
5906 DEFSYM (Qfile_name_directory, "file-name-directory");
5907 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5908 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5909 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5910 DEFSYM (Qcopy_file, "copy-file");
5911 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5912 DEFSYM (Qmake_directory, "make-directory");
5913 DEFSYM (Qdelete_file, "delete-file");
5914 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5915 DEFSYM (Qrename_file, "rename-file");
5916 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5917 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5918 DEFSYM (Qfile_exists_p, "file-exists-p");
5919 DEFSYM (Qfile_executable_p, "file-executable-p");
5920 DEFSYM (Qfile_readable_p, "file-readable-p");
5921 DEFSYM (Qfile_writable_p, "file-writable-p");
5922 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5923 DEFSYM (Qaccess_file, "access-file");
5924 DEFSYM (Qfile_directory_p, "file-directory-p");
5925 DEFSYM (Qfile_regular_p, "file-regular-p");
5926 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5927 DEFSYM (Qfile_modes, "file-modes");
5928 DEFSYM (Qset_file_modes, "set-file-modes");
5929 DEFSYM (Qset_file_times, "set-file-times");
5930 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5931 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5932 DEFSYM (Qfile_acl, "file-acl");
5933 DEFSYM (Qset_file_acl, "set-file-acl");
5934 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5935 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5936 DEFSYM (Qwrite_region, "write-region");
5937 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5938 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5939 DEFSYM (Qfile_system_info, "file-system-info");
5941 /* The symbol bound to coding-system-for-read when
5942 insert-file-contents is called for recovering a file. This is not
5943 an actual coding system name, but just an indicator to tell
5944 insert-file-contents to use `emacs-mule' with a special flag for
5945 auto saving and recovering a file. */
5946 DEFSYM (Qauto_save_coding, "auto-save-coding");
5948 DEFSYM (Qfile_name_history, "file-name-history");
5949 Fset (Qfile_name_history, Qnil);
5951 DEFSYM (Qfile_error, "file-error");
5952 DEFSYM (Qfile_already_exists, "file-already-exists");
5953 DEFSYM (Qfile_date_error, "file-date-error");
5954 DEFSYM (Qfile_missing, "file-missing");
5955 DEFSYM (Qfile_notify_error, "file-notify-error");
5956 DEFSYM (Qexcl, "excl");
5958 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5959 doc: /* Coding system for encoding file names.
5960 If it is nil, `default-file-name-coding-system' (which see) is used.
5962 On MS-Windows, the value of this variable is largely ignored if
5963 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5964 behaves as if file names were encoded in `utf-8'. */);
5965 Vfile_name_coding_system = Qnil;
5967 DEFVAR_LISP ("default-file-name-coding-system",
5968 Vdefault_file_name_coding_system,
5969 doc: /* Default coding system for encoding file names.
5970 This variable is used only when `file-name-coding-system' is nil.
5972 This variable is set/changed by the command `set-language-environment'.
5973 User should not set this variable manually,
5974 instead use `file-name-coding-system' to get a constant encoding
5975 of file names regardless of the current language environment.
5977 On MS-Windows, the value of this variable is largely ignored if
5978 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5979 behaves as if file names were encoded in `utf-8'. */);
5980 Vdefault_file_name_coding_system = Qnil;
5982 /* Lisp functions for translating file formats. */
5983 DEFSYM (Qformat_decode, "format-decode");
5984 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5986 /* Lisp function for setting buffer-file-coding-system and the
5987 multibyteness of the current buffer after inserting a file. */
5988 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5990 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5992 Fput (Qfile_error, Qerror_conditions,
5993 Fpurecopy (list2 (Qfile_error, Qerror)));
5994 Fput (Qfile_error, Qerror_message,
5995 build_pure_c_string ("File error"));
5997 Fput (Qfile_already_exists, Qerror_conditions,
5998 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5999 Fput (Qfile_already_exists, Qerror_message,
6000 build_pure_c_string ("File already exists"));
6002 Fput (Qfile_date_error, Qerror_conditions,
6003 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
6004 Fput (Qfile_date_error, Qerror_message,
6005 build_pure_c_string ("Cannot set file date"));
6007 Fput (Qfile_missing, Qerror_conditions,
6008 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
6009 Fput (Qfile_missing, Qerror_message,
6010 build_pure_c_string ("File is missing"));
6012 Fput (Qfile_notify_error, Qerror_conditions,
6013 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
6014 Fput (Qfile_notify_error, Qerror_message,
6015 build_pure_c_string ("File notification error"));
6017 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
6018 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
6019 If a file name matches REGEXP, all I/O on that file is done by calling
6020 HANDLER. If a file name matches more than one handler, the handler
6021 whose match starts last in the file name gets precedence. The
6022 function `find-file-name-handler' checks this list for a handler for
6023 its argument.
6025 HANDLER should be a function. The first argument given to it is the
6026 name of the I/O primitive to be handled; the remaining arguments are
6027 the arguments that were passed to that primitive. For example, if you
6028 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
6029 HANDLER is called like this:
6031 (funcall HANDLER \\='file-exists-p FILENAME)
6033 Note that HANDLER must be able to handle all I/O primitives; if it has
6034 nothing special to do for a primitive, it should reinvoke the
6035 primitive to handle the operation \"the usual way\".
6036 See Info node `(elisp)Magic File Names' for more details. */);
6037 Vfile_name_handler_alist = Qnil;
6039 DEFVAR_LISP ("set-auto-coding-function",
6040 Vset_auto_coding_function,
6041 doc: /* If non-nil, a function to call to decide a coding system of file.
6042 Two arguments are passed to this function: the file name
6043 and the length of a file contents following the point.
6044 This function should return a coding system to decode the file contents.
6045 It should check the file name against `auto-coding-alist'.
6046 If no coding system is decided, it should check a coding system
6047 specified in the heading lines with the format:
6048 -*- ... coding: CODING-SYSTEM; ... -*-
6049 or local variable spec of the tailing lines with `coding:' tag. */);
6050 Vset_auto_coding_function = Qnil;
6052 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
6053 doc: /* A list of functions to be called at the end of `insert-file-contents'.
6054 Each is passed one argument, the number of characters inserted,
6055 with point at the start of the inserted text. Each function
6056 should leave point the same, and return the new character count.
6057 If `insert-file-contents' is intercepted by a handler from
6058 `file-name-handler-alist', that handler is responsible for calling the
6059 functions in `after-insert-file-functions' if appropriate. */);
6060 Vafter_insert_file_functions = Qnil;
6062 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
6063 doc: /* A list of functions to be called at the start of `write-region'.
6064 Each is passed two arguments, START and END as for `write-region'.
6065 These are usually two numbers but not always; see the documentation
6066 for `write-region'. The function should return a list of pairs
6067 of the form (POSITION . STRING), consisting of strings to be effectively
6068 inserted at the specified positions of the file being written (1 means to
6069 insert before the first byte written). The POSITIONs must be sorted into
6070 increasing order.
6072 If there are several annotation functions, the lists returned by these
6073 functions are merged destructively. As each annotation function runs,
6074 the variable `write-region-annotations-so-far' contains a list of all
6075 annotations returned by previous annotation functions.
6077 An annotation function can return with a different buffer current.
6078 Doing so removes the annotations returned by previous functions, and
6079 resets START and END to `point-min' and `point-max' of the new buffer.
6081 After `write-region' completes, Emacs calls the function stored in
6082 `write-region-post-annotation-function', once for each buffer that was
6083 current when building the annotations (i.e., at least once), with that
6084 buffer current. */);
6085 Vwrite_region_annotate_functions = Qnil;
6086 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6088 DEFVAR_LISP ("write-region-post-annotation-function",
6089 Vwrite_region_post_annotation_function,
6090 doc: /* Function to call after `write-region' completes.
6091 The function is called with no arguments. If one or more of the
6092 annotation functions in `write-region-annotate-functions' changed the
6093 current buffer, the function stored in this variable is called for
6094 each of those additional buffers as well, in addition to the original
6095 buffer. The relevant buffer is current during each function call. */);
6096 Vwrite_region_post_annotation_function = Qnil;
6097 staticpro (&Vwrite_region_annotation_buffers);
6099 DEFVAR_LISP ("write-region-annotations-so-far",
6100 Vwrite_region_annotations_so_far,
6101 doc: /* When an annotation function is called, this holds the previous annotations.
6102 These are the annotations made by other annotation functions
6103 that were already called. See also `write-region-annotate-functions'. */);
6104 Vwrite_region_annotations_so_far = Qnil;
6106 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6107 doc: /* A list of file name handlers that temporarily should not be used.
6108 This applies only to the operation `inhibit-file-name-operation'. */);
6109 Vinhibit_file_name_handlers = Qnil;
6111 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6112 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6113 Vinhibit_file_name_operation = Qnil;
6115 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6116 doc: /* File name in which to write a list of all auto save file names.
6117 This variable is initialized automatically from `auto-save-list-file-prefix'
6118 shortly after Emacs reads your init file, if you have not yet given it
6119 a non-nil value. */);
6120 Vauto_save_list_file_name = Qnil;
6122 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6123 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6124 Normally auto-save files are written under other names. */);
6125 Vauto_save_visited_file_name = Qnil;
6127 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6128 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6129 If nil, deleting a substantial portion of the text disables auto-save
6130 in the buffer; this is the default behavior, because the auto-save
6131 file is usually more useful if it contains the deleted text. */);
6132 Vauto_save_include_big_deletions = Qnil;
6134 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6135 doc: /* Non-nil means don't call fsync in `write-region'.
6136 This variable affects calls to `write-region' as well as save commands.
6137 Setting this to nil may avoid data loss if the system loses power or
6138 the operating system crashes. By default, it is non-nil in batch mode. */);
6139 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6141 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6142 doc: /* Specifies whether to use the system's trash can.
6143 When non-nil, certain file deletion commands use the function
6144 `move-file-to-trash' instead of deleting files outright.
6145 This includes interactive calls to `delete-file' and
6146 `delete-directory' and the Dired deletion commands. */);
6147 delete_by_moving_to_trash = 0;
6148 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6150 /* Lisp function for moving files to trash. */
6151 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6153 /* Lisp function for recursively copying directories. */
6154 DEFSYM (Qcopy_directory, "copy-directory");
6156 /* Lisp function for recursively deleting directories. */
6157 DEFSYM (Qdelete_directory, "delete-directory");
6159 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6160 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6162 DEFSYM (Qstdin, "stdin");
6163 DEFSYM (Qstdout, "stdout");
6164 DEFSYM (Qstderr, "stderr");
6166 defsubr (&Sfind_file_name_handler);
6167 defsubr (&Sfile_name_directory);
6168 defsubr (&Sfile_name_nondirectory);
6169 defsubr (&Sunhandled_file_name_directory);
6170 defsubr (&Sfile_name_as_directory);
6171 defsubr (&Sdirectory_name_p);
6172 defsubr (&Sdirectory_file_name);
6173 defsubr (&Smake_temp_file_internal);
6174 defsubr (&Smake_temp_name);
6175 defsubr (&Sexpand_file_name);
6176 defsubr (&Ssubstitute_in_file_name);
6177 defsubr (&Scopy_file);
6178 defsubr (&Smake_directory_internal);
6179 defsubr (&Sdelete_directory_internal);
6180 defsubr (&Sdelete_file);
6181 defsubr (&Sfile_name_case_insensitive_p);
6182 defsubr (&Srename_file);
6183 defsubr (&Sadd_name_to_file);
6184 defsubr (&Smake_symbolic_link);
6185 defsubr (&Sfile_name_absolute_p);
6186 defsubr (&Sfile_exists_p);
6187 defsubr (&Sfile_executable_p);
6188 defsubr (&Sfile_readable_p);
6189 defsubr (&Sfile_writable_p);
6190 defsubr (&Saccess_file);
6191 defsubr (&Sfile_symlink_p);
6192 defsubr (&Sfile_directory_p);
6193 defsubr (&Sfile_accessible_directory_p);
6194 defsubr (&Sfile_regular_p);
6195 defsubr (&Sfile_modes);
6196 defsubr (&Sset_file_modes);
6197 defsubr (&Sset_file_times);
6198 defsubr (&Sfile_selinux_context);
6199 defsubr (&Sfile_acl);
6200 defsubr (&Sset_file_acl);
6201 defsubr (&Sset_file_selinux_context);
6202 defsubr (&Sset_default_file_modes);
6203 defsubr (&Sdefault_file_modes);
6204 defsubr (&Sfile_newer_than_file_p);
6205 defsubr (&Sinsert_file_contents);
6206 defsubr (&Swrite_region);
6207 defsubr (&Scar_less_than_car);
6208 defsubr (&Sverify_visited_file_modtime);
6209 defsubr (&Svisited_file_modtime);
6210 defsubr (&Sset_visited_file_modtime);
6211 defsubr (&Sdo_auto_save);
6212 defsubr (&Sset_buffer_auto_saved);
6213 defsubr (&Sclear_buffer_auto_save_failure);
6214 defsubr (&Srecent_auto_save_p);
6216 defsubr (&Snext_read_file_uses_dialog_p);
6218 defsubr (&Sset_binary_mode);
6220 #ifndef DOS_NT
6221 defsubr (&Sfile_system_info);
6222 #endif
6224 #ifdef HAVE_SYNC
6225 defsubr (&Sunix_sync);
6226 #endif