Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / src / fileio.c
blob52ca8b6297ee15fdce2de71e5808b8ecf92c1420
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 /* Like report_file_error, but reports a file-notify-error instead. */
229 void
230 report_file_notify_error (const char *string, Lisp_Object name)
232 char *str = emacs_strerror (errno);
233 AUTO_STRING (unibyte_str, str);
234 Lisp_Object errstring
235 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
236 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
237 Lisp_Object errdata = Fcons (errstring, data);
239 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
242 void
243 close_file_unwind (int fd)
245 emacs_close (fd);
248 void
249 fclose_unwind (void *arg)
251 FILE *stream = arg;
252 fclose (stream);
255 /* Restore point, having saved it as a marker. */
257 void
258 restore_point_unwind (Lisp_Object location)
260 Fgoto_char (location);
261 unchain_marker (XMARKER (location));
265 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
266 Sfind_file_name_handler, 2, 2, 0,
267 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
268 Otherwise, return nil.
269 A file name is handled if one of the regular expressions in
270 `file-name-handler-alist' matches it.
272 If OPERATION equals `inhibit-file-name-operation', then ignore
273 any handlers that are members of `inhibit-file-name-handlers',
274 but still do run any other handlers. This lets handlers
275 use the standard functions without calling themselves recursively. */)
276 (Lisp_Object filename, Lisp_Object operation)
278 /* This function must not munge the match data. */
279 Lisp_Object chain, inhibited_handlers, result;
280 ptrdiff_t pos = -1;
282 result = Qnil;
283 CHECK_STRING (filename);
285 if (EQ (operation, Vinhibit_file_name_operation))
286 inhibited_handlers = Vinhibit_file_name_handlers;
287 else
288 inhibited_handlers = Qnil;
290 for (chain = Vfile_name_handler_alist; CONSP (chain);
291 chain = XCDR (chain))
293 Lisp_Object elt;
294 elt = XCAR (chain);
295 if (CONSP (elt))
297 Lisp_Object string = XCAR (elt);
298 ptrdiff_t match_pos;
299 Lisp_Object handler = XCDR (elt);
300 Lisp_Object operations = Qnil;
302 if (SYMBOLP (handler))
303 operations = Fget (handler, Qoperations);
305 if (STRINGP (string)
306 && (match_pos = fast_string_match (string, filename)) > pos
307 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
309 Lisp_Object tem;
311 handler = XCDR (elt);
312 tem = Fmemq (handler, inhibited_handlers);
313 if (NILP (tem))
315 result = handler;
316 pos = match_pos;
321 maybe_quit ();
323 return result;
326 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
327 1, 1, 0,
328 doc: /* Return the directory component in file name FILENAME.
329 Return nil if FILENAME does not include a directory.
330 Otherwise return a directory name.
331 Given a Unix syntax file name, returns a string ending in slash. */)
332 (Lisp_Object filename)
334 Lisp_Object handler;
336 CHECK_STRING (filename);
338 /* If the file name has special constructs in it,
339 call the corresponding file handler. */
340 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
341 if (!NILP (handler))
343 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
344 filename);
345 return STRINGP (handled_name) ? handled_name : Qnil;
348 char *beg = SSDATA (filename);
349 char const *p = beg + SBYTES (filename);
351 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
352 #ifdef DOS_NT
353 /* only recognize drive specifier at the beginning */
354 && !(p[-1] == ':'
355 /* handle the "/:d:foo" and "/:foo" cases correctly */
356 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
357 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
358 #endif
359 ) p--;
361 if (p == beg)
362 return Qnil;
363 #ifdef DOS_NT
364 /* Expansion of "c:" to drive and default directory. */
365 Lisp_Object tem_fn;
366 USE_SAFE_ALLOCA;
367 SAFE_ALLOCA_STRING (beg, filename);
368 p = beg + (p - SSDATA (filename));
370 if (p[-1] == ':')
372 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
373 char *res = alloca (MAXPATHLEN + 1);
374 char *r = res;
376 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
378 memcpy (res, beg, 2);
379 beg += 2;
380 r += 2;
383 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
385 size_t l = strlen (res);
387 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
388 strcat (res, "/");
389 beg = res;
390 p = beg + strlen (beg);
391 dostounix_filename (beg);
392 tem_fn = make_specified_string (beg, -1, p - beg,
393 STRING_MULTIBYTE (filename));
395 else
396 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
397 STRING_MULTIBYTE (filename));
399 else if (STRING_MULTIBYTE (filename))
401 tem_fn = make_specified_string (beg, -1, p - beg, 1);
402 dostounix_filename (SSDATA (tem_fn));
403 #ifdef WINDOWSNT
404 if (!NILP (Vw32_downcase_file_names))
405 tem_fn = Fdowncase (tem_fn);
406 #endif
408 else
410 dostounix_filename (beg);
411 tem_fn = make_specified_string (beg, -1, p - beg, 0);
413 SAFE_FREE ();
414 return tem_fn;
415 #else /* DOS_NT */
416 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
417 #endif /* DOS_NT */
420 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
421 Sfile_name_nondirectory, 1, 1, 0,
422 doc: /* Return file name FILENAME sans its directory.
423 For example, in a Unix-syntax file name,
424 this is everything after the last slash,
425 or the entire name if it contains no slash. */)
426 (Lisp_Object filename)
428 register const char *beg, *p, *end;
429 Lisp_Object handler;
431 CHECK_STRING (filename);
433 /* If the file name has special constructs in it,
434 call the corresponding file handler. */
435 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
436 if (!NILP (handler))
438 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
439 filename);
440 if (STRINGP (handled_name))
441 return handled_name;
442 error ("Invalid handler in `file-name-handler-alist'");
445 beg = SSDATA (filename);
446 end = p = beg + SBYTES (filename);
448 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
449 #ifdef DOS_NT
450 /* only recognize drive specifier at beginning */
451 && !(p[-1] == ':'
452 /* handle the "/:d:foo" case correctly */
453 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
454 #endif
456 p--;
458 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
461 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
462 Sunhandled_file_name_directory, 1, 1, 0,
463 doc: /* Return a directly usable directory name somehow associated with FILENAME.
464 A `directly usable' directory name is one that may be used without the
465 intervention of any file handler.
466 If FILENAME is a directly usable file itself, return
467 \(file-name-as-directory FILENAME).
468 If FILENAME refers to a file which is not accessible from a local process,
469 then this should return nil.
470 The `call-process' and `start-process' functions use this function to
471 get a current directory to run processes in. */)
472 (Lisp_Object filename)
474 Lisp_Object handler;
476 /* If the file name has special constructs in it,
477 call the corresponding file handler. */
478 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
479 if (!NILP (handler))
481 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
482 filename);
483 return STRINGP (handled_name) ? handled_name : Qnil;
486 return Ffile_name_as_directory (filename);
489 /* Maximum number of bytes that DST will be longer than SRC
490 in file_name_as_directory. This occurs when SRCLEN == 0. */
491 enum { file_name_as_directory_slop = 2 };
493 /* Convert from file name SRC of length SRCLEN to directory name in
494 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
495 string. On UNIX, just make sure there is a terminating /. Return
496 the length of DST in bytes. */
498 static ptrdiff_t
499 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
500 bool multibyte)
502 if (srclen == 0)
504 dst[0] = '.';
505 dst[1] = '/';
506 dst[2] = '\0';
507 return 2;
510 memcpy (dst, src, srclen);
511 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
512 dst[srclen++] = DIRECTORY_SEP;
513 dst[srclen] = 0;
514 #ifdef DOS_NT
515 dostounix_filename (dst);
516 #endif
517 return srclen;
520 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
521 Sfile_name_as_directory, 1, 1, 0,
522 doc: /* Return a string representing the file name FILE interpreted as a directory.
523 This operation exists because a directory is also a file, but its name as
524 a directory is different from its name as a file.
525 The result can be used as the value of `default-directory'
526 or passed as second argument to `expand-file-name'.
527 For a Unix-syntax file name, just appends a slash unless a trailing slash
528 is already present. */)
529 (Lisp_Object file)
531 char *buf;
532 ptrdiff_t length;
533 Lisp_Object handler, val;
534 USE_SAFE_ALLOCA;
536 CHECK_STRING (file);
538 /* If the file name has special constructs in it,
539 call the corresponding file handler. */
540 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
541 if (!NILP (handler))
543 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
544 file);
545 if (STRINGP (handled_name))
546 return handled_name;
547 error ("Invalid handler in `file-name-handler-alist'");
550 #ifdef WINDOWSNT
551 if (!NILP (Vw32_downcase_file_names))
552 file = Fdowncase (file);
553 #endif
554 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
555 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
556 STRING_MULTIBYTE (file));
557 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
558 SAFE_FREE ();
559 return val;
562 /* Convert from directory name SRC of length SRCLEN to file name in
563 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
564 string. On UNIX, just make sure there isn't a terminating /.
565 Return the length of DST in bytes. */
567 static ptrdiff_t
568 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
570 /* In Unix-like systems, just remove any final slashes. However, if
571 they are all slashes, leave "/" and "//" alone, and treat "///"
572 and longer as if they were "/". */
573 if (! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
574 while (srclen > 1
575 #ifdef DOS_NT
576 && !(srclen > 2 && IS_DEVICE_SEP (src[srclen - 2]))
577 #endif
578 && IS_DIRECTORY_SEP (src[srclen - 1]))
579 srclen--;
581 memcpy (dst, src, srclen);
582 dst[srclen] = 0;
583 #ifdef DOS_NT
584 dostounix_filename (dst);
585 #endif
586 return srclen;
589 DEFUN ("directory-name-p", Fdirectory_name_p, Sdirectory_name_p, 1, 1, 0,
590 doc: /* Return non-nil if NAME ends with a directory separator character. */)
591 (Lisp_Object name)
593 CHECK_STRING (name);
594 ptrdiff_t namelen = SBYTES (name);
595 unsigned char c = namelen ? SREF (name, namelen - 1) : 0;
596 return IS_DIRECTORY_SEP (c) ? Qt : Qnil;
599 /* Return the expansion of NEWNAME, except that if NEWNAME is a
600 directory name then return the expansion of FILE's basename under
601 NEWNAME. This resembles how 'cp FILE NEWNAME' works, except that
602 it requires NEWNAME to be a directory name (typically, by ending in
603 "/"). */
605 static Lisp_Object
606 expand_cp_target (Lisp_Object file, Lisp_Object newname)
608 return (!NILP (Fdirectory_name_p (newname))
609 ? Fexpand_file_name (Ffile_name_nondirectory (file), newname)
610 : Fexpand_file_name (newname, Qnil));
613 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
614 1, 1, 0,
615 doc: /* Returns the file name of the directory named DIRECTORY.
616 This is the name of the file that holds the data for the directory DIRECTORY.
617 This operation exists because a directory is also a file, but its name as
618 a directory is different from its name as a file.
619 In Unix-syntax, this function just removes the final slash. */)
620 (Lisp_Object directory)
622 char *buf;
623 ptrdiff_t length;
624 Lisp_Object handler, val;
625 USE_SAFE_ALLOCA;
627 CHECK_STRING (directory);
629 /* If the file name has special constructs in it,
630 call the corresponding file handler. */
631 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
632 if (!NILP (handler))
634 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
635 directory);
636 if (STRINGP (handled_name))
637 return handled_name;
638 error ("Invalid handler in `file-name-handler-alist'");
641 #ifdef WINDOWSNT
642 if (!NILP (Vw32_downcase_file_names))
643 directory = Fdowncase (directory);
644 #endif
645 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
646 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
647 STRING_MULTIBYTE (directory));
648 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
649 SAFE_FREE ();
650 return val;
653 DEFUN ("make-temp-file-internal", Fmake_temp_file_internal,
654 Smake_temp_file_internal, 4, 4, 0,
655 doc: /* Generate a new file whose name starts with PREFIX, a string.
656 Return the name of the generated file. If DIR-FLAG is zero, do not
657 create the file, just its name. Otherwise, if DIR-FLAG is non-nil,
658 create an empty directory. The file name should end in SUFFIX.
659 Do not expand PREFIX; a non-absolute PREFIX is relative to the Emacs
660 working directory. If TEXT is a string, insert it into the newly
661 created file.
663 Signal an error if the file could not be created.
665 This function does not grok magic file names. */)
666 (Lisp_Object prefix, Lisp_Object dir_flag, Lisp_Object suffix,
667 Lisp_Object text)
669 CHECK_STRING (prefix);
670 CHECK_STRING (suffix);
671 Lisp_Object encoded_prefix = ENCODE_FILE (prefix);
672 Lisp_Object encoded_suffix = ENCODE_FILE (suffix);
673 ptrdiff_t prefix_len = SBYTES (encoded_prefix);
674 ptrdiff_t suffix_len = SBYTES (encoded_suffix);
675 if (INT_MAX < suffix_len)
676 args_out_of_range (prefix, suffix);
677 int nX = 6;
678 Lisp_Object val = make_uninit_string (prefix_len + nX + suffix_len);
679 char *data = SSDATA (val);
680 memcpy (data, SSDATA (encoded_prefix), prefix_len);
681 memset (data + prefix_len, 'X', nX);
682 memcpy (data + prefix_len + nX, SSDATA (encoded_suffix), suffix_len);
683 int kind = (NILP (dir_flag) ? GT_FILE
684 : EQ (dir_flag, make_number (0)) ? GT_NOCREATE
685 : GT_DIR);
686 int fd = gen_tempname (data, suffix_len, O_BINARY | O_CLOEXEC, kind);
687 bool failed = fd < 0;
688 if (!failed)
690 ptrdiff_t count = SPECPDL_INDEX ();
691 record_unwind_protect_int (close_file_unwind, fd);
692 val = DECODE_FILE (val);
693 if (STRINGP (text) && SBYTES (text) != 0)
694 write_region (text, Qnil, val, Qnil, Qnil, Qnil, Qnil, fd);
695 failed = NILP (dir_flag) && emacs_close (fd) != 0;
696 /* Discard the unwind protect. */
697 specpdl_ptr = specpdl + count;
699 if (failed)
701 static char const kind_message[][32] =
703 [GT_FILE] = "Creating file with prefix",
704 [GT_DIR] = "Creating directory with prefix",
705 [GT_NOCREATE] = "Creating file name with prefix"
707 report_file_error (kind_message[kind], prefix);
709 return val;
713 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
714 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
716 This function tries to choose a name that has no existing file.
717 For this to work, PREFIX should be an absolute file name, and PREFIX
718 and the returned string should both be non-magic.
720 There is a race condition between calling `make-temp-name' and
721 later creating the file, which opens all kinds of security holes.
722 For that reason, you should normally use `make-temp-file' instead. */)
723 (Lisp_Object prefix)
725 return Fmake_temp_file_internal (prefix, make_number (0),
726 empty_unibyte_string, Qnil);
729 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
730 doc: /* Convert filename NAME to absolute, and canonicalize it.
731 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
732 \(does not start with slash or tilde); both the directory name and
733 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
734 missing, the current buffer's value of `default-directory' is used.
735 NAME should be a string that is a valid file name for the underlying
736 filesystem.
737 File name components that are `.' are removed, and
738 so are file name components followed by `..', along with the `..' itself;
739 note that these simplifications are done without checking the resulting
740 file names in the file system.
741 Multiple consecutive slashes are collapsed into a single slash,
742 except at the beginning of the file name when they are significant (e.g.,
743 UNC file names on MS-Windows.)
744 An initial `~/' expands to your home directory.
745 An initial `~USER/' expands to USER's home directory.
746 See also the function `substitute-in-file-name'.
748 For technical reasons, this function can return correct but
749 non-intuitive results for the root directory; for instance,
750 \(expand-file-name ".." "/") returns "/..". For this reason, use
751 \(directory-file-name (file-name-directory dirname)) to traverse a
752 filesystem tree, not (expand-file-name ".." dirname). Note: make
753 sure DIRNAME in this example doesn't end in a slash, unless it's
754 the root directory. */)
755 (Lisp_Object name, Lisp_Object default_directory)
757 /* These point to SDATA and need to be careful with string-relocation
758 during GC (via DECODE_FILE). */
759 char *nm;
760 char *nmlim;
761 const char *newdir;
762 const char *newdirlim;
763 /* This should only point to alloca'd data. */
764 char *target;
766 ptrdiff_t tlen;
767 struct passwd *pw;
768 #ifdef DOS_NT
769 int drive = 0;
770 bool collapse_newdir = true;
771 bool is_escaped = 0;
772 #endif /* DOS_NT */
773 ptrdiff_t length, nbytes;
774 Lisp_Object handler, result, handled_name;
775 bool multibyte;
776 Lisp_Object hdir;
777 USE_SAFE_ALLOCA;
779 CHECK_STRING (name);
781 /* If the file name has special constructs in it,
782 call the corresponding file handler. */
783 handler = Ffind_file_name_handler (name, Qexpand_file_name);
784 if (!NILP (handler))
786 handled_name = call3 (handler, Qexpand_file_name,
787 name, default_directory);
788 if (STRINGP (handled_name))
789 return handled_name;
790 error ("Invalid handler in `file-name-handler-alist'");
794 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
795 if (NILP (default_directory))
796 default_directory = BVAR (current_buffer, directory);
797 if (! STRINGP (default_directory))
799 #ifdef DOS_NT
800 /* "/" is not considered a root directory on DOS_NT, so using "/"
801 here causes an infinite recursion in, e.g., the following:
803 (let (default-directory)
804 (expand-file-name "a"))
806 To avoid this, we set default_directory to the root of the
807 current drive. */
808 default_directory = build_string (emacs_root_dir ());
809 #else
810 default_directory = build_string ("/");
811 #endif
814 if (!NILP (default_directory))
816 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
817 if (!NILP (handler))
819 handled_name = call3 (handler, Qexpand_file_name,
820 name, default_directory);
821 if (STRINGP (handled_name))
822 return handled_name;
823 error ("Invalid handler in `file-name-handler-alist'");
828 char *o = SSDATA (default_directory);
830 /* Make sure DEFAULT_DIRECTORY is properly expanded.
831 It would be better to do this down below where we actually use
832 default_directory. Unfortunately, calling Fexpand_file_name recursively
833 could invoke GC, and the strings might be relocated. This would
834 be annoying because we have pointers into strings lying around
835 that would need adjusting, and people would add new pointers to
836 the code and forget to adjust them, resulting in intermittent bugs.
837 Putting this call here avoids all that crud.
839 The EQ test avoids infinite recursion. */
840 if (! NILP (default_directory) && !EQ (default_directory, name)
841 /* Save time in some common cases - as long as default_directory
842 is not relative, it can be canonicalized with name below (if it
843 is needed at all) without requiring it to be expanded now. */
844 #ifdef DOS_NT
845 /* Detect MSDOS file names with drive specifiers. */
846 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
847 && IS_DIRECTORY_SEP (o[2]))
848 /* Detect escaped file names without drive spec after "/:".
849 These should not be recursively expanded, to avoid
850 including the default directory twice in the expanded
851 result. */
852 && ! (o[0] == '/' && o[1] == ':')
853 #ifdef WINDOWSNT
854 /* Detect Windows file names in UNC format. */
855 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
856 #endif
857 #else /* not DOS_NT */
858 /* Detect Unix absolute file names (/... alone is not absolute on
859 DOS or Windows). */
860 && ! (IS_DIRECTORY_SEP (o[0]))
861 #endif /* not DOS_NT */
864 default_directory = Fexpand_file_name (default_directory, Qnil);
867 multibyte = STRING_MULTIBYTE (name);
868 if (multibyte != STRING_MULTIBYTE (default_directory))
870 if (multibyte)
872 unsigned char *p = SDATA (name);
874 while (*p && ASCII_CHAR_P (*p))
875 p++;
876 if (*p == '\0')
878 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
879 unibyte. Do not convert DEFAULT_DIRECTORY to
880 multibyte; instead, convert NAME to a unibyte string,
881 so that the result of this function is also a unibyte
882 string. This is needed during bootstrapping and
883 dumping, when Emacs cannot decode file names, because
884 the locale environment is not set up. */
885 name = make_unibyte_string (SSDATA (name), SBYTES (name));
886 multibyte = 0;
888 else
889 default_directory = string_to_multibyte (default_directory);
891 else
893 name = string_to_multibyte (name);
894 multibyte = 1;
898 #ifdef WINDOWSNT
899 if (!NILP (Vw32_downcase_file_names))
900 default_directory = Fdowncase (default_directory);
901 #endif
903 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
904 SAFE_ALLOCA_STRING (nm, name);
905 nmlim = nm + SBYTES (name);
907 #ifdef DOS_NT
908 /* Note if special escape prefix is present, but remove for now. */
909 if (nm[0] == '/' && nm[1] == ':')
911 is_escaped = 1;
912 nm += 2;
915 /* Find and remove drive specifier if present; this makes nm absolute
916 even if the rest of the name appears to be relative. Only look for
917 drive specifier at the beginning. */
918 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
920 drive = (unsigned char) nm[0];
921 nm += 2;
924 #ifdef WINDOWSNT
925 /* If we see "c://somedir", we want to strip the first slash after the
926 colon when stripping the drive letter. Otherwise, this expands to
927 "//somedir". */
928 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
929 nm++;
931 /* Discard any previous drive specifier if nm is now in UNC format. */
932 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
933 && !IS_DIRECTORY_SEP (nm[2]))
934 drive = 0;
935 #endif /* WINDOWSNT */
936 #endif /* DOS_NT */
938 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
939 none are found, we can probably return right away. We will avoid
940 allocating a new string if name is already fully expanded. */
941 if (
942 IS_DIRECTORY_SEP (nm[0])
943 #ifdef MSDOS
944 && drive && !is_escaped
945 #endif
946 #ifdef WINDOWSNT
947 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
948 #endif
951 /* If it turns out that the filename we want to return is just a
952 suffix of FILENAME, we don't need to go through and edit
953 things; we just need to construct a new string using data
954 starting at the middle of FILENAME. If we set LOSE, that
955 means we've discovered that we can't do that cool trick. */
956 bool lose = 0;
957 char *p = nm;
959 while (*p)
961 /* Since we know the name is absolute, we can assume that each
962 element starts with a "/". */
964 /* "." and ".." are hairy. */
965 if (IS_DIRECTORY_SEP (p[0])
966 && p[1] == '.'
967 && (IS_DIRECTORY_SEP (p[2])
968 || p[2] == 0
969 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
970 || p[3] == 0))))
971 lose = 1;
972 /* Replace multiple slashes with a single one, except
973 leave leading "//" alone. */
974 else if (IS_DIRECTORY_SEP (p[0])
975 && IS_DIRECTORY_SEP (p[1])
976 && (p != nm || IS_DIRECTORY_SEP (p[2])))
977 lose = 1;
978 p++;
980 if (!lose)
982 #ifdef DOS_NT
983 /* Make sure directories are all separated with /, but
984 avoid allocation of a new string when not required. */
985 dostounix_filename (nm);
986 #ifdef WINDOWSNT
987 if (IS_DIRECTORY_SEP (nm[1]))
989 if (strcmp (nm, SSDATA (name)) != 0)
990 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
992 else
993 #endif
994 /* Drive must be set, so this is okay. */
995 if (strcmp (nm - 2, SSDATA (name)) != 0)
997 name = make_specified_string (nm, -1, p - nm, multibyte);
998 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
999 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1000 name = concat2 (drive_prefix, name);
1002 #ifdef WINDOWSNT
1003 if (!NILP (Vw32_downcase_file_names))
1004 name = Fdowncase (name);
1005 #endif
1006 #else /* not DOS_NT */
1007 if (strcmp (nm, SSDATA (name)) != 0)
1008 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1009 #endif /* not DOS_NT */
1010 SAFE_FREE ();
1011 return name;
1015 /* At this point, nm might or might not be an absolute file name. We
1016 need to expand ~ or ~user if present, otherwise prefix nm with
1017 default_directory if nm is not absolute, and finally collapse /./
1018 and /foo/../ sequences.
1020 We set newdir to be the appropriate prefix if one is needed:
1021 - the relevant user directory if nm starts with ~ or ~user
1022 - the specified drive's working dir (DOS/NT only) if nm does not
1023 start with /
1024 - the value of default_directory.
1026 Note that these prefixes are not guaranteed to be absolute (except
1027 for the working dir of a drive). Therefore, to ensure we always
1028 return an absolute name, if the final prefix is not absolute we
1029 append it to the current working directory. */
1031 newdir = newdirlim = 0;
1033 if (nm[0] == '~' /* prefix ~ */
1034 #ifdef DOS_NT
1035 && !is_escaped /* don't expand ~ in escaped file names */
1036 #endif
1039 if (IS_DIRECTORY_SEP (nm[1])
1040 || nm[1] == 0) /* ~ by itself */
1042 Lisp_Object tem;
1044 if (!(newdir = egetenv ("HOME")))
1045 newdir = newdirlim = "";
1046 nm++;
1047 #ifdef WINDOWSNT
1048 if (newdir[0])
1050 char newdir_utf8[MAX_UTF8_PATH];
1052 filename_from_ansi (newdir, newdir_utf8);
1053 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1054 newdir = SSDATA (tem);
1056 else
1057 #endif
1058 tem = build_string (newdir);
1059 newdirlim = newdir + SBYTES (tem);
1060 /* `egetenv' may return a unibyte string, which will bite us
1061 if we expect the directory to be multibyte. */
1062 if (multibyte && !STRING_MULTIBYTE (tem))
1064 hdir = DECODE_FILE (tem);
1065 newdir = SSDATA (hdir);
1066 newdirlim = newdir + SBYTES (hdir);
1068 #ifdef DOS_NT
1069 collapse_newdir = false;
1070 #endif
1072 else /* ~user/filename */
1074 char *o, *p;
1075 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1076 continue;
1077 o = SAFE_ALLOCA (p - nm + 1);
1078 memcpy (o, nm, p - nm);
1079 o[p - nm] = 0;
1081 block_input ();
1082 pw = getpwnam (o + 1);
1083 unblock_input ();
1084 if (pw)
1086 Lisp_Object tem;
1088 newdir = pw->pw_dir;
1089 /* `getpwnam' may return a unibyte string, which will
1090 bite us when we expect the directory to be multibyte. */
1091 tem = make_unibyte_string (newdir, strlen (newdir));
1092 newdirlim = newdir + SBYTES (tem);
1093 if (multibyte && !STRING_MULTIBYTE (tem))
1095 hdir = DECODE_FILE (tem);
1096 newdir = SSDATA (hdir);
1097 newdirlim = newdir + SBYTES (hdir);
1099 nm = p;
1100 #ifdef DOS_NT
1101 collapse_newdir = false;
1102 #endif
1105 /* If we don't find a user of that name, leave the name
1106 unchanged; don't move nm forward to p. */
1110 #ifdef DOS_NT
1111 /* On DOS and Windows, nm is absolute if a drive name was specified;
1112 use the drive's current directory as the prefix if needed. */
1113 if (!newdir && drive)
1115 /* Get default directory if needed to make nm absolute. */
1116 char *adir = NULL;
1117 if (!IS_DIRECTORY_SEP (nm[0]))
1119 adir = alloca (MAXPATHLEN + 1);
1120 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1121 adir = NULL;
1122 else if (multibyte)
1124 Lisp_Object tem = build_string (adir);
1126 tem = DECODE_FILE (tem);
1127 newdirlim = adir + SBYTES (tem);
1128 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1130 else
1131 newdirlim = adir + strlen (adir);
1133 if (!adir)
1135 /* Either nm starts with /, or drive isn't mounted. */
1136 adir = alloca (4);
1137 adir[0] = DRIVE_LETTER (drive);
1138 adir[1] = ':';
1139 adir[2] = '/';
1140 adir[3] = 0;
1141 newdirlim = adir + 3;
1143 newdir = adir;
1145 #endif /* DOS_NT */
1147 /* Finally, if no prefix has been specified and nm is not absolute,
1148 then it must be expanded relative to default_directory. */
1150 if (1
1151 #ifndef DOS_NT
1152 /* /... alone is not absolute on DOS and Windows. */
1153 && !IS_DIRECTORY_SEP (nm[0])
1154 #endif
1155 #ifdef WINDOWSNT
1156 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1157 && !IS_DIRECTORY_SEP (nm[2]))
1158 #endif
1159 && !newdir)
1161 newdir = SSDATA (default_directory);
1162 newdirlim = newdir + SBYTES (default_directory);
1163 #ifdef DOS_NT
1164 /* Note if special escape prefix is present, but remove for now. */
1165 if (newdir[0] == '/' && newdir[1] == ':')
1167 is_escaped = 1;
1168 newdir += 2;
1170 #endif
1173 #ifdef DOS_NT
1174 if (newdir)
1176 /* First ensure newdir is an absolute name. */
1177 if (
1178 /* Detect MSDOS file names with drive specifiers. */
1179 ! (IS_DRIVE (newdir[0])
1180 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1181 #ifdef WINDOWSNT
1182 /* Detect Windows file names in UNC format. */
1183 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1184 && !IS_DIRECTORY_SEP (newdir[2]))
1185 #endif
1188 /* Effectively, let newdir be (expand-file-name newdir cwd).
1189 Because of the admonition against calling expand-file-name
1190 when we have pointers into lisp strings, we accomplish this
1191 indirectly by prepending newdir to nm if necessary, and using
1192 cwd (or the wd of newdir's drive) as the new newdir. */
1193 char *adir;
1194 #ifdef WINDOWSNT
1195 const int adir_size = MAX_UTF8_PATH;
1196 #else
1197 const int adir_size = MAXPATHLEN + 1;
1198 #endif
1200 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1202 drive = (unsigned char) newdir[0];
1203 newdir += 2;
1205 if (!IS_DIRECTORY_SEP (nm[0]))
1207 ptrdiff_t nmlen = nmlim - nm;
1208 ptrdiff_t newdirlen = newdirlim - newdir;
1209 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1210 + nmlen + 1);
1211 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1212 multibyte);
1213 memcpy (tmp + dlen, nm, nmlen + 1);
1214 nm = tmp;
1215 nmlim = nm + dlen + nmlen;
1217 adir = alloca (adir_size);
1218 if (drive)
1220 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1221 strcpy (adir, "/");
1223 else
1224 getcwd (adir, adir_size);
1225 if (multibyte)
1227 Lisp_Object tem = build_string (adir);
1229 tem = DECODE_FILE (tem);
1230 newdirlim = adir + SBYTES (tem);
1231 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1233 else
1234 newdirlim = adir + strlen (adir);
1235 newdir = adir;
1238 /* Strip off drive name from prefix, if present. */
1239 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1241 drive = newdir[0];
1242 newdir += 2;
1245 /* Keep only a prefix from newdir if nm starts with slash
1246 (//server/share for UNC, nothing otherwise). */
1247 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1249 #ifdef WINDOWSNT
1250 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1251 && !IS_DIRECTORY_SEP (newdir[2]))
1253 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1254 char *p = adir + 2;
1255 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1256 p++;
1257 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1258 *p = 0;
1259 newdir = adir;
1260 newdirlim = newdir + strlen (adir);
1262 else
1263 #endif
1264 newdir = newdirlim = "";
1267 #endif /* DOS_NT */
1269 /* Ignore any slash at the end of newdir, unless newdir is
1270 just "/" or "//". */
1271 length = newdirlim - newdir;
1272 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1273 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1274 length--;
1276 /* Now concatenate the directory and name to new space in the stack frame. */
1277 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1278 eassert (tlen > file_name_as_directory_slop + 1);
1279 #ifdef DOS_NT
1280 /* Reserve space for drive specifier and escape prefix, since either
1281 or both may need to be inserted. (The Microsoft x86 compiler
1282 produces incorrect code if the following two lines are combined.) */
1283 target = alloca (tlen + 4);
1284 target += 4;
1285 #else /* not DOS_NT */
1286 target = SAFE_ALLOCA (tlen);
1287 #endif /* not DOS_NT */
1288 *target = 0;
1289 nbytes = 0;
1291 if (newdir)
1293 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1295 #ifdef DOS_NT
1296 /* If newdir is effectively "C:/", then the drive letter will have
1297 been stripped and newdir will be "/". Concatenating with an
1298 absolute directory in nm produces "//", which will then be
1299 incorrectly treated as a network share. Ignore newdir in
1300 this case (keeping the drive letter). */
1301 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1302 && newdir[1] == '\0'))
1303 #endif
1305 memcpy (target, newdir, length);
1306 target[length] = 0;
1307 nbytes = length;
1310 else
1311 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1314 memcpy (target + nbytes, nm, nmlim - nm + 1);
1316 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1317 appear. */
1319 char *p = target;
1320 char *o = target;
1322 while (*p)
1324 if (!IS_DIRECTORY_SEP (*p))
1326 *o++ = *p++;
1328 else if (p[1] == '.'
1329 && (IS_DIRECTORY_SEP (p[2])
1330 || p[2] == 0))
1332 /* If "/." is the entire filename, keep the "/". Otherwise,
1333 just delete the whole "/.". */
1334 if (o == target && p[2] == '\0')
1335 *o++ = *p;
1336 p += 2;
1338 else if (p[1] == '.' && p[2] == '.'
1339 /* `/../' is the "superroot" on certain file systems.
1340 Turned off on DOS_NT systems because they have no
1341 "superroot" and because this causes us to produce
1342 file names like "d:/../foo" which fail file-related
1343 functions of the underlying OS. (To reproduce, try a
1344 long series of "../../" in default_directory, longer
1345 than the number of levels from the root.) */
1346 #ifndef DOS_NT
1347 && o != target
1348 #endif
1349 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1351 #ifdef WINDOWSNT
1352 char *prev_o = o;
1353 #endif
1354 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1355 continue;
1356 #ifdef WINDOWSNT
1357 /* Don't go below server level in UNC filenames. */
1358 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1359 && IS_DIRECTORY_SEP (*target))
1360 o = prev_o;
1361 else
1362 #endif
1363 /* Keep initial / only if this is the whole name. */
1364 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1365 ++o;
1366 p += 3;
1368 else if (IS_DIRECTORY_SEP (p[1])
1369 && (p != target || IS_DIRECTORY_SEP (p[2])))
1370 /* Collapse multiple "/", except leave leading "//" alone. */
1371 p++;
1372 else
1374 *o++ = *p++;
1378 #ifdef DOS_NT
1379 /* At last, set drive name. */
1380 #ifdef WINDOWSNT
1381 /* Except for network file name. */
1382 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1383 #endif /* WINDOWSNT */
1385 if (!drive) emacs_abort ();
1386 target -= 2;
1387 target[0] = DRIVE_LETTER (drive);
1388 target[1] = ':';
1390 /* Reinsert the escape prefix if required. */
1391 if (is_escaped)
1393 target -= 2;
1394 target[0] = '/';
1395 target[1] = ':';
1397 result = make_specified_string (target, -1, o - target, multibyte);
1398 dostounix_filename (SSDATA (result));
1399 #ifdef WINDOWSNT
1400 if (!NILP (Vw32_downcase_file_names))
1401 result = Fdowncase (result);
1402 #endif
1403 #else /* !DOS_NT */
1404 result = make_specified_string (target, -1, o - target, multibyte);
1405 #endif /* !DOS_NT */
1408 /* Again look to see if the file name has special constructs in it
1409 and perhaps call the corresponding file handler. This is needed
1410 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1411 the ".." component gives us "/user@host:/bar/../baz" which needs
1412 to be expanded again. */
1413 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1414 if (!NILP (handler))
1416 handled_name = call3 (handler, Qexpand_file_name,
1417 result, default_directory);
1418 if (! STRINGP (handled_name))
1419 error ("Invalid handler in `file-name-handler-alist'");
1420 result = handled_name;
1423 SAFE_FREE ();
1424 return result;
1427 #if 0
1428 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1429 This is the old version of expand-file-name, before it was thoroughly
1430 rewritten for Emacs 10.31. We leave this version here commented-out,
1431 because the code is very complex and likely to have subtle bugs. If
1432 bugs _are_ found, it might be of interest to look at the old code and
1433 see what did it do in the relevant situation.
1435 Don't remove this code: it's true that it will be accessible
1436 from the repository, but a few years from deletion, people will
1437 forget it is there. */
1439 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1440 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1441 "Convert FILENAME to absolute, and canonicalize it.\n\
1442 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1443 \(does not start with slash); if DEFAULT is nil or missing,\n\
1444 the current buffer's value of default-directory is used.\n\
1445 Filenames containing `.' or `..' as components are simplified;\n\
1446 initial `~/' expands to your home directory.\n\
1447 See also the function `substitute-in-file-name'.")
1448 (name, defalt)
1449 Lisp_Object name, defalt;
1451 unsigned char *nm;
1453 register unsigned char *newdir, *p, *o;
1454 ptrdiff_t tlen;
1455 unsigned char *target;
1456 struct passwd *pw;
1458 CHECK_STRING (name);
1459 nm = SDATA (name);
1461 /* If nm is absolute, flush ...// and detect /./ and /../.
1462 If no /./ or /../ we can return right away. */
1463 if (nm[0] == '/')
1465 bool lose = 0;
1466 p = nm;
1467 while (*p)
1469 if (p[0] == '/' && p[1] == '/')
1470 nm = p + 1;
1471 if (p[0] == '/' && p[1] == '~')
1472 nm = p + 1, lose = 1;
1473 if (p[0] == '/' && p[1] == '.'
1474 && (p[2] == '/' || p[2] == 0
1475 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1476 lose = 1;
1477 p++;
1479 if (!lose)
1481 if (nm == SDATA (name))
1482 return name;
1483 return build_string (nm);
1487 /* Now determine directory to start with and put it in NEWDIR. */
1489 newdir = 0;
1491 if (nm[0] == '~') /* prefix ~ */
1492 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1494 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1495 newdir = (unsigned char *) "";
1496 nm++;
1498 else /* ~user/filename */
1500 /* Get past ~ to user. */
1501 unsigned char *user = nm + 1;
1502 /* Find end of name. */
1503 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1504 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1505 /* Copy the user name into temp storage. */
1506 o = alloca (len + 1);
1507 memcpy (o, user, len);
1508 o[len] = 0;
1510 /* Look up the user name. */
1511 block_input ();
1512 pw = (struct passwd *) getpwnam (o + 1);
1513 unblock_input ();
1514 if (!pw)
1515 error ("\"%s\" isn't a registered user", o + 1);
1517 newdir = (unsigned char *) pw->pw_dir;
1519 /* Discard the user name from NM. */
1520 nm += len;
1523 if (nm[0] != '/' && !newdir)
1525 if (NILP (defalt))
1526 defalt = current_buffer->directory;
1527 CHECK_STRING (defalt);
1528 newdir = SDATA (defalt);
1531 /* Now concatenate the directory and name to new space in the stack frame. */
1533 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1534 target = alloca (tlen);
1535 *target = 0;
1537 if (newdir)
1539 if (nm[0] == 0 || nm[0] == '/')
1540 strcpy (target, newdir);
1541 else
1542 file_name_as_directory (target, newdir);
1545 strcat (target, nm);
1547 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1549 p = target;
1550 o = target;
1552 while (*p)
1554 if (*p != '/')
1556 *o++ = *p++;
1558 else if (!strncmp (p, "//", 2)
1561 o = target;
1562 p++;
1564 else if (p[0] == '/' && p[1] == '.'
1565 && (p[2] == '/' || p[2] == 0))
1566 p += 2;
1567 else if (!strncmp (p, "/..", 3)
1568 /* `/../' is the "superroot" on certain file systems. */
1569 && o != target
1570 && (p[3] == '/' || p[3] == 0))
1572 while (o != target && *--o != '/')
1574 if (o == target && *o == '/')
1575 ++o;
1576 p += 3;
1578 else
1580 *o++ = *p++;
1584 return make_string (target, o - target);
1586 #endif
1588 /* If /~ or // appears, discard everything through first slash. */
1589 static bool
1590 file_name_absolute_p (const char *filename)
1592 return
1593 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1594 #ifdef DOS_NT
1595 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1596 && IS_DIRECTORY_SEP (filename[2]))
1597 #endif
1601 static char *
1602 search_embedded_absfilename (char *nm, char *endp)
1604 char *p, *s;
1606 for (p = nm + 1; p < endp; p++)
1608 if (IS_DIRECTORY_SEP (p[-1])
1609 && file_name_absolute_p (p)
1610 #if defined (WINDOWSNT) || defined (CYGWIN)
1611 /* // at start of file name is meaningful in Apollo,
1612 WindowsNT and Cygwin systems. */
1613 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1614 #endif /* not (WINDOWSNT || CYGWIN) */
1617 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1618 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1620 USE_SAFE_ALLOCA;
1621 char *o = SAFE_ALLOCA (s - p + 1);
1622 struct passwd *pw;
1623 memcpy (o, p, s - p);
1624 o [s - p] = 0;
1626 /* If we have ~user and `user' exists, discard
1627 everything up to ~. But if `user' does not exist, leave
1628 ~user alone, it might be a literal file name. */
1629 block_input ();
1630 pw = getpwnam (o + 1);
1631 unblock_input ();
1632 SAFE_FREE ();
1633 if (pw)
1634 return p;
1636 else
1637 return p;
1640 return NULL;
1643 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1644 Ssubstitute_in_file_name, 1, 1, 0,
1645 doc: /* Substitute environment variables referred to in FILENAME.
1646 `$FOO' where FOO is an environment variable name means to substitute
1647 the value of that variable. The variable name should be terminated
1648 with a character not a letter, digit or underscore; otherwise, enclose
1649 the entire variable name in braces.
1651 If `/~' appears, all of FILENAME through that `/' is discarded.
1652 If `//' appears, everything up to and including the first of
1653 those `/' is discarded. */)
1654 (Lisp_Object filename)
1656 char *nm, *p, *x, *endp;
1657 bool substituted = false;
1658 bool multibyte;
1659 char *xnm;
1660 Lisp_Object handler;
1662 CHECK_STRING (filename);
1664 multibyte = STRING_MULTIBYTE (filename);
1666 /* If the file name has special constructs in it,
1667 call the corresponding file handler. */
1668 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1669 if (!NILP (handler))
1671 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1672 filename);
1673 if (STRINGP (handled_name))
1674 return handled_name;
1675 error ("Invalid handler in `file-name-handler-alist'");
1678 /* Always work on a copy of the string, in case GC happens during
1679 decode of environment variables, causing the original Lisp_String
1680 data to be relocated. */
1681 USE_SAFE_ALLOCA;
1682 SAFE_ALLOCA_STRING (nm, filename);
1684 #ifdef DOS_NT
1685 dostounix_filename (nm);
1686 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1687 #endif
1688 endp = nm + SBYTES (filename);
1690 /* If /~ or // appears, discard everything through first slash. */
1691 p = search_embedded_absfilename (nm, endp);
1692 if (p)
1693 /* Start over with the new string, so we check the file-name-handler
1694 again. Important with filenames like "/home/foo//:/hello///there"
1695 which would substitute to "/:/hello///there" rather than "/there". */
1697 Lisp_Object result
1698 = (Fsubstitute_in_file_name
1699 (make_specified_string (p, -1, endp - p, multibyte)));
1700 SAFE_FREE ();
1701 return result;
1704 /* See if any variables are substituted into the string. */
1706 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1708 Lisp_Object name
1709 = (!substituted ? filename
1710 : make_specified_string (nm, -1, endp - nm, multibyte));
1711 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1712 CHECK_STRING (tmp);
1713 if (!EQ (tmp, name))
1714 substituted = true;
1715 filename = tmp;
1718 if (!substituted)
1720 #ifdef WINDOWSNT
1721 if (!NILP (Vw32_downcase_file_names))
1722 filename = Fdowncase (filename);
1723 #endif
1724 SAFE_FREE ();
1725 return filename;
1728 xnm = SSDATA (filename);
1729 x = xnm + SBYTES (filename);
1731 /* If /~ or // appears, discard everything through first slash. */
1732 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1733 /* This time we do not start over because we've already expanded envvars
1734 and replaced $$ with $. Maybe we should start over as well, but we'd
1735 need to quote some $ to $$ first. */
1736 xnm = p;
1738 #ifdef WINDOWSNT
1739 if (!NILP (Vw32_downcase_file_names))
1741 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1743 filename = Fdowncase (xname);
1745 else
1746 #endif
1747 if (xnm != SSDATA (filename))
1748 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1749 SAFE_FREE ();
1750 return filename;
1753 /* A slightly faster and more convenient way to get
1754 (directory-file-name (expand-file-name FOO)). */
1756 Lisp_Object
1757 expand_and_dir_to_file (Lisp_Object filename)
1759 Lisp_Object absname = Fexpand_file_name (filename, Qnil);
1761 /* Remove final slash, if any (unless this is the root dir).
1762 stat behaves differently depending! */
1763 if (SCHARS (absname) > 1
1764 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1765 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1766 /* We cannot take shortcuts; they might be wrong for magic file names. */
1767 absname = Fdirectory_file_name (absname);
1768 return absname;
1771 /* Signal an error if the file ABSNAME already exists.
1772 If KNOWN_TO_EXIST, the file is known to exist.
1773 QUERYSTRING is a name for the action that is being considered
1774 to alter the file.
1775 If INTERACTIVE, ask the user whether to proceed,
1776 and bypass the error if the user says to go ahead.
1777 If QUICK, ask for y or n, not yes or no. */
1779 static void
1780 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1781 const char *querystring, bool interactive,
1782 bool quick)
1784 Lisp_Object tem, encoded_filename;
1785 struct stat statbuf;
1787 encoded_filename = ENCODE_FILE (absname);
1789 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1791 if (S_ISDIR (statbuf.st_mode))
1792 xsignal2 (Qfile_error,
1793 build_string ("File is a directory"), absname);
1794 known_to_exist = true;
1797 if (known_to_exist)
1799 if (! interactive)
1800 xsignal2 (Qfile_already_exists,
1801 build_string ("File already exists"), absname);
1802 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1803 tem = CALLN (Fformat, format, absname, build_string (querystring));
1804 if (quick)
1805 tem = call1 (intern ("y-or-n-p"), tem);
1806 else
1807 tem = do_yes_or_no_p (tem);
1808 if (NILP (tem))
1809 xsignal2 (Qfile_already_exists,
1810 build_string ("File already exists"), absname);
1814 #ifndef WINDOWSNT
1815 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1816 static bool
1817 clone_file (int dest, int source)
1819 #ifdef FICLONE
1820 return ioctl (dest, FICLONE, source) == 0;
1821 #endif
1822 return false;
1824 #endif
1826 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1827 "fCopy file: \nGCopy %s to file: \np\nP",
1828 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1829 If NEWNAME is a directory name, copy FILE to a like-named file under
1830 NEWNAME. For NEWNAME to be recognized as a directory name, it should
1831 end in a slash.
1833 This function always sets the file modes of the output file to match
1834 the input file.
1836 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1837 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1838 signal a `file-already-exists' error without overwriting. If
1839 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1840 about overwriting; this is what happens in interactive use with M-x.
1841 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1842 existing file.
1844 Fourth arg KEEP-TIME non-nil means give the output file the same
1845 last-modified time as the old one. (This works on only some systems.)
1847 A prefix arg makes KEEP-TIME non-nil.
1849 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1850 FILE to NEWNAME.
1852 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1853 this includes the file modes, along with ACL entries and SELinux
1854 context if present. Otherwise, if NEWNAME is created its file
1855 permission bits are those of FILE, masked by the default file
1856 permissions. */)
1857 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1858 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1859 Lisp_Object preserve_permissions)
1861 Lisp_Object handler;
1862 ptrdiff_t count = SPECPDL_INDEX ();
1863 Lisp_Object encoded_file, encoded_newname;
1864 #if HAVE_LIBSELINUX
1865 security_context_t con;
1866 int conlength = 0;
1867 #endif
1868 #ifdef WINDOWSNT
1869 int result;
1870 #else
1871 bool already_exists = false;
1872 mode_t new_mask;
1873 int ifd, ofd;
1874 struct stat st;
1875 #endif
1877 file = Fexpand_file_name (file, Qnil);
1878 newname = expand_cp_target (file, newname);
1880 /* If the input file name has special constructs in it,
1881 call the corresponding file handler. */
1882 handler = Ffind_file_name_handler (file, Qcopy_file);
1883 /* Likewise for output file name. */
1884 if (NILP (handler))
1885 handler = Ffind_file_name_handler (newname, Qcopy_file);
1886 if (!NILP (handler))
1887 return call7 (handler, Qcopy_file, file, newname,
1888 ok_if_already_exists, keep_time, preserve_uid_gid,
1889 preserve_permissions);
1891 encoded_file = ENCODE_FILE (file);
1892 encoded_newname = ENCODE_FILE (newname);
1894 #ifdef WINDOWSNT
1895 if (NILP (ok_if_already_exists)
1896 || INTEGERP (ok_if_already_exists))
1897 barf_or_query_if_file_exists (newname, false, "copy to it",
1898 INTEGERP (ok_if_already_exists), false);
1900 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1901 !NILP (keep_time), !NILP (preserve_uid_gid),
1902 !NILP (preserve_permissions));
1903 switch (result)
1905 case -1:
1906 report_file_error ("Copying file", list2 (file, newname));
1907 case -2:
1908 report_file_error ("Copying permissions from", file);
1909 case -3:
1910 xsignal2 (Qfile_date_error,
1911 build_string ("Resetting file times"), newname);
1912 case -4:
1913 report_file_error ("Copying permissions to", newname);
1915 #else /* not WINDOWSNT */
1916 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1918 if (ifd < 0)
1919 report_file_error ("Opening input file", file);
1921 record_unwind_protect_int (close_file_unwind, ifd);
1923 if (fstat (ifd, &st) != 0)
1924 report_file_error ("Input file status", file);
1926 if (!NILP (preserve_permissions))
1928 #if HAVE_LIBSELINUX
1929 if (is_selinux_enabled ())
1931 conlength = fgetfilecon (ifd, &con);
1932 if (conlength == -1)
1933 report_file_error ("Doing fgetfilecon", file);
1935 #endif
1938 /* We can copy only regular files. */
1939 if (!S_ISREG (st.st_mode))
1940 report_file_errno ("Non-regular file", file,
1941 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1943 #ifndef MSDOS
1944 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1945 #else
1946 new_mask = S_IREAD | S_IWRITE;
1947 #endif
1949 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1950 new_mask);
1951 if (ofd < 0 && errno == EEXIST)
1953 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1954 barf_or_query_if_file_exists (newname, true, "copy to it",
1955 INTEGERP (ok_if_already_exists), false);
1956 already_exists = true;
1957 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1959 if (ofd < 0)
1960 report_file_error ("Opening output file", newname);
1962 record_unwind_protect_int (close_file_unwind, ofd);
1964 off_t oldsize = 0, newsize;
1966 if (already_exists)
1968 struct stat out_st;
1969 if (fstat (ofd, &out_st) != 0)
1970 report_file_error ("Output file status", newname);
1971 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1972 report_file_errno ("Input and output files are the same",
1973 list2 (file, newname), 0);
1974 if (S_ISREG (out_st.st_mode))
1975 oldsize = out_st.st_size;
1978 maybe_quit ();
1980 if (clone_file (ofd, ifd))
1981 newsize = st.st_size;
1982 else
1984 char buf[MAX_ALLOCA];
1985 ptrdiff_t n;
1986 for (newsize = 0; 0 < (n = emacs_read_quit (ifd, buf, sizeof buf));
1987 newsize += n)
1988 if (emacs_write_quit (ofd, buf, n) != n)
1989 report_file_error ("Write error", newname);
1990 if (n < 0)
1991 report_file_error ("Read error", file);
1994 /* Truncate any existing output file after writing the data. This
1995 is more likely to work than truncation before writing, if the
1996 file system is out of space or the user is over disk quota. */
1997 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
1998 report_file_error ("Truncating output file", newname);
2000 #ifndef MSDOS
2001 /* Preserve the original file permissions, and if requested, also its
2002 owner and group. */
2004 mode_t preserved_permissions = st.st_mode & 07777;
2005 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2006 if (!NILP (preserve_uid_gid))
2008 /* Attempt to change owner and group. If that doesn't work
2009 attempt to change just the group, as that is sometimes allowed.
2010 Adjust the mode mask to eliminate setuid or setgid bits
2011 or group permissions bits that are inappropriate if the
2012 owner or group are wrong. */
2013 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2015 if (fchown (ofd, -1, st.st_gid) == 0)
2016 preserved_permissions &= ~04000;
2017 else
2019 preserved_permissions &= ~06000;
2021 /* Copy the other bits to the group bits, since the
2022 group is wrong. */
2023 preserved_permissions &= ~070;
2024 preserved_permissions |= (preserved_permissions & 7) << 3;
2025 default_permissions &= ~070;
2026 default_permissions |= (default_permissions & 7) << 3;
2031 switch (!NILP (preserve_permissions)
2032 ? qcopy_acl (SSDATA (encoded_file), ifd,
2033 SSDATA (encoded_newname), ofd,
2034 preserved_permissions)
2035 : (already_exists
2036 || (new_mask & ~realmask) == default_permissions)
2038 : fchmod (ofd, default_permissions))
2040 case -2: report_file_error ("Copying permissions from", file);
2041 case -1: report_file_error ("Copying permissions to", newname);
2044 #endif /* not MSDOS */
2046 #if HAVE_LIBSELINUX
2047 if (conlength > 0)
2049 /* Set the modified context back to the file. */
2050 bool fail = fsetfilecon (ofd, con) != 0;
2051 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
2052 if (fail && errno != ENOTSUP)
2053 report_file_error ("Doing fsetfilecon", newname);
2055 freecon (con);
2057 #endif
2059 if (!NILP (keep_time))
2061 struct timespec atime = get_stat_atime (&st);
2062 struct timespec mtime = get_stat_mtime (&st);
2063 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2064 xsignal2 (Qfile_date_error,
2065 build_string ("Cannot set file date"), newname);
2068 if (emacs_close (ofd) < 0)
2069 report_file_error ("Write error", newname);
2071 emacs_close (ifd);
2073 #ifdef MSDOS
2074 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2075 and if it can't, it tells so. Otherwise, under MSDOS we usually
2076 get only the READ bit, which will make the copied file read-only,
2077 so it's better not to chmod at all. */
2078 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2079 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2080 #endif /* MSDOS */
2081 #endif /* not WINDOWSNT */
2083 /* Discard the unwind protects. */
2084 specpdl_ptr = specpdl + count;
2086 return Qnil;
2089 DEFUN ("make-directory-internal", Fmake_directory_internal,
2090 Smake_directory_internal, 1, 1, 0,
2091 doc: /* Create a new directory named DIRECTORY. */)
2092 (Lisp_Object directory)
2094 const char *dir;
2095 Lisp_Object handler;
2096 Lisp_Object encoded_dir;
2098 CHECK_STRING (directory);
2099 directory = Fexpand_file_name (directory, Qnil);
2101 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2102 if (!NILP (handler))
2103 return call2 (handler, Qmake_directory_internal, directory);
2105 encoded_dir = ENCODE_FILE (directory);
2107 dir = SSDATA (encoded_dir);
2109 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2110 report_file_error ("Creating directory", directory);
2112 return Qnil;
2115 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2116 Sdelete_directory_internal, 1, 1, 0,
2117 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2118 (Lisp_Object directory)
2120 const char *dir;
2121 Lisp_Object encoded_dir;
2123 CHECK_STRING (directory);
2124 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2125 encoded_dir = ENCODE_FILE (directory);
2126 dir = SSDATA (encoded_dir);
2128 if (rmdir (dir) != 0)
2129 report_file_error ("Removing directory", directory);
2131 return Qnil;
2134 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2135 "(list (read-file-name \
2136 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2137 \"Move file to trash: \" \"Delete file: \") \
2138 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2139 (null current-prefix-arg))",
2140 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2141 If file has multiple names, it continues to exist with the other names.
2142 TRASH non-nil means to trash the file instead of deleting, provided
2143 `delete-by-moving-to-trash' is non-nil.
2145 When called interactively, TRASH is t if no prefix argument is given.
2146 With a prefix argument, TRASH is nil. */)
2147 (Lisp_Object filename, Lisp_Object trash)
2149 Lisp_Object handler;
2150 Lisp_Object encoded_file;
2152 if (!NILP (Ffile_directory_p (filename))
2153 && NILP (Ffile_symlink_p (filename)))
2154 xsignal2 (Qfile_error,
2155 build_string ("Removing old name: is a directory"),
2156 filename);
2157 filename = Fexpand_file_name (filename, Qnil);
2159 handler = Ffind_file_name_handler (filename, Qdelete_file);
2160 if (!NILP (handler))
2161 return call3 (handler, Qdelete_file, filename, trash);
2163 if (delete_by_moving_to_trash && !NILP (trash))
2164 return call1 (Qmove_file_to_trash, filename);
2166 encoded_file = ENCODE_FILE (filename);
2168 if (unlink (SSDATA (encoded_file)) != 0 && errno != ENOENT)
2169 report_file_error ("Removing old name", filename);
2170 return Qnil;
2173 static Lisp_Object
2174 internal_delete_file_1 (Lisp_Object ignore)
2176 return Qt;
2179 /* Delete file FILENAME, returning true if successful.
2180 This ignores `delete-by-moving-to-trash'. */
2182 bool
2183 internal_delete_file (Lisp_Object filename)
2185 Lisp_Object tem;
2187 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2188 Qt, internal_delete_file_1);
2189 return NILP (tem);
2192 /* Filesystems are case-sensitive on all supported systems except
2193 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2194 case-insensitive on the first two, but they may or may not be
2195 case-insensitive on Cygwin and OS X. The following function
2196 attempts to provide a runtime test on those two systems. If the
2197 test is not conclusive, we assume case-insensitivity on Cygwin and
2198 case-sensitivity on Mac OS X.
2200 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2201 NFS-mounted Windows volumes, might be case-insensitive. Can we
2202 detect this? */
2204 static bool
2205 file_name_case_insensitive_p (const char *filename)
2207 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2208 those flags are available. As of this writing (2017-05-20),
2209 Cygwin is the only platform known to support the former (starting
2210 with Cygwin-2.6.1), and macOS is the only platform known to
2211 support the latter. */
2213 #ifdef _PC_CASE_INSENSITIVE
2214 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2215 if (res >= 0)
2216 return res > 0;
2217 #elif defined _PC_CASE_SENSITIVE
2218 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2219 if (res >= 0)
2220 return res == 0;
2221 #endif
2223 #if defined CYGWIN || defined DOS_NT
2224 return true;
2225 #else
2226 return false;
2227 #endif
2230 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2231 Sfile_name_case_insensitive_p, 1, 1, 0,
2232 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2233 The arg must be a string. */)
2234 (Lisp_Object filename)
2236 Lisp_Object handler;
2238 CHECK_STRING (filename);
2239 filename = Fexpand_file_name (filename, Qnil);
2241 /* If the file name has special constructs in it,
2242 call the corresponding file handler. */
2243 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2244 if (!NILP (handler))
2245 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2247 filename = ENCODE_FILE (filename);
2248 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2251 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2252 "fRename file: \nGRename %s to file: \np",
2253 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2254 If file has names other than FILE, it continues to have those names.
2255 If NEWNAME is a directory name, rename FILE to a like-named file under
2256 NEWNAME. For NEWNAME to be recognized as a directory name, it should
2257 end in a slash.
2259 Signal a `file-already-exists' error if a file NEWNAME already exists
2260 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2261 An integer third arg means request confirmation if NEWNAME already exists.
2262 This is what happens in interactive use with M-x. */)
2263 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2265 Lisp_Object handler;
2266 Lisp_Object encoded_file, encoded_newname;
2268 file = Fexpand_file_name (file, Qnil);
2270 /* If the filesystem is case-insensitive and the file names are
2271 identical but for case, treat it as a change-case request, and do
2272 not worry whether NEWNAME exists or whether it is a directory, as
2273 it is already another name for FILE. */
2274 bool case_only_rename = false;
2275 #if defined CYGWIN || defined DOS_NT
2276 if (!NILP (Ffile_name_case_insensitive_p (file)))
2278 newname = Fexpand_file_name (newname, Qnil);
2279 case_only_rename = !NILP (Fstring_equal (Fdowncase (file),
2280 Fdowncase (newname)));
2282 #endif
2284 if (!case_only_rename)
2285 newname = expand_cp_target (Fdirectory_file_name (file), newname);
2287 /* If the file name has special constructs in it,
2288 call the corresponding file handler. */
2289 handler = Ffind_file_name_handler (file, Qrename_file);
2290 if (NILP (handler))
2291 handler = Ffind_file_name_handler (newname, Qrename_file);
2292 if (!NILP (handler))
2293 return call4 (handler, Qrename_file,
2294 file, newname, ok_if_already_exists);
2296 encoded_file = ENCODE_FILE (file);
2297 encoded_newname = ENCODE_FILE (newname);
2299 bool plain_rename = (case_only_rename
2300 || (!NILP (ok_if_already_exists)
2301 && !INTEGERP (ok_if_already_exists)));
2302 int rename_errno UNINIT;
2303 if (!plain_rename)
2305 if (renameat_noreplace (AT_FDCWD, SSDATA (encoded_file),
2306 AT_FDCWD, SSDATA (encoded_newname))
2307 == 0)
2308 return Qnil;
2310 rename_errno = errno;
2311 switch (rename_errno)
2313 case EEXIST: case EINVAL: case ENOSYS:
2314 #if ENOSYS != ENOTSUP
2315 case ENOTSUP:
2316 #endif
2317 barf_or_query_if_file_exists (newname, rename_errno == EEXIST,
2318 "rename to it",
2319 INTEGERP (ok_if_already_exists),
2320 false);
2321 plain_rename = true;
2322 break;
2326 if (plain_rename)
2328 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2329 return Qnil;
2330 rename_errno = errno;
2331 /* Don't prompt again. */
2332 ok_if_already_exists = Qt;
2334 else if (!NILP (ok_if_already_exists))
2335 ok_if_already_exists = Qt;
2337 if (rename_errno != EXDEV)
2338 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2340 struct stat file_st;
2341 bool dirp = !NILP (Fdirectory_name_p (file));
2342 if (!dirp)
2344 if (lstat (SSDATA (encoded_file), &file_st) != 0)
2345 report_file_error ("Renaming", list2 (file, newname));
2346 dirp = S_ISDIR (file_st.st_mode) != 0;
2348 if (dirp)
2349 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2350 else
2352 Lisp_Object symlink_target
2353 = (S_ISLNK (file_st.st_mode)
2354 ? emacs_readlinkat (AT_FDCWD, SSDATA (encoded_file))
2355 : Qnil);
2356 if (!NILP (symlink_target))
2357 Fmake_symbolic_link (symlink_target, newname, ok_if_already_exists);
2358 else
2359 Fcopy_file (file, newname, ok_if_already_exists, Qt, Qt, Qt);
2362 ptrdiff_t count = SPECPDL_INDEX ();
2363 specbind (Qdelete_by_moving_to_trash, Qnil);
2364 if (dirp)
2365 call2 (Qdelete_directory, file, Qt);
2366 else
2367 Fdelete_file (file, Qnil);
2368 return unbind_to (count, Qnil);
2371 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2372 "fAdd name to file: \nGName to add to %s: \np",
2373 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2374 If NEWNAME is a directory name, give FILE a like-named new name under
2375 NEWNAME.
2377 Signal a `file-already-exists' error if a file NEWNAME already exists
2378 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2379 An integer third arg means request confirmation if NEWNAME already exists.
2380 This is what happens in interactive use with M-x. */)
2381 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2383 Lisp_Object handler;
2384 Lisp_Object encoded_file, encoded_newname;
2386 file = Fexpand_file_name (file, Qnil);
2387 newname = expand_cp_target (file, newname);
2389 /* If the file name has special constructs in it,
2390 call the corresponding file handler. */
2391 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2392 if (!NILP (handler))
2393 return call4 (handler, Qadd_name_to_file, file,
2394 newname, ok_if_already_exists);
2396 /* If the new name has special constructs in it,
2397 call the corresponding file handler. */
2398 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2399 if (!NILP (handler))
2400 return call4 (handler, Qadd_name_to_file, file,
2401 newname, ok_if_already_exists);
2403 encoded_file = ENCODE_FILE (file);
2404 encoded_newname = ENCODE_FILE (newname);
2406 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2407 return Qnil;
2409 if (errno == EEXIST)
2411 if (NILP (ok_if_already_exists)
2412 || INTEGERP (ok_if_already_exists))
2413 barf_or_query_if_file_exists (newname, true, "make it a new name",
2414 INTEGERP (ok_if_already_exists), false);
2415 unlink (SSDATA (newname));
2416 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2417 return Qnil;
2420 report_file_error ("Adding new name", list2 (file, newname));
2423 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2424 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2425 doc: /* Make a symbolic link to TARGET, named NEWNAME.
2426 If NEWNAME is a directory name, make a like-named symbolic link under
2427 NEWNAME.
2429 Signal a `file-already-exists' error if a file NEWNAME already exists
2430 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2431 An integer third arg means request confirmation if NEWNAME already
2432 exists, and expand leading "~" or strip leading "/:" in TARGET.
2433 This happens for interactive use with M-x. */)
2434 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2436 Lisp_Object handler;
2437 Lisp_Object encoded_target, encoded_linkname;
2439 CHECK_STRING (target);
2440 if (INTEGERP (ok_if_already_exists))
2442 if (SREF (target, 0) == '~')
2443 target = Fexpand_file_name (target, Qnil);
2444 else if (SREF (target, 0) == '/' && SREF (target, 1) == ':')
2445 target = Fsubstring_no_properties (target, make_number (2), Qnil);
2447 linkname = expand_cp_target (target, linkname);
2449 /* If the new link name has special constructs in it,
2450 call the corresponding file handler. */
2451 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2452 if (!NILP (handler))
2453 return call4 (handler, Qmake_symbolic_link, target,
2454 linkname, ok_if_already_exists);
2456 encoded_target = ENCODE_FILE (target);
2457 encoded_linkname = ENCODE_FILE (linkname);
2459 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2460 return Qnil;
2462 if (errno == ENOSYS)
2463 xsignal1 (Qfile_error,
2464 build_string ("Symbolic links are not supported"));
2466 if (errno == EEXIST)
2468 if (NILP (ok_if_already_exists)
2469 || INTEGERP (ok_if_already_exists))
2470 barf_or_query_if_file_exists (linkname, true, "make it a link",
2471 INTEGERP (ok_if_already_exists), false);
2472 unlink (SSDATA (encoded_linkname));
2473 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2474 return Qnil;
2477 report_file_error ("Making symbolic link", list2 (target, linkname));
2481 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2482 1, 1, 0,
2483 doc: /* Return t if FILENAME is an absolute file name or starts with `~'.
2484 On Unix, absolute file names start with `/'. */)
2485 (Lisp_Object filename)
2487 CHECK_STRING (filename);
2488 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2491 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2492 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2493 See also `file-readable-p' and `file-attributes'.
2494 This returns nil for a symlink to a nonexistent file.
2495 Use `file-symlink-p' to test for such links. */)
2496 (Lisp_Object filename)
2498 Lisp_Object absname;
2499 Lisp_Object handler;
2501 CHECK_STRING (filename);
2502 absname = Fexpand_file_name (filename, Qnil);
2504 /* If the file name has special constructs in it,
2505 call the corresponding file handler. */
2506 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2507 if (!NILP (handler))
2509 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2510 errno = 0;
2511 return result;
2514 absname = ENCODE_FILE (absname);
2516 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2519 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2520 doc: /* Return t if FILENAME can be executed by you.
2521 For a directory, this means you can access files in that directory.
2522 \(It is generally better to use `file-accessible-directory-p' for that
2523 purpose, though.) */)
2524 (Lisp_Object filename)
2526 Lisp_Object absname;
2527 Lisp_Object handler;
2529 CHECK_STRING (filename);
2530 absname = Fexpand_file_name (filename, Qnil);
2532 /* If the file name has special constructs in it,
2533 call the corresponding file handler. */
2534 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2535 if (!NILP (handler))
2536 return call2 (handler, Qfile_executable_p, absname);
2538 absname = ENCODE_FILE (absname);
2540 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2543 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2544 doc: /* Return t if file FILENAME exists and you can read it.
2545 See also `file-exists-p' and `file-attributes'. */)
2546 (Lisp_Object filename)
2548 Lisp_Object absname;
2549 Lisp_Object handler;
2551 CHECK_STRING (filename);
2552 absname = Fexpand_file_name (filename, Qnil);
2554 /* If the file name has special constructs in it,
2555 call the corresponding file handler. */
2556 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2557 if (!NILP (handler))
2558 return call2 (handler, Qfile_readable_p, absname);
2560 absname = ENCODE_FILE (absname);
2561 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2562 ? Qt : Qnil);
2565 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2566 doc: /* Return t if file FILENAME can be written or created by you. */)
2567 (Lisp_Object filename)
2569 Lisp_Object absname, dir, encoded;
2570 Lisp_Object handler;
2572 CHECK_STRING (filename);
2573 absname = Fexpand_file_name (filename, Qnil);
2575 /* If the file name has special constructs in it,
2576 call the corresponding file handler. */
2577 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2578 if (!NILP (handler))
2579 return call2 (handler, Qfile_writable_p, absname);
2581 encoded = ENCODE_FILE (absname);
2582 if (check_writable (SSDATA (encoded), W_OK))
2583 return Qt;
2584 if (errno != ENOENT)
2585 return Qnil;
2587 dir = Ffile_name_directory (absname);
2588 eassert (!NILP (dir));
2589 #ifdef MSDOS
2590 dir = Fdirectory_file_name (dir);
2591 #endif /* MSDOS */
2593 dir = ENCODE_FILE (dir);
2594 #ifdef WINDOWSNT
2595 /* The read-only attribute of the parent directory doesn't affect
2596 whether a file or directory can be created within it. Some day we
2597 should check ACLs though, which do affect this. */
2598 return file_directory_p (dir) ? Qt : Qnil;
2599 #else
2600 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2601 #endif
2604 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2605 doc: /* Access file FILENAME, and get an error if that does not work.
2606 The second argument STRING is prepended to the error message.
2607 If there is no error, returns nil. */)
2608 (Lisp_Object filename, Lisp_Object string)
2610 Lisp_Object handler, encoded_filename, absname;
2612 CHECK_STRING (filename);
2613 absname = Fexpand_file_name (filename, Qnil);
2615 CHECK_STRING (string);
2617 /* If the file name has special constructs in it,
2618 call the corresponding file handler. */
2619 handler = Ffind_file_name_handler (absname, Qaccess_file);
2620 if (!NILP (handler))
2621 return call3 (handler, Qaccess_file, absname, string);
2623 encoded_filename = ENCODE_FILE (absname);
2625 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2626 report_file_error (SSDATA (string), filename);
2628 return Qnil;
2631 /* Relative to directory FD, return the symbolic link value of FILENAME.
2632 On failure, return nil. */
2633 Lisp_Object
2634 emacs_readlinkat (int fd, char const *filename)
2636 static struct allocator const emacs_norealloc_allocator =
2637 { xmalloc, NULL, xfree, memory_full };
2638 Lisp_Object val;
2639 char readlink_buf[1024];
2640 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2641 &emacs_norealloc_allocator, readlinkat);
2642 if (!buf)
2643 return Qnil;
2645 val = build_unibyte_string (buf);
2646 if (buf != readlink_buf)
2647 xfree (buf);
2648 val = DECODE_FILE (val);
2649 return val;
2652 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2653 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2654 The value is the link target, as a string.
2655 Otherwise it returns nil.
2657 This function does not check whether the link target exists. */)
2658 (Lisp_Object filename)
2660 Lisp_Object handler;
2662 CHECK_STRING (filename);
2663 filename = Fexpand_file_name (filename, Qnil);
2665 /* If the file name has special constructs in it,
2666 call the corresponding file handler. */
2667 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2668 if (!NILP (handler))
2669 return call2 (handler, Qfile_symlink_p, filename);
2671 filename = ENCODE_FILE (filename);
2673 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2676 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2677 doc: /* Return t if FILENAME names an existing directory.
2678 Symbolic links to directories count as directories.
2679 See `file-symlink-p' to distinguish symlinks. */)
2680 (Lisp_Object filename)
2682 Lisp_Object absname = expand_and_dir_to_file (filename);
2684 /* If the file name has special constructs in it,
2685 call the corresponding file handler. */
2686 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2687 if (!NILP (handler))
2688 return call2 (handler, Qfile_directory_p, absname);
2690 absname = ENCODE_FILE (absname);
2692 return file_directory_p (absname) ? Qt : Qnil;
2695 /* Return true if FILE is a directory or a symlink to a directory.
2696 Otherwise return false and set errno. */
2697 bool
2698 file_directory_p (Lisp_Object file)
2700 #ifdef DOS_NT
2701 /* This is cheaper than 'stat'. */
2702 return faccessat (AT_FDCWD, SSDATA (file), D_OK, AT_EACCESS) == 0;
2703 #else
2704 # ifdef O_PATH
2705 /* Use O_PATH if available, as it avoids races and EOVERFLOW issues. */
2706 int fd = openat (AT_FDCWD, SSDATA (file), O_PATH | O_CLOEXEC | O_DIRECTORY);
2707 if (0 <= fd)
2709 emacs_close (fd);
2710 return true;
2712 if (errno != EINVAL)
2713 return false;
2714 /* O_PATH is defined but evidently this Linux kernel predates 2.6.39.
2715 Fall back on generic POSIX code. */
2716 # endif
2717 /* Use file_accessible_directory, as it avoids stat EOVERFLOW
2718 problems and could be cheaper. However, if it fails because FILE
2719 is inaccessible, fall back on stat; if the latter fails with
2720 EOVERFLOW then FILE must have been a directory unless a race
2721 condition occurred (a problem hard to work around portably). */
2722 if (file_accessible_directory_p (file))
2723 return true;
2724 if (errno != EACCES)
2725 return false;
2726 struct stat st;
2727 if (stat (SSDATA (file), &st) != 0)
2728 return errno == EOVERFLOW;
2729 if (S_ISDIR (st.st_mode))
2730 return true;
2731 errno = ENOTDIR;
2732 return false;
2733 #endif
2736 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2737 Sfile_accessible_directory_p, 1, 1, 0,
2738 doc: /* Return t if FILENAME names a directory you can open.
2739 For the value to be t, FILENAME must specify the name of a directory
2740 as a file, and the directory must allow you to open files in it. In
2741 order to use a directory as a buffer's current directory, this
2742 predicate must return true. A directory name spec may be given
2743 instead; then the value is t if the directory so specified exists and
2744 really is a readable and searchable directory. */)
2745 (Lisp_Object filename)
2747 Lisp_Object absname;
2748 Lisp_Object handler;
2750 CHECK_STRING (filename);
2751 absname = Fexpand_file_name (filename, Qnil);
2753 /* If the file name has special constructs in it,
2754 call the corresponding file handler. */
2755 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2756 if (!NILP (handler))
2758 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2760 /* Set errno in case the handler failed. EACCES might be a lie
2761 (e.g., the directory might not exist, or be a regular file),
2762 but at least it does TRT in the "usual" case of an existing
2763 directory that is not accessible by the current user, and
2764 avoids reporting "Success" for a failed operation. Perhaps
2765 someday we can fix this in a better way, by improving
2766 file-accessible-directory-p's API; see Bug#25419. */
2767 if (!EQ (r, Qt))
2768 errno = EACCES;
2770 return r;
2773 absname = ENCODE_FILE (absname);
2774 return file_accessible_directory_p (absname) ? Qt : Qnil;
2777 /* If FILE is a searchable directory or a symlink to a
2778 searchable directory, return true. Otherwise return
2779 false and set errno to an error number. */
2780 bool
2781 file_accessible_directory_p (Lisp_Object file)
2783 #ifdef DOS_NT
2784 # ifdef WINDOWSNT
2785 /* We need a special-purpose test because (a) NTFS security data is
2786 not reflected in Posix-style mode bits, and (b) the trick with
2787 accessing "DIR/.", used below on Posix hosts, doesn't work on
2788 Windows, because "DIR/." is normalized to just "DIR" before
2789 hitting the disk. */
2790 return (SBYTES (file) == 0
2791 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2792 # else /* MSDOS */
2793 return file_directory_p (file);
2794 # endif /* MSDOS */
2795 #else /* !DOS_NT */
2796 /* On POSIXish platforms, use just one system call; this avoids a
2797 race and is typically faster. */
2798 const char *data = SSDATA (file);
2799 ptrdiff_t len = SBYTES (file);
2800 char const *dir;
2801 bool ok;
2802 int saved_errno;
2803 USE_SAFE_ALLOCA;
2805 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2806 There are three exceptions: "", "/", and "//". Leave "" alone,
2807 as it's invalid. Append only "." to the other two exceptions as
2808 "/" and "//" are distinct on some platforms, whereas "/", "///",
2809 "////", etc. are all equivalent. */
2810 if (! len)
2811 dir = data;
2812 else
2814 /* Just check for trailing '/' when deciding whether append '/'
2815 before appending '.'. That's simpler than testing the two
2816 special cases "/" and "//", and it's a safe optimization
2817 here. After appending '.', append another '/' to work around
2818 a macOS bug (Bug#30350). */
2819 static char const appended[] = "/./";
2820 char *buf = SAFE_ALLOCA (len + sizeof appended);
2821 memcpy (buf, data, len);
2822 strcpy (buf + len, &appended[data[len - 1] == '/']);
2823 dir = buf;
2826 ok = check_existing (dir);
2827 saved_errno = errno;
2828 SAFE_FREE ();
2829 errno = saved_errno;
2830 return ok;
2831 #endif /* !DOS_NT */
2834 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2835 doc: /* Return t if FILENAME names a regular file.
2836 This is the sort of file that holds an ordinary stream of data bytes.
2837 Symbolic links to regular files count as regular files.
2838 See `file-symlink-p' to distinguish symlinks. */)
2839 (Lisp_Object filename)
2841 struct stat st;
2842 Lisp_Object absname = expand_and_dir_to_file (filename);
2844 /* If the file name has special constructs in it,
2845 call the corresponding file handler. */
2846 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2847 if (!NILP (handler))
2848 return call2 (handler, Qfile_regular_p, absname);
2850 absname = ENCODE_FILE (absname);
2852 #ifdef WINDOWSNT
2854 int result;
2855 Lisp_Object tem = Vw32_get_true_file_attributes;
2857 /* Tell stat to use expensive method to get accurate info. */
2858 Vw32_get_true_file_attributes = Qt;
2859 result = stat (SSDATA (absname), &st);
2860 Vw32_get_true_file_attributes = tem;
2862 if (result < 0)
2863 return Qnil;
2864 return S_ISREG (st.st_mode) ? Qt : Qnil;
2866 #else
2867 if (stat (SSDATA (absname), &st) < 0)
2868 return Qnil;
2869 return S_ISREG (st.st_mode) ? Qt : Qnil;
2870 #endif
2873 DEFUN ("file-selinux-context", Ffile_selinux_context,
2874 Sfile_selinux_context, 1, 1, 0,
2875 doc: /* Return SELinux context of file named FILENAME.
2876 The return value is a list (USER ROLE TYPE RANGE), where the list
2877 elements are strings naming the user, role, type, and range of the
2878 file's SELinux security context.
2880 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2881 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2882 (Lisp_Object filename)
2884 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2885 Lisp_Object absname = expand_and_dir_to_file (filename);
2887 /* If the file name has special constructs in it,
2888 call the corresponding file handler. */
2889 Lisp_Object handler = Ffind_file_name_handler (absname,
2890 Qfile_selinux_context);
2891 if (!NILP (handler))
2892 return call2 (handler, Qfile_selinux_context, absname);
2894 absname = ENCODE_FILE (absname);
2896 #if HAVE_LIBSELINUX
2897 if (is_selinux_enabled ())
2899 security_context_t con;
2900 int conlength = lgetfilecon (SSDATA (absname), &con);
2901 if (conlength > 0)
2903 context_t context = context_new (con);
2904 if (context_user_get (context))
2905 user = build_string (context_user_get (context));
2906 if (context_role_get (context))
2907 role = build_string (context_role_get (context));
2908 if (context_type_get (context))
2909 type = build_string (context_type_get (context));
2910 if (context_range_get (context))
2911 range = build_string (context_range_get (context));
2912 context_free (context);
2913 freecon (con);
2916 #endif
2918 return list4 (user, role, type, range);
2921 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2922 Sset_file_selinux_context, 2, 2, 0,
2923 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2924 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2925 elements are strings naming the components of a SELinux context.
2927 Value is t if setting of SELinux context was successful, nil otherwise.
2929 This function does nothing and returns nil if SELinux is disabled,
2930 or if Emacs was not compiled with SELinux support. */)
2931 (Lisp_Object filename, Lisp_Object context)
2933 Lisp_Object absname;
2934 Lisp_Object handler;
2935 #if HAVE_LIBSELINUX
2936 Lisp_Object encoded_absname;
2937 Lisp_Object user = CAR_SAFE (context);
2938 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2939 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2940 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2941 security_context_t con;
2942 bool fail;
2943 int conlength;
2944 context_t parsed_con;
2945 #endif
2947 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2949 /* If the file name has special constructs in it,
2950 call the corresponding file handler. */
2951 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2952 if (!NILP (handler))
2953 return call3 (handler, Qset_file_selinux_context, absname, context);
2955 #if HAVE_LIBSELINUX
2956 if (is_selinux_enabled ())
2958 /* Get current file context. */
2959 encoded_absname = ENCODE_FILE (absname);
2960 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2961 if (conlength > 0)
2963 parsed_con = context_new (con);
2964 /* Change the parts defined in the parameter.*/
2965 if (STRINGP (user))
2967 if (context_user_set (parsed_con, SSDATA (user)))
2968 error ("Doing context_user_set");
2970 if (STRINGP (role))
2972 if (context_role_set (parsed_con, SSDATA (role)))
2973 error ("Doing context_role_set");
2975 if (STRINGP (type))
2977 if (context_type_set (parsed_con, SSDATA (type)))
2978 error ("Doing context_type_set");
2980 if (STRINGP (range))
2982 if (context_range_set (parsed_con, SSDATA (range)))
2983 error ("Doing context_range_set");
2986 /* Set the modified context back to the file. */
2987 fail = (lsetfilecon (SSDATA (encoded_absname),
2988 context_str (parsed_con))
2989 != 0);
2990 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
2991 if (fail && errno != ENOTSUP)
2992 report_file_error ("Doing lsetfilecon", absname);
2994 context_free (parsed_con);
2995 freecon (con);
2996 return fail ? Qnil : Qt;
2998 else
2999 report_file_error ("Doing lgetfilecon", absname);
3001 #endif
3003 return Qnil;
3006 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
3007 doc: /* Return ACL entries of file named FILENAME.
3008 The entries are returned in a format suitable for use in `set-file-acl'
3009 but is otherwise undocumented and subject to change.
3010 Return nil if file does not exist or is not accessible, or if Emacs
3011 was unable to determine the ACL entries. */)
3012 (Lisp_Object filename)
3014 Lisp_Object acl_string = Qnil;
3016 #if USE_ACL
3017 Lisp_Object absname = expand_and_dir_to_file (filename);
3019 /* If the file name has special constructs in it,
3020 call the corresponding file handler. */
3021 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_acl);
3022 if (!NILP (handler))
3023 return call2 (handler, Qfile_acl, absname);
3025 # ifdef HAVE_ACL_SET_FILE
3026 absname = ENCODE_FILE (absname);
3028 # ifndef HAVE_ACL_TYPE_EXTENDED
3029 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
3030 # endif
3031 acl_t acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3032 if (acl == NULL)
3033 return Qnil;
3035 char *str = acl_to_text (acl, NULL);
3036 if (str == NULL)
3038 acl_free (acl);
3039 return Qnil;
3042 acl_string = build_string (str);
3043 acl_free (str);
3044 acl_free (acl);
3045 # endif
3046 #endif
3048 return acl_string;
3051 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3052 2, 2, 0,
3053 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3054 ACL-STRING should contain the textual representation of the ACL
3055 entries in a format suitable for the platform.
3057 Value is t if setting of ACL was successful, nil otherwise.
3059 Setting ACL for local files requires Emacs to be built with ACL
3060 support. */)
3061 (Lisp_Object filename, Lisp_Object acl_string)
3063 #if USE_ACL
3064 Lisp_Object absname;
3065 Lisp_Object handler;
3066 # ifdef HAVE_ACL_SET_FILE
3067 Lisp_Object encoded_absname;
3068 acl_t acl;
3069 bool fail;
3070 # endif
3072 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3074 /* If the file name has special constructs in it,
3075 call the corresponding file handler. */
3076 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3077 if (!NILP (handler))
3078 return call3 (handler, Qset_file_acl, absname, acl_string);
3080 # ifdef HAVE_ACL_SET_FILE
3081 if (STRINGP (acl_string))
3083 acl = acl_from_text (SSDATA (acl_string));
3084 if (acl == NULL)
3086 if (acl_errno_valid (errno))
3087 report_file_error ("Converting ACL", absname);
3088 return Qnil;
3091 encoded_absname = ENCODE_FILE (absname);
3093 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3094 acl)
3095 != 0);
3096 if (fail && acl_errno_valid (errno))
3097 report_file_error ("Setting ACL", absname);
3099 acl_free (acl);
3100 return fail ? Qnil : Qt;
3102 # endif
3103 #endif
3105 return Qnil;
3108 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3109 doc: /* Return mode bits of file named FILENAME, as an integer.
3110 Return nil, if file does not exist or is not accessible. */)
3111 (Lisp_Object filename)
3113 struct stat st;
3114 Lisp_Object absname = expand_and_dir_to_file (filename);
3116 /* If the file name has special constructs in it,
3117 call the corresponding file handler. */
3118 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_modes);
3119 if (!NILP (handler))
3120 return call2 (handler, Qfile_modes, absname);
3122 absname = ENCODE_FILE (absname);
3124 if (stat (SSDATA (absname), &st) < 0)
3125 return Qnil;
3127 return make_number (st.st_mode & 07777);
3130 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3131 "(let ((file (read-file-name \"File: \"))) \
3132 (list file (read-file-modes nil file)))",
3133 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3134 Only the 12 low bits of MODE are used.
3136 Interactively, mode bits are read by `read-file-modes', which accepts
3137 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3138 (Lisp_Object filename, Lisp_Object mode)
3140 Lisp_Object absname, encoded_absname;
3141 Lisp_Object handler;
3143 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3144 CHECK_NUMBER (mode);
3146 /* If the file name has special constructs in it,
3147 call the corresponding file handler. */
3148 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3149 if (!NILP (handler))
3150 return call3 (handler, Qset_file_modes, absname, mode);
3152 encoded_absname = ENCODE_FILE (absname);
3154 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3155 report_file_error ("Doing chmod", absname);
3157 return Qnil;
3160 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3161 doc: /* Set the file permission bits for newly created files.
3162 The argument MODE should be an integer; only the low 9 bits are used.
3163 On Posix hosts, this setting is inherited by subprocesses.
3165 This function works by setting the Emacs's file mode creation mask.
3166 Each bit that is set in the mask means that the corresponding bit
3167 in the permissions of newly created files will be disabled.
3169 Note that when `write-region' creates a file, it resets the
3170 execute bit, even if the mask set by this function allows that bit
3171 by having the corresponding bit in the mask reset. */)
3172 (Lisp_Object mode)
3174 mode_t oldrealmask, oldumask, newumask;
3175 CHECK_NUMBER (mode);
3176 oldrealmask = realmask;
3177 newumask = ~ XINT (mode) & 0777;
3179 block_input ();
3180 realmask = newumask;
3181 oldumask = umask (newumask);
3182 unblock_input ();
3184 eassert (oldumask == oldrealmask);
3185 return Qnil;
3188 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3189 doc: /* Return the default file protection for created files.
3190 The value is an integer. */)
3191 (void)
3193 Lisp_Object value;
3194 XSETINT (value, (~ realmask) & 0777);
3195 return value;
3199 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3200 doc: /* Set times of file FILENAME to TIMESTAMP.
3201 Set both access and modification times.
3202 Return t on success, else nil.
3203 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3204 `current-time'. */)
3205 (Lisp_Object filename, Lisp_Object timestamp)
3207 Lisp_Object absname, encoded_absname;
3208 Lisp_Object handler;
3209 struct timespec t = lisp_time_argument (timestamp);
3211 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3213 /* If the file name has special constructs in it,
3214 call the corresponding file handler. */
3215 handler = Ffind_file_name_handler (absname, Qset_file_times);
3216 if (!NILP (handler))
3217 return call3 (handler, Qset_file_times, absname, timestamp);
3219 encoded_absname = ENCODE_FILE (absname);
3222 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3224 #ifdef MSDOS
3225 /* Setting times on a directory always fails. */
3226 if (file_directory_p (encoded_absname))
3227 return Qnil;
3228 #endif
3229 report_file_error ("Setting file times", absname);
3233 return Qt;
3236 #ifdef HAVE_SYNC
3237 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3238 doc: /* Tell Unix to finish all pending disk updates. */)
3239 (void)
3241 sync ();
3242 return Qnil;
3245 #endif /* HAVE_SYNC */
3247 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3248 doc: /* Return t if file FILE1 is newer than file FILE2.
3249 If FILE1 does not exist, the answer is nil;
3250 otherwise, if FILE2 does not exist, the answer is t. */)
3251 (Lisp_Object file1, Lisp_Object file2)
3253 struct stat st1, st2;
3255 CHECK_STRING (file1);
3256 CHECK_STRING (file2);
3258 Lisp_Object absname1 = expand_and_dir_to_file (file1);
3259 Lisp_Object absname2 = expand_and_dir_to_file (file2);
3261 /* If the file name has special constructs in it,
3262 call the corresponding file handler. */
3263 Lisp_Object handler = Ffind_file_name_handler (absname1,
3264 Qfile_newer_than_file_p);
3265 if (NILP (handler))
3266 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3267 if (!NILP (handler))
3268 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3270 absname1 = ENCODE_FILE (absname1);
3271 absname2 = ENCODE_FILE (absname2);
3273 if (stat (SSDATA (absname1), &st1) < 0)
3274 return Qnil;
3276 if (stat (SSDATA (absname2), &st2) < 0)
3277 return Qt;
3279 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3280 ? Qt : Qnil);
3283 enum { READ_BUF_SIZE = MAX_ALLOCA };
3285 /* This function is called after Lisp functions to decide a coding
3286 system are called, or when they cause an error. Before they are
3287 called, the current buffer is set unibyte and it contains only a
3288 newly inserted text (thus the buffer was empty before the
3289 insertion).
3291 The functions may set markers, overlays, text properties, or even
3292 alter the buffer contents, change the current buffer.
3294 Here, we reset all those changes by:
3295 o set back the current buffer.
3296 o move all markers and overlays to BEG.
3297 o remove all text properties.
3298 o set back the buffer multibyteness. */
3300 static void
3301 decide_coding_unwind (Lisp_Object unwind_data)
3303 Lisp_Object multibyte, undo_list, buffer;
3305 multibyte = XCAR (unwind_data);
3306 unwind_data = XCDR (unwind_data);
3307 undo_list = XCAR (unwind_data);
3308 buffer = XCDR (unwind_data);
3310 set_buffer_internal (XBUFFER (buffer));
3311 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3312 adjust_overlays_for_delete (BEG, Z - BEG);
3313 set_buffer_intervals (current_buffer, NULL);
3314 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3316 /* Now we are safe to change the buffer's multibyteness directly. */
3317 bset_enable_multibyte_characters (current_buffer, multibyte);
3318 bset_undo_list (current_buffer, undo_list);
3321 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3322 object where slot 0 is the file descriptor, slot 1 specifies
3323 an offset to put the read bytes, and slot 2 is the maximum
3324 amount of bytes to read. Value is the number of bytes read. */
3326 static Lisp_Object
3327 read_non_regular (Lisp_Object state)
3329 int nbytes = emacs_read_quit (XSAVE_INTEGER (state, 0),
3330 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3331 + XSAVE_INTEGER (state, 1)),
3332 XSAVE_INTEGER (state, 2));
3333 /* Fast recycle this object for the likely next call. */
3334 free_misc (state);
3335 return make_number (nbytes);
3339 /* Condition-case handler used when reading from non-regular files
3340 in insert-file-contents. */
3342 static Lisp_Object
3343 read_non_regular_quit (Lisp_Object ignore)
3345 return Qnil;
3348 /* Return the file offset that VAL represents, checking for type
3349 errors and overflow. */
3350 static off_t
3351 file_offset (Lisp_Object val)
3353 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3354 return XINT (val);
3356 if (FLOATP (val))
3358 double v = XFLOAT_DATA (val);
3359 if (0 <= v && v < 1.0 + TYPE_MAXIMUM (off_t))
3361 off_t o = v;
3362 if (o == v)
3363 return o;
3367 wrong_type_argument (intern ("file-offset"), val);
3370 /* Return a special time value indicating the error number ERRNUM. */
3371 static struct timespec
3372 time_error_value (int errnum)
3374 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3375 ? NONEXISTENT_MODTIME_NSECS
3376 : UNKNOWN_MODTIME_NSECS);
3377 return make_timespec (0, ns);
3380 static Lisp_Object
3381 get_window_points_and_markers (void)
3383 Lisp_Object pt_marker = Fpoint_marker ();
3384 Lisp_Object windows
3385 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3386 Lisp_Object window_markers = windows;
3387 /* Window markers (and point) are handled specially: rather than move to
3388 just before or just after the modified text, we try to keep the
3389 markers at the same distance (bug#19161).
3390 In general, this is wrong, but for window-markers, this should be harmless
3391 and is convenient for the end user when most of the file is unmodified,
3392 except for a few minor details near the beginning and near the end. */
3393 for (; CONSP (windows); windows = XCDR (windows))
3394 if (WINDOWP (XCAR (windows)))
3396 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3397 XSETCAR (windows,
3398 Fcons (window_marker, Fmarker_position (window_marker)));
3400 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3403 static void
3404 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3405 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3407 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3408 if (CONSP (XCAR (window_markers)))
3410 Lisp_Object car = XCAR (window_markers);
3411 Lisp_Object marker = XCAR (car);
3412 Lisp_Object oldpos = XCDR (car);
3413 if (MARKERP (marker) && INTEGERP (oldpos)
3414 && XINT (oldpos) > same_at_start
3415 && XINT (oldpos) < same_at_end)
3417 ptrdiff_t oldsize = same_at_end - same_at_start;
3418 ptrdiff_t newsize = inserted;
3419 double growth = newsize / (double)oldsize;
3420 ptrdiff_t newpos
3421 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3422 Fset_marker (marker, make_number (newpos), Qnil);
3427 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3428 text as a linear C char array. */
3429 static void
3430 maybe_move_gap (struct buffer *b)
3432 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3434 struct buffer *cb = current_buffer;
3436 set_buffer_internal (b);
3437 move_gap_both (Z, Z_BYTE);
3438 set_buffer_internal (cb);
3442 /* FIXME: insert-file-contents should be split with the top-level moved to
3443 Elisp and only the core kept in C. */
3445 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3446 1, 5, 0,
3447 doc: /* Insert contents of file FILENAME after point.
3448 Returns list of absolute file name and number of characters inserted.
3449 If second argument VISIT is non-nil, the buffer's visited filename and
3450 last save file modtime are set, and it is marked unmodified. If
3451 visiting and the file does not exist, visiting is completed before the
3452 error is signaled.
3454 The optional third and fourth arguments BEG and END specify what portion
3455 of the file to insert. These arguments count bytes in the file, not
3456 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3458 If optional fifth argument REPLACE is non-nil, replace the current
3459 buffer contents (in the accessible portion) with the file contents.
3460 This is better than simply deleting and inserting the whole thing
3461 because (1) it preserves some marker positions and (2) it puts less data
3462 in the undo list. When REPLACE is non-nil, the second return value is
3463 the number of characters that replace previous buffer contents.
3465 This function does code conversion according to the value of
3466 `coding-system-for-read' or `file-coding-system-alist', and sets the
3467 variable `last-coding-system-used' to the coding system actually used.
3469 In addition, this function decodes the inserted text from known formats
3470 by calling `format-decode', which see. */)
3471 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3473 struct stat st;
3474 struct timespec mtime;
3475 int fd;
3476 ptrdiff_t inserted = 0;
3477 ptrdiff_t how_much;
3478 off_t beg_offset, end_offset;
3479 int unprocessed;
3480 ptrdiff_t count = SPECPDL_INDEX ();
3481 Lisp_Object handler, val, insval, orig_filename, old_undo;
3482 Lisp_Object p;
3483 ptrdiff_t total = 0;
3484 bool not_regular = 0;
3485 int save_errno = 0;
3486 char read_buf[READ_BUF_SIZE];
3487 struct coding_system coding;
3488 bool replace_handled = false;
3489 bool set_coding_system = false;
3490 Lisp_Object coding_system;
3491 bool read_quit = false;
3492 /* If the undo log only contains the insertion, there's no point
3493 keeping it. It's typically when we first fill a file-buffer. */
3494 bool empty_undo_list_p
3495 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3496 && BEG == Z);
3497 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3498 bool we_locked_file = false;
3499 ptrdiff_t fd_index;
3500 Lisp_Object window_markers = Qnil;
3501 /* same_at_start and same_at_end count bytes, because file access counts
3502 bytes and BEG and END count bytes. */
3503 ptrdiff_t same_at_start = BEGV_BYTE;
3504 ptrdiff_t same_at_end = ZV_BYTE;
3505 /* SAME_AT_END_CHARPOS counts characters, because
3506 restore_window_points needs the old character count. */
3507 ptrdiff_t same_at_end_charpos = ZV;
3509 if (current_buffer->base_buffer && ! NILP (visit))
3510 error ("Cannot do file visiting in an indirect buffer");
3512 if (!NILP (BVAR (current_buffer, read_only)))
3513 Fbarf_if_buffer_read_only (Qnil);
3515 val = Qnil;
3516 p = Qnil;
3517 orig_filename = Qnil;
3518 old_undo = Qnil;
3520 CHECK_STRING (filename);
3521 filename = Fexpand_file_name (filename, Qnil);
3523 /* The value Qnil means that the coding system is not yet
3524 decided. */
3525 coding_system = Qnil;
3527 /* If the file name has special constructs in it,
3528 call the corresponding file handler. */
3529 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3530 if (!NILP (handler))
3532 val = call6 (handler, Qinsert_file_contents, filename,
3533 visit, beg, end, replace);
3534 if (CONSP (val) && CONSP (XCDR (val))
3535 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3536 inserted = XINT (XCAR (XCDR (val)));
3537 goto handled;
3540 orig_filename = filename;
3541 filename = ENCODE_FILE (filename);
3543 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3544 if (fd < 0)
3546 save_errno = errno;
3547 if (NILP (visit))
3548 report_file_error ("Opening input file", orig_filename);
3549 mtime = time_error_value (save_errno);
3550 st.st_size = -1;
3551 if (!NILP (Vcoding_system_for_read))
3553 /* Don't let invalid values into buffer-file-coding-system. */
3554 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3555 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3557 goto notfound;
3560 fd_index = SPECPDL_INDEX ();
3561 record_unwind_protect_int (close_file_unwind, fd);
3563 /* Replacement should preserve point as it preserves markers. */
3564 if (!NILP (replace))
3566 window_markers = get_window_points_and_markers ();
3567 record_unwind_protect (restore_point_unwind,
3568 XCAR (XCAR (window_markers)));
3571 if (fstat (fd, &st) != 0)
3572 report_file_error ("Input file status", orig_filename);
3573 mtime = get_stat_mtime (&st);
3575 /* This code will need to be changed in order to work on named
3576 pipes, and it's probably just not worth it. So we should at
3577 least signal an error. */
3578 if (!S_ISREG (st.st_mode))
3580 not_regular = 1;
3582 if (! NILP (visit))
3583 goto notfound;
3585 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3586 xsignal2 (Qfile_error,
3587 build_string ("not a regular file"), orig_filename);
3590 if (!NILP (visit))
3592 if (!NILP (beg) || !NILP (end))
3593 error ("Attempt to visit less than an entire file");
3594 if (BEG < Z && NILP (replace))
3595 error ("Cannot do file visiting in a non-empty buffer");
3598 if (!NILP (beg))
3599 beg_offset = file_offset (beg);
3600 else
3601 beg_offset = 0;
3603 if (!NILP (end))
3604 end_offset = file_offset (end);
3605 else
3607 if (not_regular)
3608 end_offset = TYPE_MAXIMUM (off_t);
3609 else
3611 end_offset = st.st_size;
3613 /* A negative size can happen on a platform that allows file
3614 sizes greater than the maximum off_t value. */
3615 if (end_offset < 0)
3616 buffer_overflow ();
3618 /* The file size returned from stat may be zero, but data
3619 may be readable nonetheless, for example when this is a
3620 file in the /proc filesystem. */
3621 if (end_offset == 0)
3622 end_offset = READ_BUF_SIZE;
3626 /* Check now whether the buffer will become too large,
3627 in the likely case where the file's length is not changing.
3628 This saves a lot of needless work before a buffer overflow. */
3629 if (! not_regular)
3631 /* The likely offset where we will stop reading. We could read
3632 more (or less), if the file grows (or shrinks) as we read it. */
3633 off_t likely_end = min (end_offset, st.st_size);
3635 if (beg_offset < likely_end)
3637 ptrdiff_t buf_bytes
3638 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3639 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3640 off_t likely_growth = likely_end - beg_offset;
3641 if (buf_growth_max < likely_growth)
3642 buffer_overflow ();
3646 /* Prevent redisplay optimizations. */
3647 current_buffer->clip_changed = true;
3649 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3651 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3652 setup_coding_system (coding_system, &coding);
3653 /* Ensure we set Vlast_coding_system_used. */
3654 set_coding_system = true;
3656 else if (BEG < Z)
3658 /* Decide the coding system to use for reading the file now
3659 because we can't use an optimized method for handling
3660 `coding:' tag if the current buffer is not empty. */
3661 if (!NILP (Vcoding_system_for_read))
3662 coding_system = Vcoding_system_for_read;
3663 else
3665 /* Don't try looking inside a file for a coding system
3666 specification if it is not seekable. */
3667 if (! not_regular && ! NILP (Vset_auto_coding_function))
3669 /* Find a coding system specified in the heading two
3670 lines or in the tailing several lines of the file.
3671 We assume that the 1K-byte and 3K-byte for heading
3672 and tailing respectively are sufficient for this
3673 purpose. */
3674 int nread;
3676 if (st.st_size <= (1024 * 4))
3677 nread = emacs_read_quit (fd, read_buf, 1024 * 4);
3678 else
3680 nread = emacs_read_quit (fd, read_buf, 1024);
3681 if (nread == 1024)
3683 int ntail;
3684 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3685 report_file_error ("Setting file position",
3686 orig_filename);
3687 ntail = emacs_read_quit (fd, read_buf + nread, 1024 * 3);
3688 nread = ntail < 0 ? ntail : nread + ntail;
3692 if (nread < 0)
3693 report_file_error ("Read error", orig_filename);
3694 else if (nread > 0)
3696 AUTO_STRING (name, " *code-converting-work*");
3697 struct buffer *prev = current_buffer;
3698 Lisp_Object workbuf;
3699 struct buffer *buf;
3701 record_unwind_current_buffer ();
3703 workbuf = Fget_buffer_create (name);
3704 buf = XBUFFER (workbuf);
3706 delete_all_overlays (buf);
3707 bset_directory (buf, BVAR (current_buffer, directory));
3708 bset_read_only (buf, Qnil);
3709 bset_filename (buf, Qnil);
3710 bset_undo_list (buf, Qt);
3711 eassert (buf->overlays_before == NULL);
3712 eassert (buf->overlays_after == NULL);
3714 set_buffer_internal (buf);
3715 Ferase_buffer ();
3716 bset_enable_multibyte_characters (buf, Qnil);
3718 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3719 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3720 coding_system = call2 (Vset_auto_coding_function,
3721 filename, make_number (nread));
3722 set_buffer_internal (prev);
3724 /* Discard the unwind protect for recovering the
3725 current buffer. */
3726 specpdl_ptr--;
3728 /* Rewind the file for the actual read done later. */
3729 if (lseek (fd, 0, SEEK_SET) < 0)
3730 report_file_error ("Setting file position", orig_filename);
3734 if (NILP (coding_system))
3736 /* If we have not yet decided a coding system, check
3737 file-coding-system-alist. */
3738 coding_system = CALLN (Ffind_operation_coding_system,
3739 Qinsert_file_contents, orig_filename,
3740 visit, beg, end, replace);
3741 if (CONSP (coding_system))
3742 coding_system = XCAR (coding_system);
3746 if (NILP (coding_system))
3747 coding_system = Qundecided;
3748 else
3749 CHECK_CODING_SYSTEM (coding_system);
3751 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3752 /* We must suppress all character code conversion except for
3753 end-of-line conversion. */
3754 coding_system = raw_text_coding_system (coding_system);
3756 setup_coding_system (coding_system, &coding);
3757 /* Ensure we set Vlast_coding_system_used. */
3758 set_coding_system = true;
3761 /* If requested, replace the accessible part of the buffer
3762 with the file contents. Avoid replacing text at the
3763 beginning or end of the buffer that matches the file contents;
3764 that preserves markers pointing to the unchanged parts.
3766 Here we implement this feature in an optimized way
3767 for the case where code conversion is NOT needed.
3768 The following if-statement handles the case of conversion
3769 in a less optimal way.
3771 If the code conversion is "automatic" then we try using this
3772 method and hope for the best.
3773 But if we discover the need for conversion, we give up on this method
3774 and let the following if-statement handle the replace job. */
3775 if (!NILP (replace)
3776 && BEGV < ZV
3777 && (NILP (coding_system)
3778 || ! CODING_REQUIRE_DECODING (&coding)))
3780 ptrdiff_t overlap;
3781 /* There is still a possibility we will find the need to do code
3782 conversion. If that happens, set this variable to
3783 give up on handling REPLACE in the optimized way. */
3784 bool giveup_match_end = false;
3786 if (beg_offset != 0)
3788 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3789 report_file_error ("Setting file position", orig_filename);
3792 /* Count how many chars at the start of the file
3793 match the text at the beginning of the buffer. */
3794 while (true)
3796 int nread = emacs_read_quit (fd, read_buf, sizeof read_buf);
3797 if (nread < 0)
3798 report_file_error ("Read error", orig_filename);
3799 else if (nread == 0)
3800 break;
3802 if (CODING_REQUIRE_DETECTION (&coding))
3804 coding_system = detect_coding_system ((unsigned char *) read_buf,
3805 nread, nread, 1, 0,
3806 coding_system);
3807 setup_coding_system (coding_system, &coding);
3810 if (CODING_REQUIRE_DECODING (&coding))
3811 /* We found that the file should be decoded somehow.
3812 Let's give up here. */
3814 giveup_match_end = true;
3815 break;
3818 int bufpos = 0;
3819 while (bufpos < nread && same_at_start < ZV_BYTE
3820 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3821 same_at_start++, bufpos++;
3822 /* If we found a discrepancy, stop the scan.
3823 Otherwise loop around and scan the next bufferful. */
3824 if (bufpos != nread)
3825 break;
3827 /* If the file matches the buffer completely,
3828 there's no need to replace anything. */
3829 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3831 emacs_close (fd);
3832 clear_unwind_protect (fd_index);
3834 /* Truncate the buffer to the size of the file. */
3835 del_range_1 (same_at_start, same_at_end, 0, 0);
3836 goto handled;
3839 /* Count how many chars at the end of the file
3840 match the text at the end of the buffer. But, if we have
3841 already found that decoding is necessary, don't waste time. */
3842 while (!giveup_match_end)
3844 int total_read, nread, bufpos, trial;
3845 off_t curpos;
3847 /* At what file position are we now scanning? */
3848 curpos = end_offset - (ZV_BYTE - same_at_end);
3849 /* If the entire file matches the buffer tail, stop the scan. */
3850 if (curpos == 0)
3851 break;
3852 /* How much can we scan in the next step? */
3853 trial = min (curpos, sizeof read_buf);
3854 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3855 report_file_error ("Setting file position", orig_filename);
3857 total_read = nread = 0;
3858 while (total_read < trial)
3860 nread = emacs_read_quit (fd, read_buf + total_read,
3861 trial - total_read);
3862 if (nread < 0)
3863 report_file_error ("Read error", orig_filename);
3864 else if (nread == 0)
3865 break;
3866 total_read += nread;
3869 /* Scan this bufferful from the end, comparing with
3870 the Emacs buffer. */
3871 bufpos = total_read;
3873 /* Compare with same_at_start to avoid counting some buffer text
3874 as matching both at the file's beginning and at the end. */
3875 while (bufpos > 0 && same_at_end > same_at_start
3876 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3877 same_at_end--, bufpos--;
3879 /* If we found a discrepancy, stop the scan.
3880 Otherwise loop around and scan the preceding bufferful. */
3881 if (bufpos != 0)
3883 /* If this discrepancy is because of code conversion,
3884 we cannot use this method; giveup and try the other. */
3885 if (same_at_end > same_at_start
3886 && FETCH_BYTE (same_at_end - 1) >= 0200
3887 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3888 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3889 giveup_match_end = true;
3890 break;
3893 if (nread == 0)
3894 break;
3897 if (! giveup_match_end)
3899 ptrdiff_t temp;
3900 ptrdiff_t this_count = SPECPDL_INDEX ();
3902 /* We win! We can handle REPLACE the optimized way. */
3904 /* Extend the start of non-matching text area to multibyte
3905 character boundary. */
3906 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3907 while (same_at_start > BEGV_BYTE
3908 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3909 same_at_start--;
3911 /* Extend the end of non-matching text area to multibyte
3912 character boundary. */
3913 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3914 while (same_at_end < ZV_BYTE
3915 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3916 same_at_end++;
3918 /* Don't try to reuse the same piece of text twice. */
3919 overlap = (same_at_start - BEGV_BYTE
3920 - (same_at_end
3921 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3922 if (overlap > 0)
3923 same_at_end += overlap;
3924 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3926 /* Arrange to read only the nonmatching middle part of the file. */
3927 beg_offset += same_at_start - BEGV_BYTE;
3928 end_offset -= ZV_BYTE - same_at_end;
3930 /* This binding is to avoid ask-user-about-supersession-threat
3931 being called in insert_from_buffer or del_range_bytes (via
3932 prepare_to_modify_buffer).
3933 AFAICT we could avoid ask-user-about-supersession-threat by setting
3934 current_buffer->modtime earlier, but we could still end up calling
3935 ask-user-about-supersession-threat if the file is modified while
3936 we read it, so we bind buffer-file-name instead. */
3937 specbind (intern ("buffer-file-name"), Qnil);
3938 del_range_byte (same_at_start, same_at_end);
3939 /* Insert from the file at the proper position. */
3940 temp = BYTE_TO_CHAR (same_at_start);
3941 SET_PT_BOTH (temp, same_at_start);
3942 unbind_to (this_count, Qnil);
3944 /* If display currently starts at beginning of line,
3945 keep it that way. */
3946 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3947 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3949 replace_handled = true;
3953 /* If requested, replace the accessible part of the buffer
3954 with the file contents. Avoid replacing text at the
3955 beginning or end of the buffer that matches the file contents;
3956 that preserves markers pointing to the unchanged parts.
3958 Here we implement this feature for the case where code conversion
3959 is needed, in a simple way that needs a lot of memory.
3960 The preceding if-statement handles the case of no conversion
3961 in a more optimized way. */
3962 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3964 ptrdiff_t same_at_start_charpos;
3965 ptrdiff_t inserted_chars;
3966 ptrdiff_t overlap;
3967 ptrdiff_t bufpos;
3968 unsigned char *decoded;
3969 ptrdiff_t temp;
3970 ptrdiff_t this = 0;
3971 ptrdiff_t this_count = SPECPDL_INDEX ();
3972 bool multibyte
3973 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3974 Lisp_Object conversion_buffer;
3976 conversion_buffer = code_conversion_save (1, multibyte);
3978 /* First read the whole file, performing code conversion into
3979 CONVERSION_BUFFER. */
3981 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3982 report_file_error ("Setting file position", orig_filename);
3984 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3985 unprocessed = 0; /* Bytes not processed in previous loop. */
3987 while (true)
3989 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3990 quitting while reading a huge file. */
3992 this = emacs_read_quit (fd, read_buf + unprocessed,
3993 READ_BUF_SIZE - unprocessed);
3994 if (this <= 0)
3995 break;
3997 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3998 BUF_Z (XBUFFER (conversion_buffer)));
3999 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4000 unprocessed + this, conversion_buffer);
4001 unprocessed = coding.carryover_bytes;
4002 if (coding.carryover_bytes > 0)
4003 memcpy (read_buf, coding.carryover, unprocessed);
4006 if (this < 0)
4007 report_file_error ("Read error", orig_filename);
4008 emacs_close (fd);
4009 clear_unwind_protect (fd_index);
4011 if (unprocessed > 0)
4013 coding.mode |= CODING_MODE_LAST_BLOCK;
4014 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4015 unprocessed, conversion_buffer);
4016 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4019 coding_system = CODING_ID_NAME (coding.id);
4020 set_coding_system = true;
4021 maybe_move_gap (XBUFFER (conversion_buffer));
4022 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
4023 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4024 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4026 /* Compare the beginning of the converted string with the buffer
4027 text. */
4029 bufpos = 0;
4030 while (bufpos < inserted && same_at_start < same_at_end
4031 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4032 same_at_start++, bufpos++;
4034 /* If the file matches the head of buffer completely,
4035 there's no need to replace anything. */
4037 if (bufpos == inserted)
4039 /* Truncate the buffer to the size of the file. */
4040 if (same_at_start != same_at_end)
4042 /* See previous specbind for the reason behind this. */
4043 specbind (intern ("buffer-file-name"), Qnil);
4044 del_range_byte (same_at_start, same_at_end);
4046 inserted = 0;
4048 unbind_to (this_count, Qnil);
4049 goto handled;
4052 /* Extend the start of non-matching text area to the previous
4053 multibyte character boundary. */
4054 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4055 while (same_at_start > BEGV_BYTE
4056 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4057 same_at_start--;
4059 /* Scan this bufferful from the end, comparing with
4060 the Emacs buffer. */
4061 bufpos = inserted;
4063 /* Compare with same_at_start to avoid counting some buffer text
4064 as matching both at the file's beginning and at the end. */
4065 while (bufpos > 0 && same_at_end > same_at_start
4066 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4067 same_at_end--, bufpos--;
4069 /* Extend the end of non-matching text area to the next
4070 multibyte character boundary. */
4071 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4072 while (same_at_end < ZV_BYTE
4073 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4074 same_at_end++;
4076 /* Don't try to reuse the same piece of text twice. */
4077 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4078 if (overlap > 0)
4079 same_at_end += overlap;
4080 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4082 /* If display currently starts at beginning of line,
4083 keep it that way. */
4084 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4085 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4087 /* Replace the chars that we need to replace,
4088 and update INSERTED to equal the number of bytes
4089 we are taking from the decoded string. */
4090 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4092 /* See previous specbind for the reason behind this. */
4093 specbind (intern ("buffer-file-name"), Qnil);
4094 if (same_at_end != same_at_start)
4096 del_range_byte (same_at_start, same_at_end);
4097 temp = GPT;
4098 eassert (same_at_start == GPT_BYTE);
4099 same_at_start = GPT_BYTE;
4101 else
4103 temp = same_at_end_charpos;
4105 /* Insert from the file at the proper position. */
4106 SET_PT_BOTH (temp, same_at_start);
4107 same_at_start_charpos
4108 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4109 same_at_start - BEGV_BYTE
4110 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4111 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4112 inserted_chars
4113 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4114 same_at_start + inserted - BEGV_BYTE
4115 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4116 - same_at_start_charpos);
4117 insert_from_buffer (XBUFFER (conversion_buffer),
4118 same_at_start_charpos, inserted_chars, 0);
4119 /* Set `inserted' to the number of inserted characters. */
4120 inserted = PT - temp;
4121 /* Set point before the inserted characters. */
4122 SET_PT_BOTH (temp, same_at_start);
4124 unbind_to (this_count, Qnil);
4126 goto handled;
4129 if (! not_regular)
4130 total = end_offset - beg_offset;
4131 else
4132 /* For a special file, all we can do is guess. */
4133 total = READ_BUF_SIZE;
4135 if (NILP (visit) && total > 0)
4137 if (!NILP (BVAR (current_buffer, file_truename))
4138 /* Make binding buffer-file-name to nil effective. */
4139 && !NILP (BVAR (current_buffer, filename))
4140 && SAVE_MODIFF >= MODIFF)
4141 we_locked_file = true;
4142 prepare_to_modify_buffer (PT, PT, NULL);
4145 move_gap_both (PT, PT_BYTE);
4146 if (GAP_SIZE < total)
4147 make_gap (total - GAP_SIZE);
4149 if (beg_offset != 0 || !NILP (replace))
4151 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4152 report_file_error ("Setting file position", orig_filename);
4155 /* In the following loop, HOW_MUCH contains the total bytes read so
4156 far for a regular file, and not changed for a special file. But,
4157 before exiting the loop, it is set to a negative value if I/O
4158 error occurs. */
4159 how_much = 0;
4161 /* Total bytes inserted. */
4162 inserted = 0;
4164 /* Here, we don't do code conversion in the loop. It is done by
4165 decode_coding_gap after all data are read into the buffer. */
4167 ptrdiff_t gap_size = GAP_SIZE;
4169 while (how_much < total)
4171 /* `try' is reserved in some compilers (Microsoft C). */
4172 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4173 ptrdiff_t this;
4175 if (not_regular)
4177 Lisp_Object nbytes;
4179 /* Maybe make more room. */
4180 if (gap_size < trytry)
4182 make_gap (trytry - gap_size);
4183 gap_size = GAP_SIZE - inserted;
4186 /* Read from the file, capturing `quit'. When an
4187 error occurs, end the loop, and arrange for a quit
4188 to be signaled after decoding the text we read. */
4189 nbytes = internal_condition_case_1
4190 (read_non_regular,
4191 make_save_int_int_int (fd, inserted, trytry),
4192 Qerror, read_non_regular_quit);
4194 if (NILP (nbytes))
4196 read_quit = true;
4197 break;
4200 this = XINT (nbytes);
4202 else
4204 /* Allow quitting out of the actual I/O. We don't make text
4205 part of the buffer until all the reading is done, so a C-g
4206 here doesn't do any harm. */
4207 this = emacs_read_quit (fd,
4208 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4209 + inserted),
4210 trytry);
4213 if (this <= 0)
4215 how_much = this;
4216 break;
4219 gap_size -= this;
4221 /* For a regular file, where TOTAL is the real size,
4222 count HOW_MUCH to compare with it.
4223 For a special file, where TOTAL is just a buffer size,
4224 so don't bother counting in HOW_MUCH.
4225 (INSERTED is where we count the number of characters inserted.) */
4226 if (! not_regular)
4227 how_much += this;
4228 inserted += this;
4232 /* Now we have either read all the file data into the gap,
4233 or stop reading on I/O error or quit. If nothing was
4234 read, undo marking the buffer modified. */
4236 if (inserted == 0)
4238 if (we_locked_file)
4239 unlock_file (BVAR (current_buffer, file_truename));
4240 Vdeactivate_mark = old_Vdeactivate_mark;
4242 else
4243 Fset (Qdeactivate_mark, Qt);
4245 emacs_close (fd);
4246 clear_unwind_protect (fd_index);
4248 if (how_much < 0)
4249 report_file_error ("Read error", orig_filename);
4251 /* Make the text read part of the buffer. */
4252 GAP_SIZE -= inserted;
4253 GPT += inserted;
4254 GPT_BYTE += inserted;
4255 ZV += inserted;
4256 ZV_BYTE += inserted;
4257 Z += inserted;
4258 Z_BYTE += inserted;
4260 if (GAP_SIZE > 0)
4261 /* Put an anchor to ensure multi-byte form ends at gap. */
4262 *GPT_ADDR = 0;
4264 notfound:
4266 if (NILP (coding_system))
4268 /* The coding system is not yet decided. Decide it by an
4269 optimized method for handling `coding:' tag.
4271 Note that we can get here only if the buffer was empty
4272 before the insertion. */
4274 if (!NILP (Vcoding_system_for_read))
4275 coding_system = Vcoding_system_for_read;
4276 else
4278 /* Since we are sure that the current buffer was empty
4279 before the insertion, we can toggle
4280 enable-multibyte-characters directly here without taking
4281 care of marker adjustment. By this way, we can run Lisp
4282 program safely before decoding the inserted text. */
4283 Lisp_Object unwind_data;
4284 ptrdiff_t count1 = SPECPDL_INDEX ();
4286 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4287 Fcons (BVAR (current_buffer, undo_list),
4288 Fcurrent_buffer ()));
4289 bset_enable_multibyte_characters (current_buffer, Qnil);
4290 bset_undo_list (current_buffer, Qt);
4291 record_unwind_protect (decide_coding_unwind, unwind_data);
4293 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4295 coding_system = call2 (Vset_auto_coding_function,
4296 filename, make_number (inserted));
4299 if (NILP (coding_system))
4301 /* If the coding system is not yet decided, check
4302 file-coding-system-alist. */
4303 coding_system = CALLN (Ffind_operation_coding_system,
4304 Qinsert_file_contents, orig_filename,
4305 visit, beg, end, Qnil);
4306 if (CONSP (coding_system))
4307 coding_system = XCAR (coding_system);
4309 unbind_to (count1, Qnil);
4310 inserted = Z_BYTE - BEG_BYTE;
4313 if (NILP (coding_system))
4314 coding_system = Qundecided;
4315 else
4316 CHECK_CODING_SYSTEM (coding_system);
4318 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4319 /* We must suppress all character code conversion except for
4320 end-of-line conversion. */
4321 coding_system = raw_text_coding_system (coding_system);
4322 setup_coding_system (coding_system, &coding);
4323 /* Ensure we set Vlast_coding_system_used. */
4324 set_coding_system = true;
4327 if (!NILP (visit))
4329 /* When we visit a file by raw-text, we change the buffer to
4330 unibyte. */
4331 if (CODING_FOR_UNIBYTE (&coding)
4332 /* Can't do this if part of the buffer might be preserved. */
4333 && NILP (replace))
4335 /* Visiting a file with these coding system makes the buffer
4336 unibyte. */
4337 if (inserted > 0)
4338 bset_enable_multibyte_characters (current_buffer, Qnil);
4339 else
4340 Fset_buffer_multibyte (Qnil);
4344 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4345 if (CODING_MAY_REQUIRE_DECODING (&coding)
4346 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4348 move_gap_both (PT, PT_BYTE);
4349 GAP_SIZE += inserted;
4350 ZV_BYTE -= inserted;
4351 Z_BYTE -= inserted;
4352 ZV -= inserted;
4353 Z -= inserted;
4354 decode_coding_gap (&coding, inserted, inserted);
4355 inserted = coding.produced_char;
4356 coding_system = CODING_ID_NAME (coding.id);
4358 else if (inserted > 0)
4360 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4361 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4362 inserted);
4365 /* Call after-change hooks for the inserted text, aside from the case
4366 of normal visiting (not with REPLACE), which is done in a new buffer
4367 "before" the buffer is changed. */
4368 if (inserted > 0 && total > 0
4369 && (NILP (visit) || !NILP (replace)))
4371 signal_after_change (PT, 0, inserted);
4372 update_compositions (PT, PT, CHECK_BORDER);
4375 /* Now INSERTED is measured in characters. */
4377 handled:
4379 if (inserted > 0)
4380 restore_window_points (window_markers, inserted,
4381 BYTE_TO_CHAR (same_at_start),
4382 same_at_end_charpos);
4384 if (!NILP (visit))
4386 if (empty_undo_list_p)
4387 bset_undo_list (current_buffer, Qnil);
4389 if (NILP (handler))
4391 current_buffer->modtime = mtime;
4392 current_buffer->modtime_size = st.st_size;
4393 bset_filename (current_buffer, orig_filename);
4396 SAVE_MODIFF = MODIFF;
4397 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4398 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4399 if (NILP (handler))
4401 if (!NILP (BVAR (current_buffer, file_truename)))
4402 unlock_file (BVAR (current_buffer, file_truename));
4403 unlock_file (filename);
4405 if (not_regular)
4406 xsignal2 (Qfile_error,
4407 build_string ("not a regular file"), orig_filename);
4410 if (set_coding_system)
4411 Vlast_coding_system_used = coding_system;
4413 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4415 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4416 visit);
4417 if (! NILP (insval))
4419 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4420 wrong_type_argument (intern ("inserted-chars"), insval);
4421 inserted = XFASTINT (insval);
4425 /* Decode file format. */
4426 if (inserted > 0)
4428 /* Don't run point motion or modification hooks when decoding. */
4429 ptrdiff_t count1 = SPECPDL_INDEX ();
4430 ptrdiff_t old_inserted = inserted;
4431 specbind (Qinhibit_point_motion_hooks, Qt);
4432 specbind (Qinhibit_modification_hooks, Qt);
4434 /* Save old undo list and don't record undo for decoding. */
4435 old_undo = BVAR (current_buffer, undo_list);
4436 bset_undo_list (current_buffer, Qt);
4438 if (NILP (replace))
4440 insval = call3 (Qformat_decode,
4441 Qnil, make_number (inserted), visit);
4442 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4443 wrong_type_argument (intern ("inserted-chars"), insval);
4444 inserted = XFASTINT (insval);
4446 else
4448 /* If REPLACE is non-nil and we succeeded in not replacing the
4449 beginning or end of the buffer text with the file's contents,
4450 call format-decode with `point' positioned at the beginning
4451 of the buffer and `inserted' equaling the number of
4452 characters in the buffer. Otherwise, format-decode might
4453 fail to correctly analyze the beginning or end of the buffer.
4454 Hence we temporarily save `point' and `inserted' here and
4455 restore `point' iff format-decode did not insert or delete
4456 any text. Otherwise we leave `point' at point-min. */
4457 ptrdiff_t opoint = PT;
4458 ptrdiff_t opoint_byte = PT_BYTE;
4459 ptrdiff_t oinserted = ZV - BEGV;
4460 EMACS_INT ochars_modiff = CHARS_MODIFF;
4462 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4463 insval = call3 (Qformat_decode,
4464 Qnil, make_number (oinserted), visit);
4465 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4466 wrong_type_argument (intern ("inserted-chars"), insval);
4467 if (ochars_modiff == CHARS_MODIFF)
4468 /* format_decode didn't modify buffer's characters => move
4469 point back to position before inserted text and leave
4470 value of inserted alone. */
4471 SET_PT_BOTH (opoint, opoint_byte);
4472 else
4473 /* format_decode modified buffer's characters => consider
4474 entire buffer changed and leave point at point-min. */
4475 inserted = XFASTINT (insval);
4478 /* For consistency with format-decode call these now iff inserted > 0
4479 (martin 2007-06-28). */
4480 p = Vafter_insert_file_functions;
4481 while (CONSP (p))
4483 if (NILP (replace))
4485 insval = call1 (XCAR (p), make_number (inserted));
4486 if (!NILP (insval))
4488 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4489 wrong_type_argument (intern ("inserted-chars"), insval);
4490 inserted = XFASTINT (insval);
4493 else
4495 /* For the rationale of this see the comment on
4496 format-decode above. */
4497 ptrdiff_t opoint = PT;
4498 ptrdiff_t opoint_byte = PT_BYTE;
4499 ptrdiff_t oinserted = ZV - BEGV;
4500 EMACS_INT ochars_modiff = CHARS_MODIFF;
4502 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4503 insval = call1 (XCAR (p), make_number (oinserted));
4504 if (!NILP (insval))
4506 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4507 wrong_type_argument (intern ("inserted-chars"), insval);
4508 if (ochars_modiff == CHARS_MODIFF)
4509 /* after_insert_file_functions didn't modify
4510 buffer's characters => move point back to
4511 position before inserted text and leave value of
4512 inserted alone. */
4513 SET_PT_BOTH (opoint, opoint_byte);
4514 else
4515 /* after_insert_file_functions did modify buffer's
4516 characters => consider entire buffer changed and
4517 leave point at point-min. */
4518 inserted = XFASTINT (insval);
4522 maybe_quit ();
4523 p = XCDR (p);
4526 if (!empty_undo_list_p)
4528 bset_undo_list (current_buffer, old_undo);
4529 if (CONSP (old_undo) && inserted != old_inserted)
4531 /* Adjust the last undo record for the size change during
4532 the format conversion. */
4533 Lisp_Object tem = XCAR (old_undo);
4534 if (CONSP (tem) && INTEGERP (XCAR (tem))
4535 && INTEGERP (XCDR (tem))
4536 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4537 XSETCDR (tem, make_number (PT + inserted));
4540 else
4541 /* If undo_list was Qt before, keep it that way.
4542 Otherwise start with an empty undo_list. */
4543 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4545 unbind_to (count1, Qnil);
4548 if (!NILP (visit)
4549 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4551 /* If visiting nonexistent file, return nil. */
4552 report_file_errno ("Opening input file", orig_filename, save_errno);
4555 /* We made a lot of deletions and insertions above, so invalidate
4556 the newline cache for the entire region of the inserted
4557 characters. */
4558 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4559 invalidate_region_cache (current_buffer->base_buffer,
4560 current_buffer->base_buffer->newline_cache,
4561 PT - BEG, Z - PT - inserted);
4562 else if (current_buffer->newline_cache)
4563 invalidate_region_cache (current_buffer,
4564 current_buffer->newline_cache,
4565 PT - BEG, Z - PT - inserted);
4567 if (read_quit)
4568 quit ();
4570 /* Retval needs to be dealt with in all cases consistently. */
4571 if (NILP (val))
4572 val = list2 (orig_filename, make_number (inserted));
4574 return unbind_to (count, val);
4577 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4579 static void
4580 build_annotations_unwind (Lisp_Object arg)
4582 Vwrite_region_annotation_buffers = arg;
4585 /* Decide the coding-system to encode the data with. */
4587 static Lisp_Object
4588 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4589 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4590 struct coding_system *coding)
4592 Lisp_Object val;
4593 Lisp_Object eol_parent = Qnil;
4595 if (auto_saving
4596 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4597 BVAR (current_buffer, auto_save_file_name))))
4599 val = Qutf_8_emacs;
4600 eol_parent = Qunix;
4602 else if (!NILP (Vcoding_system_for_write))
4604 val = Vcoding_system_for_write;
4605 if (coding_system_require_warning
4606 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4607 /* Confirm that VAL can surely encode the current region. */
4608 val = call5 (Vselect_safe_coding_system_function,
4609 start, end, list2 (Qt, val),
4610 Qnil, filename);
4612 else
4614 /* If the variable `buffer-file-coding-system' is set locally,
4615 it means that the file was read with some kind of code
4616 conversion or the variable is explicitly set by users. We
4617 had better write it out with the same coding system even if
4618 `enable-multibyte-characters' is nil.
4620 If it is not set locally, we anyway have to convert EOL
4621 format if the default value of `buffer-file-coding-system'
4622 tells that it is not Unix-like (LF only) format. */
4623 bool using_default_coding = 0;
4624 bool force_raw_text = 0;
4626 val = BVAR (current_buffer, buffer_file_coding_system);
4627 if (NILP (val)
4628 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4630 val = Qnil;
4631 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4632 force_raw_text = 1;
4635 if (NILP (val))
4637 /* Check file-coding-system-alist. */
4638 Lisp_Object coding_systems
4639 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4640 filename, append, visit, lockname);
4641 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4642 val = XCDR (coding_systems);
4645 if (NILP (val))
4647 /* If we still have not decided a coding system, use the
4648 current buffer's value of buffer-file-coding-system. */
4649 val = BVAR (current_buffer, buffer_file_coding_system);
4650 using_default_coding = 1;
4653 if (! NILP (val) && ! force_raw_text)
4655 Lisp_Object spec, attrs;
4657 CHECK_CODING_SYSTEM (val);
4658 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4659 attrs = AREF (spec, 0);
4660 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4661 force_raw_text = 1;
4664 if (!force_raw_text
4665 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4667 /* Confirm that VAL can surely encode the current region. */
4668 val = call5 (Vselect_safe_coding_system_function,
4669 start, end, val, Qnil, filename);
4670 /* As the function specified by select-safe-coding-system-function
4671 is out of our control, make sure we are not fed by bogus
4672 values. */
4673 if (!NILP (val))
4674 CHECK_CODING_SYSTEM (val);
4677 /* If the decided coding-system doesn't specify end-of-line
4678 format, we use that of `buffer-file-coding-system'. */
4679 if (! using_default_coding)
4681 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4683 if (! NILP (dflt))
4684 val = coding_inherit_eol_type (val, dflt);
4687 /* If we decide not to encode text, use `raw-text' or one of its
4688 subsidiaries. */
4689 if (force_raw_text)
4690 val = raw_text_coding_system (val);
4693 val = coding_inherit_eol_type (val, eol_parent);
4694 setup_coding_system (val, coding);
4696 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4697 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4698 return val;
4701 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4702 "r\nFWrite region to file: \ni\ni\ni\np",
4703 doc: /* Write current region into specified file.
4704 When called from a program, requires three arguments:
4705 START, END and FILENAME. START and END are normally buffer positions
4706 specifying the part of the buffer to write.
4707 If START is nil, that means to use the entire buffer contents; END is
4708 ignored.
4709 If START is a string, then output that string to the file
4710 instead of any buffer contents; END is ignored.
4712 Optional fourth argument APPEND if non-nil means
4713 append to existing file contents (if any). If it is a number,
4714 seek to that offset in the file before writing.
4715 Optional fifth argument VISIT, if t or a string, means
4716 set the last-save-file-modtime of buffer to this file's modtime
4717 and mark buffer not modified.
4718 If VISIT is a string, it is a second file name;
4719 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4720 VISIT is also the file name to lock and unlock for clash detection.
4721 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4722 do not display the \"Wrote file\" message.
4723 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4724 use for locking and unlocking, overriding FILENAME and VISIT.
4725 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4726 for an existing file with the same name. If MUSTBENEW is `excl',
4727 that means to get an error if the file already exists; never overwrite.
4728 If MUSTBENEW is neither nil nor `excl', that means ask for
4729 confirmation before overwriting, but do go ahead and overwrite the file
4730 if the user confirms.
4732 This does code conversion according to the value of
4733 `coding-system-for-write', `buffer-file-coding-system', or
4734 `file-coding-system-alist', and sets the variable
4735 `last-coding-system-used' to the coding system actually used.
4737 This calls `write-region-annotate-functions' at the start, and
4738 `write-region-post-annotation-function' at the end. */)
4739 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4740 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4742 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4743 -1);
4746 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4747 descriptor for FILENAME, so do not open or close FILENAME. */
4749 Lisp_Object
4750 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4751 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4752 Lisp_Object mustbenew, int desc)
4754 int open_flags;
4755 int mode;
4756 off_t offset UNINIT;
4757 bool open_and_close_file = desc < 0;
4758 bool ok;
4759 int save_errno = 0;
4760 const char *fn;
4761 struct stat st;
4762 struct timespec modtime;
4763 ptrdiff_t count = SPECPDL_INDEX ();
4764 ptrdiff_t count1 UNINIT;
4765 Lisp_Object handler;
4766 Lisp_Object visit_file;
4767 Lisp_Object annotations;
4768 Lisp_Object encoded_filename;
4769 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4770 bool quietly = !NILP (visit);
4771 bool file_locked = 0;
4772 struct buffer *given_buffer;
4773 struct coding_system coding;
4775 if (current_buffer->base_buffer && visiting)
4776 error ("Cannot do file visiting in an indirect buffer");
4778 if (!NILP (start) && !STRINGP (start))
4779 validate_region (&start, &end);
4781 visit_file = Qnil;
4783 filename = Fexpand_file_name (filename, Qnil);
4785 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4786 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4788 if (STRINGP (visit))
4789 visit_file = Fexpand_file_name (visit, Qnil);
4790 else
4791 visit_file = filename;
4793 if (NILP (lockname))
4794 lockname = visit_file;
4796 annotations = Qnil;
4798 /* If the file name has special constructs in it,
4799 call the corresponding file handler. */
4800 handler = Ffind_file_name_handler (filename, Qwrite_region);
4801 /* If FILENAME has no handler, see if VISIT has one. */
4802 if (NILP (handler) && STRINGP (visit))
4803 handler = Ffind_file_name_handler (visit, Qwrite_region);
4805 if (!NILP (handler))
4807 Lisp_Object val;
4808 val = call8 (handler, Qwrite_region, start, end,
4809 filename, append, visit, lockname, mustbenew);
4811 if (visiting)
4813 SAVE_MODIFF = MODIFF;
4814 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4815 bset_filename (current_buffer, visit_file);
4818 return val;
4821 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4823 /* Special kludge to simplify auto-saving. */
4824 if (NILP (start))
4826 /* Do it later, so write-region-annotate-function can work differently
4827 if we save "the buffer" vs "a region".
4828 This is useful in tar-mode. --Stef
4829 XSETFASTINT (start, BEG);
4830 XSETFASTINT (end, Z); */
4831 Fwiden ();
4834 record_unwind_protect (build_annotations_unwind,
4835 Vwrite_region_annotation_buffers);
4836 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4838 given_buffer = current_buffer;
4840 if (!STRINGP (start))
4842 annotations = build_annotations (start, end);
4844 if (current_buffer != given_buffer)
4846 XSETFASTINT (start, BEGV);
4847 XSETFASTINT (end, ZV);
4851 if (NILP (start))
4853 XSETFASTINT (start, BEGV);
4854 XSETFASTINT (end, ZV);
4857 /* Decide the coding-system to encode the data with.
4858 We used to make this choice before calling build_annotations, but that
4859 leads to problems when a write-annotate-function takes care of
4860 unsavable chars (as was the case with X-Symbol). */
4861 Vlast_coding_system_used
4862 = choose_write_coding_system (start, end, filename,
4863 append, visit, lockname, &coding);
4865 if (open_and_close_file && !auto_saving)
4867 lock_file (lockname);
4868 file_locked = 1;
4871 encoded_filename = ENCODE_FILE (filename);
4872 fn = SSDATA (encoded_filename);
4873 open_flags = O_WRONLY | O_CREAT;
4874 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4875 if (NUMBERP (append))
4876 offset = file_offset (append);
4877 else if (!NILP (append))
4878 open_flags |= O_APPEND;
4879 #ifdef DOS_NT
4880 mode = S_IREAD | S_IWRITE;
4881 #else
4882 mode = auto_saving ? auto_save_mode_bits : 0666;
4883 #endif
4885 if (open_and_close_file)
4887 desc = emacs_open (fn, open_flags, mode);
4888 if (desc < 0)
4890 int open_errno = errno;
4891 if (file_locked)
4892 unlock_file (lockname);
4893 report_file_errno ("Opening output file", filename, open_errno);
4896 count1 = SPECPDL_INDEX ();
4897 record_unwind_protect_int (close_file_unwind, desc);
4900 if (NUMBERP (append))
4902 off_t ret = lseek (desc, offset, SEEK_SET);
4903 if (ret < 0)
4905 int lseek_errno = errno;
4906 if (file_locked)
4907 unlock_file (lockname);
4908 report_file_errno ("Lseek error", filename, lseek_errno);
4912 if (STRINGP (start))
4913 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4914 else if (XINT (start) != XINT (end))
4915 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4916 &annotations, &coding);
4917 else
4919 /* If file was empty, still need to write the annotations. */
4920 coding.mode |= CODING_MODE_LAST_BLOCK;
4921 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4923 save_errno = errno;
4925 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4926 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4928 /* We have to flush out a data. */
4929 coding.mode |= CODING_MODE_LAST_BLOCK;
4930 ok = e_write (desc, Qnil, 1, 1, &coding);
4931 save_errno = errno;
4934 /* fsync is not crucial for temporary files. Nor for auto-save
4935 files, since they might lose some work anyway. */
4936 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4938 /* Transfer data and metadata to disk, retrying if interrupted.
4939 fsync can report a write failure here, e.g., due to disk full
4940 under NFS. But ignore EINVAL, which means fsync is not
4941 supported on this file. */
4942 while (fsync (desc) != 0)
4943 if (errno != EINTR)
4945 if (errno != EINVAL)
4946 ok = 0, save_errno = errno;
4947 break;
4951 modtime = invalid_timespec ();
4952 if (visiting)
4954 if (fstat (desc, &st) == 0)
4955 modtime = get_stat_mtime (&st);
4956 else
4957 ok = 0, save_errno = errno;
4960 if (open_and_close_file)
4962 /* NFS can report a write failure now. */
4963 if (emacs_close (desc) < 0)
4964 ok = 0, save_errno = errno;
4966 /* Discard the unwind protect for close_file_unwind. */
4967 specpdl_ptr = specpdl + count1;
4970 /* Some file systems have a bug where st_mtime is not updated
4971 properly after a write. For example, CIFS might not see the
4972 st_mtime change until after the file is opened again.
4974 Attempt to detect this file system bug, and update MODTIME to the
4975 newer st_mtime if the bug appears to be present. This introduces
4976 a race condition, so to avoid most instances of the race condition
4977 on non-buggy file systems, skip this check if the most recently
4978 encountered non-buggy file system was the current file system.
4980 A race condition can occur if some other process modifies the
4981 file between the fstat above and the fstat below, but the race is
4982 unlikely and a similar race between the last write and the fstat
4983 above cannot possibly be closed anyway. */
4985 if (timespec_valid_p (modtime)
4986 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4988 int desc1 = emacs_open (fn, O_WRONLY, 0);
4989 if (desc1 >= 0)
4991 struct stat st1;
4992 if (fstat (desc1, &st1) == 0
4993 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4995 /* Use the heuristic if it appears to be valid. With neither
4996 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4997 file, the time stamp won't change. Also, some non-POSIX
4998 systems don't update an empty file's time stamp when
4999 truncating it. Finally, file systems with 100 ns or worse
5000 resolution sometimes seem to have bugs: on a system with ns
5001 resolution, checking ns % 100 incorrectly avoids the heuristic
5002 1% of the time, but the problem should be temporary as we will
5003 try again on the next time stamp. */
5004 bool use_heuristic
5005 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
5006 && st.st_size != 0
5007 && modtime.tv_nsec % 100 != 0);
5009 struct timespec modtime1 = get_stat_mtime (&st1);
5010 if (use_heuristic
5011 && timespec_cmp (modtime, modtime1) == 0
5012 && st.st_size == st1.st_size)
5014 timestamp_file_system = st.st_dev;
5015 valid_timestamp_file_system = 1;
5017 else
5019 st.st_size = st1.st_size;
5020 modtime = modtime1;
5023 emacs_close (desc1);
5027 /* Call write-region-post-annotation-function. */
5028 while (CONSP (Vwrite_region_annotation_buffers))
5030 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5031 if (!NILP (Fbuffer_live_p (buf)))
5033 Fset_buffer (buf);
5034 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5035 call0 (Vwrite_region_post_annotation_function);
5037 Vwrite_region_annotation_buffers
5038 = XCDR (Vwrite_region_annotation_buffers);
5041 unbind_to (count, Qnil);
5043 if (file_locked)
5044 unlock_file (lockname);
5046 /* Do this before reporting IO error
5047 to avoid a "file has changed on disk" warning on
5048 next attempt to save. */
5049 if (timespec_valid_p (modtime))
5051 current_buffer->modtime = modtime;
5052 current_buffer->modtime_size = st.st_size;
5055 if (! ok)
5056 report_file_errno ("Write error", filename, save_errno);
5058 bool auto_saving_into_visited_file =
5059 auto_saving
5060 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5061 BVAR (current_buffer, auto_save_file_name)));
5062 if (visiting)
5064 SAVE_MODIFF = MODIFF;
5065 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5066 bset_filename (current_buffer, visit_file);
5067 update_mode_lines = 14;
5068 if (auto_saving_into_visited_file)
5069 unlock_file (lockname);
5071 else if (quietly)
5073 if (auto_saving_into_visited_file)
5075 SAVE_MODIFF = MODIFF;
5076 unlock_file (lockname);
5079 return Qnil;
5082 if (!auto_saving && !noninteractive)
5083 message_with_string ((NUMBERP (append)
5084 ? "Updated %s"
5085 : ! NILP (append)
5086 ? "Added to %s"
5087 : "Wrote %s"),
5088 visit_file, 1);
5090 return Qnil;
5093 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5094 doc: /* Return t if (car A) is numerically less than (car B). */)
5095 (Lisp_Object a, Lisp_Object b)
5097 return arithcompare (Fcar (a), Fcar (b), ARITH_LESS);
5100 /* Build the complete list of annotations appropriate for writing out
5101 the text between START and END, by calling all the functions in
5102 write-region-annotate-functions and merging the lists they return.
5103 If one of these functions switches to a different buffer, we assume
5104 that buffer contains altered text. Therefore, the caller must
5105 make sure to restore the current buffer in all cases,
5106 as save-excursion would do. */
5108 static Lisp_Object
5109 build_annotations (Lisp_Object start, Lisp_Object end)
5111 Lisp_Object annotations;
5112 Lisp_Object p, res;
5113 Lisp_Object original_buffer;
5114 int i;
5115 bool used_global = false;
5117 XSETBUFFER (original_buffer, current_buffer);
5119 annotations = Qnil;
5120 p = Vwrite_region_annotate_functions;
5121 while (CONSP (p))
5123 struct buffer *given_buffer = current_buffer;
5124 if (EQ (Qt, XCAR (p)) && !used_global)
5125 { /* Use the global value of the hook. */
5126 used_global = true;
5127 p = CALLN (Fappend,
5128 Fdefault_value (Qwrite_region_annotate_functions),
5129 XCDR (p));
5130 continue;
5132 Vwrite_region_annotations_so_far = annotations;
5133 res = call2 (XCAR (p), start, end);
5134 /* If the function makes a different buffer current,
5135 assume that means this buffer contains altered text to be output.
5136 Reset START and END from the buffer bounds
5137 and discard all previous annotations because they should have
5138 been dealt with by this function. */
5139 if (current_buffer != given_buffer)
5141 Vwrite_region_annotation_buffers
5142 = Fcons (Fcurrent_buffer (),
5143 Vwrite_region_annotation_buffers);
5144 XSETFASTINT (start, BEGV);
5145 XSETFASTINT (end, ZV);
5146 annotations = Qnil;
5148 Flength (res); /* Check basic validity of return value */
5149 annotations = merge (annotations, res, Qcar_less_than_car);
5150 p = XCDR (p);
5153 /* Now do the same for annotation functions implied by the file-format */
5154 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5155 p = BVAR (current_buffer, auto_save_file_format);
5156 else
5157 p = BVAR (current_buffer, file_format);
5158 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5160 struct buffer *given_buffer = current_buffer;
5162 Vwrite_region_annotations_so_far = annotations;
5164 /* Value is either a list of annotations or nil if the function
5165 has written annotations to a temporary buffer, which is now
5166 current. */
5167 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5168 original_buffer, make_number (i));
5169 if (current_buffer != given_buffer)
5171 XSETFASTINT (start, BEGV);
5172 XSETFASTINT (end, ZV);
5173 annotations = Qnil;
5176 if (CONSP (res))
5177 annotations = merge (annotations, res, Qcar_less_than_car);
5180 return annotations;
5184 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5185 If STRING is nil, POS is the character position in the current buffer.
5186 Intersperse with them the annotations from *ANNOT
5187 which fall within the range of POS to POS + NCHARS,
5188 each at its appropriate position.
5190 We modify *ANNOT by discarding elements as we use them up.
5192 Return true if successful. */
5194 static bool
5195 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5196 ptrdiff_t nchars, Lisp_Object *annot,
5197 struct coding_system *coding)
5199 Lisp_Object tem;
5200 ptrdiff_t nextpos;
5201 ptrdiff_t lastpos = pos + nchars;
5203 while (NILP (*annot) || CONSP (*annot))
5205 tem = Fcar_safe (Fcar (*annot));
5206 nextpos = pos - 1;
5207 if (INTEGERP (tem))
5208 nextpos = XFASTINT (tem);
5210 /* If there are no more annotations in this range,
5211 output the rest of the range all at once. */
5212 if (! (nextpos >= pos && nextpos <= lastpos))
5213 return e_write (desc, string, pos, lastpos, coding);
5215 /* Output buffer text up to the next annotation's position. */
5216 if (nextpos > pos)
5218 if (!e_write (desc, string, pos, nextpos, coding))
5219 return 0;
5220 pos = nextpos;
5222 /* Output the annotation. */
5223 tem = Fcdr (Fcar (*annot));
5224 if (STRINGP (tem))
5226 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5227 return 0;
5229 *annot = Fcdr (*annot);
5231 return 1;
5234 /* Maximum number of characters that the next
5235 function encodes per one loop iteration. */
5237 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5239 /* Write text in the range START and END into descriptor DESC,
5240 encoding them with coding system CODING. If STRING is nil, START
5241 and END are character positions of the current buffer, else they
5242 are indexes to the string STRING. Return true if successful. */
5244 static bool
5245 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5246 struct coding_system *coding)
5248 if (STRINGP (string))
5250 start = 0;
5251 end = SCHARS (string);
5254 /* We used to have a code for handling selective display here. But,
5255 now it is handled within encode_coding. */
5257 while (start < end)
5259 if (STRINGP (string))
5261 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5262 if (CODING_REQUIRE_ENCODING (coding))
5264 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5266 /* Avoid creating huge Lisp string in encode_coding_object. */
5267 if (nchars == E_WRITE_MAX)
5268 coding->raw_destination = 1;
5270 encode_coding_object
5271 (coding, string, start, string_char_to_byte (string, start),
5272 start + nchars, string_char_to_byte (string, start + nchars),
5273 Qt);
5275 else
5277 coding->dst_object = string;
5278 coding->consumed_char = SCHARS (string);
5279 coding->produced = SBYTES (string);
5282 else
5284 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5285 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5287 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5288 if (CODING_REQUIRE_ENCODING (coding))
5290 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5292 /* Likewise. */
5293 if (nchars == E_WRITE_MAX)
5294 coding->raw_destination = 1;
5296 encode_coding_object
5297 (coding, Fcurrent_buffer (), start, start_byte,
5298 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5300 else
5302 coding->dst_object = Qnil;
5303 coding->dst_pos_byte = start_byte;
5304 if (start >= GPT || end <= GPT)
5306 coding->consumed_char = end - start;
5307 coding->produced = end_byte - start_byte;
5309 else
5311 coding->consumed_char = GPT - start;
5312 coding->produced = GPT_BYTE - start_byte;
5317 if (coding->produced > 0)
5319 char *buf = (coding->raw_destination ? (char *) coding->destination
5320 : (STRINGP (coding->dst_object)
5321 ? SSDATA (coding->dst_object)
5322 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5323 coding->produced -= emacs_write_quit (desc, buf, coding->produced);
5325 if (coding->raw_destination)
5327 /* We're responsible for freeing this, see
5328 encode_coding_object to check why. */
5329 xfree (coding->destination);
5330 coding->raw_destination = 0;
5332 if (coding->produced)
5333 return 0;
5335 start += coding->consumed_char;
5338 return 1;
5341 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5342 Sverify_visited_file_modtime, 0, 1, 0,
5343 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5344 This means that the file has not been changed since it was visited or saved.
5345 If BUF is omitted or nil, it defaults to the current buffer.
5346 See Info node `(elisp)Modification Time' for more details. */)
5347 (Lisp_Object buf)
5349 struct buffer *b = decode_buffer (buf);
5350 struct stat st;
5351 Lisp_Object handler;
5352 Lisp_Object filename;
5353 struct timespec mtime;
5355 if (!STRINGP (BVAR (b, filename))) return Qt;
5356 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5358 /* If the file name has special constructs in it,
5359 call the corresponding file handler. */
5360 handler = Ffind_file_name_handler (BVAR (b, filename),
5361 Qverify_visited_file_modtime);
5362 if (!NILP (handler))
5363 return call2 (handler, Qverify_visited_file_modtime, buf);
5365 filename = ENCODE_FILE (BVAR (b, filename));
5367 mtime = (stat (SSDATA (filename), &st) == 0
5368 ? get_stat_mtime (&st)
5369 : time_error_value (errno));
5370 if (timespec_cmp (mtime, b->modtime) == 0
5371 && (b->modtime_size < 0
5372 || st.st_size == b->modtime_size))
5373 return Qt;
5374 return Qnil;
5377 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5378 Svisited_file_modtime, 0, 0, 0,
5379 doc: /* Return the current buffer's recorded visited file modification time.
5380 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5381 `file-attributes' returns. If the current buffer has no recorded file
5382 modification time, this function returns 0. If the visited file
5383 doesn't exist, return -1.
5384 See Info node `(elisp)Modification Time' for more details. */)
5385 (void)
5387 int ns = current_buffer->modtime.tv_nsec;
5388 if (ns < 0)
5389 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5390 return make_lisp_time (current_buffer->modtime);
5393 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5394 Sset_visited_file_modtime, 0, 1, 0,
5395 doc: /* Update buffer's recorded modification time from the visited file's time.
5396 Useful if the buffer was not read from the file normally
5397 or if the file itself has been changed for some known benign reason.
5398 An argument specifies the modification time value to use
5399 \(instead of that of the visited file), in the form of a list
5400 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5401 `visited-file-modtime'. */)
5402 (Lisp_Object time_flag)
5404 if (!NILP (time_flag))
5406 struct timespec mtime;
5407 if (INTEGERP (time_flag))
5409 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5410 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5412 else
5413 mtime = lisp_time_argument (time_flag);
5415 current_buffer->modtime = mtime;
5416 current_buffer->modtime_size = -1;
5418 else
5420 register Lisp_Object filename;
5421 struct stat st;
5422 Lisp_Object handler;
5424 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5426 /* If the file name has special constructs in it,
5427 call the corresponding file handler. */
5428 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5429 if (!NILP (handler))
5430 /* The handler can find the file name the same way we did. */
5431 return call2 (handler, Qset_visited_file_modtime, Qnil);
5433 filename = ENCODE_FILE (filename);
5435 if (stat (SSDATA (filename), &st) >= 0)
5437 current_buffer->modtime = get_stat_mtime (&st);
5438 current_buffer->modtime_size = st.st_size;
5442 return Qnil;
5445 static Lisp_Object
5446 auto_save_error (Lisp_Object error_val)
5448 auto_save_error_occurred = 1;
5450 ring_bell (XFRAME (selected_frame));
5452 AUTO_STRING (format, "Auto-saving %s: %s");
5453 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5454 Ferror_message_string (error_val));
5455 call3 (intern ("display-warning"),
5456 intern ("auto-save"), msg, intern ("error"));
5458 return Qnil;
5461 static Lisp_Object
5462 auto_save_1 (void)
5464 struct stat st;
5465 Lisp_Object modes;
5467 auto_save_mode_bits = 0666;
5469 /* Get visited file's mode to become the auto save file's mode. */
5470 if (! NILP (BVAR (current_buffer, filename)))
5472 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5473 /* But make sure we can overwrite it later! */
5474 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5475 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5476 INTEGERP (modes))
5477 /* Remote files don't cooperate with stat. */
5478 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5481 return
5482 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5483 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5484 Qnil, Qnil);
5487 struct auto_save_unwind
5489 FILE *stream;
5490 bool auto_raise;
5493 static void
5494 do_auto_save_unwind (void *arg)
5496 struct auto_save_unwind *p = arg;
5497 FILE *stream = p->stream;
5498 minibuffer_auto_raise = p->auto_raise;
5499 auto_saving = 0;
5500 if (stream != NULL)
5502 block_input ();
5503 fclose (stream);
5504 unblock_input ();
5508 static Lisp_Object
5509 do_auto_save_make_dir (Lisp_Object dir)
5511 Lisp_Object result;
5513 auto_saving_dir_umask = 077;
5514 result = call2 (Qmake_directory, dir, Qt);
5515 auto_saving_dir_umask = 0;
5516 return result;
5519 static Lisp_Object
5520 do_auto_save_eh (Lisp_Object ignore)
5522 auto_saving_dir_umask = 0;
5523 return Qnil;
5526 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5527 doc: /* Auto-save all buffers that need it.
5528 This is all buffers that have auto-saving enabled
5529 and are changed since last auto-saved.
5530 Auto-saving writes the buffer into a file
5531 so that your editing is not lost if the system crashes.
5532 This file is not the file you visited; that changes only when you save.
5533 Normally, run the normal hook `auto-save-hook' before saving.
5535 A non-nil NO-MESSAGE argument means do not print any message if successful.
5536 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5537 (Lisp_Object no_message, Lisp_Object current_only)
5539 struct buffer *old = current_buffer, *b;
5540 Lisp_Object tail, buf, hook;
5541 bool auto_saved = 0;
5542 int do_handled_files;
5543 Lisp_Object oquit;
5544 FILE *stream = NULL;
5545 ptrdiff_t count = SPECPDL_INDEX ();
5546 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5547 bool old_message_p = 0;
5548 struct auto_save_unwind auto_save_unwind;
5550 if (max_specpdl_size < specpdl_size + 40)
5551 max_specpdl_size = specpdl_size + 40;
5553 if (minibuf_level)
5554 no_message = Qt;
5556 if (NILP (no_message))
5558 old_message_p = push_message ();
5559 record_unwind_protect_void (pop_message_unwind);
5562 /* Ordinarily don't quit within this function,
5563 but don't make it impossible to quit (in case we get hung in I/O). */
5564 oquit = Vquit_flag;
5565 Vquit_flag = Qnil;
5567 hook = intern ("auto-save-hook");
5568 safe_run_hooks (hook);
5570 if (STRINGP (Vauto_save_list_file_name))
5572 Lisp_Object listfile;
5574 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5576 /* Don't try to create the directory when shutting down Emacs,
5577 because creating the directory might signal an error, and
5578 that would leave Emacs in a strange state. */
5579 if (!NILP (Vrun_hooks))
5581 Lisp_Object dir;
5582 dir = Ffile_name_directory (listfile);
5583 if (NILP (Ffile_directory_p (dir)))
5584 internal_condition_case_1 (do_auto_save_make_dir,
5585 dir, Qt,
5586 do_auto_save_eh);
5589 stream = emacs_fopen (SSDATA (listfile), "w");
5592 auto_save_unwind.stream = stream;
5593 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5594 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5595 minibuffer_auto_raise = 0;
5596 auto_saving = 1;
5597 auto_save_error_occurred = 0;
5599 /* On first pass, save all files that don't have handlers.
5600 On second pass, save all files that do have handlers.
5602 If Emacs is crashing, the handlers may tweak what is causing
5603 Emacs to crash in the first place, and it would be a shame if
5604 Emacs failed to autosave perfectly ordinary files because it
5605 couldn't handle some ange-ftp'd file. */
5607 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5608 FOR_EACH_LIVE_BUFFER (tail, buf)
5610 b = XBUFFER (buf);
5612 /* Record all the buffers that have auto save mode
5613 in the special file that lists them. For each of these buffers,
5614 Record visited name (if any) and auto save name. */
5615 if (STRINGP (BVAR (b, auto_save_file_name))
5616 && stream != NULL && do_handled_files == 0)
5618 block_input ();
5619 if (!NILP (BVAR (b, filename)))
5620 fwrite_unlocked (SDATA (BVAR (b, filename)), 1,
5621 SBYTES (BVAR (b, filename)), stream);
5622 putc_unlocked ('\n', stream);
5623 fwrite_unlocked (SDATA (BVAR (b, auto_save_file_name)), 1,
5624 SBYTES (BVAR (b, auto_save_file_name)), stream);
5625 putc_unlocked ('\n', stream);
5626 unblock_input ();
5629 if (!NILP (current_only)
5630 && b != current_buffer)
5631 continue;
5633 /* Don't auto-save indirect buffers.
5634 The base buffer takes care of it. */
5635 if (b->base_buffer)
5636 continue;
5638 /* Check for auto save enabled
5639 and file changed since last auto save
5640 and file changed since last real save. */
5641 if (STRINGP (BVAR (b, auto_save_file_name))
5642 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5643 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5644 /* -1 means we've turned off autosaving for a while--see below. */
5645 && XINT (BVAR (b, save_length)) >= 0
5646 && (do_handled_files
5647 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5648 Qwrite_region))))
5650 struct timespec before_time = current_timespec ();
5651 struct timespec after_time;
5653 /* If we had a failure, don't try again for 20 minutes. */
5654 if (b->auto_save_failure_time > 0
5655 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5656 continue;
5658 set_buffer_internal (b);
5659 if (NILP (Vauto_save_include_big_deletions)
5660 && (XFASTINT (BVAR (b, save_length)) * 10
5661 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5662 /* A short file is likely to change a large fraction;
5663 spare the user annoying messages. */
5664 && XFASTINT (BVAR (b, save_length)) > 5000
5665 /* These messages are frequent and annoying for `*mail*'. */
5666 && !EQ (BVAR (b, filename), Qnil)
5667 && NILP (no_message))
5669 /* It has shrunk too much; turn off auto-saving here. */
5670 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5671 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5672 BVAR (b, name), 1);
5673 minibuffer_auto_raise = 0;
5674 /* Turn off auto-saving until there's a real save,
5675 and prevent any more warnings. */
5676 XSETINT (BVAR (b, save_length), -1);
5677 Fsleep_for (make_number (1), Qnil);
5678 continue;
5680 if (!auto_saved && NILP (no_message))
5681 message1 ("Auto-saving...");
5682 internal_condition_case (auto_save_1, Qt, auto_save_error);
5683 auto_saved = 1;
5684 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5685 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5686 set_buffer_internal (old);
5688 after_time = current_timespec ();
5690 /* If auto-save took more than 60 seconds,
5691 assume it was an NFS failure that got a timeout. */
5692 if (after_time.tv_sec - before_time.tv_sec > 60)
5693 b->auto_save_failure_time = after_time.tv_sec;
5697 /* Prevent another auto save till enough input events come in. */
5698 record_auto_save ();
5700 if (auto_saved && NILP (no_message))
5702 if (old_message_p)
5704 /* If we are going to restore an old message,
5705 give time to read ours. */
5706 sit_for (make_number (1), 0, 0);
5707 restore_message ();
5709 else if (!auto_save_error_occurred)
5710 /* Don't overwrite the error message if an error occurred.
5711 If we displayed a message and then restored a state
5712 with no message, leave a "done" message on the screen. */
5713 message1 ("Auto-saving...done");
5716 Vquit_flag = oquit;
5718 /* This restores the message-stack status. */
5719 unbind_to (count, Qnil);
5720 return Qnil;
5723 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5724 Sset_buffer_auto_saved, 0, 0, 0,
5725 doc: /* Mark current buffer as auto-saved with its current text.
5726 No auto-save file will be written until the buffer changes again. */)
5727 (void)
5729 /* FIXME: This should not be called in indirect buffers, since
5730 they're not autosaved. */
5731 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5732 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5733 current_buffer->auto_save_failure_time = 0;
5734 return Qnil;
5737 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5738 Sclear_buffer_auto_save_failure, 0, 0, 0,
5739 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5740 (void)
5742 current_buffer->auto_save_failure_time = 0;
5743 return Qnil;
5746 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5747 0, 0, 0,
5748 doc: /* Return t if current buffer has been auto-saved recently.
5749 More precisely, if it has been auto-saved since last read from or saved
5750 in the visited file. If the buffer has no visited file,
5751 then any auto-save counts as "recent". */)
5752 (void)
5754 /* FIXME: maybe we should return nil for indirect buffers since
5755 they're never autosaved. */
5756 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5759 /* Reading and completing file names. */
5761 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5762 Snext_read_file_uses_dialog_p, 0, 0, 0,
5763 doc: /* Return t if a call to `read-file-name' will use a dialog.
5764 The return value is only relevant for a call to `read-file-name' that happens
5765 before any other event (mouse or keypress) is handled. */)
5766 (void)
5768 #if (defined USE_GTK || defined USE_MOTIF \
5769 || defined HAVE_NS || defined HAVE_NTGUI)
5770 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5771 && use_dialog_box
5772 && use_file_dialog
5773 && window_system_available (SELECTED_FRAME ()))
5774 return Qt;
5775 #endif
5776 return Qnil;
5780 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5781 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5782 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5783 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5784 it to text mode.
5786 As a side effect, this function flushes any pending STREAM's data.
5788 Value is the previous value of STREAM's I/O mode, nil for text mode,
5789 non-nil for binary mode.
5791 On MS-Windows and MS-DOS, binary mode is needed to read or write
5792 arbitrary binary data, and for disabling translation between CR-LF
5793 pairs and a single newline character. Examples include generation
5794 of text files with Unix-style end-of-line format using `princ' in
5795 batch mode, with standard output redirected to a file.
5797 On Posix systems, this function always returns non-nil, and has no
5798 effect except for flushing STREAM's data. */)
5799 (Lisp_Object stream, Lisp_Object mode)
5801 FILE *fp = NULL;
5802 int binmode;
5804 CHECK_SYMBOL (stream);
5805 if (EQ (stream, Qstdin))
5806 fp = stdin;
5807 else if (EQ (stream, Qstdout))
5808 fp = stdout;
5809 else if (EQ (stream, Qstderr))
5810 fp = stderr;
5811 else
5812 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5814 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5815 if (fp != stdin)
5816 fflush_unlocked (fp);
5818 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5821 #ifndef DOS_NT
5823 /* Yield a Lisp float as close as possible to BLOCKSIZE * BLOCKS, with
5824 the result negated if NEGATE. */
5825 static Lisp_Object
5826 blocks_to_bytes (uintmax_t blocksize, uintmax_t blocks, bool negate)
5828 /* On typical platforms the following code is accurate to 53 bits,
5829 which is close enough. BLOCKSIZE is invariably a power of 2, so
5830 converting it to double does not lose information. */
5831 double bs = blocksize;
5832 return make_float (negate ? -bs * -blocks : bs * blocks);
5835 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
5836 doc: /* Return storage information about the file system FILENAME is on.
5837 Value is a list of numbers (TOTAL FREE AVAIL), where TOTAL is the total
5838 storage of the file system, FREE is the free storage, and AVAIL is the
5839 storage available to a non-superuser. All 3 numbers are in bytes.
5840 If the underlying system call fails, value is nil. */)
5841 (Lisp_Object filename)
5843 Lisp_Object encoded = ENCODE_FILE (Fexpand_file_name (filename, Qnil));
5845 /* If the file name has special constructs in it,
5846 call the corresponding file handler. */
5847 Lisp_Object handler = Ffind_file_name_handler (encoded, Qfile_system_info);
5848 if (!NILP (handler))
5850 Lisp_Object result = call2 (handler, Qfile_system_info, encoded);
5851 if (CONSP (result) || NILP (result))
5852 return result;
5853 error ("Invalid handler in `file-name-handler-alist'");
5856 struct fs_usage u;
5857 if (get_fs_usage (SSDATA (encoded), NULL, &u) != 0)
5858 return Qnil;
5859 return list3 (blocks_to_bytes (u.fsu_blocksize, u.fsu_blocks, false),
5860 blocks_to_bytes (u.fsu_blocksize, u.fsu_bfree, false),
5861 blocks_to_bytes (u.fsu_blocksize, u.fsu_bavail,
5862 u.fsu_bavail_top_bit_set));
5865 #endif /* !DOS_NT */
5867 void
5868 init_fileio (void)
5870 realmask = umask (0);
5871 umask (realmask);
5873 valid_timestamp_file_system = 0;
5875 /* fsync can be a significant performance hit. Often it doesn't
5876 suffice to make the file-save operation survive a crash. For
5877 batch scripts, which are typically part of larger shell commands
5878 that don't fsync other files, its effect on performance can be
5879 significant so its utility is particularly questionable.
5880 Hence, for now by default fsync is used only when interactive.
5882 For more on why fsync often fails to work on today's hardware, see:
5883 Zheng M et al. Understanding the robustness of SSDs under power fault.
5884 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5885 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5887 For more on why fsync does not suffice even if it works properly, see:
5888 Roche X. Necessary step(s) to synchronize filename operations on disk.
5889 Austin Group Defect 672, 2013-03-19
5890 http://austingroupbugs.net/view.php?id=672 */
5891 write_region_inhibit_fsync = noninteractive;
5894 void
5895 syms_of_fileio (void)
5897 /* Property name of a file name handler,
5898 which gives a list of operations it handles. */
5899 DEFSYM (Qoperations, "operations");
5901 DEFSYM (Qexpand_file_name, "expand-file-name");
5902 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5903 DEFSYM (Qdirectory_file_name, "directory-file-name");
5904 DEFSYM (Qfile_name_directory, "file-name-directory");
5905 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5906 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5907 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5908 DEFSYM (Qcopy_file, "copy-file");
5909 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5910 DEFSYM (Qmake_directory, "make-directory");
5911 DEFSYM (Qdelete_file, "delete-file");
5912 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5913 DEFSYM (Qrename_file, "rename-file");
5914 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5915 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5916 DEFSYM (Qfile_exists_p, "file-exists-p");
5917 DEFSYM (Qfile_executable_p, "file-executable-p");
5918 DEFSYM (Qfile_readable_p, "file-readable-p");
5919 DEFSYM (Qfile_writable_p, "file-writable-p");
5920 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5921 DEFSYM (Qaccess_file, "access-file");
5922 DEFSYM (Qfile_directory_p, "file-directory-p");
5923 DEFSYM (Qfile_regular_p, "file-regular-p");
5924 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5925 DEFSYM (Qfile_modes, "file-modes");
5926 DEFSYM (Qset_file_modes, "set-file-modes");
5927 DEFSYM (Qset_file_times, "set-file-times");
5928 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5929 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5930 DEFSYM (Qfile_acl, "file-acl");
5931 DEFSYM (Qset_file_acl, "set-file-acl");
5932 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5933 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5934 DEFSYM (Qwrite_region, "write-region");
5935 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5936 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5937 DEFSYM (Qfile_system_info, "file-system-info");
5939 /* The symbol bound to coding-system-for-read when
5940 insert-file-contents is called for recovering a file. This is not
5941 an actual coding system name, but just an indicator to tell
5942 insert-file-contents to use `emacs-mule' with a special flag for
5943 auto saving and recovering a file. */
5944 DEFSYM (Qauto_save_coding, "auto-save-coding");
5946 DEFSYM (Qfile_name_history, "file-name-history");
5947 Fset (Qfile_name_history, Qnil);
5949 DEFSYM (Qfile_error, "file-error");
5950 DEFSYM (Qfile_already_exists, "file-already-exists");
5951 DEFSYM (Qfile_date_error, "file-date-error");
5952 DEFSYM (Qfile_missing, "file-missing");
5953 DEFSYM (Qfile_notify_error, "file-notify-error");
5954 DEFSYM (Qexcl, "excl");
5956 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5957 doc: /* Coding system for encoding file names.
5958 If it is nil, `default-file-name-coding-system' (which see) is used.
5960 On MS-Windows, the value of this variable is largely ignored if
5961 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5962 behaves as if file names were encoded in `utf-8'. */);
5963 Vfile_name_coding_system = Qnil;
5965 DEFVAR_LISP ("default-file-name-coding-system",
5966 Vdefault_file_name_coding_system,
5967 doc: /* Default coding system for encoding file names.
5968 This variable is used only when `file-name-coding-system' is nil.
5970 This variable is set/changed by the command `set-language-environment'.
5971 User should not set this variable manually,
5972 instead use `file-name-coding-system' to get a constant encoding
5973 of file names regardless of the current language environment.
5975 On MS-Windows, the value of this variable is largely ignored if
5976 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5977 behaves as if file names were encoded in `utf-8'. */);
5978 Vdefault_file_name_coding_system = Qnil;
5980 /* Lisp functions for translating file formats. */
5981 DEFSYM (Qformat_decode, "format-decode");
5982 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5984 /* Lisp function for setting buffer-file-coding-system and the
5985 multibyteness of the current buffer after inserting a file. */
5986 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5988 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5990 Fput (Qfile_error, Qerror_conditions,
5991 Fpurecopy (list2 (Qfile_error, Qerror)));
5992 Fput (Qfile_error, Qerror_message,
5993 build_pure_c_string ("File error"));
5995 Fput (Qfile_already_exists, Qerror_conditions,
5996 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5997 Fput (Qfile_already_exists, Qerror_message,
5998 build_pure_c_string ("File already exists"));
6000 Fput (Qfile_date_error, Qerror_conditions,
6001 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
6002 Fput (Qfile_date_error, Qerror_message,
6003 build_pure_c_string ("Cannot set file date"));
6005 Fput (Qfile_missing, Qerror_conditions,
6006 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
6007 Fput (Qfile_missing, Qerror_message,
6008 build_pure_c_string ("File is missing"));
6010 Fput (Qfile_notify_error, Qerror_conditions,
6011 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
6012 Fput (Qfile_notify_error, Qerror_message,
6013 build_pure_c_string ("File notification error"));
6015 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
6016 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
6017 If a file name matches REGEXP, all I/O on that file is done by calling
6018 HANDLER. If a file name matches more than one handler, the handler
6019 whose match starts last in the file name gets precedence. The
6020 function `find-file-name-handler' checks this list for a handler for
6021 its argument.
6023 HANDLER should be a function. The first argument given to it is the
6024 name of the I/O primitive to be handled; the remaining arguments are
6025 the arguments that were passed to that primitive. For example, if you
6026 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
6027 HANDLER is called like this:
6029 (funcall HANDLER \\='file-exists-p FILENAME)
6031 Note that HANDLER must be able to handle all I/O primitives; if it has
6032 nothing special to do for a primitive, it should reinvoke the
6033 primitive to handle the operation \"the usual way\".
6034 See Info node `(elisp)Magic File Names' for more details. */);
6035 Vfile_name_handler_alist = Qnil;
6037 DEFVAR_LISP ("set-auto-coding-function",
6038 Vset_auto_coding_function,
6039 doc: /* If non-nil, a function to call to decide a coding system of file.
6040 Two arguments are passed to this function: the file name
6041 and the length of a file contents following the point.
6042 This function should return a coding system to decode the file contents.
6043 It should check the file name against `auto-coding-alist'.
6044 If no coding system is decided, it should check a coding system
6045 specified in the heading lines with the format:
6046 -*- ... coding: CODING-SYSTEM; ... -*-
6047 or local variable spec of the tailing lines with `coding:' tag. */);
6048 Vset_auto_coding_function = Qnil;
6050 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
6051 doc: /* A list of functions to be called at the end of `insert-file-contents'.
6052 Each is passed one argument, the number of characters inserted,
6053 with point at the start of the inserted text. Each function
6054 should leave point the same, and return the new character count.
6055 If `insert-file-contents' is intercepted by a handler from
6056 `file-name-handler-alist', that handler is responsible for calling the
6057 functions in `after-insert-file-functions' if appropriate. */);
6058 Vafter_insert_file_functions = Qnil;
6060 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
6061 doc: /* A list of functions to be called at the start of `write-region'.
6062 Each is passed two arguments, START and END as for `write-region'.
6063 These are usually two numbers but not always; see the documentation
6064 for `write-region'. The function should return a list of pairs
6065 of the form (POSITION . STRING), consisting of strings to be effectively
6066 inserted at the specified positions of the file being written (1 means to
6067 insert before the first byte written). The POSITIONs must be sorted into
6068 increasing order.
6070 If there are several annotation functions, the lists returned by these
6071 functions are merged destructively. As each annotation function runs,
6072 the variable `write-region-annotations-so-far' contains a list of all
6073 annotations returned by previous annotation functions.
6075 An annotation function can return with a different buffer current.
6076 Doing so removes the annotations returned by previous functions, and
6077 resets START and END to `point-min' and `point-max' of the new buffer.
6079 After `write-region' completes, Emacs calls the function stored in
6080 `write-region-post-annotation-function', once for each buffer that was
6081 current when building the annotations (i.e., at least once), with that
6082 buffer current. */);
6083 Vwrite_region_annotate_functions = Qnil;
6084 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6086 DEFVAR_LISP ("write-region-post-annotation-function",
6087 Vwrite_region_post_annotation_function,
6088 doc: /* Function to call after `write-region' completes.
6089 The function is called with no arguments. If one or more of the
6090 annotation functions in `write-region-annotate-functions' changed the
6091 current buffer, the function stored in this variable is called for
6092 each of those additional buffers as well, in addition to the original
6093 buffer. The relevant buffer is current during each function call. */);
6094 Vwrite_region_post_annotation_function = Qnil;
6095 staticpro (&Vwrite_region_annotation_buffers);
6097 DEFVAR_LISP ("write-region-annotations-so-far",
6098 Vwrite_region_annotations_so_far,
6099 doc: /* When an annotation function is called, this holds the previous annotations.
6100 These are the annotations made by other annotation functions
6101 that were already called. See also `write-region-annotate-functions'. */);
6102 Vwrite_region_annotations_so_far = Qnil;
6104 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6105 doc: /* A list of file name handlers that temporarily should not be used.
6106 This applies only to the operation `inhibit-file-name-operation'. */);
6107 Vinhibit_file_name_handlers = Qnil;
6109 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6110 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6111 Vinhibit_file_name_operation = Qnil;
6113 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6114 doc: /* File name in which to write a list of all auto save file names.
6115 This variable is initialized automatically from `auto-save-list-file-prefix'
6116 shortly after Emacs reads your init file, if you have not yet given it
6117 a non-nil value. */);
6118 Vauto_save_list_file_name = Qnil;
6120 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6121 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6122 Normally auto-save files are written under other names. */);
6123 Vauto_save_visited_file_name = Qnil;
6125 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6126 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6127 If nil, deleting a substantial portion of the text disables auto-save
6128 in the buffer; this is the default behavior, because the auto-save
6129 file is usually more useful if it contains the deleted text. */);
6130 Vauto_save_include_big_deletions = Qnil;
6132 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6133 doc: /* Non-nil means don't call fsync in `write-region'.
6134 This variable affects calls to `write-region' as well as save commands.
6135 Setting this to nil may avoid data loss if the system loses power or
6136 the operating system crashes. By default, it is non-nil in batch mode. */);
6137 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6139 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6140 doc: /* Specifies whether to use the system's trash can.
6141 When non-nil, certain file deletion commands use the function
6142 `move-file-to-trash' instead of deleting files outright.
6143 This includes interactive calls to `delete-file' and
6144 `delete-directory' and the Dired deletion commands. */);
6145 delete_by_moving_to_trash = 0;
6146 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6148 /* Lisp function for moving files to trash. */
6149 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6151 /* Lisp function for recursively copying directories. */
6152 DEFSYM (Qcopy_directory, "copy-directory");
6154 /* Lisp function for recursively deleting directories. */
6155 DEFSYM (Qdelete_directory, "delete-directory");
6157 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6158 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6160 DEFSYM (Qstdin, "stdin");
6161 DEFSYM (Qstdout, "stdout");
6162 DEFSYM (Qstderr, "stderr");
6164 defsubr (&Sfind_file_name_handler);
6165 defsubr (&Sfile_name_directory);
6166 defsubr (&Sfile_name_nondirectory);
6167 defsubr (&Sunhandled_file_name_directory);
6168 defsubr (&Sfile_name_as_directory);
6169 defsubr (&Sdirectory_name_p);
6170 defsubr (&Sdirectory_file_name);
6171 defsubr (&Smake_temp_file_internal);
6172 defsubr (&Smake_temp_name);
6173 defsubr (&Sexpand_file_name);
6174 defsubr (&Ssubstitute_in_file_name);
6175 defsubr (&Scopy_file);
6176 defsubr (&Smake_directory_internal);
6177 defsubr (&Sdelete_directory_internal);
6178 defsubr (&Sdelete_file);
6179 defsubr (&Sfile_name_case_insensitive_p);
6180 defsubr (&Srename_file);
6181 defsubr (&Sadd_name_to_file);
6182 defsubr (&Smake_symbolic_link);
6183 defsubr (&Sfile_name_absolute_p);
6184 defsubr (&Sfile_exists_p);
6185 defsubr (&Sfile_executable_p);
6186 defsubr (&Sfile_readable_p);
6187 defsubr (&Sfile_writable_p);
6188 defsubr (&Saccess_file);
6189 defsubr (&Sfile_symlink_p);
6190 defsubr (&Sfile_directory_p);
6191 defsubr (&Sfile_accessible_directory_p);
6192 defsubr (&Sfile_regular_p);
6193 defsubr (&Sfile_modes);
6194 defsubr (&Sset_file_modes);
6195 defsubr (&Sset_file_times);
6196 defsubr (&Sfile_selinux_context);
6197 defsubr (&Sfile_acl);
6198 defsubr (&Sset_file_acl);
6199 defsubr (&Sset_file_selinux_context);
6200 defsubr (&Sset_default_file_modes);
6201 defsubr (&Sdefault_file_modes);
6202 defsubr (&Sfile_newer_than_file_p);
6203 defsubr (&Sinsert_file_contents);
6204 defsubr (&Swrite_region);
6205 defsubr (&Scar_less_than_car);
6206 defsubr (&Sverify_visited_file_modtime);
6207 defsubr (&Svisited_file_modtime);
6208 defsubr (&Sset_visited_file_modtime);
6209 defsubr (&Sdo_auto_save);
6210 defsubr (&Sset_buffer_auto_saved);
6211 defsubr (&Sclear_buffer_auto_save_failure);
6212 defsubr (&Srecent_auto_save_p);
6214 defsubr (&Snext_read_file_uses_dialog_p);
6216 defsubr (&Sset_binary_mode);
6218 #ifndef DOS_NT
6219 defsubr (&Sfile_system_info);
6220 #endif
6222 #ifdef HAVE_SYNC
6223 defsubr (&Sunix_sync);
6224 #endif