* src/fileio.c (Fexpand_file_name): Doc fix. (Bug#27982)
[emacs.git] / src / fileio.c
blob0a52982291d1ccf1150a525621a4c5d33bb6f58a
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2017 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include "sysstdio.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #ifdef DARWIN_OS
29 #include <sys/attr.h>
30 #endif
32 #ifdef HAVE_PWD_H
33 #include <pwd.h>
34 #endif
36 #include <errno.h>
38 #ifdef HAVE_LIBSELINUX
39 #include <selinux/selinux.h>
40 #include <selinux/context.h>
41 #endif
43 #if USE_ACL && defined HAVE_ACL_SET_FILE
44 #include <sys/acl.h>
45 #endif
47 #include <c-ctype.h>
49 #include "lisp.h"
50 #include "composite.h"
51 #include "character.h"
52 #include "buffer.h"
53 #include "coding.h"
54 #include "window.h"
55 #include "blockinput.h"
56 #include "region-cache.h"
57 #include "frame.h"
59 #ifdef HAVE_LINUX_FS_H
60 # include <sys/ioctl.h>
61 # include <linux/fs.h>
62 #endif
64 #ifdef WINDOWSNT
65 #define NOMINMAX 1
66 #include <windows.h>
67 /* The redundant #ifdef is to avoid compiler warning about unused macro. */
68 #ifdef NOMINMAX
69 #undef NOMINMAX
70 #endif
71 #include <sys/file.h>
72 #include "w32.h"
73 #endif /* not WINDOWSNT */
75 #ifdef MSDOS
76 #include "msdos.h"
77 #include <sys/param.h>
78 #endif
80 #ifdef DOS_NT
81 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
82 redirector allows the six letters between 'Z' and 'a' as well. */
83 #ifdef MSDOS
84 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
85 #endif
86 #ifdef WINDOWSNT
87 #define IS_DRIVE(x) c_isalpha (x)
88 #endif
89 /* Need to lower-case the drive letter, or else expanded
90 filenames will sometimes compare unequal, because
91 `expand-file-name' doesn't always down-case the drive letter. */
92 #define DRIVE_LETTER(x) c_tolower (x)
93 #endif
95 #include "systime.h"
96 #include <acl.h>
97 #include <allocator.h>
98 #include <careadlinkat.h>
99 #include <stat-time.h>
100 #include <tempname.h>
102 #include <binary-io.h>
104 #ifdef HPUX
105 #include <netio.h>
106 #endif
108 #include "commands.h"
110 /* True during writing of auto-save files. */
111 static bool auto_saving;
113 /* Emacs's real umask. */
114 static mode_t realmask;
116 /* Nonzero umask during creation of auto-save directories. */
117 static mode_t auto_saving_dir_umask;
119 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
120 a new file with the same mode as the original. */
121 static mode_t auto_save_mode_bits;
123 /* Set by auto_save_1 if an error occurred during the last auto-save. */
124 static bool auto_save_error_occurred;
126 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
127 number of a file system where time stamps were observed to to work. */
128 static bool valid_timestamp_file_system;
129 static dev_t timestamp_file_system;
131 /* Each time an annotation function changes the buffer, the new buffer
132 is added here. */
133 static Lisp_Object Vwrite_region_annotation_buffers;
135 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
136 Lisp_Object *, struct coding_system *);
137 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
138 struct coding_system *);
141 /* Return true if FILENAME exists. */
143 static bool
144 check_existing (const char *filename)
146 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
149 /* Return true if file FILENAME exists and can be executed. */
151 static bool
152 check_executable (char *filename)
154 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
157 /* Return true if file FILENAME exists and can be accessed
158 according to AMODE, which should include W_OK.
159 On failure, return false and set errno. */
161 static bool
162 check_writable (const char *filename, int amode)
164 #ifdef MSDOS
165 /* FIXME: an faccessat implementation should be added to the
166 DOS/Windows ports and this #ifdef branch should be removed. */
167 struct stat st;
168 if (stat (filename, &st) < 0)
169 return 0;
170 errno = EPERM;
171 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
172 #else /* not MSDOS */
173 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
174 #ifdef CYGWIN
175 /* faccessat may have returned failure because Cygwin couldn't
176 determine the file's UID or GID; if so, we return success. */
177 if (!res)
179 int faccessat_errno = errno;
180 struct stat st;
181 if (stat (filename, &st) < 0)
182 return 0;
183 res = (st.st_uid == -1 || st.st_gid == -1);
184 errno = faccessat_errno;
186 #endif /* CYGWIN */
187 return res;
188 #endif /* not MSDOS */
191 /* Signal a file-access failure. STRING describes the failure,
192 NAME the file involved, and ERRORNO the errno value.
194 If NAME is neither null nor a pair, package it up as a singleton
195 list before reporting it; this saves report_file_errno's caller the
196 trouble of preserving errno before calling list1. */
198 void
199 report_file_errno (char const *string, Lisp_Object name, int errorno)
201 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
202 char *str = emacs_strerror (errorno);
203 AUTO_STRING (unibyte_str, str);
204 Lisp_Object errstring
205 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
206 Lisp_Object errdata = Fcons (errstring, data);
208 if (errorno == EEXIST)
209 xsignal (Qfile_already_exists, errdata);
210 else
211 xsignal (errorno == ENOENT ? Qfile_missing : Qfile_error,
212 Fcons (build_string (string), errdata));
215 /* Signal a file-access failure that set errno. STRING describes the
216 failure, NAME the file involved. When invoking this function, take
217 care to not use arguments such as build_string ("foo") that involve
218 side effects that may set errno. */
220 void
221 report_file_error (char const *string, Lisp_Object name)
223 report_file_errno (string, name, errno);
226 /* Like report_file_error, but reports a file-notify-error instead. */
228 void
229 report_file_notify_error (const char *string, Lisp_Object name)
231 char *str = emacs_strerror (errno);
232 AUTO_STRING (unibyte_str, str);
233 Lisp_Object errstring
234 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
235 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
236 Lisp_Object errdata = Fcons (errstring, data);
238 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
241 void
242 close_file_unwind (int fd)
244 emacs_close (fd);
247 void
248 fclose_unwind (void *arg)
250 FILE *stream = arg;
251 fclose (stream);
254 /* Restore point, having saved it as a marker. */
256 void
257 restore_point_unwind (Lisp_Object location)
259 Fgoto_char (location);
260 unchain_marker (XMARKER (location));
264 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
265 Sfind_file_name_handler, 2, 2, 0,
266 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
267 Otherwise, return nil.
268 A file name is handled if one of the regular expressions in
269 `file-name-handler-alist' matches it.
271 If OPERATION equals `inhibit-file-name-operation', then ignore
272 any handlers that are members of `inhibit-file-name-handlers',
273 but still do run any other handlers. This lets handlers
274 use the standard functions without calling themselves recursively. */)
275 (Lisp_Object filename, Lisp_Object operation)
277 /* This function must not munge the match data. */
278 Lisp_Object chain, inhibited_handlers, result;
279 ptrdiff_t pos = -1;
281 result = Qnil;
282 CHECK_STRING (filename);
284 if (EQ (operation, Vinhibit_file_name_operation))
285 inhibited_handlers = Vinhibit_file_name_handlers;
286 else
287 inhibited_handlers = Qnil;
289 for (chain = Vfile_name_handler_alist; CONSP (chain);
290 chain = XCDR (chain))
292 Lisp_Object elt;
293 elt = XCAR (chain);
294 if (CONSP (elt))
296 Lisp_Object string = XCAR (elt);
297 ptrdiff_t match_pos;
298 Lisp_Object handler = XCDR (elt);
299 Lisp_Object operations = Qnil;
301 if (SYMBOLP (handler))
302 operations = Fget (handler, Qoperations);
304 if (STRINGP (string)
305 && (match_pos = fast_string_match (string, filename)) > pos
306 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
308 Lisp_Object tem;
310 handler = XCDR (elt);
311 tem = Fmemq (handler, inhibited_handlers);
312 if (NILP (tem))
314 result = handler;
315 pos = match_pos;
320 maybe_quit ();
322 return result;
325 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
326 1, 1, 0,
327 doc: /* Return the directory component in file name FILENAME.
328 Return nil if FILENAME does not include a directory.
329 Otherwise return a directory name.
330 Given a Unix syntax file name, returns a string ending in slash. */)
331 (Lisp_Object filename)
333 Lisp_Object handler;
335 CHECK_STRING (filename);
337 /* If the file name has special constructs in it,
338 call the corresponding file handler. */
339 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
340 if (!NILP (handler))
342 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
343 filename);
344 return STRINGP (handled_name) ? handled_name : Qnil;
347 char *beg = SSDATA (filename);
348 char const *p = beg + SBYTES (filename);
350 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
351 #ifdef DOS_NT
352 /* only recognize drive specifier at the beginning */
353 && !(p[-1] == ':'
354 /* handle the "/:d:foo" and "/:foo" cases correctly */
355 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
356 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
357 #endif
358 ) p--;
360 if (p == beg)
361 return Qnil;
362 #ifdef DOS_NT
363 /* Expansion of "c:" to drive and default directory. */
364 Lisp_Object tem_fn;
365 USE_SAFE_ALLOCA;
366 SAFE_ALLOCA_STRING (beg, filename);
367 p = beg + (p - SSDATA (filename));
369 if (p[-1] == ':')
371 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
372 char *res = alloca (MAXPATHLEN + 1);
373 char *r = res;
375 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
377 memcpy (res, beg, 2);
378 beg += 2;
379 r += 2;
382 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
384 size_t l = strlen (res);
386 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
387 strcat (res, "/");
388 beg = res;
389 p = beg + strlen (beg);
390 dostounix_filename (beg);
391 tem_fn = make_specified_string (beg, -1, p - beg,
392 STRING_MULTIBYTE (filename));
394 else
395 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
396 STRING_MULTIBYTE (filename));
398 else if (STRING_MULTIBYTE (filename))
400 tem_fn = make_specified_string (beg, -1, p - beg, 1);
401 dostounix_filename (SSDATA (tem_fn));
402 #ifdef WINDOWSNT
403 if (!NILP (Vw32_downcase_file_names))
404 tem_fn = Fdowncase (tem_fn);
405 #endif
407 else
409 dostounix_filename (beg);
410 tem_fn = make_specified_string (beg, -1, p - beg, 0);
412 SAFE_FREE ();
413 return tem_fn;
414 #else /* DOS_NT */
415 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
416 #endif /* DOS_NT */
419 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
420 Sfile_name_nondirectory, 1, 1, 0,
421 doc: /* Return file name FILENAME sans its directory.
422 For example, in a Unix-syntax file name,
423 this is everything after the last slash,
424 or the entire name if it contains no slash. */)
425 (Lisp_Object filename)
427 register const char *beg, *p, *end;
428 Lisp_Object handler;
430 CHECK_STRING (filename);
432 /* If the file name has special constructs in it,
433 call the corresponding file handler. */
434 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
435 if (!NILP (handler))
437 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
438 filename);
439 if (STRINGP (handled_name))
440 return handled_name;
441 error ("Invalid handler in `file-name-handler-alist'");
444 beg = SSDATA (filename);
445 end = p = beg + SBYTES (filename);
447 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
448 #ifdef DOS_NT
449 /* only recognize drive specifier at beginning */
450 && !(p[-1] == ':'
451 /* handle the "/:d:foo" case correctly */
452 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
453 #endif
455 p--;
457 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
460 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
461 Sunhandled_file_name_directory, 1, 1, 0,
462 doc: /* Return a directly usable directory name somehow associated with FILENAME.
463 A `directly usable' directory name is one that may be used without the
464 intervention of any file handler.
465 If FILENAME is a directly usable file itself, return
466 \(file-name-as-directory FILENAME).
467 If FILENAME refers to a file which is not accessible from a local process,
468 then this should return nil.
469 The `call-process' and `start-process' functions use this function to
470 get a current directory to run processes in. */)
471 (Lisp_Object filename)
473 Lisp_Object handler;
475 /* If the file name has special constructs in it,
476 call the corresponding file handler. */
477 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
478 if (!NILP (handler))
480 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
481 filename);
482 return STRINGP (handled_name) ? handled_name : Qnil;
485 return Ffile_name_as_directory (filename);
488 /* Maximum number of bytes that DST will be longer than SRC
489 in file_name_as_directory. This occurs when SRCLEN == 0. */
490 enum { file_name_as_directory_slop = 2 };
492 /* Convert from file name SRC of length SRCLEN to directory name in
493 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
494 string. On UNIX, just make sure there is a terminating /. Return
495 the length of DST in bytes. */
497 static ptrdiff_t
498 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
499 bool multibyte)
501 if (srclen == 0)
503 dst[0] = '.';
504 dst[1] = '/';
505 dst[2] = '\0';
506 return 2;
509 memcpy (dst, src, srclen);
510 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
511 dst[srclen++] = DIRECTORY_SEP;
512 dst[srclen] = 0;
513 #ifdef DOS_NT
514 dostounix_filename (dst);
515 #endif
516 return srclen;
519 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
520 Sfile_name_as_directory, 1, 1, 0,
521 doc: /* Return a string representing the file name FILE interpreted as a directory.
522 This operation exists because a directory is also a file, but its name as
523 a directory is different from its name as a file.
524 The result can be used as the value of `default-directory'
525 or passed as second argument to `expand-file-name'.
526 For a Unix-syntax file name, just appends a slash unless a trailing slash
527 is already present. */)
528 (Lisp_Object file)
530 char *buf;
531 ptrdiff_t length;
532 Lisp_Object handler, val;
533 USE_SAFE_ALLOCA;
535 CHECK_STRING (file);
537 /* If the file name has special constructs in it,
538 call the corresponding file handler. */
539 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
540 if (!NILP (handler))
542 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
543 file);
544 if (STRINGP (handled_name))
545 return handled_name;
546 error ("Invalid handler in `file-name-handler-alist'");
549 #ifdef WINDOWSNT
550 if (!NILP (Vw32_downcase_file_names))
551 file = Fdowncase (file);
552 #endif
553 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
554 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
555 STRING_MULTIBYTE (file));
556 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
557 SAFE_FREE ();
558 return val;
561 /* Convert from directory name SRC of length SRCLEN to file name in
562 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
563 string. On UNIX, just make sure there isn't a terminating /.
564 Return the length of DST in bytes. */
566 static ptrdiff_t
567 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
569 /* Process as Unix format: just remove any final slash.
570 But leave "/" and "//" unchanged. */
571 while (srclen > 1
572 #ifdef DOS_NT
573 && !IS_ANY_SEP (src[srclen - 2])
574 #endif
575 && IS_DIRECTORY_SEP (src[srclen - 1])
576 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
577 srclen--;
579 memcpy (dst, src, srclen);
580 dst[srclen] = 0;
581 #ifdef DOS_NT
582 dostounix_filename (dst);
583 #endif
584 return srclen;
587 DEFUN ("directory-name-p", Fdirectory_name_p, Sdirectory_name_p, 1, 1, 0,
588 doc: /* Return non-nil if NAME ends with a directory separator character. */)
589 (Lisp_Object name)
591 CHECK_STRING (name);
592 ptrdiff_t namelen = SBYTES (name);
593 unsigned char c = namelen ? SREF (name, namelen - 1) : 0;
594 return IS_DIRECTORY_SEP (c) ? Qt : Qnil;
597 /* Return true if NAME must be that of a directory if it exists.
598 When NAME is a directory name, this avoids system calls compared to
599 just calling Ffile_directory_p. */
601 static bool
602 directory_like (Lisp_Object name)
604 return !NILP (Fdirectory_name_p (name)) || !NILP (Ffile_directory_p (name));
607 /* Return the expansion of NEWNAME, except that if NEWNAME is like a
608 directory then return the expansion of FILE's basename under
609 NEWNAME. This is like how 'cp FILE NEWNAME' works. */
611 static Lisp_Object
612 expand_cp_target (Lisp_Object file, Lisp_Object newname)
614 return (directory_like (newname)
615 ? Fexpand_file_name (Ffile_name_nondirectory (file), newname)
616 : Fexpand_file_name (newname, Qnil));
619 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
620 1, 1, 0,
621 doc: /* Returns the file name of the directory named DIRECTORY.
622 This is the name of the file that holds the data for the directory DIRECTORY.
623 This operation exists because a directory is also a file, but its name as
624 a directory is different from its name as a file.
625 In Unix-syntax, this function just removes the final slash. */)
626 (Lisp_Object directory)
628 char *buf;
629 ptrdiff_t length;
630 Lisp_Object handler, val;
631 USE_SAFE_ALLOCA;
633 CHECK_STRING (directory);
635 /* If the file name has special constructs in it,
636 call the corresponding file handler. */
637 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
638 if (!NILP (handler))
640 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
641 directory);
642 if (STRINGP (handled_name))
643 return handled_name;
644 error ("Invalid handler in `file-name-handler-alist'");
647 #ifdef WINDOWSNT
648 if (!NILP (Vw32_downcase_file_names))
649 directory = Fdowncase (directory);
650 #endif
651 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
652 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
653 STRING_MULTIBYTE (directory));
654 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
655 SAFE_FREE ();
656 return val;
659 DEFUN ("make-temp-file-internal", Fmake_temp_file_internal,
660 Smake_temp_file_internal, 4, 4, 0,
661 doc: /* Generate a new file whose name starts with PREFIX, a string.
662 Return the name of the generated file. If DIR-FLAG is zero, do not
663 create the file, just its name. Otherwise, if DIR-FLAG is non-nil,
664 create an empty directory. The file name should end in SUFFIX.
665 Do not expand PREFIX; a non-absolute PREFIX is relative to the Emacs
666 working directory. If TEXT is a string, insert it into the newly
667 created file.
669 Signal an error if the file could not be created.
671 This function does not grok magic file names. */)
672 (Lisp_Object prefix, Lisp_Object dir_flag, Lisp_Object suffix,
673 Lisp_Object text)
675 CHECK_STRING (prefix);
676 CHECK_STRING (suffix);
677 Lisp_Object encoded_prefix = ENCODE_FILE (prefix);
678 Lisp_Object encoded_suffix = ENCODE_FILE (suffix);
679 ptrdiff_t prefix_len = SBYTES (encoded_prefix);
680 ptrdiff_t suffix_len = SBYTES (encoded_suffix);
681 if (INT_MAX < suffix_len)
682 args_out_of_range (prefix, suffix);
683 int nX = 6;
684 Lisp_Object val = make_uninit_string (prefix_len + nX + suffix_len);
685 char *data = SSDATA (val);
686 memcpy (data, SSDATA (encoded_prefix), prefix_len);
687 memset (data + prefix_len, 'X', nX);
688 memcpy (data + prefix_len + nX, SSDATA (encoded_suffix), suffix_len);
689 int kind = (NILP (dir_flag) ? GT_FILE
690 : EQ (dir_flag, make_number (0)) ? GT_NOCREATE
691 : GT_DIR);
692 int fd = gen_tempname (data, suffix_len, O_BINARY | O_CLOEXEC, kind);
693 bool failed = fd < 0;
694 if (!failed)
696 ptrdiff_t count = SPECPDL_INDEX ();
697 record_unwind_protect_int (close_file_unwind, fd);
698 val = DECODE_FILE (val);
699 if (STRINGP (text) && SBYTES (text) != 0)
700 write_region (text, Qnil, val, Qnil, Qnil, Qnil, Qnil, fd);
701 failed = NILP (dir_flag) && emacs_close (fd) != 0;
702 /* Discard the unwind protect. */
703 specpdl_ptr = specpdl + count;
705 if (failed)
707 static char const kind_message[][32] =
709 [GT_FILE] = "Creating file with prefix",
710 [GT_DIR] = "Creating directory with prefix",
711 [GT_NOCREATE] = "Creating file name with prefix"
713 report_file_error (kind_message[kind], prefix);
715 return val;
719 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
720 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
722 This function tries to choose a name that has no existing file.
723 For this to work, PREFIX should be an absolute file name, and PREFIX
724 and the returned string should both be non-magic.
726 There is a race condition between calling `make-temp-name' and
727 later creating the file, which opens all kinds of security holes.
728 For that reason, you should normally use `make-temp-file' instead. */)
729 (Lisp_Object prefix)
731 return Fmake_temp_file_internal (prefix, make_number (0),
732 empty_unibyte_string, Qnil);
735 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
736 doc: /* Convert filename NAME to absolute, and canonicalize it.
737 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
738 \(does not start with slash or tilde); both the directory name and
739 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
740 missing, the current buffer's value of `default-directory' is used.
741 NAME should be a string that is a valid file name for the underlying
742 filesystem.
743 File name components that are `.' are removed, and
744 so are file name components followed by `..', along with the `..' itself;
745 note that these simplifications are done without checking the resulting
746 file names in the file system.
747 Multiple consecutive slashes are collapsed into a single slash,
748 except at the beginning of the file name when they are significant (e.g.,
749 UNC file names on MS-Windows.)
750 An initial `~/' expands to your home directory.
751 An initial `~USER/' expands to USER's home directory.
752 See also the function `substitute-in-file-name'.
754 For technical reasons, this function can return correct but
755 non-intuitive results for the root directory; for instance,
756 \(expand-file-name ".." "/") returns "/..". For this reason, use
757 \(directory-file-name (file-name-directory dirname)) to traverse a
758 filesystem tree, not (expand-file-name ".." dirname). Note: make
759 sure DIRNAME in this example doesn't end in a slash, unless it's
760 the root directory. */)
761 (Lisp_Object name, Lisp_Object default_directory)
763 /* These point to SDATA and need to be careful with string-relocation
764 during GC (via DECODE_FILE). */
765 char *nm;
766 char *nmlim;
767 const char *newdir;
768 const char *newdirlim;
769 /* This should only point to alloca'd data. */
770 char *target;
772 ptrdiff_t tlen;
773 struct passwd *pw;
774 #ifdef DOS_NT
775 int drive = 0;
776 bool collapse_newdir = true;
777 bool is_escaped = 0;
778 #endif /* DOS_NT */
779 ptrdiff_t length, nbytes;
780 Lisp_Object handler, result, handled_name;
781 bool multibyte;
782 Lisp_Object hdir;
783 USE_SAFE_ALLOCA;
785 CHECK_STRING (name);
787 /* If the file name has special constructs in it,
788 call the corresponding file handler. */
789 handler = Ffind_file_name_handler (name, Qexpand_file_name);
790 if (!NILP (handler))
792 handled_name = call3 (handler, Qexpand_file_name,
793 name, default_directory);
794 if (STRINGP (handled_name))
795 return handled_name;
796 error ("Invalid handler in `file-name-handler-alist'");
800 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
801 if (NILP (default_directory))
802 default_directory = BVAR (current_buffer, directory);
803 if (! STRINGP (default_directory))
805 #ifdef DOS_NT
806 /* "/" is not considered a root directory on DOS_NT, so using "/"
807 here causes an infinite recursion in, e.g., the following:
809 (let (default-directory)
810 (expand-file-name "a"))
812 To avoid this, we set default_directory to the root of the
813 current drive. */
814 default_directory = build_string (emacs_root_dir ());
815 #else
816 default_directory = build_string ("/");
817 #endif
820 if (!NILP (default_directory))
822 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
823 if (!NILP (handler))
825 handled_name = call3 (handler, Qexpand_file_name,
826 name, default_directory);
827 if (STRINGP (handled_name))
828 return handled_name;
829 error ("Invalid handler in `file-name-handler-alist'");
834 char *o = SSDATA (default_directory);
836 /* Make sure DEFAULT_DIRECTORY is properly expanded.
837 It would be better to do this down below where we actually use
838 default_directory. Unfortunately, calling Fexpand_file_name recursively
839 could invoke GC, and the strings might be relocated. This would
840 be annoying because we have pointers into strings lying around
841 that would need adjusting, and people would add new pointers to
842 the code and forget to adjust them, resulting in intermittent bugs.
843 Putting this call here avoids all that crud.
845 The EQ test avoids infinite recursion. */
846 if (! NILP (default_directory) && !EQ (default_directory, name)
847 /* Save time in some common cases - as long as default_directory
848 is not relative, it can be canonicalized with name below (if it
849 is needed at all) without requiring it to be expanded now. */
850 #ifdef DOS_NT
851 /* Detect MSDOS file names with drive specifiers. */
852 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
853 && IS_DIRECTORY_SEP (o[2]))
854 /* Detect escaped file names without drive spec after "/:".
855 These should not be recursively expanded, to avoid
856 including the default directory twice in the expanded
857 result. */
858 && ! (o[0] == '/' && o[1] == ':')
859 #ifdef WINDOWSNT
860 /* Detect Windows file names in UNC format. */
861 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
862 #endif
863 #else /* not DOS_NT */
864 /* Detect Unix absolute file names (/... alone is not absolute on
865 DOS or Windows). */
866 && ! (IS_DIRECTORY_SEP (o[0]))
867 #endif /* not DOS_NT */
870 default_directory = Fexpand_file_name (default_directory, Qnil);
873 multibyte = STRING_MULTIBYTE (name);
874 if (multibyte != STRING_MULTIBYTE (default_directory))
876 if (multibyte)
878 unsigned char *p = SDATA (name);
880 while (*p && ASCII_CHAR_P (*p))
881 p++;
882 if (*p == '\0')
884 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
885 unibyte. Do not convert DEFAULT_DIRECTORY to
886 multibyte; instead, convert NAME to a unibyte string,
887 so that the result of this function is also a unibyte
888 string. This is needed during bootstrapping and
889 dumping, when Emacs cannot decode file names, because
890 the locale environment is not set up. */
891 name = make_unibyte_string (SSDATA (name), SBYTES (name));
892 multibyte = 0;
894 else
895 default_directory = string_to_multibyte (default_directory);
897 else
899 name = string_to_multibyte (name);
900 multibyte = 1;
904 #ifdef WINDOWSNT
905 if (!NILP (Vw32_downcase_file_names))
906 default_directory = Fdowncase (default_directory);
907 #endif
909 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
910 SAFE_ALLOCA_STRING (nm, name);
911 nmlim = nm + SBYTES (name);
913 #ifdef DOS_NT
914 /* Note if special escape prefix is present, but remove for now. */
915 if (nm[0] == '/' && nm[1] == ':')
917 is_escaped = 1;
918 nm += 2;
921 /* Find and remove drive specifier if present; this makes nm absolute
922 even if the rest of the name appears to be relative. Only look for
923 drive specifier at the beginning. */
924 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
926 drive = (unsigned char) nm[0];
927 nm += 2;
930 #ifdef WINDOWSNT
931 /* If we see "c://somedir", we want to strip the first slash after the
932 colon when stripping the drive letter. Otherwise, this expands to
933 "//somedir". */
934 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
935 nm++;
937 /* Discard any previous drive specifier if nm is now in UNC format. */
938 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
939 && !IS_DIRECTORY_SEP (nm[2]))
940 drive = 0;
941 #endif /* WINDOWSNT */
942 #endif /* DOS_NT */
944 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
945 none are found, we can probably return right away. We will avoid
946 allocating a new string if name is already fully expanded. */
947 if (
948 IS_DIRECTORY_SEP (nm[0])
949 #ifdef MSDOS
950 && drive && !is_escaped
951 #endif
952 #ifdef WINDOWSNT
953 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
954 #endif
957 /* If it turns out that the filename we want to return is just a
958 suffix of FILENAME, we don't need to go through and edit
959 things; we just need to construct a new string using data
960 starting at the middle of FILENAME. If we set LOSE, that
961 means we've discovered that we can't do that cool trick. */
962 bool lose = 0;
963 char *p = nm;
965 while (*p)
967 /* Since we know the name is absolute, we can assume that each
968 element starts with a "/". */
970 /* "." and ".." are hairy. */
971 if (IS_DIRECTORY_SEP (p[0])
972 && p[1] == '.'
973 && (IS_DIRECTORY_SEP (p[2])
974 || p[2] == 0
975 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
976 || p[3] == 0))))
977 lose = 1;
978 /* Replace multiple slashes with a single one, except
979 leave leading "//" alone. */
980 else if (IS_DIRECTORY_SEP (p[0])
981 && IS_DIRECTORY_SEP (p[1])
982 && (p != nm || IS_DIRECTORY_SEP (p[2])))
983 lose = 1;
984 p++;
986 if (!lose)
988 #ifdef DOS_NT
989 /* Make sure directories are all separated with /, but
990 avoid allocation of a new string when not required. */
991 dostounix_filename (nm);
992 #ifdef WINDOWSNT
993 if (IS_DIRECTORY_SEP (nm[1]))
995 if (strcmp (nm, SSDATA (name)) != 0)
996 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
998 else
999 #endif
1000 /* Drive must be set, so this is okay. */
1001 if (strcmp (nm - 2, SSDATA (name)) != 0)
1003 name = make_specified_string (nm, -1, p - nm, multibyte);
1004 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1005 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1006 name = concat2 (drive_prefix, name);
1008 #ifdef WINDOWSNT
1009 if (!NILP (Vw32_downcase_file_names))
1010 name = Fdowncase (name);
1011 #endif
1012 #else /* not DOS_NT */
1013 if (strcmp (nm, SSDATA (name)) != 0)
1014 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1015 #endif /* not DOS_NT */
1016 SAFE_FREE ();
1017 return name;
1021 /* At this point, nm might or might not be an absolute file name. We
1022 need to expand ~ or ~user if present, otherwise prefix nm with
1023 default_directory if nm is not absolute, and finally collapse /./
1024 and /foo/../ sequences.
1026 We set newdir to be the appropriate prefix if one is needed:
1027 - the relevant user directory if nm starts with ~ or ~user
1028 - the specified drive's working dir (DOS/NT only) if nm does not
1029 start with /
1030 - the value of default_directory.
1032 Note that these prefixes are not guaranteed to be absolute (except
1033 for the working dir of a drive). Therefore, to ensure we always
1034 return an absolute name, if the final prefix is not absolute we
1035 append it to the current working directory. */
1037 newdir = newdirlim = 0;
1039 if (nm[0] == '~' /* prefix ~ */
1040 #ifdef DOS_NT
1041 && !is_escaped /* don't expand ~ in escaped file names */
1042 #endif
1045 if (IS_DIRECTORY_SEP (nm[1])
1046 || nm[1] == 0) /* ~ by itself */
1048 Lisp_Object tem;
1050 if (!(newdir = egetenv ("HOME")))
1051 newdir = newdirlim = "";
1052 nm++;
1053 #ifdef WINDOWSNT
1054 if (newdir[0])
1056 char newdir_utf8[MAX_UTF8_PATH];
1058 filename_from_ansi (newdir, newdir_utf8);
1059 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1060 newdir = SSDATA (tem);
1062 else
1063 #endif
1064 tem = build_string (newdir);
1065 newdirlim = newdir + SBYTES (tem);
1066 /* `egetenv' may return a unibyte string, which will bite us
1067 if we expect the directory to be multibyte. */
1068 if (multibyte && !STRING_MULTIBYTE (tem))
1070 hdir = DECODE_FILE (tem);
1071 newdir = SSDATA (hdir);
1072 newdirlim = newdir + SBYTES (hdir);
1074 #ifdef DOS_NT
1075 collapse_newdir = false;
1076 #endif
1078 else /* ~user/filename */
1080 char *o, *p;
1081 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1082 continue;
1083 o = SAFE_ALLOCA (p - nm + 1);
1084 memcpy (o, nm, p - nm);
1085 o[p - nm] = 0;
1087 block_input ();
1088 pw = getpwnam (o + 1);
1089 unblock_input ();
1090 if (pw)
1092 Lisp_Object tem;
1094 newdir = pw->pw_dir;
1095 /* `getpwnam' may return a unibyte string, which will
1096 bite us when we expect the directory to be multibyte. */
1097 tem = make_unibyte_string (newdir, strlen (newdir));
1098 newdirlim = newdir + SBYTES (tem);
1099 if (multibyte && !STRING_MULTIBYTE (tem))
1101 hdir = DECODE_FILE (tem);
1102 newdir = SSDATA (hdir);
1103 newdirlim = newdir + SBYTES (hdir);
1105 nm = p;
1106 #ifdef DOS_NT
1107 collapse_newdir = false;
1108 #endif
1111 /* If we don't find a user of that name, leave the name
1112 unchanged; don't move nm forward to p. */
1116 #ifdef DOS_NT
1117 /* On DOS and Windows, nm is absolute if a drive name was specified;
1118 use the drive's current directory as the prefix if needed. */
1119 if (!newdir && drive)
1121 /* Get default directory if needed to make nm absolute. */
1122 char *adir = NULL;
1123 if (!IS_DIRECTORY_SEP (nm[0]))
1125 adir = alloca (MAXPATHLEN + 1);
1126 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1127 adir = NULL;
1128 else if (multibyte)
1130 Lisp_Object tem = build_string (adir);
1132 tem = DECODE_FILE (tem);
1133 newdirlim = adir + SBYTES (tem);
1134 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1136 else
1137 newdirlim = adir + strlen (adir);
1139 if (!adir)
1141 /* Either nm starts with /, or drive isn't mounted. */
1142 adir = alloca (4);
1143 adir[0] = DRIVE_LETTER (drive);
1144 adir[1] = ':';
1145 adir[2] = '/';
1146 adir[3] = 0;
1147 newdirlim = adir + 3;
1149 newdir = adir;
1151 #endif /* DOS_NT */
1153 /* Finally, if no prefix has been specified and nm is not absolute,
1154 then it must be expanded relative to default_directory. */
1156 if (1
1157 #ifndef DOS_NT
1158 /* /... alone is not absolute on DOS and Windows. */
1159 && !IS_DIRECTORY_SEP (nm[0])
1160 #endif
1161 #ifdef WINDOWSNT
1162 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1163 && !IS_DIRECTORY_SEP (nm[2]))
1164 #endif
1165 && !newdir)
1167 newdir = SSDATA (default_directory);
1168 newdirlim = newdir + SBYTES (default_directory);
1169 #ifdef DOS_NT
1170 /* Note if special escape prefix is present, but remove for now. */
1171 if (newdir[0] == '/' && newdir[1] == ':')
1173 is_escaped = 1;
1174 newdir += 2;
1176 #endif
1179 #ifdef DOS_NT
1180 if (newdir)
1182 /* First ensure newdir is an absolute name. */
1183 if (
1184 /* Detect MSDOS file names with drive specifiers. */
1185 ! (IS_DRIVE (newdir[0])
1186 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1187 #ifdef WINDOWSNT
1188 /* Detect Windows file names in UNC format. */
1189 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1190 && !IS_DIRECTORY_SEP (newdir[2]))
1191 #endif
1194 /* Effectively, let newdir be (expand-file-name newdir cwd).
1195 Because of the admonition against calling expand-file-name
1196 when we have pointers into lisp strings, we accomplish this
1197 indirectly by prepending newdir to nm if necessary, and using
1198 cwd (or the wd of newdir's drive) as the new newdir. */
1199 char *adir;
1200 #ifdef WINDOWSNT
1201 const int adir_size = MAX_UTF8_PATH;
1202 #else
1203 const int adir_size = MAXPATHLEN + 1;
1204 #endif
1206 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1208 drive = (unsigned char) newdir[0];
1209 newdir += 2;
1211 if (!IS_DIRECTORY_SEP (nm[0]))
1213 ptrdiff_t nmlen = nmlim - nm;
1214 ptrdiff_t newdirlen = newdirlim - newdir;
1215 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1216 + nmlen + 1);
1217 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1218 multibyte);
1219 memcpy (tmp + dlen, nm, nmlen + 1);
1220 nm = tmp;
1221 nmlim = nm + dlen + nmlen;
1223 adir = alloca (adir_size);
1224 if (drive)
1226 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1227 strcpy (adir, "/");
1229 else
1230 getcwd (adir, adir_size);
1231 if (multibyte)
1233 Lisp_Object tem = build_string (adir);
1235 tem = DECODE_FILE (tem);
1236 newdirlim = adir + SBYTES (tem);
1237 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1239 else
1240 newdirlim = adir + strlen (adir);
1241 newdir = adir;
1244 /* Strip off drive name from prefix, if present. */
1245 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1247 drive = newdir[0];
1248 newdir += 2;
1251 /* Keep only a prefix from newdir if nm starts with slash
1252 (//server/share for UNC, nothing otherwise). */
1253 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1255 #ifdef WINDOWSNT
1256 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1257 && !IS_DIRECTORY_SEP (newdir[2]))
1259 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1260 char *p = adir + 2;
1261 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1262 p++;
1263 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1264 *p = 0;
1265 newdir = adir;
1266 newdirlim = newdir + strlen (adir);
1268 else
1269 #endif
1270 newdir = newdirlim = "";
1273 #endif /* DOS_NT */
1275 /* Ignore any slash at the end of newdir, unless newdir is
1276 just "/" or "//". */
1277 length = newdirlim - newdir;
1278 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1279 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1280 length--;
1282 /* Now concatenate the directory and name to new space in the stack frame. */
1283 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1284 eassert (tlen > file_name_as_directory_slop + 1);
1285 #ifdef DOS_NT
1286 /* Reserve space for drive specifier and escape prefix, since either
1287 or both may need to be inserted. (The Microsoft x86 compiler
1288 produces incorrect code if the following two lines are combined.) */
1289 target = alloca (tlen + 4);
1290 target += 4;
1291 #else /* not DOS_NT */
1292 target = SAFE_ALLOCA (tlen);
1293 #endif /* not DOS_NT */
1294 *target = 0;
1295 nbytes = 0;
1297 if (newdir)
1299 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1301 #ifdef DOS_NT
1302 /* If newdir is effectively "C:/", then the drive letter will have
1303 been stripped and newdir will be "/". Concatenating with an
1304 absolute directory in nm produces "//", which will then be
1305 incorrectly treated as a network share. Ignore newdir in
1306 this case (keeping the drive letter). */
1307 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1308 && newdir[1] == '\0'))
1309 #endif
1311 memcpy (target, newdir, length);
1312 target[length] = 0;
1313 nbytes = length;
1316 else
1317 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1320 memcpy (target + nbytes, nm, nmlim - nm + 1);
1322 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1323 appear. */
1325 char *p = target;
1326 char *o = target;
1328 while (*p)
1330 if (!IS_DIRECTORY_SEP (*p))
1332 *o++ = *p++;
1334 else if (p[1] == '.'
1335 && (IS_DIRECTORY_SEP (p[2])
1336 || p[2] == 0))
1338 /* If "/." is the entire filename, keep the "/". Otherwise,
1339 just delete the whole "/.". */
1340 if (o == target && p[2] == '\0')
1341 *o++ = *p;
1342 p += 2;
1344 else if (p[1] == '.' && p[2] == '.'
1345 /* `/../' is the "superroot" on certain file systems.
1346 Turned off on DOS_NT systems because they have no
1347 "superroot" and because this causes us to produce
1348 file names like "d:/../foo" which fail file-related
1349 functions of the underlying OS. (To reproduce, try a
1350 long series of "../../" in default_directory, longer
1351 than the number of levels from the root.) */
1352 #ifndef DOS_NT
1353 && o != target
1354 #endif
1355 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1357 #ifdef WINDOWSNT
1358 char *prev_o = o;
1359 #endif
1360 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1361 continue;
1362 #ifdef WINDOWSNT
1363 /* Don't go below server level in UNC filenames. */
1364 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1365 && IS_DIRECTORY_SEP (*target))
1366 o = prev_o;
1367 else
1368 #endif
1369 /* Keep initial / only if this is the whole name. */
1370 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1371 ++o;
1372 p += 3;
1374 else if (IS_DIRECTORY_SEP (p[1])
1375 && (p != target || IS_DIRECTORY_SEP (p[2])))
1376 /* Collapse multiple "/", except leave leading "//" alone. */
1377 p++;
1378 else
1380 *o++ = *p++;
1384 #ifdef DOS_NT
1385 /* At last, set drive name. */
1386 #ifdef WINDOWSNT
1387 /* Except for network file name. */
1388 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1389 #endif /* WINDOWSNT */
1391 if (!drive) emacs_abort ();
1392 target -= 2;
1393 target[0] = DRIVE_LETTER (drive);
1394 target[1] = ':';
1396 /* Reinsert the escape prefix if required. */
1397 if (is_escaped)
1399 target -= 2;
1400 target[0] = '/';
1401 target[1] = ':';
1403 result = make_specified_string (target, -1, o - target, multibyte);
1404 dostounix_filename (SSDATA (result));
1405 #ifdef WINDOWSNT
1406 if (!NILP (Vw32_downcase_file_names))
1407 result = Fdowncase (result);
1408 #endif
1409 #else /* !DOS_NT */
1410 result = make_specified_string (target, -1, o - target, multibyte);
1411 #endif /* !DOS_NT */
1414 /* Again look to see if the file name has special constructs in it
1415 and perhaps call the corresponding file handler. This is needed
1416 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1417 the ".." component gives us "/user@host:/bar/../baz" which needs
1418 to be expanded again. */
1419 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1420 if (!NILP (handler))
1422 handled_name = call3 (handler, Qexpand_file_name,
1423 result, default_directory);
1424 if (! STRINGP (handled_name))
1425 error ("Invalid handler in `file-name-handler-alist'");
1426 result = handled_name;
1429 SAFE_FREE ();
1430 return result;
1433 #if 0
1434 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1435 This is the old version of expand-file-name, before it was thoroughly
1436 rewritten for Emacs 10.31. We leave this version here commented-out,
1437 because the code is very complex and likely to have subtle bugs. If
1438 bugs _are_ found, it might be of interest to look at the old code and
1439 see what did it do in the relevant situation.
1441 Don't remove this code: it's true that it will be accessible
1442 from the repository, but a few years from deletion, people will
1443 forget it is there. */
1445 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1446 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1447 "Convert FILENAME to absolute, and canonicalize it.\n\
1448 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1449 \(does not start with slash); if DEFAULT is nil or missing,\n\
1450 the current buffer's value of default-directory is used.\n\
1451 Filenames containing `.' or `..' as components are simplified;\n\
1452 initial `~/' expands to your home directory.\n\
1453 See also the function `substitute-in-file-name'.")
1454 (name, defalt)
1455 Lisp_Object name, defalt;
1457 unsigned char *nm;
1459 register unsigned char *newdir, *p, *o;
1460 ptrdiff_t tlen;
1461 unsigned char *target;
1462 struct passwd *pw;
1464 CHECK_STRING (name);
1465 nm = SDATA (name);
1467 /* If nm is absolute, flush ...// and detect /./ and /../.
1468 If no /./ or /../ we can return right away. */
1469 if (nm[0] == '/')
1471 bool lose = 0;
1472 p = nm;
1473 while (*p)
1475 if (p[0] == '/' && p[1] == '/')
1476 nm = p + 1;
1477 if (p[0] == '/' && p[1] == '~')
1478 nm = p + 1, lose = 1;
1479 if (p[0] == '/' && p[1] == '.'
1480 && (p[2] == '/' || p[2] == 0
1481 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1482 lose = 1;
1483 p++;
1485 if (!lose)
1487 if (nm == SDATA (name))
1488 return name;
1489 return build_string (nm);
1493 /* Now determine directory to start with and put it in NEWDIR. */
1495 newdir = 0;
1497 if (nm[0] == '~') /* prefix ~ */
1498 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1500 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1501 newdir = (unsigned char *) "";
1502 nm++;
1504 else /* ~user/filename */
1506 /* Get past ~ to user. */
1507 unsigned char *user = nm + 1;
1508 /* Find end of name. */
1509 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1510 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1511 /* Copy the user name into temp storage. */
1512 o = alloca (len + 1);
1513 memcpy (o, user, len);
1514 o[len] = 0;
1516 /* Look up the user name. */
1517 block_input ();
1518 pw = (struct passwd *) getpwnam (o + 1);
1519 unblock_input ();
1520 if (!pw)
1521 error ("\"%s\" isn't a registered user", o + 1);
1523 newdir = (unsigned char *) pw->pw_dir;
1525 /* Discard the user name from NM. */
1526 nm += len;
1529 if (nm[0] != '/' && !newdir)
1531 if (NILP (defalt))
1532 defalt = current_buffer->directory;
1533 CHECK_STRING (defalt);
1534 newdir = SDATA (defalt);
1537 /* Now concatenate the directory and name to new space in the stack frame. */
1539 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1540 target = alloca (tlen);
1541 *target = 0;
1543 if (newdir)
1545 if (nm[0] == 0 || nm[0] == '/')
1546 strcpy (target, newdir);
1547 else
1548 file_name_as_directory (target, newdir);
1551 strcat (target, nm);
1553 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1555 p = target;
1556 o = target;
1558 while (*p)
1560 if (*p != '/')
1562 *o++ = *p++;
1564 else if (!strncmp (p, "//", 2)
1567 o = target;
1568 p++;
1570 else if (p[0] == '/' && p[1] == '.'
1571 && (p[2] == '/' || p[2] == 0))
1572 p += 2;
1573 else if (!strncmp (p, "/..", 3)
1574 /* `/../' is the "superroot" on certain file systems. */
1575 && o != target
1576 && (p[3] == '/' || p[3] == 0))
1578 while (o != target && *--o != '/')
1580 if (o == target && *o == '/')
1581 ++o;
1582 p += 3;
1584 else
1586 *o++ = *p++;
1590 return make_string (target, o - target);
1592 #endif
1594 /* If /~ or // appears, discard everything through first slash. */
1595 static bool
1596 file_name_absolute_p (const char *filename)
1598 return
1599 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1600 #ifdef DOS_NT
1601 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1602 && IS_DIRECTORY_SEP (filename[2]))
1603 #endif
1607 static char *
1608 search_embedded_absfilename (char *nm, char *endp)
1610 char *p, *s;
1612 for (p = nm + 1; p < endp; p++)
1614 if (IS_DIRECTORY_SEP (p[-1])
1615 && file_name_absolute_p (p)
1616 #if defined (WINDOWSNT) || defined (CYGWIN)
1617 /* // at start of file name is meaningful in Apollo,
1618 WindowsNT and Cygwin systems. */
1619 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1620 #endif /* not (WINDOWSNT || CYGWIN) */
1623 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1624 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1626 USE_SAFE_ALLOCA;
1627 char *o = SAFE_ALLOCA (s - p + 1);
1628 struct passwd *pw;
1629 memcpy (o, p, s - p);
1630 o [s - p] = 0;
1632 /* If we have ~user and `user' exists, discard
1633 everything up to ~. But if `user' does not exist, leave
1634 ~user alone, it might be a literal file name. */
1635 block_input ();
1636 pw = getpwnam (o + 1);
1637 unblock_input ();
1638 SAFE_FREE ();
1639 if (pw)
1640 return p;
1642 else
1643 return p;
1646 return NULL;
1649 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1650 Ssubstitute_in_file_name, 1, 1, 0,
1651 doc: /* Substitute environment variables referred to in FILENAME.
1652 `$FOO' where FOO is an environment variable name means to substitute
1653 the value of that variable. The variable name should be terminated
1654 with a character not a letter, digit or underscore; otherwise, enclose
1655 the entire variable name in braces.
1657 If `/~' appears, all of FILENAME through that `/' is discarded.
1658 If `//' appears, everything up to and including the first of
1659 those `/' is discarded. */)
1660 (Lisp_Object filename)
1662 char *nm, *p, *x, *endp;
1663 bool substituted = false;
1664 bool multibyte;
1665 char *xnm;
1666 Lisp_Object handler;
1668 CHECK_STRING (filename);
1670 multibyte = STRING_MULTIBYTE (filename);
1672 /* If the file name has special constructs in it,
1673 call the corresponding file handler. */
1674 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1675 if (!NILP (handler))
1677 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1678 filename);
1679 if (STRINGP (handled_name))
1680 return handled_name;
1681 error ("Invalid handler in `file-name-handler-alist'");
1684 /* Always work on a copy of the string, in case GC happens during
1685 decode of environment variables, causing the original Lisp_String
1686 data to be relocated. */
1687 USE_SAFE_ALLOCA;
1688 SAFE_ALLOCA_STRING (nm, filename);
1690 #ifdef DOS_NT
1691 dostounix_filename (nm);
1692 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1693 #endif
1694 endp = nm + SBYTES (filename);
1696 /* If /~ or // appears, discard everything through first slash. */
1697 p = search_embedded_absfilename (nm, endp);
1698 if (p)
1699 /* Start over with the new string, so we check the file-name-handler
1700 again. Important with filenames like "/home/foo//:/hello///there"
1701 which would substitute to "/:/hello///there" rather than "/there". */
1703 Lisp_Object result
1704 = (Fsubstitute_in_file_name
1705 (make_specified_string (p, -1, endp - p, multibyte)));
1706 SAFE_FREE ();
1707 return result;
1710 /* See if any variables are substituted into the string. */
1712 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1714 Lisp_Object name
1715 = (!substituted ? filename
1716 : make_specified_string (nm, -1, endp - nm, multibyte));
1717 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1718 CHECK_STRING (tmp);
1719 if (!EQ (tmp, name))
1720 substituted = true;
1721 filename = tmp;
1724 if (!substituted)
1726 #ifdef WINDOWSNT
1727 if (!NILP (Vw32_downcase_file_names))
1728 filename = Fdowncase (filename);
1729 #endif
1730 SAFE_FREE ();
1731 return filename;
1734 xnm = SSDATA (filename);
1735 x = xnm + SBYTES (filename);
1737 /* If /~ or // appears, discard everything through first slash. */
1738 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1739 /* This time we do not start over because we've already expanded envvars
1740 and replaced $$ with $. Maybe we should start over as well, but we'd
1741 need to quote some $ to $$ first. */
1742 xnm = p;
1744 #ifdef WINDOWSNT
1745 if (!NILP (Vw32_downcase_file_names))
1747 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1749 filename = Fdowncase (xname);
1751 else
1752 #endif
1753 if (xnm != SSDATA (filename))
1754 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1755 SAFE_FREE ();
1756 return filename;
1759 /* A slightly faster and more convenient way to get
1760 (directory-file-name (expand-file-name FOO)). */
1762 Lisp_Object
1763 expand_and_dir_to_file (Lisp_Object filename)
1765 Lisp_Object absname = Fexpand_file_name (filename, Qnil);
1767 /* Remove final slash, if any (unless this is the root dir).
1768 stat behaves differently depending! */
1769 if (SCHARS (absname) > 1
1770 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1771 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1772 /* We cannot take shortcuts; they might be wrong for magic file names. */
1773 absname = Fdirectory_file_name (absname);
1774 return absname;
1777 /* Signal an error if the file ABSNAME already exists.
1778 If KNOWN_TO_EXIST, the file is known to exist.
1779 QUERYSTRING is a name for the action that is being considered
1780 to alter the file.
1781 If INTERACTIVE, ask the user whether to proceed,
1782 and bypass the error if the user says to go ahead.
1783 If QUICK, ask for y or n, not yes or no. */
1785 static void
1786 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1787 const char *querystring, bool interactive,
1788 bool quick)
1790 Lisp_Object tem, encoded_filename;
1791 struct stat statbuf;
1793 encoded_filename = ENCODE_FILE (absname);
1795 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1797 if (S_ISDIR (statbuf.st_mode))
1798 xsignal2 (Qfile_error,
1799 build_string ("File is a directory"), absname);
1800 known_to_exist = true;
1803 if (known_to_exist)
1805 if (! interactive)
1806 xsignal2 (Qfile_already_exists,
1807 build_string ("File already exists"), absname);
1808 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1809 tem = CALLN (Fformat, format, absname, build_string (querystring));
1810 if (quick)
1811 tem = call1 (intern ("y-or-n-p"), tem);
1812 else
1813 tem = do_yes_or_no_p (tem);
1814 if (NILP (tem))
1815 xsignal2 (Qfile_already_exists,
1816 build_string ("File already exists"), absname);
1820 #ifndef WINDOWSNT
1821 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1822 static bool
1823 clone_file (int dest, int source)
1825 #ifdef FICLONE
1826 return ioctl (dest, FICLONE, source) == 0;
1827 #endif
1828 return false;
1830 #endif
1832 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1833 "fCopy file: \nGCopy %s to file: \np\nP",
1834 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1835 If NEWNAME names a directory, copy FILE there.
1837 This function always sets the file modes of the output file to match
1838 the input file.
1840 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1841 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1842 signal a `file-already-exists' error without overwriting. If
1843 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1844 about overwriting; this is what happens in interactive use with M-x.
1845 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1846 existing file.
1848 Fourth arg KEEP-TIME non-nil means give the output file the same
1849 last-modified time as the old one. (This works on only some systems.)
1851 A prefix arg makes KEEP-TIME non-nil.
1853 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1854 FILE to NEWNAME.
1856 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1857 this includes the file modes, along with ACL entries and SELinux
1858 context if present. Otherwise, if NEWNAME is created its file
1859 permission bits are those of FILE, masked by the default file
1860 permissions. */)
1861 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1862 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1863 Lisp_Object preserve_permissions)
1865 Lisp_Object handler;
1866 ptrdiff_t count = SPECPDL_INDEX ();
1867 Lisp_Object encoded_file, encoded_newname;
1868 #if HAVE_LIBSELINUX
1869 security_context_t con;
1870 int conlength = 0;
1871 #endif
1872 #ifdef WINDOWSNT
1873 int result;
1874 #else
1875 bool already_exists = false;
1876 mode_t new_mask;
1877 int ifd, ofd;
1878 struct stat st;
1879 #endif
1881 file = Fexpand_file_name (file, Qnil);
1882 newname = expand_cp_target (file, newname);
1884 /* If the input file name has special constructs in it,
1885 call the corresponding file handler. */
1886 handler = Ffind_file_name_handler (file, Qcopy_file);
1887 /* Likewise for output file name. */
1888 if (NILP (handler))
1889 handler = Ffind_file_name_handler (newname, Qcopy_file);
1890 if (!NILP (handler))
1891 return call7 (handler, Qcopy_file, file, newname,
1892 ok_if_already_exists, keep_time, preserve_uid_gid,
1893 preserve_permissions);
1895 encoded_file = ENCODE_FILE (file);
1896 encoded_newname = ENCODE_FILE (newname);
1898 #ifdef WINDOWSNT
1899 if (NILP (ok_if_already_exists)
1900 || INTEGERP (ok_if_already_exists))
1901 barf_or_query_if_file_exists (newname, false, "copy to it",
1902 INTEGERP (ok_if_already_exists), false);
1904 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1905 !NILP (keep_time), !NILP (preserve_uid_gid),
1906 !NILP (preserve_permissions));
1907 switch (result)
1909 case -1:
1910 report_file_error ("Copying file", list2 (file, newname));
1911 case -2:
1912 report_file_error ("Copying permissions from", file);
1913 case -3:
1914 xsignal2 (Qfile_date_error,
1915 build_string ("Resetting file times"), newname);
1916 case -4:
1917 report_file_error ("Copying permissions to", newname);
1919 #else /* not WINDOWSNT */
1920 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1922 if (ifd < 0)
1923 report_file_error ("Opening input file", file);
1925 record_unwind_protect_int (close_file_unwind, ifd);
1927 if (fstat (ifd, &st) != 0)
1928 report_file_error ("Input file status", file);
1930 if (!NILP (preserve_permissions))
1932 #if HAVE_LIBSELINUX
1933 if (is_selinux_enabled ())
1935 conlength = fgetfilecon (ifd, &con);
1936 if (conlength == -1)
1937 report_file_error ("Doing fgetfilecon", file);
1939 #endif
1942 /* We can copy only regular files. */
1943 if (!S_ISREG (st.st_mode))
1944 report_file_errno ("Non-regular file", file,
1945 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1947 #ifndef MSDOS
1948 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1949 #else
1950 new_mask = S_IREAD | S_IWRITE;
1951 #endif
1953 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1954 new_mask);
1955 if (ofd < 0 && errno == EEXIST)
1957 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1958 barf_or_query_if_file_exists (newname, true, "copy to it",
1959 INTEGERP (ok_if_already_exists), false);
1960 already_exists = true;
1961 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1963 if (ofd < 0)
1964 report_file_error ("Opening output file", newname);
1966 record_unwind_protect_int (close_file_unwind, ofd);
1968 off_t oldsize = 0, newsize;
1970 if (already_exists)
1972 struct stat out_st;
1973 if (fstat (ofd, &out_st) != 0)
1974 report_file_error ("Output file status", newname);
1975 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1976 report_file_errno ("Input and output files are the same",
1977 list2 (file, newname), 0);
1978 if (S_ISREG (out_st.st_mode))
1979 oldsize = out_st.st_size;
1982 maybe_quit ();
1984 if (clone_file (ofd, ifd))
1985 newsize = st.st_size;
1986 else
1988 char buf[MAX_ALLOCA];
1989 ptrdiff_t n;
1990 for (newsize = 0; 0 < (n = emacs_read_quit (ifd, buf, sizeof buf));
1991 newsize += n)
1992 if (emacs_write_quit (ofd, buf, n) != n)
1993 report_file_error ("Write error", newname);
1994 if (n < 0)
1995 report_file_error ("Read error", file);
1998 /* Truncate any existing output file after writing the data. This
1999 is more likely to work than truncation before writing, if the
2000 file system is out of space or the user is over disk quota. */
2001 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2002 report_file_error ("Truncating output file", newname);
2004 #ifndef MSDOS
2005 /* Preserve the original file permissions, and if requested, also its
2006 owner and group. */
2008 mode_t preserved_permissions = st.st_mode & 07777;
2009 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2010 if (!NILP (preserve_uid_gid))
2012 /* Attempt to change owner and group. If that doesn't work
2013 attempt to change just the group, as that is sometimes allowed.
2014 Adjust the mode mask to eliminate setuid or setgid bits
2015 or group permissions bits that are inappropriate if the
2016 owner or group are wrong. */
2017 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2019 if (fchown (ofd, -1, st.st_gid) == 0)
2020 preserved_permissions &= ~04000;
2021 else
2023 preserved_permissions &= ~06000;
2025 /* Copy the other bits to the group bits, since the
2026 group is wrong. */
2027 preserved_permissions &= ~070;
2028 preserved_permissions |= (preserved_permissions & 7) << 3;
2029 default_permissions &= ~070;
2030 default_permissions |= (default_permissions & 7) << 3;
2035 switch (!NILP (preserve_permissions)
2036 ? qcopy_acl (SSDATA (encoded_file), ifd,
2037 SSDATA (encoded_newname), ofd,
2038 preserved_permissions)
2039 : (already_exists
2040 || (new_mask & ~realmask) == default_permissions)
2042 : fchmod (ofd, default_permissions))
2044 case -2: report_file_error ("Copying permissions from", file);
2045 case -1: report_file_error ("Copying permissions to", newname);
2048 #endif /* not MSDOS */
2050 #if HAVE_LIBSELINUX
2051 if (conlength > 0)
2053 /* Set the modified context back to the file. */
2054 bool fail = fsetfilecon (ofd, con) != 0;
2055 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2056 if (fail && errno != ENOTSUP)
2057 report_file_error ("Doing fsetfilecon", newname);
2059 freecon (con);
2061 #endif
2063 if (!NILP (keep_time))
2065 struct timespec atime = get_stat_atime (&st);
2066 struct timespec mtime = get_stat_mtime (&st);
2067 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2068 xsignal2 (Qfile_date_error,
2069 build_string ("Cannot set file date"), newname);
2072 if (emacs_close (ofd) < 0)
2073 report_file_error ("Write error", newname);
2075 emacs_close (ifd);
2077 #ifdef MSDOS
2078 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2079 and if it can't, it tells so. Otherwise, under MSDOS we usually
2080 get only the READ bit, which will make the copied file read-only,
2081 so it's better not to chmod at all. */
2082 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2083 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2084 #endif /* MSDOS */
2085 #endif /* not WINDOWSNT */
2087 /* Discard the unwind protects. */
2088 specpdl_ptr = specpdl + count;
2090 return Qnil;
2093 DEFUN ("make-directory-internal", Fmake_directory_internal,
2094 Smake_directory_internal, 1, 1, 0,
2095 doc: /* Create a new directory named DIRECTORY. */)
2096 (Lisp_Object directory)
2098 const char *dir;
2099 Lisp_Object handler;
2100 Lisp_Object encoded_dir;
2102 CHECK_STRING (directory);
2103 directory = Fexpand_file_name (directory, Qnil);
2105 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2106 if (!NILP (handler))
2107 return call2 (handler, Qmake_directory_internal, directory);
2109 encoded_dir = ENCODE_FILE (directory);
2111 dir = SSDATA (encoded_dir);
2113 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2114 report_file_error ("Creating directory", directory);
2116 return Qnil;
2119 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2120 Sdelete_directory_internal, 1, 1, 0,
2121 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2122 (Lisp_Object directory)
2124 const char *dir;
2125 Lisp_Object encoded_dir;
2127 CHECK_STRING (directory);
2128 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2129 encoded_dir = ENCODE_FILE (directory);
2130 dir = SSDATA (encoded_dir);
2132 if (rmdir (dir) != 0)
2133 report_file_error ("Removing directory", directory);
2135 return Qnil;
2138 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2139 "(list (read-file-name \
2140 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2141 \"Move file to trash: \" \"Delete file: \") \
2142 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2143 (null current-prefix-arg))",
2144 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2145 If file has multiple names, it continues to exist with the other names.
2146 TRASH non-nil means to trash the file instead of deleting, provided
2147 `delete-by-moving-to-trash' is non-nil.
2149 When called interactively, TRASH is t if no prefix argument is given.
2150 With a prefix argument, TRASH is nil. */)
2151 (Lisp_Object filename, Lisp_Object trash)
2153 Lisp_Object handler;
2154 Lisp_Object encoded_file;
2156 if (!NILP (Ffile_directory_p (filename))
2157 && NILP (Ffile_symlink_p (filename)))
2158 xsignal2 (Qfile_error,
2159 build_string ("Removing old name: is a directory"),
2160 filename);
2161 filename = Fexpand_file_name (filename, Qnil);
2163 handler = Ffind_file_name_handler (filename, Qdelete_file);
2164 if (!NILP (handler))
2165 return call3 (handler, Qdelete_file, filename, trash);
2167 if (delete_by_moving_to_trash && !NILP (trash))
2168 return call1 (Qmove_file_to_trash, filename);
2170 encoded_file = ENCODE_FILE (filename);
2172 if (unlink (SSDATA (encoded_file)) != 0 && errno != ENOENT)
2173 report_file_error ("Removing old name", filename);
2174 return Qnil;
2177 static Lisp_Object
2178 internal_delete_file_1 (Lisp_Object ignore)
2180 return Qt;
2183 /* Delete file FILENAME, returning true if successful.
2184 This ignores `delete-by-moving-to-trash'. */
2186 bool
2187 internal_delete_file (Lisp_Object filename)
2189 Lisp_Object tem;
2191 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2192 Qt, internal_delete_file_1);
2193 return NILP (tem);
2196 /* Filesystems are case-sensitive on all supported systems except
2197 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2198 case-insensitive on the first two, but they may or may not be
2199 case-insensitive on Cygwin and OS X. The following function
2200 attempts to provide a runtime test on those two systems. If the
2201 test is not conclusive, we assume case-insensitivity on Cygwin and
2202 case-sensitivity on Mac OS X.
2204 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2205 NFS-mounted Windows volumes, might be case-insensitive. Can we
2206 detect this? */
2208 static bool
2209 file_name_case_insensitive_p (const char *filename)
2211 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2212 those flags are available. As of this writing (2017-05-20),
2213 Cygwin is the only platform known to support the former (starting
2214 with Cygwin-2.6.1), and macOS is the only platform known to
2215 support the latter. */
2217 #ifdef _PC_CASE_INSENSITIVE
2218 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2219 if (res >= 0)
2220 return res > 0;
2221 #elif defined _PC_CASE_SENSITIVE
2222 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2223 if (res >= 0)
2224 return res == 0;
2225 #endif
2227 #if defined CYGWIN || defined DOS_NT
2228 return true;
2229 #else
2230 return false;
2231 #endif
2234 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2235 Sfile_name_case_insensitive_p, 1, 1, 0,
2236 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2237 The arg must be a string. */)
2238 (Lisp_Object filename)
2240 Lisp_Object handler;
2242 CHECK_STRING (filename);
2243 filename = Fexpand_file_name (filename, Qnil);
2245 /* If the file name has special constructs in it,
2246 call the corresponding file handler. */
2247 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2248 if (!NILP (handler))
2249 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2251 filename = ENCODE_FILE (filename);
2252 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2255 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2256 "fRename file: \nGRename %s to file: \np",
2257 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2258 If file has names other than FILE, it continues to have those names.
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, symlink_target;
2267 int dirp = -1;
2269 file = Fexpand_file_name (file, Qnil);
2271 /* If the filesystem is case-insensitive and the file names are
2272 identical but for case, treat it as a change-case request, and do
2273 not worry whether NEWNAME exists or whether it is a directory, as
2274 it is already another name for FILE. */
2275 bool case_only_rename = false;
2276 #if defined CYGWIN || defined DOS_NT
2277 if (!NILP (Ffile_name_case_insensitive_p (file)))
2279 newname = Fexpand_file_name (newname, Qnil);
2280 case_only_rename = !NILP (Fstring_equal (Fdowncase (file),
2281 Fdowncase (newname)));
2283 #endif
2285 if (!case_only_rename)
2286 newname = expand_cp_target (Fdirectory_file_name (file), newname);
2288 /* If the file name has special constructs in it,
2289 call the corresponding file handler. */
2290 handler = Ffind_file_name_handler (file, Qrename_file);
2291 if (NILP (handler))
2292 handler = Ffind_file_name_handler (newname, Qrename_file);
2293 if (!NILP (handler))
2294 return call4 (handler, Qrename_file,
2295 file, newname, ok_if_already_exists);
2297 encoded_file = ENCODE_FILE (file);
2298 encoded_newname = ENCODE_FILE (newname);
2300 bool plain_rename = (case_only_rename
2301 || (!NILP (ok_if_already_exists)
2302 && !INTEGERP (ok_if_already_exists)));
2303 int rename_errno;
2304 if (!plain_rename)
2306 if (renameat_noreplace (AT_FDCWD, SSDATA (encoded_file),
2307 AT_FDCWD, SSDATA (encoded_newname))
2308 == 0)
2309 return Qnil;
2311 rename_errno = errno;
2312 switch (rename_errno)
2314 case EEXIST: case EINVAL: case ENOSYS:
2315 #if ENOSYS != ENOTSUP
2316 case ENOTSUP:
2317 #endif
2318 barf_or_query_if_file_exists (newname, rename_errno == EEXIST,
2319 "rename to it",
2320 INTEGERP (ok_if_already_exists),
2321 false);
2322 plain_rename = true;
2323 break;
2327 if (plain_rename)
2329 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2330 return Qnil;
2331 rename_errno = errno;
2332 /* Don't prompt again. */
2333 ok_if_already_exists = Qt;
2335 else if (!NILP (ok_if_already_exists))
2336 ok_if_already_exists = Qt;
2338 if (rename_errno != EXDEV)
2339 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2341 symlink_target = Ffile_symlink_p (file);
2342 if (!NILP (symlink_target))
2343 Fmake_symbolic_link (symlink_target, newname, ok_if_already_exists);
2344 else
2346 if (dirp < 0)
2347 dirp = directory_like (file);
2348 if (dirp)
2349 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2350 else
2351 Fcopy_file (file, newname, ok_if_already_exists, Qt, Qt, Qt);
2354 ptrdiff_t count = SPECPDL_INDEX ();
2355 specbind (Qdelete_by_moving_to_trash, Qnil);
2356 if (dirp && NILP (symlink_target))
2357 call2 (Qdelete_directory, file, Qt);
2358 else
2359 Fdelete_file (file, Qnil);
2360 return unbind_to (count, Qnil);
2363 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2364 "fAdd name to file: \nGName to add to %s: \np",
2365 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2366 Signal a `file-already-exists' error if a file NEWNAME already exists
2367 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2368 An integer third arg means request confirmation if NEWNAME already exists.
2369 This is what happens in interactive use with M-x. */)
2370 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2372 Lisp_Object handler;
2373 Lisp_Object encoded_file, encoded_newname;
2375 file = Fexpand_file_name (file, Qnil);
2376 newname = expand_cp_target (file, newname);
2378 /* If the file name has special constructs in it,
2379 call the corresponding file handler. */
2380 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2381 if (!NILP (handler))
2382 return call4 (handler, Qadd_name_to_file, file,
2383 newname, ok_if_already_exists);
2385 /* If the new name has special constructs in it,
2386 call the corresponding file handler. */
2387 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2388 if (!NILP (handler))
2389 return call4 (handler, Qadd_name_to_file, file,
2390 newname, ok_if_already_exists);
2392 encoded_file = ENCODE_FILE (file);
2393 encoded_newname = ENCODE_FILE (newname);
2395 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2396 return Qnil;
2398 if (errno == EEXIST)
2400 if (NILP (ok_if_already_exists)
2401 || INTEGERP (ok_if_already_exists))
2402 barf_or_query_if_file_exists (newname, true, "make it a new name",
2403 INTEGERP (ok_if_already_exists), false);
2404 unlink (SSDATA (newname));
2405 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2406 return Qnil;
2409 report_file_error ("Adding new name", list2 (file, newname));
2412 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2413 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2414 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2415 Both args must be strings.
2416 Signal a `file-already-exists' error if a file LINKNAME already exists
2417 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2418 An integer third arg means request confirmation if LINKNAME already
2419 exists, and expand leading "~" or strip leading "/:" in TARGET.
2420 This happens for interactive use with M-x. */)
2421 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2423 Lisp_Object handler;
2424 Lisp_Object encoded_target, encoded_linkname;
2426 CHECK_STRING (target);
2427 if (INTEGERP (ok_if_already_exists))
2429 if (SREF (target, 0) == '~')
2430 target = Fexpand_file_name (target, Qnil);
2431 else if (SREF (target, 0) == '/' && SREF (target, 1) == ':')
2432 target = Fsubstring_no_properties (target, make_number (2), Qnil);
2434 linkname = expand_cp_target (target, linkname);
2436 /* If the new link name has special constructs in it,
2437 call the corresponding file handler. */
2438 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2439 if (!NILP (handler))
2440 return call4 (handler, Qmake_symbolic_link, target,
2441 linkname, ok_if_already_exists);
2443 encoded_target = ENCODE_FILE (target);
2444 encoded_linkname = ENCODE_FILE (linkname);
2446 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2447 return Qnil;
2449 if (errno == ENOSYS)
2450 xsignal1 (Qfile_error,
2451 build_string ("Symbolic links are not supported"));
2453 if (errno == EEXIST)
2455 if (NILP (ok_if_already_exists)
2456 || INTEGERP (ok_if_already_exists))
2457 barf_or_query_if_file_exists (linkname, true, "make it a link",
2458 INTEGERP (ok_if_already_exists), false);
2459 unlink (SSDATA (encoded_linkname));
2460 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2461 return Qnil;
2464 report_file_error ("Making symbolic link", list2 (target, linkname));
2468 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2469 1, 1, 0,
2470 doc: /* Return t if FILENAME is an absolute file name or starts with `~'.
2471 On Unix, absolute file names start with `/'. */)
2472 (Lisp_Object filename)
2474 CHECK_STRING (filename);
2475 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2478 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2479 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2480 See also `file-readable-p' and `file-attributes'.
2481 This returns nil for a symlink to a nonexistent file.
2482 Use `file-symlink-p' to test for such links. */)
2483 (Lisp_Object filename)
2485 Lisp_Object absname;
2486 Lisp_Object handler;
2488 CHECK_STRING (filename);
2489 absname = Fexpand_file_name (filename, Qnil);
2491 /* If the file name has special constructs in it,
2492 call the corresponding file handler. */
2493 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2494 if (!NILP (handler))
2496 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2497 errno = 0;
2498 return result;
2501 absname = ENCODE_FILE (absname);
2503 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2506 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2507 doc: /* Return t if FILENAME can be executed by you.
2508 For a directory, this means you can access files in that directory.
2509 \(It is generally better to use `file-accessible-directory-p' for that
2510 purpose, though.) */)
2511 (Lisp_Object filename)
2513 Lisp_Object absname;
2514 Lisp_Object handler;
2516 CHECK_STRING (filename);
2517 absname = Fexpand_file_name (filename, Qnil);
2519 /* If the file name has special constructs in it,
2520 call the corresponding file handler. */
2521 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2522 if (!NILP (handler))
2523 return call2 (handler, Qfile_executable_p, absname);
2525 absname = ENCODE_FILE (absname);
2527 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2530 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2531 doc: /* Return t if file FILENAME exists and you can read it.
2532 See also `file-exists-p' and `file-attributes'. */)
2533 (Lisp_Object filename)
2535 Lisp_Object absname;
2536 Lisp_Object handler;
2538 CHECK_STRING (filename);
2539 absname = Fexpand_file_name (filename, Qnil);
2541 /* If the file name has special constructs in it,
2542 call the corresponding file handler. */
2543 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2544 if (!NILP (handler))
2545 return call2 (handler, Qfile_readable_p, absname);
2547 absname = ENCODE_FILE (absname);
2548 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2549 ? Qt : Qnil);
2552 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2553 doc: /* Return t if file FILENAME can be written or created by you. */)
2554 (Lisp_Object filename)
2556 Lisp_Object absname, dir, encoded;
2557 Lisp_Object handler;
2559 CHECK_STRING (filename);
2560 absname = Fexpand_file_name (filename, Qnil);
2562 /* If the file name has special constructs in it,
2563 call the corresponding file handler. */
2564 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2565 if (!NILP (handler))
2566 return call2 (handler, Qfile_writable_p, absname);
2568 encoded = ENCODE_FILE (absname);
2569 if (check_writable (SSDATA (encoded), W_OK))
2570 return Qt;
2571 if (errno != ENOENT)
2572 return Qnil;
2574 dir = Ffile_name_directory (absname);
2575 eassert (!NILP (dir));
2576 #ifdef MSDOS
2577 dir = Fdirectory_file_name (dir);
2578 #endif /* MSDOS */
2580 dir = ENCODE_FILE (dir);
2581 #ifdef WINDOWSNT
2582 /* The read-only attribute of the parent directory doesn't affect
2583 whether a file or directory can be created within it. Some day we
2584 should check ACLs though, which do affect this. */
2585 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2586 #else
2587 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2588 #endif
2591 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2592 doc: /* Access file FILENAME, and get an error if that does not work.
2593 The second argument STRING is prepended to the error message.
2594 If there is no error, returns nil. */)
2595 (Lisp_Object filename, Lisp_Object string)
2597 Lisp_Object handler, encoded_filename, absname;
2599 CHECK_STRING (filename);
2600 absname = Fexpand_file_name (filename, Qnil);
2602 CHECK_STRING (string);
2604 /* If the file name has special constructs in it,
2605 call the corresponding file handler. */
2606 handler = Ffind_file_name_handler (absname, Qaccess_file);
2607 if (!NILP (handler))
2608 return call3 (handler, Qaccess_file, absname, string);
2610 encoded_filename = ENCODE_FILE (absname);
2612 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2613 report_file_error (SSDATA (string), filename);
2615 return Qnil;
2618 /* Relative to directory FD, return the symbolic link value of FILENAME.
2619 On failure, return nil. */
2620 Lisp_Object
2621 emacs_readlinkat (int fd, char const *filename)
2623 static struct allocator const emacs_norealloc_allocator =
2624 { xmalloc, NULL, xfree, memory_full };
2625 Lisp_Object val;
2626 char readlink_buf[1024];
2627 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2628 &emacs_norealloc_allocator, readlinkat);
2629 if (!buf)
2630 return Qnil;
2632 val = build_unibyte_string (buf);
2633 if (buf != readlink_buf)
2634 xfree (buf);
2635 val = DECODE_FILE (val);
2636 return val;
2639 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2640 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2641 The value is the link target, as a string.
2642 Otherwise it returns nil.
2644 This function does not check whether the link target exists. */)
2645 (Lisp_Object filename)
2647 Lisp_Object handler;
2649 CHECK_STRING (filename);
2650 filename = Fexpand_file_name (filename, Qnil);
2652 /* If the file name has special constructs in it,
2653 call the corresponding file handler. */
2654 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2655 if (!NILP (handler))
2656 return call2 (handler, Qfile_symlink_p, filename);
2658 filename = ENCODE_FILE (filename);
2660 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2663 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2664 doc: /* Return t if FILENAME names an existing directory.
2665 Symbolic links to directories count as directories.
2666 See `file-symlink-p' to distinguish symlinks. */)
2667 (Lisp_Object filename)
2669 Lisp_Object absname = expand_and_dir_to_file (filename);
2671 /* If the file name has special constructs in it,
2672 call the corresponding file handler. */
2673 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2674 if (!NILP (handler))
2675 return call2 (handler, Qfile_directory_p, absname);
2677 absname = ENCODE_FILE (absname);
2679 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2682 /* Return true if FILE is a directory or a symlink to a directory. */
2683 bool
2684 file_directory_p (char const *file)
2686 #ifdef WINDOWSNT
2687 /* This is cheaper than 'stat'. */
2688 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2689 #else
2690 struct stat st;
2691 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2692 #endif
2695 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2696 Sfile_accessible_directory_p, 1, 1, 0,
2697 doc: /* Return t if FILENAME names a directory you can open.
2698 For the value to be t, FILENAME must specify the name of a directory
2699 as a file, and the directory must allow you to open files in it. In
2700 order to use a directory as a buffer's current directory, this
2701 predicate must return true. A directory name spec may be given
2702 instead; then the value is t if the directory so specified exists and
2703 really is a readable and searchable directory. */)
2704 (Lisp_Object filename)
2706 Lisp_Object absname;
2707 Lisp_Object handler;
2709 CHECK_STRING (filename);
2710 absname = Fexpand_file_name (filename, Qnil);
2712 /* If the file name has special constructs in it,
2713 call the corresponding file handler. */
2714 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2715 if (!NILP (handler))
2717 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2719 /* Set errno in case the handler failed. EACCES might be a lie
2720 (e.g., the directory might not exist, or be a regular file),
2721 but at least it does TRT in the "usual" case of an existing
2722 directory that is not accessible by the current user, and
2723 avoids reporting "Success" for a failed operation. Perhaps
2724 someday we can fix this in a better way, by improving
2725 file-accessible-directory-p's API; see Bug#25419. */
2726 if (!EQ (r, Qt))
2727 errno = EACCES;
2729 return r;
2732 absname = ENCODE_FILE (absname);
2733 return file_accessible_directory_p (absname) ? Qt : Qnil;
2736 /* If FILE is a searchable directory or a symlink to a
2737 searchable directory, return true. Otherwise return
2738 false and set errno to an error number. */
2739 bool
2740 file_accessible_directory_p (Lisp_Object file)
2742 #ifdef DOS_NT
2743 # ifdef WINDOWSNT
2744 /* We need a special-purpose test because (a) NTFS security data is
2745 not reflected in Posix-style mode bits, and (b) the trick with
2746 accessing "DIR/.", used below on Posix hosts, doesn't work on
2747 Windows, because "DIR/." is normalized to just "DIR" before
2748 hitting the disk. */
2749 return (SBYTES (file) == 0
2750 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2751 # else /* MSDOS */
2752 return file_directory_p (SSDATA (file));
2753 # endif /* MSDOS */
2754 #else /* !DOS_NT */
2755 /* On POSIXish platforms, use just one system call; this avoids a
2756 race and is typically faster. */
2757 const char *data = SSDATA (file);
2758 ptrdiff_t len = SBYTES (file);
2759 char const *dir;
2760 bool ok;
2761 int saved_errno;
2762 USE_SAFE_ALLOCA;
2764 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2765 There are three exceptions: "", "/", and "//". Leave "" alone,
2766 as it's invalid. Append only "." to the other two exceptions as
2767 "/" and "//" are distinct on some platforms, whereas "/", "///",
2768 "////", etc. are all equivalent. */
2769 if (! len)
2770 dir = data;
2771 else
2773 /* Just check for trailing '/' when deciding whether to append '/'.
2774 That's simpler than testing the two special cases "/" and "//",
2775 and it's a safe optimization here. */
2776 char *buf = SAFE_ALLOCA (len + 3);
2777 memcpy (buf, data, len);
2778 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2779 dir = buf;
2782 ok = check_existing (dir);
2783 saved_errno = errno;
2784 SAFE_FREE ();
2785 errno = saved_errno;
2786 return ok;
2787 #endif /* !DOS_NT */
2790 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2791 doc: /* Return t if FILENAME names a regular file.
2792 This is the sort of file that holds an ordinary stream of data bytes.
2793 Symbolic links to regular files count as regular files.
2794 See `file-symlink-p' to distinguish symlinks. */)
2795 (Lisp_Object filename)
2797 struct stat st;
2798 Lisp_Object absname = expand_and_dir_to_file (filename);
2800 /* If the file name has special constructs in it,
2801 call the corresponding file handler. */
2802 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2803 if (!NILP (handler))
2804 return call2 (handler, Qfile_regular_p, absname);
2806 absname = ENCODE_FILE (absname);
2808 #ifdef WINDOWSNT
2810 int result;
2811 Lisp_Object tem = Vw32_get_true_file_attributes;
2813 /* Tell stat to use expensive method to get accurate info. */
2814 Vw32_get_true_file_attributes = Qt;
2815 result = stat (SSDATA (absname), &st);
2816 Vw32_get_true_file_attributes = tem;
2818 if (result < 0)
2819 return Qnil;
2820 return S_ISREG (st.st_mode) ? Qt : Qnil;
2822 #else
2823 if (stat (SSDATA (absname), &st) < 0)
2824 return Qnil;
2825 return S_ISREG (st.st_mode) ? Qt : Qnil;
2826 #endif
2829 DEFUN ("file-selinux-context", Ffile_selinux_context,
2830 Sfile_selinux_context, 1, 1, 0,
2831 doc: /* Return SELinux context of file named FILENAME.
2832 The return value is a list (USER ROLE TYPE RANGE), where the list
2833 elements are strings naming the user, role, type, and range of the
2834 file's SELinux security context.
2836 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2837 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2838 (Lisp_Object filename)
2840 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2841 Lisp_Object absname = expand_and_dir_to_file (filename);
2843 /* If the file name has special constructs in it,
2844 call the corresponding file handler. */
2845 Lisp_Object handler = Ffind_file_name_handler (absname,
2846 Qfile_selinux_context);
2847 if (!NILP (handler))
2848 return call2 (handler, Qfile_selinux_context, absname);
2850 absname = ENCODE_FILE (absname);
2852 #if HAVE_LIBSELINUX
2853 if (is_selinux_enabled ())
2855 security_context_t con;
2856 int conlength = lgetfilecon (SSDATA (absname), &con);
2857 if (conlength > 0)
2859 context_t context = context_new (con);
2860 if (context_user_get (context))
2861 user = build_string (context_user_get (context));
2862 if (context_role_get (context))
2863 role = build_string (context_role_get (context));
2864 if (context_type_get (context))
2865 type = build_string (context_type_get (context));
2866 if (context_range_get (context))
2867 range = build_string (context_range_get (context));
2868 context_free (context);
2869 freecon (con);
2872 #endif
2874 return list4 (user, role, type, range);
2877 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2878 Sset_file_selinux_context, 2, 2, 0,
2879 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2880 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2881 elements are strings naming the components of a SELinux context.
2883 Value is t if setting of SELinux context was successful, nil otherwise.
2885 This function does nothing and returns nil if SELinux is disabled,
2886 or if Emacs was not compiled with SELinux support. */)
2887 (Lisp_Object filename, Lisp_Object context)
2889 Lisp_Object absname;
2890 Lisp_Object handler;
2891 #if HAVE_LIBSELINUX
2892 Lisp_Object encoded_absname;
2893 Lisp_Object user = CAR_SAFE (context);
2894 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2895 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2896 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2897 security_context_t con;
2898 bool fail;
2899 int conlength;
2900 context_t parsed_con;
2901 #endif
2903 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2905 /* If the file name has special constructs in it,
2906 call the corresponding file handler. */
2907 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2908 if (!NILP (handler))
2909 return call3 (handler, Qset_file_selinux_context, absname, context);
2911 #if HAVE_LIBSELINUX
2912 if (is_selinux_enabled ())
2914 /* Get current file context. */
2915 encoded_absname = ENCODE_FILE (absname);
2916 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2917 if (conlength > 0)
2919 parsed_con = context_new (con);
2920 /* Change the parts defined in the parameter.*/
2921 if (STRINGP (user))
2923 if (context_user_set (parsed_con, SSDATA (user)))
2924 error ("Doing context_user_set");
2926 if (STRINGP (role))
2928 if (context_role_set (parsed_con, SSDATA (role)))
2929 error ("Doing context_role_set");
2931 if (STRINGP (type))
2933 if (context_type_set (parsed_con, SSDATA (type)))
2934 error ("Doing context_type_set");
2936 if (STRINGP (range))
2938 if (context_range_set (parsed_con, SSDATA (range)))
2939 error ("Doing context_range_set");
2942 /* Set the modified context back to the file. */
2943 fail = (lsetfilecon (SSDATA (encoded_absname),
2944 context_str (parsed_con))
2945 != 0);
2946 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2947 if (fail && errno != ENOTSUP)
2948 report_file_error ("Doing lsetfilecon", absname);
2950 context_free (parsed_con);
2951 freecon (con);
2952 return fail ? Qnil : Qt;
2954 else
2955 report_file_error ("Doing lgetfilecon", absname);
2957 #endif
2959 return Qnil;
2962 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2963 doc: /* Return ACL entries of file named FILENAME.
2964 The entries are returned in a format suitable for use in `set-file-acl'
2965 but is otherwise undocumented and subject to change.
2966 Return nil if file does not exist or is not accessible, or if Emacs
2967 was unable to determine the ACL entries. */)
2968 (Lisp_Object filename)
2970 Lisp_Object acl_string = Qnil;
2972 #if USE_ACL
2973 Lisp_Object absname = expand_and_dir_to_file (filename);
2975 /* If the file name has special constructs in it,
2976 call the corresponding file handler. */
2977 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_acl);
2978 if (!NILP (handler))
2979 return call2 (handler, Qfile_acl, absname);
2981 # ifdef HAVE_ACL_SET_FILE
2982 absname = ENCODE_FILE (absname);
2984 # ifndef HAVE_ACL_TYPE_EXTENDED
2985 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2986 # endif
2987 acl_t acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2988 if (acl == NULL)
2989 return Qnil;
2991 char *str = acl_to_text (acl, NULL);
2992 if (str == NULL)
2994 acl_free (acl);
2995 return Qnil;
2998 acl_string = build_string (str);
2999 acl_free (str);
3000 acl_free (acl);
3001 # endif
3002 #endif
3004 return acl_string;
3007 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3008 2, 2, 0,
3009 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3010 ACL-STRING should contain the textual representation of the ACL
3011 entries in a format suitable for the platform.
3013 Value is t if setting of ACL was successful, nil otherwise.
3015 Setting ACL for local files requires Emacs to be built with ACL
3016 support. */)
3017 (Lisp_Object filename, Lisp_Object acl_string)
3019 #if USE_ACL
3020 Lisp_Object absname;
3021 Lisp_Object handler;
3022 # ifdef HAVE_ACL_SET_FILE
3023 Lisp_Object encoded_absname;
3024 acl_t acl;
3025 bool fail;
3026 # endif
3028 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3030 /* If the file name has special constructs in it,
3031 call the corresponding file handler. */
3032 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3033 if (!NILP (handler))
3034 return call3 (handler, Qset_file_acl, absname, acl_string);
3036 # ifdef HAVE_ACL_SET_FILE
3037 if (STRINGP (acl_string))
3039 acl = acl_from_text (SSDATA (acl_string));
3040 if (acl == NULL)
3042 report_file_error ("Converting ACL", absname);
3043 return Qnil;
3046 encoded_absname = ENCODE_FILE (absname);
3048 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3049 acl)
3050 != 0);
3051 if (fail && acl_errno_valid (errno))
3052 report_file_error ("Setting ACL", absname);
3054 acl_free (acl);
3055 return fail ? Qnil : Qt;
3057 # endif
3058 #endif
3060 return Qnil;
3063 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3064 doc: /* Return mode bits of file named FILENAME, as an integer.
3065 Return nil, if file does not exist or is not accessible. */)
3066 (Lisp_Object filename)
3068 struct stat st;
3069 Lisp_Object absname = expand_and_dir_to_file (filename);
3071 /* If the file name has special constructs in it,
3072 call the corresponding file handler. */
3073 Lisp_Object handler = Ffind_file_name_handler (absname, Qfile_modes);
3074 if (!NILP (handler))
3075 return call2 (handler, Qfile_modes, absname);
3077 absname = ENCODE_FILE (absname);
3079 if (stat (SSDATA (absname), &st) < 0)
3080 return Qnil;
3082 return make_number (st.st_mode & 07777);
3085 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3086 "(let ((file (read-file-name \"File: \"))) \
3087 (list file (read-file-modes nil file)))",
3088 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3089 Only the 12 low bits of MODE are used.
3091 Interactively, mode bits are read by `read-file-modes', which accepts
3092 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3093 (Lisp_Object filename, Lisp_Object mode)
3095 Lisp_Object absname, encoded_absname;
3096 Lisp_Object handler;
3098 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3099 CHECK_NUMBER (mode);
3101 /* If the file name has special constructs in it,
3102 call the corresponding file handler. */
3103 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3104 if (!NILP (handler))
3105 return call3 (handler, Qset_file_modes, absname, mode);
3107 encoded_absname = ENCODE_FILE (absname);
3109 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3110 report_file_error ("Doing chmod", absname);
3112 return Qnil;
3115 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3116 doc: /* Set the file permission bits for newly created files.
3117 The argument MODE should be an integer; only the low 9 bits are used.
3118 This setting is inherited by subprocesses. */)
3119 (Lisp_Object mode)
3121 mode_t oldrealmask, oldumask, newumask;
3122 CHECK_NUMBER (mode);
3123 oldrealmask = realmask;
3124 newumask = ~ XINT (mode) & 0777;
3126 block_input ();
3127 realmask = newumask;
3128 oldumask = umask (newumask);
3129 unblock_input ();
3131 eassert (oldumask == oldrealmask);
3132 return Qnil;
3135 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3136 doc: /* Return the default file protection for created files.
3137 The value is an integer. */)
3138 (void)
3140 Lisp_Object value;
3141 XSETINT (value, (~ realmask) & 0777);
3142 return value;
3146 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3147 doc: /* Set times of file FILENAME to TIMESTAMP.
3148 Set both access and modification times.
3149 Return t on success, else nil.
3150 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3151 `current-time'. */)
3152 (Lisp_Object filename, Lisp_Object timestamp)
3154 Lisp_Object absname, encoded_absname;
3155 Lisp_Object handler;
3156 struct timespec t = lisp_time_argument (timestamp);
3158 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3160 /* If the file name has special constructs in it,
3161 call the corresponding file handler. */
3162 handler = Ffind_file_name_handler (absname, Qset_file_times);
3163 if (!NILP (handler))
3164 return call3 (handler, Qset_file_times, absname, timestamp);
3166 encoded_absname = ENCODE_FILE (absname);
3169 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3171 #ifdef MSDOS
3172 /* Setting times on a directory always fails. */
3173 if (file_directory_p (SSDATA (encoded_absname)))
3174 return Qnil;
3175 #endif
3176 report_file_error ("Setting file times", absname);
3180 return Qt;
3183 #ifdef HAVE_SYNC
3184 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3185 doc: /* Tell Unix to finish all pending disk updates. */)
3186 (void)
3188 sync ();
3189 return Qnil;
3192 #endif /* HAVE_SYNC */
3194 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3195 doc: /* Return t if file FILE1 is newer than file FILE2.
3196 If FILE1 does not exist, the answer is nil;
3197 otherwise, if FILE2 does not exist, the answer is t. */)
3198 (Lisp_Object file1, Lisp_Object file2)
3200 struct stat st1, st2;
3202 CHECK_STRING (file1);
3203 CHECK_STRING (file2);
3205 Lisp_Object absname1 = expand_and_dir_to_file (file1);
3206 Lisp_Object absname2 = expand_and_dir_to_file (file2);
3208 /* If the file name has special constructs in it,
3209 call the corresponding file handler. */
3210 Lisp_Object handler = Ffind_file_name_handler (absname1,
3211 Qfile_newer_than_file_p);
3212 if (NILP (handler))
3213 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3214 if (!NILP (handler))
3215 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3217 absname1 = ENCODE_FILE (absname1);
3218 absname2 = ENCODE_FILE (absname2);
3220 if (stat (SSDATA (absname1), &st1) < 0)
3221 return Qnil;
3223 if (stat (SSDATA (absname2), &st2) < 0)
3224 return Qt;
3226 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3227 ? Qt : Qnil);
3230 enum { READ_BUF_SIZE = MAX_ALLOCA };
3232 /* This function is called after Lisp functions to decide a coding
3233 system are called, or when they cause an error. Before they are
3234 called, the current buffer is set unibyte and it contains only a
3235 newly inserted text (thus the buffer was empty before the
3236 insertion).
3238 The functions may set markers, overlays, text properties, or even
3239 alter the buffer contents, change the current buffer.
3241 Here, we reset all those changes by:
3242 o set back the current buffer.
3243 o move all markers and overlays to BEG.
3244 o remove all text properties.
3245 o set back the buffer multibyteness. */
3247 static void
3248 decide_coding_unwind (Lisp_Object unwind_data)
3250 Lisp_Object multibyte, undo_list, buffer;
3252 multibyte = XCAR (unwind_data);
3253 unwind_data = XCDR (unwind_data);
3254 undo_list = XCAR (unwind_data);
3255 buffer = XCDR (unwind_data);
3257 set_buffer_internal (XBUFFER (buffer));
3258 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3259 adjust_overlays_for_delete (BEG, Z - BEG);
3260 set_buffer_intervals (current_buffer, NULL);
3261 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3263 /* Now we are safe to change the buffer's multibyteness directly. */
3264 bset_enable_multibyte_characters (current_buffer, multibyte);
3265 bset_undo_list (current_buffer, undo_list);
3268 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3269 object where slot 0 is the file descriptor, slot 1 specifies
3270 an offset to put the read bytes, and slot 2 is the maximum
3271 amount of bytes to read. Value is the number of bytes read. */
3273 static Lisp_Object
3274 read_non_regular (Lisp_Object state)
3276 int nbytes = emacs_read_quit (XSAVE_INTEGER (state, 0),
3277 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3278 + XSAVE_INTEGER (state, 1)),
3279 XSAVE_INTEGER (state, 2));
3280 /* Fast recycle this object for the likely next call. */
3281 free_misc (state);
3282 return make_number (nbytes);
3286 /* Condition-case handler used when reading from non-regular files
3287 in insert-file-contents. */
3289 static Lisp_Object
3290 read_non_regular_quit (Lisp_Object ignore)
3292 return Qnil;
3295 /* Return the file offset that VAL represents, checking for type
3296 errors and overflow. */
3297 static off_t
3298 file_offset (Lisp_Object val)
3300 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3301 return XINT (val);
3303 if (FLOATP (val))
3305 double v = XFLOAT_DATA (val);
3306 if (0 <= v && v < 1.0 + TYPE_MAXIMUM (off_t))
3308 off_t o = v;
3309 if (o == v)
3310 return o;
3314 wrong_type_argument (intern ("file-offset"), val);
3317 /* Return a special time value indicating the error number ERRNUM. */
3318 static struct timespec
3319 time_error_value (int errnum)
3321 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3322 ? NONEXISTENT_MODTIME_NSECS
3323 : UNKNOWN_MODTIME_NSECS);
3324 return make_timespec (0, ns);
3327 static Lisp_Object
3328 get_window_points_and_markers (void)
3330 Lisp_Object pt_marker = Fpoint_marker ();
3331 Lisp_Object windows
3332 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3333 Lisp_Object window_markers = windows;
3334 /* Window markers (and point) are handled specially: rather than move to
3335 just before or just after the modified text, we try to keep the
3336 markers at the same distance (bug#19161).
3337 In general, this is wrong, but for window-markers, this should be harmless
3338 and is convenient for the end user when most of the file is unmodified,
3339 except for a few minor details near the beginning and near the end. */
3340 for (; CONSP (windows); windows = XCDR (windows))
3341 if (WINDOWP (XCAR (windows)))
3343 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3344 XSETCAR (windows,
3345 Fcons (window_marker, Fmarker_position (window_marker)));
3347 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3350 static void
3351 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3352 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3354 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3355 if (CONSP (XCAR (window_markers)))
3357 Lisp_Object car = XCAR (window_markers);
3358 Lisp_Object marker = XCAR (car);
3359 Lisp_Object oldpos = XCDR (car);
3360 if (MARKERP (marker) && INTEGERP (oldpos)
3361 && XINT (oldpos) > same_at_start
3362 && XINT (oldpos) < same_at_end)
3364 ptrdiff_t oldsize = same_at_end - same_at_start;
3365 ptrdiff_t newsize = inserted;
3366 double growth = newsize / (double)oldsize;
3367 ptrdiff_t newpos
3368 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3369 Fset_marker (marker, make_number (newpos), Qnil);
3374 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3375 text as a linear C char array. */
3376 static void
3377 maybe_move_gap (struct buffer *b)
3379 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3381 struct buffer *cb = current_buffer;
3383 set_buffer_internal (b);
3384 move_gap_both (Z, Z_BYTE);
3385 set_buffer_internal (cb);
3389 /* FIXME: insert-file-contents should be split with the top-level moved to
3390 Elisp and only the core kept in C. */
3392 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3393 1, 5, 0,
3394 doc: /* Insert contents of file FILENAME after point.
3395 Returns list of absolute file name and number of characters inserted.
3396 If second argument VISIT is non-nil, the buffer's visited filename and
3397 last save file modtime are set, and it is marked unmodified. If
3398 visiting and the file does not exist, visiting is completed before the
3399 error is signaled.
3401 The optional third and fourth arguments BEG and END specify what portion
3402 of the file to insert. These arguments count bytes in the file, not
3403 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3405 If optional fifth argument REPLACE is non-nil, replace the current
3406 buffer contents (in the accessible portion) with the file contents.
3407 This is better than simply deleting and inserting the whole thing
3408 because (1) it preserves some marker positions and (2) it puts less data
3409 in the undo list. When REPLACE is non-nil, the second return value is
3410 the number of characters that replace previous buffer contents.
3412 This function does code conversion according to the value of
3413 `coding-system-for-read' or `file-coding-system-alist', and sets the
3414 variable `last-coding-system-used' to the coding system actually used.
3416 In addition, this function decodes the inserted text from known formats
3417 by calling `format-decode', which see. */)
3418 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3420 struct stat st;
3421 struct timespec mtime;
3422 int fd;
3423 ptrdiff_t inserted = 0;
3424 ptrdiff_t how_much;
3425 off_t beg_offset, end_offset;
3426 int unprocessed;
3427 ptrdiff_t count = SPECPDL_INDEX ();
3428 Lisp_Object handler, val, insval, orig_filename, old_undo;
3429 Lisp_Object p;
3430 ptrdiff_t total = 0;
3431 bool not_regular = 0;
3432 int save_errno = 0;
3433 char read_buf[READ_BUF_SIZE];
3434 struct coding_system coding;
3435 bool replace_handled = false;
3436 bool set_coding_system = false;
3437 Lisp_Object coding_system;
3438 bool read_quit = false;
3439 /* If the undo log only contains the insertion, there's no point
3440 keeping it. It's typically when we first fill a file-buffer. */
3441 bool empty_undo_list_p
3442 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3443 && BEG == Z);
3444 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3445 bool we_locked_file = false;
3446 ptrdiff_t fd_index;
3447 Lisp_Object window_markers = Qnil;
3448 /* same_at_start and same_at_end count bytes, because file access counts
3449 bytes and BEG and END count bytes. */
3450 ptrdiff_t same_at_start = BEGV_BYTE;
3451 ptrdiff_t same_at_end = ZV_BYTE;
3452 /* SAME_AT_END_CHARPOS counts characters, because
3453 restore_window_points needs the old character count. */
3454 ptrdiff_t same_at_end_charpos = ZV;
3456 if (current_buffer->base_buffer && ! NILP (visit))
3457 error ("Cannot do file visiting in an indirect buffer");
3459 if (!NILP (BVAR (current_buffer, read_only)))
3460 Fbarf_if_buffer_read_only (Qnil);
3462 val = Qnil;
3463 p = Qnil;
3464 orig_filename = Qnil;
3465 old_undo = Qnil;
3467 CHECK_STRING (filename);
3468 filename = Fexpand_file_name (filename, Qnil);
3470 /* The value Qnil means that the coding system is not yet
3471 decided. */
3472 coding_system = Qnil;
3474 /* If the file name has special constructs in it,
3475 call the corresponding file handler. */
3476 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3477 if (!NILP (handler))
3479 val = call6 (handler, Qinsert_file_contents, filename,
3480 visit, beg, end, replace);
3481 if (CONSP (val) && CONSP (XCDR (val))
3482 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3483 inserted = XINT (XCAR (XCDR (val)));
3484 goto handled;
3487 orig_filename = filename;
3488 filename = ENCODE_FILE (filename);
3490 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3491 if (fd < 0)
3493 save_errno = errno;
3494 if (NILP (visit))
3495 report_file_error ("Opening input file", orig_filename);
3496 mtime = time_error_value (save_errno);
3497 st.st_size = -1;
3498 if (!NILP (Vcoding_system_for_read))
3500 /* Don't let invalid values into buffer-file-coding-system. */
3501 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3502 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3504 goto notfound;
3507 fd_index = SPECPDL_INDEX ();
3508 record_unwind_protect_int (close_file_unwind, fd);
3510 /* Replacement should preserve point as it preserves markers. */
3511 if (!NILP (replace))
3513 window_markers = get_window_points_and_markers ();
3514 record_unwind_protect (restore_point_unwind,
3515 XCAR (XCAR (window_markers)));
3518 if (fstat (fd, &st) != 0)
3519 report_file_error ("Input file status", orig_filename);
3520 mtime = get_stat_mtime (&st);
3522 /* This code will need to be changed in order to work on named
3523 pipes, and it's probably just not worth it. So we should at
3524 least signal an error. */
3525 if (!S_ISREG (st.st_mode))
3527 not_regular = 1;
3529 if (! NILP (visit))
3530 goto notfound;
3532 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3533 xsignal2 (Qfile_error,
3534 build_string ("not a regular file"), orig_filename);
3537 if (!NILP (visit))
3539 if (!NILP (beg) || !NILP (end))
3540 error ("Attempt to visit less than an entire file");
3541 if (BEG < Z && NILP (replace))
3542 error ("Cannot do file visiting in a non-empty buffer");
3545 if (!NILP (beg))
3546 beg_offset = file_offset (beg);
3547 else
3548 beg_offset = 0;
3550 if (!NILP (end))
3551 end_offset = file_offset (end);
3552 else
3554 if (not_regular)
3555 end_offset = TYPE_MAXIMUM (off_t);
3556 else
3558 end_offset = st.st_size;
3560 /* A negative size can happen on a platform that allows file
3561 sizes greater than the maximum off_t value. */
3562 if (end_offset < 0)
3563 buffer_overflow ();
3565 /* The file size returned from stat may be zero, but data
3566 may be readable nonetheless, for example when this is a
3567 file in the /proc filesystem. */
3568 if (end_offset == 0)
3569 end_offset = READ_BUF_SIZE;
3573 /* Check now whether the buffer will become too large,
3574 in the likely case where the file's length is not changing.
3575 This saves a lot of needless work before a buffer overflow. */
3576 if (! not_regular)
3578 /* The likely offset where we will stop reading. We could read
3579 more (or less), if the file grows (or shrinks) as we read it. */
3580 off_t likely_end = min (end_offset, st.st_size);
3582 if (beg_offset < likely_end)
3584 ptrdiff_t buf_bytes
3585 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3586 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3587 off_t likely_growth = likely_end - beg_offset;
3588 if (buf_growth_max < likely_growth)
3589 buffer_overflow ();
3593 /* Prevent redisplay optimizations. */
3594 current_buffer->clip_changed = true;
3596 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3598 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3599 setup_coding_system (coding_system, &coding);
3600 /* Ensure we set Vlast_coding_system_used. */
3601 set_coding_system = true;
3603 else if (BEG < Z)
3605 /* Decide the coding system to use for reading the file now
3606 because we can't use an optimized method for handling
3607 `coding:' tag if the current buffer is not empty. */
3608 if (!NILP (Vcoding_system_for_read))
3609 coding_system = Vcoding_system_for_read;
3610 else
3612 /* Don't try looking inside a file for a coding system
3613 specification if it is not seekable. */
3614 if (! not_regular && ! NILP (Vset_auto_coding_function))
3616 /* Find a coding system specified in the heading two
3617 lines or in the tailing several lines of the file.
3618 We assume that the 1K-byte and 3K-byte for heading
3619 and tailing respectively are sufficient for this
3620 purpose. */
3621 int nread;
3623 if (st.st_size <= (1024 * 4))
3624 nread = emacs_read_quit (fd, read_buf, 1024 * 4);
3625 else
3627 nread = emacs_read_quit (fd, read_buf, 1024);
3628 if (nread == 1024)
3630 int ntail;
3631 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3632 report_file_error ("Setting file position",
3633 orig_filename);
3634 ntail = emacs_read_quit (fd, read_buf + nread, 1024 * 3);
3635 nread = ntail < 0 ? ntail : nread + ntail;
3639 if (nread < 0)
3640 report_file_error ("Read error", orig_filename);
3641 else if (nread > 0)
3643 AUTO_STRING (name, " *code-converting-work*");
3644 struct buffer *prev = current_buffer;
3645 Lisp_Object workbuf;
3646 struct buffer *buf;
3648 record_unwind_current_buffer ();
3650 workbuf = Fget_buffer_create (name);
3651 buf = XBUFFER (workbuf);
3653 delete_all_overlays (buf);
3654 bset_directory (buf, BVAR (current_buffer, directory));
3655 bset_read_only (buf, Qnil);
3656 bset_filename (buf, Qnil);
3657 bset_undo_list (buf, Qt);
3658 eassert (buf->overlays_before == NULL);
3659 eassert (buf->overlays_after == NULL);
3661 set_buffer_internal (buf);
3662 Ferase_buffer ();
3663 bset_enable_multibyte_characters (buf, Qnil);
3665 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3666 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3667 coding_system = call2 (Vset_auto_coding_function,
3668 filename, make_number (nread));
3669 set_buffer_internal (prev);
3671 /* Discard the unwind protect for recovering the
3672 current buffer. */
3673 specpdl_ptr--;
3675 /* Rewind the file for the actual read done later. */
3676 if (lseek (fd, 0, SEEK_SET) < 0)
3677 report_file_error ("Setting file position", orig_filename);
3681 if (NILP (coding_system))
3683 /* If we have not yet decided a coding system, check
3684 file-coding-system-alist. */
3685 coding_system = CALLN (Ffind_operation_coding_system,
3686 Qinsert_file_contents, orig_filename,
3687 visit, beg, end, replace);
3688 if (CONSP (coding_system))
3689 coding_system = XCAR (coding_system);
3693 if (NILP (coding_system))
3694 coding_system = Qundecided;
3695 else
3696 CHECK_CODING_SYSTEM (coding_system);
3698 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3699 /* We must suppress all character code conversion except for
3700 end-of-line conversion. */
3701 coding_system = raw_text_coding_system (coding_system);
3703 setup_coding_system (coding_system, &coding);
3704 /* Ensure we set Vlast_coding_system_used. */
3705 set_coding_system = true;
3708 /* If requested, replace the accessible part of the buffer
3709 with the file contents. Avoid replacing text at the
3710 beginning or end of the buffer that matches the file contents;
3711 that preserves markers pointing to the unchanged parts.
3713 Here we implement this feature in an optimized way
3714 for the case where code conversion is NOT needed.
3715 The following if-statement handles the case of conversion
3716 in a less optimal way.
3718 If the code conversion is "automatic" then we try using this
3719 method and hope for the best.
3720 But if we discover the need for conversion, we give up on this method
3721 and let the following if-statement handle the replace job. */
3722 if (!NILP (replace)
3723 && BEGV < ZV
3724 && (NILP (coding_system)
3725 || ! CODING_REQUIRE_DECODING (&coding)))
3727 ptrdiff_t overlap;
3728 /* There is still a possibility we will find the need to do code
3729 conversion. If that happens, set this variable to
3730 give up on handling REPLACE in the optimized way. */
3731 bool giveup_match_end = false;
3733 if (beg_offset != 0)
3735 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3736 report_file_error ("Setting file position", orig_filename);
3739 /* Count how many chars at the start of the file
3740 match the text at the beginning of the buffer. */
3741 while (true)
3743 int nread = emacs_read_quit (fd, read_buf, sizeof read_buf);
3744 if (nread < 0)
3745 report_file_error ("Read error", orig_filename);
3746 else if (nread == 0)
3747 break;
3749 if (CODING_REQUIRE_DETECTION (&coding))
3751 coding_system = detect_coding_system ((unsigned char *) read_buf,
3752 nread, nread, 1, 0,
3753 coding_system);
3754 setup_coding_system (coding_system, &coding);
3757 if (CODING_REQUIRE_DECODING (&coding))
3758 /* We found that the file should be decoded somehow.
3759 Let's give up here. */
3761 giveup_match_end = true;
3762 break;
3765 int bufpos = 0;
3766 while (bufpos < nread && same_at_start < ZV_BYTE
3767 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3768 same_at_start++, bufpos++;
3769 /* If we found a discrepancy, stop the scan.
3770 Otherwise loop around and scan the next bufferful. */
3771 if (bufpos != nread)
3772 break;
3774 /* If the file matches the buffer completely,
3775 there's no need to replace anything. */
3776 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3778 emacs_close (fd);
3779 clear_unwind_protect (fd_index);
3781 /* Truncate the buffer to the size of the file. */
3782 del_range_1 (same_at_start, same_at_end, 0, 0);
3783 goto handled;
3786 /* Count how many chars at the end of the file
3787 match the text at the end of the buffer. But, if we have
3788 already found that decoding is necessary, don't waste time. */
3789 while (!giveup_match_end)
3791 int total_read, nread, bufpos, trial;
3792 off_t curpos;
3794 /* At what file position are we now scanning? */
3795 curpos = end_offset - (ZV_BYTE - same_at_end);
3796 /* If the entire file matches the buffer tail, stop the scan. */
3797 if (curpos == 0)
3798 break;
3799 /* How much can we scan in the next step? */
3800 trial = min (curpos, sizeof read_buf);
3801 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3802 report_file_error ("Setting file position", orig_filename);
3804 total_read = nread = 0;
3805 while (total_read < trial)
3807 nread = emacs_read_quit (fd, read_buf + total_read,
3808 trial - total_read);
3809 if (nread < 0)
3810 report_file_error ("Read error", orig_filename);
3811 else if (nread == 0)
3812 break;
3813 total_read += nread;
3816 /* Scan this bufferful from the end, comparing with
3817 the Emacs buffer. */
3818 bufpos = total_read;
3820 /* Compare with same_at_start to avoid counting some buffer text
3821 as matching both at the file's beginning and at the end. */
3822 while (bufpos > 0 && same_at_end > same_at_start
3823 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3824 same_at_end--, bufpos--;
3826 /* If we found a discrepancy, stop the scan.
3827 Otherwise loop around and scan the preceding bufferful. */
3828 if (bufpos != 0)
3830 /* If this discrepancy is because of code conversion,
3831 we cannot use this method; giveup and try the other. */
3832 if (same_at_end > same_at_start
3833 && FETCH_BYTE (same_at_end - 1) >= 0200
3834 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3835 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3836 giveup_match_end = true;
3837 break;
3840 if (nread == 0)
3841 break;
3844 if (! giveup_match_end)
3846 ptrdiff_t temp;
3847 ptrdiff_t this_count = SPECPDL_INDEX ();
3849 /* We win! We can handle REPLACE the optimized way. */
3851 /* Extend the start of non-matching text area to multibyte
3852 character boundary. */
3853 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3854 while (same_at_start > BEGV_BYTE
3855 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3856 same_at_start--;
3858 /* Extend the end of non-matching text area to multibyte
3859 character boundary. */
3860 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3861 while (same_at_end < ZV_BYTE
3862 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3863 same_at_end++;
3865 /* Don't try to reuse the same piece of text twice. */
3866 overlap = (same_at_start - BEGV_BYTE
3867 - (same_at_end
3868 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3869 if (overlap > 0)
3870 same_at_end += overlap;
3871 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3873 /* Arrange to read only the nonmatching middle part of the file. */
3874 beg_offset += same_at_start - BEGV_BYTE;
3875 end_offset -= ZV_BYTE - same_at_end;
3877 /* This binding is to avoid ask-user-about-supersession-threat
3878 being called in insert_from_buffer or del_range_bytes (via
3879 prepare_to_modify_buffer).
3880 AFAICT we could avoid ask-user-about-supersession-threat by setting
3881 current_buffer->modtime earlier, but we could still end up calling
3882 ask-user-about-supersession-threat if the file is modified while
3883 we read it, so we bind buffer-file-name instead. */
3884 specbind (intern ("buffer-file-name"), Qnil);
3885 del_range_byte (same_at_start, same_at_end);
3886 /* Insert from the file at the proper position. */
3887 temp = BYTE_TO_CHAR (same_at_start);
3888 SET_PT_BOTH (temp, same_at_start);
3889 unbind_to (this_count, Qnil);
3891 /* If display currently starts at beginning of line,
3892 keep it that way. */
3893 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3894 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3896 replace_handled = true;
3900 /* If requested, replace the accessible part of the buffer
3901 with the file contents. Avoid replacing text at the
3902 beginning or end of the buffer that matches the file contents;
3903 that preserves markers pointing to the unchanged parts.
3905 Here we implement this feature for the case where code conversion
3906 is needed, in a simple way that needs a lot of memory.
3907 The preceding if-statement handles the case of no conversion
3908 in a more optimized way. */
3909 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3911 ptrdiff_t same_at_start_charpos;
3912 ptrdiff_t inserted_chars;
3913 ptrdiff_t overlap;
3914 ptrdiff_t bufpos;
3915 unsigned char *decoded;
3916 ptrdiff_t temp;
3917 ptrdiff_t this = 0;
3918 ptrdiff_t this_count = SPECPDL_INDEX ();
3919 bool multibyte
3920 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3921 Lisp_Object conversion_buffer;
3923 conversion_buffer = code_conversion_save (1, multibyte);
3925 /* First read the whole file, performing code conversion into
3926 CONVERSION_BUFFER. */
3928 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3929 report_file_error ("Setting file position", orig_filename);
3931 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3932 unprocessed = 0; /* Bytes not processed in previous loop. */
3934 while (true)
3936 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3937 quitting while reading a huge file. */
3939 this = emacs_read_quit (fd, read_buf + unprocessed,
3940 READ_BUF_SIZE - unprocessed);
3941 if (this <= 0)
3942 break;
3944 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3945 BUF_Z (XBUFFER (conversion_buffer)));
3946 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3947 unprocessed + this, conversion_buffer);
3948 unprocessed = coding.carryover_bytes;
3949 if (coding.carryover_bytes > 0)
3950 memcpy (read_buf, coding.carryover, unprocessed);
3953 if (this < 0)
3954 report_file_error ("Read error", orig_filename);
3955 emacs_close (fd);
3956 clear_unwind_protect (fd_index);
3958 if (unprocessed > 0)
3960 coding.mode |= CODING_MODE_LAST_BLOCK;
3961 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3962 unprocessed, conversion_buffer);
3963 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3966 coding_system = CODING_ID_NAME (coding.id);
3967 set_coding_system = true;
3968 maybe_move_gap (XBUFFER (conversion_buffer));
3969 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3970 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3971 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3973 /* Compare the beginning of the converted string with the buffer
3974 text. */
3976 bufpos = 0;
3977 while (bufpos < inserted && same_at_start < same_at_end
3978 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3979 same_at_start++, bufpos++;
3981 /* If the file matches the head of buffer completely,
3982 there's no need to replace anything. */
3984 if (bufpos == inserted)
3986 /* Truncate the buffer to the size of the file. */
3987 if (same_at_start != same_at_end)
3989 /* See previous specbind for the reason behind this. */
3990 specbind (intern ("buffer-file-name"), Qnil);
3991 del_range_byte (same_at_start, same_at_end);
3993 inserted = 0;
3995 unbind_to (this_count, Qnil);
3996 goto handled;
3999 /* Extend the start of non-matching text area to the previous
4000 multibyte character boundary. */
4001 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4002 while (same_at_start > BEGV_BYTE
4003 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4004 same_at_start--;
4006 /* Scan this bufferful from the end, comparing with
4007 the Emacs buffer. */
4008 bufpos = inserted;
4010 /* Compare with same_at_start to avoid counting some buffer text
4011 as matching both at the file's beginning and at the end. */
4012 while (bufpos > 0 && same_at_end > same_at_start
4013 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4014 same_at_end--, bufpos--;
4016 /* Extend the end of non-matching text area to the next
4017 multibyte character boundary. */
4018 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4019 while (same_at_end < ZV_BYTE
4020 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4021 same_at_end++;
4023 /* Don't try to reuse the same piece of text twice. */
4024 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4025 if (overlap > 0)
4026 same_at_end += overlap;
4027 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4029 /* If display currently starts at beginning of line,
4030 keep it that way. */
4031 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4032 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4034 /* Replace the chars that we need to replace,
4035 and update INSERTED to equal the number of bytes
4036 we are taking from the decoded string. */
4037 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4039 /* See previous specbind for the reason behind this. */
4040 specbind (intern ("buffer-file-name"), Qnil);
4041 if (same_at_end != same_at_start)
4043 del_range_byte (same_at_start, same_at_end);
4044 temp = GPT;
4045 eassert (same_at_start == GPT_BYTE);
4046 same_at_start = GPT_BYTE;
4048 else
4050 temp = same_at_end_charpos;
4052 /* Insert from the file at the proper position. */
4053 SET_PT_BOTH (temp, same_at_start);
4054 same_at_start_charpos
4055 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4056 same_at_start - BEGV_BYTE
4057 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4058 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4059 inserted_chars
4060 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4061 same_at_start + inserted - BEGV_BYTE
4062 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4063 - same_at_start_charpos);
4064 insert_from_buffer (XBUFFER (conversion_buffer),
4065 same_at_start_charpos, inserted_chars, 0);
4066 /* Set `inserted' to the number of inserted characters. */
4067 inserted = PT - temp;
4068 /* Set point before the inserted characters. */
4069 SET_PT_BOTH (temp, same_at_start);
4071 unbind_to (this_count, Qnil);
4073 goto handled;
4076 if (! not_regular)
4077 total = end_offset - beg_offset;
4078 else
4079 /* For a special file, all we can do is guess. */
4080 total = READ_BUF_SIZE;
4082 if (NILP (visit) && total > 0)
4084 if (!NILP (BVAR (current_buffer, file_truename))
4085 /* Make binding buffer-file-name to nil effective. */
4086 && !NILP (BVAR (current_buffer, filename))
4087 && SAVE_MODIFF >= MODIFF)
4088 we_locked_file = true;
4089 prepare_to_modify_buffer (PT, PT, NULL);
4092 move_gap_both (PT, PT_BYTE);
4093 if (GAP_SIZE < total)
4094 make_gap (total - GAP_SIZE);
4096 if (beg_offset != 0 || !NILP (replace))
4098 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4099 report_file_error ("Setting file position", orig_filename);
4102 /* In the following loop, HOW_MUCH contains the total bytes read so
4103 far for a regular file, and not changed for a special file. But,
4104 before exiting the loop, it is set to a negative value if I/O
4105 error occurs. */
4106 how_much = 0;
4108 /* Total bytes inserted. */
4109 inserted = 0;
4111 /* Here, we don't do code conversion in the loop. It is done by
4112 decode_coding_gap after all data are read into the buffer. */
4114 ptrdiff_t gap_size = GAP_SIZE;
4116 while (how_much < total)
4118 /* `try' is reserved in some compilers (Microsoft C). */
4119 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4120 ptrdiff_t this;
4122 if (not_regular)
4124 Lisp_Object nbytes;
4126 /* Maybe make more room. */
4127 if (gap_size < trytry)
4129 make_gap (trytry - gap_size);
4130 gap_size = GAP_SIZE - inserted;
4133 /* Read from the file, capturing `quit'. When an
4134 error occurs, end the loop, and arrange for a quit
4135 to be signaled after decoding the text we read. */
4136 nbytes = internal_condition_case_1
4137 (read_non_regular,
4138 make_save_int_int_int (fd, inserted, trytry),
4139 Qerror, read_non_regular_quit);
4141 if (NILP (nbytes))
4143 read_quit = true;
4144 break;
4147 this = XINT (nbytes);
4149 else
4151 /* Allow quitting out of the actual I/O. We don't make text
4152 part of the buffer until all the reading is done, so a C-g
4153 here doesn't do any harm. */
4154 this = emacs_read_quit (fd,
4155 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4156 + inserted),
4157 trytry);
4160 if (this <= 0)
4162 how_much = this;
4163 break;
4166 gap_size -= this;
4168 /* For a regular file, where TOTAL is the real size,
4169 count HOW_MUCH to compare with it.
4170 For a special file, where TOTAL is just a buffer size,
4171 so don't bother counting in HOW_MUCH.
4172 (INSERTED is where we count the number of characters inserted.) */
4173 if (! not_regular)
4174 how_much += this;
4175 inserted += this;
4179 /* Now we have either read all the file data into the gap,
4180 or stop reading on I/O error or quit. If nothing was
4181 read, undo marking the buffer modified. */
4183 if (inserted == 0)
4185 if (we_locked_file)
4186 unlock_file (BVAR (current_buffer, file_truename));
4187 Vdeactivate_mark = old_Vdeactivate_mark;
4189 else
4190 Fset (Qdeactivate_mark, Qt);
4192 emacs_close (fd);
4193 clear_unwind_protect (fd_index);
4195 if (how_much < 0)
4196 report_file_error ("Read error", orig_filename);
4198 /* Make the text read part of the buffer. */
4199 GAP_SIZE -= inserted;
4200 GPT += inserted;
4201 GPT_BYTE += inserted;
4202 ZV += inserted;
4203 ZV_BYTE += inserted;
4204 Z += inserted;
4205 Z_BYTE += inserted;
4207 if (GAP_SIZE > 0)
4208 /* Put an anchor to ensure multi-byte form ends at gap. */
4209 *GPT_ADDR = 0;
4211 notfound:
4213 if (NILP (coding_system))
4215 /* The coding system is not yet decided. Decide it by an
4216 optimized method for handling `coding:' tag.
4218 Note that we can get here only if the buffer was empty
4219 before the insertion. */
4221 if (!NILP (Vcoding_system_for_read))
4222 coding_system = Vcoding_system_for_read;
4223 else
4225 /* Since we are sure that the current buffer was empty
4226 before the insertion, we can toggle
4227 enable-multibyte-characters directly here without taking
4228 care of marker adjustment. By this way, we can run Lisp
4229 program safely before decoding the inserted text. */
4230 Lisp_Object unwind_data;
4231 ptrdiff_t count1 = SPECPDL_INDEX ();
4233 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4234 Fcons (BVAR (current_buffer, undo_list),
4235 Fcurrent_buffer ()));
4236 bset_enable_multibyte_characters (current_buffer, Qnil);
4237 bset_undo_list (current_buffer, Qt);
4238 record_unwind_protect (decide_coding_unwind, unwind_data);
4240 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4242 coding_system = call2 (Vset_auto_coding_function,
4243 filename, make_number (inserted));
4246 if (NILP (coding_system))
4248 /* If the coding system is not yet decided, check
4249 file-coding-system-alist. */
4250 coding_system = CALLN (Ffind_operation_coding_system,
4251 Qinsert_file_contents, orig_filename,
4252 visit, beg, end, Qnil);
4253 if (CONSP (coding_system))
4254 coding_system = XCAR (coding_system);
4256 unbind_to (count1, Qnil);
4257 inserted = Z_BYTE - BEG_BYTE;
4260 if (NILP (coding_system))
4261 coding_system = Qundecided;
4262 else
4263 CHECK_CODING_SYSTEM (coding_system);
4265 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4266 /* We must suppress all character code conversion except for
4267 end-of-line conversion. */
4268 coding_system = raw_text_coding_system (coding_system);
4269 setup_coding_system (coding_system, &coding);
4270 /* Ensure we set Vlast_coding_system_used. */
4271 set_coding_system = true;
4274 if (!NILP (visit))
4276 /* When we visit a file by raw-text, we change the buffer to
4277 unibyte. */
4278 if (CODING_FOR_UNIBYTE (&coding)
4279 /* Can't do this if part of the buffer might be preserved. */
4280 && NILP (replace))
4282 /* Visiting a file with these coding system makes the buffer
4283 unibyte. */
4284 if (inserted > 0)
4285 bset_enable_multibyte_characters (current_buffer, Qnil);
4286 else
4287 Fset_buffer_multibyte (Qnil);
4291 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4292 if (CODING_MAY_REQUIRE_DECODING (&coding)
4293 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4295 move_gap_both (PT, PT_BYTE);
4296 GAP_SIZE += inserted;
4297 ZV_BYTE -= inserted;
4298 Z_BYTE -= inserted;
4299 ZV -= inserted;
4300 Z -= inserted;
4301 decode_coding_gap (&coding, inserted, inserted);
4302 inserted = coding.produced_char;
4303 coding_system = CODING_ID_NAME (coding.id);
4305 else if (inserted > 0)
4307 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4308 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4309 inserted);
4312 /* Call after-change hooks for the inserted text, aside from the case
4313 of normal visiting (not with REPLACE), which is done in a new buffer
4314 "before" the buffer is changed. */
4315 if (inserted > 0 && total > 0
4316 && (NILP (visit) || !NILP (replace)))
4318 signal_after_change (PT, 0, inserted);
4319 update_compositions (PT, PT, CHECK_BORDER);
4322 /* Now INSERTED is measured in characters. */
4324 handled:
4326 if (inserted > 0)
4327 restore_window_points (window_markers, inserted,
4328 BYTE_TO_CHAR (same_at_start),
4329 same_at_end_charpos);
4331 if (!NILP (visit))
4333 if (empty_undo_list_p)
4334 bset_undo_list (current_buffer, Qnil);
4336 if (NILP (handler))
4338 current_buffer->modtime = mtime;
4339 current_buffer->modtime_size = st.st_size;
4340 bset_filename (current_buffer, orig_filename);
4343 SAVE_MODIFF = MODIFF;
4344 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4345 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4346 if (NILP (handler))
4348 if (!NILP (BVAR (current_buffer, file_truename)))
4349 unlock_file (BVAR (current_buffer, file_truename));
4350 unlock_file (filename);
4352 if (not_regular)
4353 xsignal2 (Qfile_error,
4354 build_string ("not a regular file"), orig_filename);
4357 if (set_coding_system)
4358 Vlast_coding_system_used = coding_system;
4360 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4362 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4363 visit);
4364 if (! NILP (insval))
4366 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4367 wrong_type_argument (intern ("inserted-chars"), insval);
4368 inserted = XFASTINT (insval);
4372 /* Decode file format. */
4373 if (inserted > 0)
4375 /* Don't run point motion or modification hooks when decoding. */
4376 ptrdiff_t count1 = SPECPDL_INDEX ();
4377 ptrdiff_t old_inserted = inserted;
4378 specbind (Qinhibit_point_motion_hooks, Qt);
4379 specbind (Qinhibit_modification_hooks, Qt);
4381 /* Save old undo list and don't record undo for decoding. */
4382 old_undo = BVAR (current_buffer, undo_list);
4383 bset_undo_list (current_buffer, Qt);
4385 if (NILP (replace))
4387 insval = call3 (Qformat_decode,
4388 Qnil, make_number (inserted), visit);
4389 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4390 wrong_type_argument (intern ("inserted-chars"), insval);
4391 inserted = XFASTINT (insval);
4393 else
4395 /* If REPLACE is non-nil and we succeeded in not replacing the
4396 beginning or end of the buffer text with the file's contents,
4397 call format-decode with `point' positioned at the beginning
4398 of the buffer and `inserted' equaling the number of
4399 characters in the buffer. Otherwise, format-decode might
4400 fail to correctly analyze the beginning or end of the buffer.
4401 Hence we temporarily save `point' and `inserted' here and
4402 restore `point' iff format-decode did not insert or delete
4403 any text. Otherwise we leave `point' at point-min. */
4404 ptrdiff_t opoint = PT;
4405 ptrdiff_t opoint_byte = PT_BYTE;
4406 ptrdiff_t oinserted = ZV - BEGV;
4407 EMACS_INT ochars_modiff = CHARS_MODIFF;
4409 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4410 insval = call3 (Qformat_decode,
4411 Qnil, make_number (oinserted), visit);
4412 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4413 wrong_type_argument (intern ("inserted-chars"), insval);
4414 if (ochars_modiff == CHARS_MODIFF)
4415 /* format_decode didn't modify buffer's characters => move
4416 point back to position before inserted text and leave
4417 value of inserted alone. */
4418 SET_PT_BOTH (opoint, opoint_byte);
4419 else
4420 /* format_decode modified buffer's characters => consider
4421 entire buffer changed and leave point at point-min. */
4422 inserted = XFASTINT (insval);
4425 /* For consistency with format-decode call these now iff inserted > 0
4426 (martin 2007-06-28). */
4427 p = Vafter_insert_file_functions;
4428 while (CONSP (p))
4430 if (NILP (replace))
4432 insval = call1 (XCAR (p), make_number (inserted));
4433 if (!NILP (insval))
4435 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4436 wrong_type_argument (intern ("inserted-chars"), insval);
4437 inserted = XFASTINT (insval);
4440 else
4442 /* For the rationale of this see the comment on
4443 format-decode above. */
4444 ptrdiff_t opoint = PT;
4445 ptrdiff_t opoint_byte = PT_BYTE;
4446 ptrdiff_t oinserted = ZV - BEGV;
4447 EMACS_INT ochars_modiff = CHARS_MODIFF;
4449 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4450 insval = call1 (XCAR (p), make_number (oinserted));
4451 if (!NILP (insval))
4453 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4454 wrong_type_argument (intern ("inserted-chars"), insval);
4455 if (ochars_modiff == CHARS_MODIFF)
4456 /* after_insert_file_functions didn't modify
4457 buffer's characters => move point back to
4458 position before inserted text and leave value of
4459 inserted alone. */
4460 SET_PT_BOTH (opoint, opoint_byte);
4461 else
4462 /* after_insert_file_functions did modify buffer's
4463 characters => consider entire buffer changed and
4464 leave point at point-min. */
4465 inserted = XFASTINT (insval);
4469 maybe_quit ();
4470 p = XCDR (p);
4473 if (!empty_undo_list_p)
4475 bset_undo_list (current_buffer, old_undo);
4476 if (CONSP (old_undo) && inserted != old_inserted)
4478 /* Adjust the last undo record for the size change during
4479 the format conversion. */
4480 Lisp_Object tem = XCAR (old_undo);
4481 if (CONSP (tem) && INTEGERP (XCAR (tem))
4482 && INTEGERP (XCDR (tem))
4483 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4484 XSETCDR (tem, make_number (PT + inserted));
4487 else
4488 /* If undo_list was Qt before, keep it that way.
4489 Otherwise start with an empty undo_list. */
4490 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4492 unbind_to (count1, Qnil);
4495 if (!NILP (visit)
4496 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4498 /* If visiting nonexistent file, return nil. */
4499 report_file_errno ("Opening input file", orig_filename, save_errno);
4502 /* We made a lot of deletions and insertions above, so invalidate
4503 the newline cache for the entire region of the inserted
4504 characters. */
4505 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4506 invalidate_region_cache (current_buffer->base_buffer,
4507 current_buffer->base_buffer->newline_cache,
4508 PT - BEG, Z - PT - inserted);
4509 else if (current_buffer->newline_cache)
4510 invalidate_region_cache (current_buffer,
4511 current_buffer->newline_cache,
4512 PT - BEG, Z - PT - inserted);
4514 if (read_quit)
4515 quit ();
4517 /* Retval needs to be dealt with in all cases consistently. */
4518 if (NILP (val))
4519 val = list2 (orig_filename, make_number (inserted));
4521 return unbind_to (count, val);
4524 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4526 static void
4527 build_annotations_unwind (Lisp_Object arg)
4529 Vwrite_region_annotation_buffers = arg;
4532 /* Decide the coding-system to encode the data with. */
4534 static Lisp_Object
4535 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4536 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4537 struct coding_system *coding)
4539 Lisp_Object val;
4540 Lisp_Object eol_parent = Qnil;
4542 if (auto_saving
4543 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4544 BVAR (current_buffer, auto_save_file_name))))
4546 val = Qutf_8_emacs;
4547 eol_parent = Qunix;
4549 else if (!NILP (Vcoding_system_for_write))
4551 val = Vcoding_system_for_write;
4552 if (coding_system_require_warning
4553 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4554 /* Confirm that VAL can surely encode the current region. */
4555 val = call5 (Vselect_safe_coding_system_function,
4556 start, end, list2 (Qt, val),
4557 Qnil, filename);
4559 else
4561 /* If the variable `buffer-file-coding-system' is set locally,
4562 it means that the file was read with some kind of code
4563 conversion or the variable is explicitly set by users. We
4564 had better write it out with the same coding system even if
4565 `enable-multibyte-characters' is nil.
4567 If it is not set locally, we anyway have to convert EOL
4568 format if the default value of `buffer-file-coding-system'
4569 tells that it is not Unix-like (LF only) format. */
4570 bool using_default_coding = 0;
4571 bool force_raw_text = 0;
4573 val = BVAR (current_buffer, buffer_file_coding_system);
4574 if (NILP (val)
4575 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4577 val = Qnil;
4578 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4579 force_raw_text = 1;
4582 if (NILP (val))
4584 /* Check file-coding-system-alist. */
4585 Lisp_Object coding_systems
4586 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4587 filename, append, visit, lockname);
4588 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4589 val = XCDR (coding_systems);
4592 if (NILP (val))
4594 /* If we still have not decided a coding system, use the
4595 current buffer's value of buffer-file-coding-system. */
4596 val = BVAR (current_buffer, buffer_file_coding_system);
4597 using_default_coding = 1;
4600 if (! NILP (val) && ! force_raw_text)
4602 Lisp_Object spec, attrs;
4604 CHECK_CODING_SYSTEM (val);
4605 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4606 attrs = AREF (spec, 0);
4607 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4608 force_raw_text = 1;
4611 if (!force_raw_text
4612 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4614 /* Confirm that VAL can surely encode the current region. */
4615 val = call5 (Vselect_safe_coding_system_function,
4616 start, end, val, Qnil, filename);
4617 /* As the function specified by select-safe-coding-system-function
4618 is out of our control, make sure we are not fed by bogus
4619 values. */
4620 if (!NILP (val))
4621 CHECK_CODING_SYSTEM (val);
4624 /* If the decided coding-system doesn't specify end-of-line
4625 format, we use that of `buffer-file-coding-system'. */
4626 if (! using_default_coding)
4628 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4630 if (! NILP (dflt))
4631 val = coding_inherit_eol_type (val, dflt);
4634 /* If we decide not to encode text, use `raw-text' or one of its
4635 subsidiaries. */
4636 if (force_raw_text)
4637 val = raw_text_coding_system (val);
4640 val = coding_inherit_eol_type (val, eol_parent);
4641 setup_coding_system (val, coding);
4643 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4644 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4645 return val;
4648 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4649 "r\nFWrite region to file: \ni\ni\ni\np",
4650 doc: /* Write current region into specified file.
4651 When called from a program, requires three arguments:
4652 START, END and FILENAME. START and END are normally buffer positions
4653 specifying the part of the buffer to write.
4654 If START is nil, that means to use the entire buffer contents; END is
4655 ignored.
4656 If START is a string, then output that string to the file
4657 instead of any buffer contents; END is ignored.
4659 Optional fourth argument APPEND if non-nil means
4660 append to existing file contents (if any). If it is a number,
4661 seek to that offset in the file before writing.
4662 Optional fifth argument VISIT, if t or a string, means
4663 set the last-save-file-modtime of buffer to this file's modtime
4664 and mark buffer not modified.
4665 If VISIT is a string, it is a second file name;
4666 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4667 VISIT is also the file name to lock and unlock for clash detection.
4668 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4669 do not display the \"Wrote file\" message.
4670 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4671 use for locking and unlocking, overriding FILENAME and VISIT.
4672 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4673 for an existing file with the same name. If MUSTBENEW is `excl',
4674 that means to get an error if the file already exists; never overwrite.
4675 If MUSTBENEW is neither nil nor `excl', that means ask for
4676 confirmation before overwriting, but do go ahead and overwrite the file
4677 if the user confirms.
4679 This does code conversion according to the value of
4680 `coding-system-for-write', `buffer-file-coding-system', or
4681 `file-coding-system-alist', and sets the variable
4682 `last-coding-system-used' to the coding system actually used.
4684 This calls `write-region-annotate-functions' at the start, and
4685 `write-region-post-annotation-function' at the end. */)
4686 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4687 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4689 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4690 -1);
4693 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4694 descriptor for FILENAME, so do not open or close FILENAME. */
4696 Lisp_Object
4697 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4698 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4699 Lisp_Object mustbenew, int desc)
4701 int open_flags;
4702 int mode;
4703 off_t offset UNINIT;
4704 bool open_and_close_file = desc < 0;
4705 bool ok;
4706 int save_errno = 0;
4707 const char *fn;
4708 struct stat st;
4709 struct timespec modtime;
4710 ptrdiff_t count = SPECPDL_INDEX ();
4711 ptrdiff_t count1 UNINIT;
4712 Lisp_Object handler;
4713 Lisp_Object visit_file;
4714 Lisp_Object annotations;
4715 Lisp_Object encoded_filename;
4716 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4717 bool quietly = !NILP (visit);
4718 bool file_locked = 0;
4719 struct buffer *given_buffer;
4720 struct coding_system coding;
4722 if (current_buffer->base_buffer && visiting)
4723 error ("Cannot do file visiting in an indirect buffer");
4725 if (!NILP (start) && !STRINGP (start))
4726 validate_region (&start, &end);
4728 visit_file = Qnil;
4730 filename = Fexpand_file_name (filename, Qnil);
4732 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4733 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4735 if (STRINGP (visit))
4736 visit_file = Fexpand_file_name (visit, Qnil);
4737 else
4738 visit_file = filename;
4740 if (NILP (lockname))
4741 lockname = visit_file;
4743 annotations = Qnil;
4745 /* If the file name has special constructs in it,
4746 call the corresponding file handler. */
4747 handler = Ffind_file_name_handler (filename, Qwrite_region);
4748 /* If FILENAME has no handler, see if VISIT has one. */
4749 if (NILP (handler) && STRINGP (visit))
4750 handler = Ffind_file_name_handler (visit, Qwrite_region);
4752 if (!NILP (handler))
4754 Lisp_Object val;
4755 val = call8 (handler, Qwrite_region, start, end,
4756 filename, append, visit, lockname, mustbenew);
4758 if (visiting)
4760 SAVE_MODIFF = MODIFF;
4761 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4762 bset_filename (current_buffer, visit_file);
4765 return val;
4768 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4770 /* Special kludge to simplify auto-saving. */
4771 if (NILP (start))
4773 /* Do it later, so write-region-annotate-function can work differently
4774 if we save "the buffer" vs "a region".
4775 This is useful in tar-mode. --Stef
4776 XSETFASTINT (start, BEG);
4777 XSETFASTINT (end, Z); */
4778 Fwiden ();
4781 record_unwind_protect (build_annotations_unwind,
4782 Vwrite_region_annotation_buffers);
4783 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4785 given_buffer = current_buffer;
4787 if (!STRINGP (start))
4789 annotations = build_annotations (start, end);
4791 if (current_buffer != given_buffer)
4793 XSETFASTINT (start, BEGV);
4794 XSETFASTINT (end, ZV);
4798 if (NILP (start))
4800 XSETFASTINT (start, BEGV);
4801 XSETFASTINT (end, ZV);
4804 /* Decide the coding-system to encode the data with.
4805 We used to make this choice before calling build_annotations, but that
4806 leads to problems when a write-annotate-function takes care of
4807 unsavable chars (as was the case with X-Symbol). */
4808 Vlast_coding_system_used
4809 = choose_write_coding_system (start, end, filename,
4810 append, visit, lockname, &coding);
4812 if (open_and_close_file && !auto_saving)
4814 lock_file (lockname);
4815 file_locked = 1;
4818 encoded_filename = ENCODE_FILE (filename);
4819 fn = SSDATA (encoded_filename);
4820 open_flags = O_WRONLY | O_CREAT;
4821 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4822 if (NUMBERP (append))
4823 offset = file_offset (append);
4824 else if (!NILP (append))
4825 open_flags |= O_APPEND;
4826 #ifdef DOS_NT
4827 mode = S_IREAD | S_IWRITE;
4828 #else
4829 mode = auto_saving ? auto_save_mode_bits : 0666;
4830 #endif
4832 if (open_and_close_file)
4834 desc = emacs_open (fn, open_flags, mode);
4835 if (desc < 0)
4837 int open_errno = errno;
4838 if (file_locked)
4839 unlock_file (lockname);
4840 report_file_errno ("Opening output file", filename, open_errno);
4843 count1 = SPECPDL_INDEX ();
4844 record_unwind_protect_int (close_file_unwind, desc);
4847 if (NUMBERP (append))
4849 off_t ret = lseek (desc, offset, SEEK_SET);
4850 if (ret < 0)
4852 int lseek_errno = errno;
4853 if (file_locked)
4854 unlock_file (lockname);
4855 report_file_errno ("Lseek error", filename, lseek_errno);
4859 if (STRINGP (start))
4860 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4861 else if (XINT (start) != XINT (end))
4862 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4863 &annotations, &coding);
4864 else
4866 /* If file was empty, still need to write the annotations. */
4867 coding.mode |= CODING_MODE_LAST_BLOCK;
4868 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4870 save_errno = errno;
4872 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4873 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4875 /* We have to flush out a data. */
4876 coding.mode |= CODING_MODE_LAST_BLOCK;
4877 ok = e_write (desc, Qnil, 1, 1, &coding);
4878 save_errno = errno;
4881 /* fsync is not crucial for temporary files. Nor for auto-save
4882 files, since they might lose some work anyway. */
4883 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4885 /* Transfer data and metadata to disk, retrying if interrupted.
4886 fsync can report a write failure here, e.g., due to disk full
4887 under NFS. But ignore EINVAL, which means fsync is not
4888 supported on this file. */
4889 while (fsync (desc) != 0)
4890 if (errno != EINTR)
4892 if (errno != EINVAL)
4893 ok = 0, save_errno = errno;
4894 break;
4898 modtime = invalid_timespec ();
4899 if (visiting)
4901 if (fstat (desc, &st) == 0)
4902 modtime = get_stat_mtime (&st);
4903 else
4904 ok = 0, save_errno = errno;
4907 if (open_and_close_file)
4909 /* NFS can report a write failure now. */
4910 if (emacs_close (desc) < 0)
4911 ok = 0, save_errno = errno;
4913 /* Discard the unwind protect for close_file_unwind. */
4914 specpdl_ptr = specpdl + count1;
4917 /* Some file systems have a bug where st_mtime is not updated
4918 properly after a write. For example, CIFS might not see the
4919 st_mtime change until after the file is opened again.
4921 Attempt to detect this file system bug, and update MODTIME to the
4922 newer st_mtime if the bug appears to be present. This introduces
4923 a race condition, so to avoid most instances of the race condition
4924 on non-buggy file systems, skip this check if the most recently
4925 encountered non-buggy file system was the current file system.
4927 A race condition can occur if some other process modifies the
4928 file between the fstat above and the fstat below, but the race is
4929 unlikely and a similar race between the last write and the fstat
4930 above cannot possibly be closed anyway. */
4932 if (timespec_valid_p (modtime)
4933 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4935 int desc1 = emacs_open (fn, O_WRONLY, 0);
4936 if (desc1 >= 0)
4938 struct stat st1;
4939 if (fstat (desc1, &st1) == 0
4940 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4942 /* Use the heuristic if it appears to be valid. With neither
4943 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4944 file, the time stamp won't change. Also, some non-POSIX
4945 systems don't update an empty file's time stamp when
4946 truncating it. Finally, file systems with 100 ns or worse
4947 resolution sometimes seem to have bugs: on a system with ns
4948 resolution, checking ns % 100 incorrectly avoids the heuristic
4949 1% of the time, but the problem should be temporary as we will
4950 try again on the next time stamp. */
4951 bool use_heuristic
4952 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4953 && st.st_size != 0
4954 && modtime.tv_nsec % 100 != 0);
4956 struct timespec modtime1 = get_stat_mtime (&st1);
4957 if (use_heuristic
4958 && timespec_cmp (modtime, modtime1) == 0
4959 && st.st_size == st1.st_size)
4961 timestamp_file_system = st.st_dev;
4962 valid_timestamp_file_system = 1;
4964 else
4966 st.st_size = st1.st_size;
4967 modtime = modtime1;
4970 emacs_close (desc1);
4974 /* Call write-region-post-annotation-function. */
4975 while (CONSP (Vwrite_region_annotation_buffers))
4977 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4978 if (!NILP (Fbuffer_live_p (buf)))
4980 Fset_buffer (buf);
4981 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4982 call0 (Vwrite_region_post_annotation_function);
4984 Vwrite_region_annotation_buffers
4985 = XCDR (Vwrite_region_annotation_buffers);
4988 unbind_to (count, Qnil);
4990 if (file_locked)
4991 unlock_file (lockname);
4993 /* Do this before reporting IO error
4994 to avoid a "file has changed on disk" warning on
4995 next attempt to save. */
4996 if (timespec_valid_p (modtime))
4998 current_buffer->modtime = modtime;
4999 current_buffer->modtime_size = st.st_size;
5002 if (! ok)
5003 report_file_errno ("Write error", filename, save_errno);
5005 bool auto_saving_into_visited_file =
5006 auto_saving
5007 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5008 BVAR (current_buffer, auto_save_file_name)));
5009 if (visiting)
5011 SAVE_MODIFF = MODIFF;
5012 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5013 bset_filename (current_buffer, visit_file);
5014 update_mode_lines = 14;
5015 if (auto_saving_into_visited_file)
5016 unlock_file (lockname);
5018 else if (quietly)
5020 if (auto_saving_into_visited_file)
5022 SAVE_MODIFF = MODIFF;
5023 unlock_file (lockname);
5026 return Qnil;
5029 if (!auto_saving && !noninteractive)
5030 message_with_string ((NUMBERP (append)
5031 ? "Updated %s"
5032 : ! NILP (append)
5033 ? "Added to %s"
5034 : "Wrote %s"),
5035 visit_file, 1);
5037 return Qnil;
5040 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5041 doc: /* Return t if (car A) is numerically less than (car B). */)
5042 (Lisp_Object a, Lisp_Object b)
5044 return arithcompare (Fcar (a), Fcar (b), ARITH_LESS);
5047 /* Build the complete list of annotations appropriate for writing out
5048 the text between START and END, by calling all the functions in
5049 write-region-annotate-functions and merging the lists they return.
5050 If one of these functions switches to a different buffer, we assume
5051 that buffer contains altered text. Therefore, the caller must
5052 make sure to restore the current buffer in all cases,
5053 as save-excursion would do. */
5055 static Lisp_Object
5056 build_annotations (Lisp_Object start, Lisp_Object end)
5058 Lisp_Object annotations;
5059 Lisp_Object p, res;
5060 Lisp_Object original_buffer;
5061 int i;
5062 bool used_global = false;
5064 XSETBUFFER (original_buffer, current_buffer);
5066 annotations = Qnil;
5067 p = Vwrite_region_annotate_functions;
5068 while (CONSP (p))
5070 struct buffer *given_buffer = current_buffer;
5071 if (EQ (Qt, XCAR (p)) && !used_global)
5072 { /* Use the global value of the hook. */
5073 used_global = true;
5074 p = CALLN (Fappend,
5075 Fdefault_value (Qwrite_region_annotate_functions),
5076 XCDR (p));
5077 continue;
5079 Vwrite_region_annotations_so_far = annotations;
5080 res = call2 (XCAR (p), start, end);
5081 /* If the function makes a different buffer current,
5082 assume that means this buffer contains altered text to be output.
5083 Reset START and END from the buffer bounds
5084 and discard all previous annotations because they should have
5085 been dealt with by this function. */
5086 if (current_buffer != given_buffer)
5088 Vwrite_region_annotation_buffers
5089 = Fcons (Fcurrent_buffer (),
5090 Vwrite_region_annotation_buffers);
5091 XSETFASTINT (start, BEGV);
5092 XSETFASTINT (end, ZV);
5093 annotations = Qnil;
5095 Flength (res); /* Check basic validity of return value */
5096 annotations = merge (annotations, res, Qcar_less_than_car);
5097 p = XCDR (p);
5100 /* Now do the same for annotation functions implied by the file-format */
5101 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5102 p = BVAR (current_buffer, auto_save_file_format);
5103 else
5104 p = BVAR (current_buffer, file_format);
5105 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5107 struct buffer *given_buffer = current_buffer;
5109 Vwrite_region_annotations_so_far = annotations;
5111 /* Value is either a list of annotations or nil if the function
5112 has written annotations to a temporary buffer, which is now
5113 current. */
5114 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5115 original_buffer, make_number (i));
5116 if (current_buffer != given_buffer)
5118 XSETFASTINT (start, BEGV);
5119 XSETFASTINT (end, ZV);
5120 annotations = Qnil;
5123 if (CONSP (res))
5124 annotations = merge (annotations, res, Qcar_less_than_car);
5127 return annotations;
5131 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5132 If STRING is nil, POS is the character position in the current buffer.
5133 Intersperse with them the annotations from *ANNOT
5134 which fall within the range of POS to POS + NCHARS,
5135 each at its appropriate position.
5137 We modify *ANNOT by discarding elements as we use them up.
5139 Return true if successful. */
5141 static bool
5142 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5143 ptrdiff_t nchars, Lisp_Object *annot,
5144 struct coding_system *coding)
5146 Lisp_Object tem;
5147 ptrdiff_t nextpos;
5148 ptrdiff_t lastpos = pos + nchars;
5150 while (NILP (*annot) || CONSP (*annot))
5152 tem = Fcar_safe (Fcar (*annot));
5153 nextpos = pos - 1;
5154 if (INTEGERP (tem))
5155 nextpos = XFASTINT (tem);
5157 /* If there are no more annotations in this range,
5158 output the rest of the range all at once. */
5159 if (! (nextpos >= pos && nextpos <= lastpos))
5160 return e_write (desc, string, pos, lastpos, coding);
5162 /* Output buffer text up to the next annotation's position. */
5163 if (nextpos > pos)
5165 if (!e_write (desc, string, pos, nextpos, coding))
5166 return 0;
5167 pos = nextpos;
5169 /* Output the annotation. */
5170 tem = Fcdr (Fcar (*annot));
5171 if (STRINGP (tem))
5173 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5174 return 0;
5176 *annot = Fcdr (*annot);
5178 return 1;
5181 /* Maximum number of characters that the next
5182 function encodes per one loop iteration. */
5184 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5186 /* Write text in the range START and END into descriptor DESC,
5187 encoding them with coding system CODING. If STRING is nil, START
5188 and END are character positions of the current buffer, else they
5189 are indexes to the string STRING. Return true if successful. */
5191 static bool
5192 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5193 struct coding_system *coding)
5195 if (STRINGP (string))
5197 start = 0;
5198 end = SCHARS (string);
5201 /* We used to have a code for handling selective display here. But,
5202 now it is handled within encode_coding. */
5204 while (start < end)
5206 if (STRINGP (string))
5208 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5209 if (CODING_REQUIRE_ENCODING (coding))
5211 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5213 /* Avoid creating huge Lisp string in encode_coding_object. */
5214 if (nchars == E_WRITE_MAX)
5215 coding->raw_destination = 1;
5217 encode_coding_object
5218 (coding, string, start, string_char_to_byte (string, start),
5219 start + nchars, string_char_to_byte (string, start + nchars),
5220 Qt);
5222 else
5224 coding->dst_object = string;
5225 coding->consumed_char = SCHARS (string);
5226 coding->produced = SBYTES (string);
5229 else
5231 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5232 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5234 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5235 if (CODING_REQUIRE_ENCODING (coding))
5237 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5239 /* Likewise. */
5240 if (nchars == E_WRITE_MAX)
5241 coding->raw_destination = 1;
5243 encode_coding_object
5244 (coding, Fcurrent_buffer (), start, start_byte,
5245 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5247 else
5249 coding->dst_object = Qnil;
5250 coding->dst_pos_byte = start_byte;
5251 if (start >= GPT || end <= GPT)
5253 coding->consumed_char = end - start;
5254 coding->produced = end_byte - start_byte;
5256 else
5258 coding->consumed_char = GPT - start;
5259 coding->produced = GPT_BYTE - start_byte;
5264 if (coding->produced > 0)
5266 char *buf = (coding->raw_destination ? (char *) coding->destination
5267 : (STRINGP (coding->dst_object)
5268 ? SSDATA (coding->dst_object)
5269 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5270 coding->produced -= emacs_write_quit (desc, buf, coding->produced);
5272 if (coding->raw_destination)
5274 /* We're responsible for freeing this, see
5275 encode_coding_object to check why. */
5276 xfree (coding->destination);
5277 coding->raw_destination = 0;
5279 if (coding->produced)
5280 return 0;
5282 start += coding->consumed_char;
5285 return 1;
5288 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5289 Sverify_visited_file_modtime, 0, 1, 0,
5290 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5291 This means that the file has not been changed since it was visited or saved.
5292 If BUF is omitted or nil, it defaults to the current buffer.
5293 See Info node `(elisp)Modification Time' for more details. */)
5294 (Lisp_Object buf)
5296 struct buffer *b = decode_buffer (buf);
5297 struct stat st;
5298 Lisp_Object handler;
5299 Lisp_Object filename;
5300 struct timespec mtime;
5302 if (!STRINGP (BVAR (b, filename))) return Qt;
5303 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5305 /* If the file name has special constructs in it,
5306 call the corresponding file handler. */
5307 handler = Ffind_file_name_handler (BVAR (b, filename),
5308 Qverify_visited_file_modtime);
5309 if (!NILP (handler))
5310 return call2 (handler, Qverify_visited_file_modtime, buf);
5312 filename = ENCODE_FILE (BVAR (b, filename));
5314 mtime = (stat (SSDATA (filename), &st) == 0
5315 ? get_stat_mtime (&st)
5316 : time_error_value (errno));
5317 if (timespec_cmp (mtime, b->modtime) == 0
5318 && (b->modtime_size < 0
5319 || st.st_size == b->modtime_size))
5320 return Qt;
5321 return Qnil;
5324 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5325 Svisited_file_modtime, 0, 0, 0,
5326 doc: /* Return the current buffer's recorded visited file modification time.
5327 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5328 `file-attributes' returns. If the current buffer has no recorded file
5329 modification time, this function returns 0. If the visited file
5330 doesn't exist, return -1.
5331 See Info node `(elisp)Modification Time' for more details. */)
5332 (void)
5334 int ns = current_buffer->modtime.tv_nsec;
5335 if (ns < 0)
5336 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5337 return make_lisp_time (current_buffer->modtime);
5340 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5341 Sset_visited_file_modtime, 0, 1, 0,
5342 doc: /* Update buffer's recorded modification time from the visited file's time.
5343 Useful if the buffer was not read from the file normally
5344 or if the file itself has been changed for some known benign reason.
5345 An argument specifies the modification time value to use
5346 \(instead of that of the visited file), in the form of a list
5347 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5348 `visited-file-modtime'. */)
5349 (Lisp_Object time_flag)
5351 if (!NILP (time_flag))
5353 struct timespec mtime;
5354 if (INTEGERP (time_flag))
5356 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5357 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5359 else
5360 mtime = lisp_time_argument (time_flag);
5362 current_buffer->modtime = mtime;
5363 current_buffer->modtime_size = -1;
5365 else
5367 register Lisp_Object filename;
5368 struct stat st;
5369 Lisp_Object handler;
5371 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5373 /* If the file name has special constructs in it,
5374 call the corresponding file handler. */
5375 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5376 if (!NILP (handler))
5377 /* The handler can find the file name the same way we did. */
5378 return call2 (handler, Qset_visited_file_modtime, Qnil);
5380 filename = ENCODE_FILE (filename);
5382 if (stat (SSDATA (filename), &st) >= 0)
5384 current_buffer->modtime = get_stat_mtime (&st);
5385 current_buffer->modtime_size = st.st_size;
5389 return Qnil;
5392 static Lisp_Object
5393 auto_save_error (Lisp_Object error_val)
5395 auto_save_error_occurred = 1;
5397 ring_bell (XFRAME (selected_frame));
5399 AUTO_STRING (format, "Auto-saving %s: %s");
5400 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5401 Ferror_message_string (error_val));
5402 call3 (intern ("display-warning"),
5403 intern ("auto-save"), msg, intern ("error"));
5405 return Qnil;
5408 static Lisp_Object
5409 auto_save_1 (void)
5411 struct stat st;
5412 Lisp_Object modes;
5414 auto_save_mode_bits = 0666;
5416 /* Get visited file's mode to become the auto save file's mode. */
5417 if (! NILP (BVAR (current_buffer, filename)))
5419 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5420 /* But make sure we can overwrite it later! */
5421 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5422 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5423 INTEGERP (modes))
5424 /* Remote files don't cooperate with stat. */
5425 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5428 return
5429 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5430 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5431 Qnil, Qnil);
5434 struct auto_save_unwind
5436 FILE *stream;
5437 bool auto_raise;
5440 static void
5441 do_auto_save_unwind (void *arg)
5443 struct auto_save_unwind *p = arg;
5444 FILE *stream = p->stream;
5445 minibuffer_auto_raise = p->auto_raise;
5446 auto_saving = 0;
5447 if (stream != NULL)
5449 block_input ();
5450 fclose (stream);
5451 unblock_input ();
5455 static Lisp_Object
5456 do_auto_save_make_dir (Lisp_Object dir)
5458 Lisp_Object result;
5460 auto_saving_dir_umask = 077;
5461 result = call2 (Qmake_directory, dir, Qt);
5462 auto_saving_dir_umask = 0;
5463 return result;
5466 static Lisp_Object
5467 do_auto_save_eh (Lisp_Object ignore)
5469 auto_saving_dir_umask = 0;
5470 return Qnil;
5473 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5474 doc: /* Auto-save all buffers that need it.
5475 This is all buffers that have auto-saving enabled
5476 and are changed since last auto-saved.
5477 Auto-saving writes the buffer into a file
5478 so that your editing is not lost if the system crashes.
5479 This file is not the file you visited; that changes only when you save.
5480 Normally, run the normal hook `auto-save-hook' before saving.
5482 A non-nil NO-MESSAGE argument means do not print any message if successful.
5483 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5484 (Lisp_Object no_message, Lisp_Object current_only)
5486 struct buffer *old = current_buffer, *b;
5487 Lisp_Object tail, buf, hook;
5488 bool auto_saved = 0;
5489 int do_handled_files;
5490 Lisp_Object oquit;
5491 FILE *stream = NULL;
5492 ptrdiff_t count = SPECPDL_INDEX ();
5493 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5494 bool old_message_p = 0;
5495 struct auto_save_unwind auto_save_unwind;
5497 if (max_specpdl_size < specpdl_size + 40)
5498 max_specpdl_size = specpdl_size + 40;
5500 if (minibuf_level)
5501 no_message = Qt;
5503 if (NILP (no_message))
5505 old_message_p = push_message ();
5506 record_unwind_protect_void (pop_message_unwind);
5509 /* Ordinarily don't quit within this function,
5510 but don't make it impossible to quit (in case we get hung in I/O). */
5511 oquit = Vquit_flag;
5512 Vquit_flag = Qnil;
5514 hook = intern ("auto-save-hook");
5515 safe_run_hooks (hook);
5517 if (STRINGP (Vauto_save_list_file_name))
5519 Lisp_Object listfile;
5521 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5523 /* Don't try to create the directory when shutting down Emacs,
5524 because creating the directory might signal an error, and
5525 that would leave Emacs in a strange state. */
5526 if (!NILP (Vrun_hooks))
5528 Lisp_Object dir;
5529 dir = Ffile_name_directory (listfile);
5530 if (NILP (Ffile_directory_p (dir)))
5531 internal_condition_case_1 (do_auto_save_make_dir,
5532 dir, Qt,
5533 do_auto_save_eh);
5536 stream = emacs_fopen (SSDATA (listfile), "w");
5539 auto_save_unwind.stream = stream;
5540 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5541 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5542 minibuffer_auto_raise = 0;
5543 auto_saving = 1;
5544 auto_save_error_occurred = 0;
5546 /* On first pass, save all files that don't have handlers.
5547 On second pass, save all files that do have handlers.
5549 If Emacs is crashing, the handlers may tweak what is causing
5550 Emacs to crash in the first place, and it would be a shame if
5551 Emacs failed to autosave perfectly ordinary files because it
5552 couldn't handle some ange-ftp'd file. */
5554 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5555 FOR_EACH_LIVE_BUFFER (tail, buf)
5557 b = XBUFFER (buf);
5559 /* Record all the buffers that have auto save mode
5560 in the special file that lists them. For each of these buffers,
5561 Record visited name (if any) and auto save name. */
5562 if (STRINGP (BVAR (b, auto_save_file_name))
5563 && stream != NULL && do_handled_files == 0)
5565 block_input ();
5566 if (!NILP (BVAR (b, filename)))
5567 fwrite_unlocked (SDATA (BVAR (b, filename)), 1,
5568 SBYTES (BVAR (b, filename)), stream);
5569 putc_unlocked ('\n', stream);
5570 fwrite_unlocked (SDATA (BVAR (b, auto_save_file_name)), 1,
5571 SBYTES (BVAR (b, auto_save_file_name)), stream);
5572 putc_unlocked ('\n', stream);
5573 unblock_input ();
5576 if (!NILP (current_only)
5577 && b != current_buffer)
5578 continue;
5580 /* Don't auto-save indirect buffers.
5581 The base buffer takes care of it. */
5582 if (b->base_buffer)
5583 continue;
5585 /* Check for auto save enabled
5586 and file changed since last auto save
5587 and file changed since last real save. */
5588 if (STRINGP (BVAR (b, auto_save_file_name))
5589 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5590 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5591 /* -1 means we've turned off autosaving for a while--see below. */
5592 && XINT (BVAR (b, save_length)) >= 0
5593 && (do_handled_files
5594 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5595 Qwrite_region))))
5597 struct timespec before_time = current_timespec ();
5598 struct timespec after_time;
5600 /* If we had a failure, don't try again for 20 minutes. */
5601 if (b->auto_save_failure_time > 0
5602 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5603 continue;
5605 set_buffer_internal (b);
5606 if (NILP (Vauto_save_include_big_deletions)
5607 && (XFASTINT (BVAR (b, save_length)) * 10
5608 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5609 /* A short file is likely to change a large fraction;
5610 spare the user annoying messages. */
5611 && XFASTINT (BVAR (b, save_length)) > 5000
5612 /* These messages are frequent and annoying for `*mail*'. */
5613 && !EQ (BVAR (b, filename), Qnil)
5614 && NILP (no_message))
5616 /* It has shrunk too much; turn off auto-saving here. */
5617 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5618 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5619 BVAR (b, name), 1);
5620 minibuffer_auto_raise = 0;
5621 /* Turn off auto-saving until there's a real save,
5622 and prevent any more warnings. */
5623 XSETINT (BVAR (b, save_length), -1);
5624 Fsleep_for (make_number (1), Qnil);
5625 continue;
5627 if (!auto_saved && NILP (no_message))
5628 message1 ("Auto-saving...");
5629 internal_condition_case (auto_save_1, Qt, auto_save_error);
5630 auto_saved = 1;
5631 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5632 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5633 set_buffer_internal (old);
5635 after_time = current_timespec ();
5637 /* If auto-save took more than 60 seconds,
5638 assume it was an NFS failure that got a timeout. */
5639 if (after_time.tv_sec - before_time.tv_sec > 60)
5640 b->auto_save_failure_time = after_time.tv_sec;
5644 /* Prevent another auto save till enough input events come in. */
5645 record_auto_save ();
5647 if (auto_saved && NILP (no_message))
5649 if (old_message_p)
5651 /* If we are going to restore an old message,
5652 give time to read ours. */
5653 sit_for (make_number (1), 0, 0);
5654 restore_message ();
5656 else if (!auto_save_error_occurred)
5657 /* Don't overwrite the error message if an error occurred.
5658 If we displayed a message and then restored a state
5659 with no message, leave a "done" message on the screen. */
5660 message1 ("Auto-saving...done");
5663 Vquit_flag = oquit;
5665 /* This restores the message-stack status. */
5666 unbind_to (count, Qnil);
5667 return Qnil;
5670 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5671 Sset_buffer_auto_saved, 0, 0, 0,
5672 doc: /* Mark current buffer as auto-saved with its current text.
5673 No auto-save file will be written until the buffer changes again. */)
5674 (void)
5676 /* FIXME: This should not be called in indirect buffers, since
5677 they're not autosaved. */
5678 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5679 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5680 current_buffer->auto_save_failure_time = 0;
5681 return Qnil;
5684 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5685 Sclear_buffer_auto_save_failure, 0, 0, 0,
5686 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5687 (void)
5689 current_buffer->auto_save_failure_time = 0;
5690 return Qnil;
5693 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5694 0, 0, 0,
5695 doc: /* Return t if current buffer has been auto-saved recently.
5696 More precisely, if it has been auto-saved since last read from or saved
5697 in the visited file. If the buffer has no visited file,
5698 then any auto-save counts as "recent". */)
5699 (void)
5701 /* FIXME: maybe we should return nil for indirect buffers since
5702 they're never autosaved. */
5703 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5706 /* Reading and completing file names. */
5708 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5709 Snext_read_file_uses_dialog_p, 0, 0, 0,
5710 doc: /* Return t if a call to `read-file-name' will use a dialog.
5711 The return value is only relevant for a call to `read-file-name' that happens
5712 before any other event (mouse or keypress) is handled. */)
5713 (void)
5715 #if (defined USE_GTK || defined USE_MOTIF \
5716 || defined HAVE_NS || defined HAVE_NTGUI)
5717 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5718 && use_dialog_box
5719 && use_file_dialog
5720 && window_system_available (SELECTED_FRAME ()))
5721 return Qt;
5722 #endif
5723 return Qnil;
5727 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5728 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5729 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5730 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5731 it to text mode.
5733 As a side effect, this function flushes any pending STREAM's data.
5735 Value is the previous value of STREAM's I/O mode, nil for text mode,
5736 non-nil for binary mode.
5738 On MS-Windows and MS-DOS, binary mode is needed to read or write
5739 arbitrary binary data, and for disabling translation between CR-LF
5740 pairs and a single newline character. Examples include generation
5741 of text files with Unix-style end-of-line format using `princ' in
5742 batch mode, with standard output redirected to a file.
5744 On Posix systems, this function always returns non-nil, and has no
5745 effect except for flushing STREAM's data. */)
5746 (Lisp_Object stream, Lisp_Object mode)
5748 FILE *fp = NULL;
5749 int binmode;
5751 CHECK_SYMBOL (stream);
5752 if (EQ (stream, Qstdin))
5753 fp = stdin;
5754 else if (EQ (stream, Qstdout))
5755 fp = stdout;
5756 else if (EQ (stream, Qstderr))
5757 fp = stderr;
5758 else
5759 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5761 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5762 if (fp != stdin)
5763 fflush_unlocked (fp);
5765 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5768 void
5769 init_fileio (void)
5771 realmask = umask (0);
5772 umask (realmask);
5774 valid_timestamp_file_system = 0;
5776 /* fsync can be a significant performance hit. Often it doesn't
5777 suffice to make the file-save operation survive a crash. For
5778 batch scripts, which are typically part of larger shell commands
5779 that don't fsync other files, its effect on performance can be
5780 significant so its utility is particularly questionable.
5781 Hence, for now by default fsync is used only when interactive.
5783 For more on why fsync often fails to work on today's hardware, see:
5784 Zheng M et al. Understanding the robustness of SSDs under power fault.
5785 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5786 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5788 For more on why fsync does not suffice even if it works properly, see:
5789 Roche X. Necessary step(s) to synchronize filename operations on disk.
5790 Austin Group Defect 672, 2013-03-19
5791 http://austingroupbugs.net/view.php?id=672 */
5792 write_region_inhibit_fsync = noninteractive;
5795 void
5796 syms_of_fileio (void)
5798 /* Property name of a file name handler,
5799 which gives a list of operations it handles. */
5800 DEFSYM (Qoperations, "operations");
5802 DEFSYM (Qexpand_file_name, "expand-file-name");
5803 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5804 DEFSYM (Qdirectory_file_name, "directory-file-name");
5805 DEFSYM (Qfile_name_directory, "file-name-directory");
5806 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5807 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5808 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5809 DEFSYM (Qcopy_file, "copy-file");
5810 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5811 DEFSYM (Qmake_directory, "make-directory");
5812 DEFSYM (Qdelete_file, "delete-file");
5813 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5814 DEFSYM (Qrename_file, "rename-file");
5815 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5816 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5817 DEFSYM (Qfile_exists_p, "file-exists-p");
5818 DEFSYM (Qfile_executable_p, "file-executable-p");
5819 DEFSYM (Qfile_readable_p, "file-readable-p");
5820 DEFSYM (Qfile_writable_p, "file-writable-p");
5821 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5822 DEFSYM (Qaccess_file, "access-file");
5823 DEFSYM (Qfile_directory_p, "file-directory-p");
5824 DEFSYM (Qfile_regular_p, "file-regular-p");
5825 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5826 DEFSYM (Qfile_modes, "file-modes");
5827 DEFSYM (Qset_file_modes, "set-file-modes");
5828 DEFSYM (Qset_file_times, "set-file-times");
5829 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5830 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5831 DEFSYM (Qfile_acl, "file-acl");
5832 DEFSYM (Qset_file_acl, "set-file-acl");
5833 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5834 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5835 DEFSYM (Qwrite_region, "write-region");
5836 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5837 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5839 /* The symbol bound to coding-system-for-read when
5840 insert-file-contents is called for recovering a file. This is not
5841 an actual coding system name, but just an indicator to tell
5842 insert-file-contents to use `emacs-mule' with a special flag for
5843 auto saving and recovering a file. */
5844 DEFSYM (Qauto_save_coding, "auto-save-coding");
5846 DEFSYM (Qfile_name_history, "file-name-history");
5847 Fset (Qfile_name_history, Qnil);
5849 DEFSYM (Qfile_error, "file-error");
5850 DEFSYM (Qfile_already_exists, "file-already-exists");
5851 DEFSYM (Qfile_date_error, "file-date-error");
5852 DEFSYM (Qfile_missing, "file-missing");
5853 DEFSYM (Qfile_notify_error, "file-notify-error");
5854 DEFSYM (Qexcl, "excl");
5856 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5857 doc: /* Coding system for encoding file names.
5858 If it is nil, `default-file-name-coding-system' (which see) is used.
5860 On MS-Windows, the value of this variable is largely ignored if
5861 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5862 behaves as if file names were encoded in `utf-8'. */);
5863 Vfile_name_coding_system = Qnil;
5865 DEFVAR_LISP ("default-file-name-coding-system",
5866 Vdefault_file_name_coding_system,
5867 doc: /* Default coding system for encoding file names.
5868 This variable is used only when `file-name-coding-system' is nil.
5870 This variable is set/changed by the command `set-language-environment'.
5871 User should not set this variable manually,
5872 instead use `file-name-coding-system' to get a constant encoding
5873 of file names regardless of the current language environment.
5875 On MS-Windows, the value of this variable is largely ignored if
5876 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5877 behaves as if file names were encoded in `utf-8'. */);
5878 Vdefault_file_name_coding_system = Qnil;
5880 /* Lisp functions for translating file formats. */
5881 DEFSYM (Qformat_decode, "format-decode");
5882 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5884 /* Lisp function for setting buffer-file-coding-system and the
5885 multibyteness of the current buffer after inserting a file. */
5886 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5888 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5890 Fput (Qfile_error, Qerror_conditions,
5891 Fpurecopy (list2 (Qfile_error, Qerror)));
5892 Fput (Qfile_error, Qerror_message,
5893 build_pure_c_string ("File error"));
5895 Fput (Qfile_already_exists, Qerror_conditions,
5896 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5897 Fput (Qfile_already_exists, Qerror_message,
5898 build_pure_c_string ("File already exists"));
5900 Fput (Qfile_date_error, Qerror_conditions,
5901 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5902 Fput (Qfile_date_error, Qerror_message,
5903 build_pure_c_string ("Cannot set file date"));
5905 Fput (Qfile_missing, Qerror_conditions,
5906 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
5907 Fput (Qfile_missing, Qerror_message,
5908 build_pure_c_string ("File is missing"));
5910 Fput (Qfile_notify_error, Qerror_conditions,
5911 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5912 Fput (Qfile_notify_error, Qerror_message,
5913 build_pure_c_string ("File notification error"));
5915 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5916 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5917 If a file name matches REGEXP, all I/O on that file is done by calling
5918 HANDLER. If a file name matches more than one handler, the handler
5919 whose match starts last in the file name gets precedence. The
5920 function `find-file-name-handler' checks this list for a handler for
5921 its argument.
5923 HANDLER should be a function. The first argument given to it is the
5924 name of the I/O primitive to be handled; the remaining arguments are
5925 the arguments that were passed to that primitive. For example, if you
5926 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5927 HANDLER is called like this:
5929 (funcall HANDLER \\='file-exists-p FILENAME)
5931 Note that HANDLER must be able to handle all I/O primitives; if it has
5932 nothing special to do for a primitive, it should reinvoke the
5933 primitive to handle the operation \"the usual way\".
5934 See Info node `(elisp)Magic File Names' for more details. */);
5935 Vfile_name_handler_alist = Qnil;
5937 DEFVAR_LISP ("set-auto-coding-function",
5938 Vset_auto_coding_function,
5939 doc: /* If non-nil, a function to call to decide a coding system of file.
5940 Two arguments are passed to this function: the file name
5941 and the length of a file contents following the point.
5942 This function should return a coding system to decode the file contents.
5943 It should check the file name against `auto-coding-alist'.
5944 If no coding system is decided, it should check a coding system
5945 specified in the heading lines with the format:
5946 -*- ... coding: CODING-SYSTEM; ... -*-
5947 or local variable spec of the tailing lines with `coding:' tag. */);
5948 Vset_auto_coding_function = Qnil;
5950 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5951 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5952 Each is passed one argument, the number of characters inserted,
5953 with point at the start of the inserted text. Each function
5954 should leave point the same, and return the new character count.
5955 If `insert-file-contents' is intercepted by a handler from
5956 `file-name-handler-alist', that handler is responsible for calling the
5957 functions in `after-insert-file-functions' if appropriate. */);
5958 Vafter_insert_file_functions = Qnil;
5960 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5961 doc: /* A list of functions to be called at the start of `write-region'.
5962 Each is passed two arguments, START and END as for `write-region'.
5963 These are usually two numbers but not always; see the documentation
5964 for `write-region'. The function should return a list of pairs
5965 of the form (POSITION . STRING), consisting of strings to be effectively
5966 inserted at the specified positions of the file being written (1 means to
5967 insert before the first byte written). The POSITIONs must be sorted into
5968 increasing order.
5970 If there are several annotation functions, the lists returned by these
5971 functions are merged destructively. As each annotation function runs,
5972 the variable `write-region-annotations-so-far' contains a list of all
5973 annotations returned by previous annotation functions.
5975 An annotation function can return with a different buffer current.
5976 Doing so removes the annotations returned by previous functions, and
5977 resets START and END to `point-min' and `point-max' of the new buffer.
5979 After `write-region' completes, Emacs calls the function stored in
5980 `write-region-post-annotation-function', once for each buffer that was
5981 current when building the annotations (i.e., at least once), with that
5982 buffer current. */);
5983 Vwrite_region_annotate_functions = Qnil;
5984 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5986 DEFVAR_LISP ("write-region-post-annotation-function",
5987 Vwrite_region_post_annotation_function,
5988 doc: /* Function to call after `write-region' completes.
5989 The function is called with no arguments. If one or more of the
5990 annotation functions in `write-region-annotate-functions' changed the
5991 current buffer, the function stored in this variable is called for
5992 each of those additional buffers as well, in addition to the original
5993 buffer. The relevant buffer is current during each function call. */);
5994 Vwrite_region_post_annotation_function = Qnil;
5995 staticpro (&Vwrite_region_annotation_buffers);
5997 DEFVAR_LISP ("write-region-annotations-so-far",
5998 Vwrite_region_annotations_so_far,
5999 doc: /* When an annotation function is called, this holds the previous annotations.
6000 These are the annotations made by other annotation functions
6001 that were already called. See also `write-region-annotate-functions'. */);
6002 Vwrite_region_annotations_so_far = Qnil;
6004 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6005 doc: /* A list of file name handlers that temporarily should not be used.
6006 This applies only to the operation `inhibit-file-name-operation'. */);
6007 Vinhibit_file_name_handlers = Qnil;
6009 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6010 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6011 Vinhibit_file_name_operation = Qnil;
6013 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6014 doc: /* File name in which to write a list of all auto save file names.
6015 This variable is initialized automatically from `auto-save-list-file-prefix'
6016 shortly after Emacs reads your init file, if you have not yet given it
6017 a non-nil value. */);
6018 Vauto_save_list_file_name = Qnil;
6020 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6021 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6022 Normally auto-save files are written under other names. */);
6023 Vauto_save_visited_file_name = Qnil;
6025 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6026 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6027 If nil, deleting a substantial portion of the text disables auto-save
6028 in the buffer; this is the default behavior, because the auto-save
6029 file is usually more useful if it contains the deleted text. */);
6030 Vauto_save_include_big_deletions = Qnil;
6032 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6033 doc: /* Non-nil means don't call fsync in `write-region'.
6034 This variable affects calls to `write-region' as well as save commands.
6035 Setting this to nil may avoid data loss if the system loses power or
6036 the operating system crashes. By default, it is non-nil in batch mode. */);
6037 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6039 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6040 doc: /* Specifies whether to use the system's trash can.
6041 When non-nil, certain file deletion commands use the function
6042 `move-file-to-trash' instead of deleting files outright.
6043 This includes interactive calls to `delete-file' and
6044 `delete-directory' and the Dired deletion commands. */);
6045 delete_by_moving_to_trash = 0;
6046 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6048 /* Lisp function for moving files to trash. */
6049 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6051 /* Lisp function for recursively copying directories. */
6052 DEFSYM (Qcopy_directory, "copy-directory");
6054 /* Lisp function for recursively deleting directories. */
6055 DEFSYM (Qdelete_directory, "delete-directory");
6057 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6058 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6060 DEFSYM (Qstdin, "stdin");
6061 DEFSYM (Qstdout, "stdout");
6062 DEFSYM (Qstderr, "stderr");
6064 defsubr (&Sfind_file_name_handler);
6065 defsubr (&Sfile_name_directory);
6066 defsubr (&Sfile_name_nondirectory);
6067 defsubr (&Sunhandled_file_name_directory);
6068 defsubr (&Sfile_name_as_directory);
6069 defsubr (&Sdirectory_name_p);
6070 defsubr (&Sdirectory_file_name);
6071 defsubr (&Smake_temp_file_internal);
6072 defsubr (&Smake_temp_name);
6073 defsubr (&Sexpand_file_name);
6074 defsubr (&Ssubstitute_in_file_name);
6075 defsubr (&Scopy_file);
6076 defsubr (&Smake_directory_internal);
6077 defsubr (&Sdelete_directory_internal);
6078 defsubr (&Sdelete_file);
6079 defsubr (&Sfile_name_case_insensitive_p);
6080 defsubr (&Srename_file);
6081 defsubr (&Sadd_name_to_file);
6082 defsubr (&Smake_symbolic_link);
6083 defsubr (&Sfile_name_absolute_p);
6084 defsubr (&Sfile_exists_p);
6085 defsubr (&Sfile_executable_p);
6086 defsubr (&Sfile_readable_p);
6087 defsubr (&Sfile_writable_p);
6088 defsubr (&Saccess_file);
6089 defsubr (&Sfile_symlink_p);
6090 defsubr (&Sfile_directory_p);
6091 defsubr (&Sfile_accessible_directory_p);
6092 defsubr (&Sfile_regular_p);
6093 defsubr (&Sfile_modes);
6094 defsubr (&Sset_file_modes);
6095 defsubr (&Sset_file_times);
6096 defsubr (&Sfile_selinux_context);
6097 defsubr (&Sfile_acl);
6098 defsubr (&Sset_file_acl);
6099 defsubr (&Sset_file_selinux_context);
6100 defsubr (&Sset_default_file_modes);
6101 defsubr (&Sdefault_file_modes);
6102 defsubr (&Sfile_newer_than_file_p);
6103 defsubr (&Sinsert_file_contents);
6104 defsubr (&Swrite_region);
6105 defsubr (&Scar_less_than_car);
6106 defsubr (&Sverify_visited_file_modtime);
6107 defsubr (&Svisited_file_modtime);
6108 defsubr (&Sset_visited_file_modtime);
6109 defsubr (&Sdo_auto_save);
6110 defsubr (&Sset_buffer_auto_saved);
6111 defsubr (&Sclear_buffer_auto_save_failure);
6112 defsubr (&Srecent_auto_save_p);
6114 defsubr (&Snext_read_file_uses_dialog_p);
6116 defsubr (&Sset_binary_mode);
6118 #ifdef HAVE_SYNC
6119 defsubr (&Sunix_sync);
6120 #endif