Fix the MS-Windows build
[emacs.git] / src / fileio.c
blob1b832be344dbf67ab94021a7aaf486ce189a4aec
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, 3, 3, 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.
668 Signal an error if the file could not be created.
670 This function does not grok magic file names. */)
671 (Lisp_Object prefix, Lisp_Object dir_flag, Lisp_Object suffix)
673 CHECK_STRING (prefix);
674 CHECK_STRING (suffix);
675 Lisp_Object encoded_prefix = ENCODE_FILE (prefix);
676 Lisp_Object encoded_suffix = ENCODE_FILE (suffix);
677 ptrdiff_t prefix_len = SBYTES (encoded_prefix);
678 ptrdiff_t suffix_len = SBYTES (encoded_suffix);
679 if (INT_MAX < suffix_len)
680 args_out_of_range (prefix, suffix);
681 int nX = 6;
682 Lisp_Object val = make_uninit_string (prefix_len + nX + suffix_len);
683 char *data = SSDATA (val);
684 memcpy (data, SSDATA (encoded_prefix), prefix_len);
685 memset (data + prefix_len, 'X', nX);
686 memcpy (data + prefix_len + nX, SSDATA (encoded_suffix), suffix_len);
687 int kind = (NILP (dir_flag) ? GT_FILE
688 : EQ (dir_flag, make_number (0)) ? GT_NOCREATE
689 : GT_DIR);
690 int fd = gen_tempname (data, suffix_len, O_BINARY | O_CLOEXEC, kind);
691 if (fd < 0 || (NILP (dir_flag) && emacs_close (fd) != 0))
693 static char const kind_message[][32] =
695 [GT_FILE] = "Creating file with prefix",
696 [GT_DIR] = "Creating directory with prefix",
697 [GT_NOCREATE] = "Creating file name with prefix"
699 report_file_error (kind_message[kind], prefix);
701 return DECODE_FILE (val);
705 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
706 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
708 This function tries to choose a name that has no existing file.
709 For this to work, PREFIX should be an absolute file name, and PREFIX
710 and the returned string should both be non-magic.
712 There is a race condition between calling `make-temp-name' and
713 later creating the file, which opens all kinds of security holes.
714 For that reason, you should normally use `make-temp-file' instead. */)
715 (Lisp_Object prefix)
717 return Fmake_temp_file_internal (prefix, make_number (0),
718 empty_unibyte_string);
721 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
722 doc: /* Convert filename NAME to absolute, and canonicalize it.
723 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
724 \(does not start with slash or tilde); both the directory name and
725 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
726 missing, the current buffer's value of `default-directory' is used.
727 NAME should be a string that is a valid file name for the underlying
728 filesystem.
729 File name components that are `.' are removed, and
730 so are file name components followed by `..', along with the `..' itself;
731 note that these simplifications are done without checking the resulting
732 file names in the file system.
733 Multiple consecutive slashes are collapsed into a single slash,
734 except at the beginning of the file name when they are significant (e.g.,
735 UNC file names on MS-Windows.)
736 An initial `~/' expands to your home directory.
737 An initial `~USER/' expands to USER's home directory.
738 See also the function `substitute-in-file-name'.
740 For technical reasons, this function can return correct but
741 non-intuitive results for the root directory; for instance,
742 \(expand-file-name ".." "/") returns "/..". For this reason, use
743 \(directory-file-name (file-name-directory dirname)) to traverse a
744 filesystem tree, not (expand-file-name ".." dirname). */)
745 (Lisp_Object name, Lisp_Object default_directory)
747 /* These point to SDATA and need to be careful with string-relocation
748 during GC (via DECODE_FILE). */
749 char *nm;
750 char *nmlim;
751 const char *newdir;
752 const char *newdirlim;
753 /* This should only point to alloca'd data. */
754 char *target;
756 ptrdiff_t tlen;
757 struct passwd *pw;
758 #ifdef DOS_NT
759 int drive = 0;
760 bool collapse_newdir = true;
761 bool is_escaped = 0;
762 #endif /* DOS_NT */
763 ptrdiff_t length, nbytes;
764 Lisp_Object handler, result, handled_name;
765 bool multibyte;
766 Lisp_Object hdir;
767 USE_SAFE_ALLOCA;
769 CHECK_STRING (name);
771 /* If the file name has special constructs in it,
772 call the corresponding file handler. */
773 handler = Ffind_file_name_handler (name, Qexpand_file_name);
774 if (!NILP (handler))
776 handled_name = call3 (handler, Qexpand_file_name,
777 name, default_directory);
778 if (STRINGP (handled_name))
779 return handled_name;
780 error ("Invalid handler in `file-name-handler-alist'");
784 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
785 if (NILP (default_directory))
786 default_directory = BVAR (current_buffer, directory);
787 if (! STRINGP (default_directory))
789 #ifdef DOS_NT
790 /* "/" is not considered a root directory on DOS_NT, so using "/"
791 here causes an infinite recursion in, e.g., the following:
793 (let (default-directory)
794 (expand-file-name "a"))
796 To avoid this, we set default_directory to the root of the
797 current drive. */
798 default_directory = build_string (emacs_root_dir ());
799 #else
800 default_directory = build_string ("/");
801 #endif
804 if (!NILP (default_directory))
806 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
807 if (!NILP (handler))
809 handled_name = call3 (handler, Qexpand_file_name,
810 name, default_directory);
811 if (STRINGP (handled_name))
812 return handled_name;
813 error ("Invalid handler in `file-name-handler-alist'");
818 char *o = SSDATA (default_directory);
820 /* Make sure DEFAULT_DIRECTORY is properly expanded.
821 It would be better to do this down below where we actually use
822 default_directory. Unfortunately, calling Fexpand_file_name recursively
823 could invoke GC, and the strings might be relocated. This would
824 be annoying because we have pointers into strings lying around
825 that would need adjusting, and people would add new pointers to
826 the code and forget to adjust them, resulting in intermittent bugs.
827 Putting this call here avoids all that crud.
829 The EQ test avoids infinite recursion. */
830 if (! NILP (default_directory) && !EQ (default_directory, name)
831 /* Save time in some common cases - as long as default_directory
832 is not relative, it can be canonicalized with name below (if it
833 is needed at all) without requiring it to be expanded now. */
834 #ifdef DOS_NT
835 /* Detect MSDOS file names with drive specifiers. */
836 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
837 && IS_DIRECTORY_SEP (o[2]))
838 /* Detect escaped file names without drive spec after "/:".
839 These should not be recursively expanded, to avoid
840 including the default directory twice in the expanded
841 result. */
842 && ! (o[0] == '/' && o[1] == ':')
843 #ifdef WINDOWSNT
844 /* Detect Windows file names in UNC format. */
845 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
846 #endif
847 #else /* not DOS_NT */
848 /* Detect Unix absolute file names (/... alone is not absolute on
849 DOS or Windows). */
850 && ! (IS_DIRECTORY_SEP (o[0]))
851 #endif /* not DOS_NT */
854 default_directory = Fexpand_file_name (default_directory, Qnil);
857 multibyte = STRING_MULTIBYTE (name);
858 if (multibyte != STRING_MULTIBYTE (default_directory))
860 if (multibyte)
862 unsigned char *p = SDATA (name);
864 while (*p && ASCII_CHAR_P (*p))
865 p++;
866 if (*p == '\0')
868 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
869 unibyte. Do not convert DEFAULT_DIRECTORY to
870 multibyte; instead, convert NAME to a unibyte string,
871 so that the result of this function is also a unibyte
872 string. This is needed during bootstrapping and
873 dumping, when Emacs cannot decode file names, because
874 the locale environment is not set up. */
875 name = make_unibyte_string (SSDATA (name), SBYTES (name));
876 multibyte = 0;
878 else
879 default_directory = string_to_multibyte (default_directory);
881 else
883 name = string_to_multibyte (name);
884 multibyte = 1;
888 #ifdef WINDOWSNT
889 if (!NILP (Vw32_downcase_file_names))
890 default_directory = Fdowncase (default_directory);
891 #endif
893 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
894 SAFE_ALLOCA_STRING (nm, name);
895 nmlim = nm + SBYTES (name);
897 #ifdef DOS_NT
898 /* Note if special escape prefix is present, but remove for now. */
899 if (nm[0] == '/' && nm[1] == ':')
901 is_escaped = 1;
902 nm += 2;
905 /* Find and remove drive specifier if present; this makes nm absolute
906 even if the rest of the name appears to be relative. Only look for
907 drive specifier at the beginning. */
908 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
910 drive = (unsigned char) nm[0];
911 nm += 2;
914 #ifdef WINDOWSNT
915 /* If we see "c://somedir", we want to strip the first slash after the
916 colon when stripping the drive letter. Otherwise, this expands to
917 "//somedir". */
918 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
919 nm++;
921 /* Discard any previous drive specifier if nm is now in UNC format. */
922 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
923 && !IS_DIRECTORY_SEP (nm[2]))
924 drive = 0;
925 #endif /* WINDOWSNT */
926 #endif /* DOS_NT */
928 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
929 none are found, we can probably return right away. We will avoid
930 allocating a new string if name is already fully expanded. */
931 if (
932 IS_DIRECTORY_SEP (nm[0])
933 #ifdef MSDOS
934 && drive && !is_escaped
935 #endif
936 #ifdef WINDOWSNT
937 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
938 #endif
941 /* If it turns out that the filename we want to return is just a
942 suffix of FILENAME, we don't need to go through and edit
943 things; we just need to construct a new string using data
944 starting at the middle of FILENAME. If we set LOSE, that
945 means we've discovered that we can't do that cool trick. */
946 bool lose = 0;
947 char *p = nm;
949 while (*p)
951 /* Since we know the name is absolute, we can assume that each
952 element starts with a "/". */
954 /* "." and ".." are hairy. */
955 if (IS_DIRECTORY_SEP (p[0])
956 && p[1] == '.'
957 && (IS_DIRECTORY_SEP (p[2])
958 || p[2] == 0
959 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
960 || p[3] == 0))))
961 lose = 1;
962 /* Replace multiple slashes with a single one, except
963 leave leading "//" alone. */
964 else if (IS_DIRECTORY_SEP (p[0])
965 && IS_DIRECTORY_SEP (p[1])
966 && (p != nm || IS_DIRECTORY_SEP (p[2])))
967 lose = 1;
968 p++;
970 if (!lose)
972 #ifdef DOS_NT
973 /* Make sure directories are all separated with /, but
974 avoid allocation of a new string when not required. */
975 dostounix_filename (nm);
976 #ifdef WINDOWSNT
977 if (IS_DIRECTORY_SEP (nm[1]))
979 if (strcmp (nm, SSDATA (name)) != 0)
980 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
982 else
983 #endif
984 /* Drive must be set, so this is okay. */
985 if (strcmp (nm - 2, SSDATA (name)) != 0)
987 name = make_specified_string (nm, -1, p - nm, multibyte);
988 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
989 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
990 name = concat2 (drive_prefix, name);
992 #ifdef WINDOWSNT
993 if (!NILP (Vw32_downcase_file_names))
994 name = Fdowncase (name);
995 #endif
996 #else /* not DOS_NT */
997 if (strcmp (nm, SSDATA (name)) != 0)
998 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
999 #endif /* not DOS_NT */
1000 SAFE_FREE ();
1001 return name;
1005 /* At this point, nm might or might not be an absolute file name. We
1006 need to expand ~ or ~user if present, otherwise prefix nm with
1007 default_directory if nm is not absolute, and finally collapse /./
1008 and /foo/../ sequences.
1010 We set newdir to be the appropriate prefix if one is needed:
1011 - the relevant user directory if nm starts with ~ or ~user
1012 - the specified drive's working dir (DOS/NT only) if nm does not
1013 start with /
1014 - the value of default_directory.
1016 Note that these prefixes are not guaranteed to be absolute (except
1017 for the working dir of a drive). Therefore, to ensure we always
1018 return an absolute name, if the final prefix is not absolute we
1019 append it to the current working directory. */
1021 newdir = newdirlim = 0;
1023 if (nm[0] == '~' /* prefix ~ */
1024 #ifdef DOS_NT
1025 && !is_escaped /* don't expand ~ in escaped file names */
1026 #endif
1029 if (IS_DIRECTORY_SEP (nm[1])
1030 || nm[1] == 0) /* ~ by itself */
1032 Lisp_Object tem;
1034 if (!(newdir = egetenv ("HOME")))
1035 newdir = newdirlim = "";
1036 nm++;
1037 #ifdef WINDOWSNT
1038 if (newdir[0])
1040 char newdir_utf8[MAX_UTF8_PATH];
1042 filename_from_ansi (newdir, newdir_utf8);
1043 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1044 newdir = SSDATA (tem);
1046 else
1047 #endif
1048 tem = build_string (newdir);
1049 newdirlim = newdir + SBYTES (tem);
1050 /* `egetenv' may return a unibyte string, which will bite us
1051 if we expect the directory to be multibyte. */
1052 if (multibyte && !STRING_MULTIBYTE (tem))
1054 hdir = DECODE_FILE (tem);
1055 newdir = SSDATA (hdir);
1056 newdirlim = newdir + SBYTES (hdir);
1058 #ifdef DOS_NT
1059 collapse_newdir = false;
1060 #endif
1062 else /* ~user/filename */
1064 char *o, *p;
1065 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1066 continue;
1067 o = SAFE_ALLOCA (p - nm + 1);
1068 memcpy (o, nm, p - nm);
1069 o[p - nm] = 0;
1071 block_input ();
1072 pw = getpwnam (o + 1);
1073 unblock_input ();
1074 if (pw)
1076 Lisp_Object tem;
1078 newdir = pw->pw_dir;
1079 /* `getpwnam' may return a unibyte string, which will
1080 bite us when we expect the directory to be multibyte. */
1081 tem = make_unibyte_string (newdir, strlen (newdir));
1082 newdirlim = newdir + SBYTES (tem);
1083 if (multibyte && !STRING_MULTIBYTE (tem))
1085 hdir = DECODE_FILE (tem);
1086 newdir = SSDATA (hdir);
1087 newdirlim = newdir + SBYTES (hdir);
1089 nm = p;
1090 #ifdef DOS_NT
1091 collapse_newdir = false;
1092 #endif
1095 /* If we don't find a user of that name, leave the name
1096 unchanged; don't move nm forward to p. */
1100 #ifdef DOS_NT
1101 /* On DOS and Windows, nm is absolute if a drive name was specified;
1102 use the drive's current directory as the prefix if needed. */
1103 if (!newdir && drive)
1105 /* Get default directory if needed to make nm absolute. */
1106 char *adir = NULL;
1107 if (!IS_DIRECTORY_SEP (nm[0]))
1109 adir = alloca (MAXPATHLEN + 1);
1110 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1111 adir = NULL;
1112 else if (multibyte)
1114 Lisp_Object tem = build_string (adir);
1116 tem = DECODE_FILE (tem);
1117 newdirlim = adir + SBYTES (tem);
1118 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1120 else
1121 newdirlim = adir + strlen (adir);
1123 if (!adir)
1125 /* Either nm starts with /, or drive isn't mounted. */
1126 adir = alloca (4);
1127 adir[0] = DRIVE_LETTER (drive);
1128 adir[1] = ':';
1129 adir[2] = '/';
1130 adir[3] = 0;
1131 newdirlim = adir + 3;
1133 newdir = adir;
1135 #endif /* DOS_NT */
1137 /* Finally, if no prefix has been specified and nm is not absolute,
1138 then it must be expanded relative to default_directory. */
1140 if (1
1141 #ifndef DOS_NT
1142 /* /... alone is not absolute on DOS and Windows. */
1143 && !IS_DIRECTORY_SEP (nm[0])
1144 #endif
1145 #ifdef WINDOWSNT
1146 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1147 && !IS_DIRECTORY_SEP (nm[2]))
1148 #endif
1149 && !newdir)
1151 newdir = SSDATA (default_directory);
1152 newdirlim = newdir + SBYTES (default_directory);
1153 #ifdef DOS_NT
1154 /* Note if special escape prefix is present, but remove for now. */
1155 if (newdir[0] == '/' && newdir[1] == ':')
1157 is_escaped = 1;
1158 newdir += 2;
1160 #endif
1163 #ifdef DOS_NT
1164 if (newdir)
1166 /* First ensure newdir is an absolute name. */
1167 if (
1168 /* Detect MSDOS file names with drive specifiers. */
1169 ! (IS_DRIVE (newdir[0])
1170 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1171 #ifdef WINDOWSNT
1172 /* Detect Windows file names in UNC format. */
1173 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1174 && !IS_DIRECTORY_SEP (newdir[2]))
1175 #endif
1178 /* Effectively, let newdir be (expand-file-name newdir cwd).
1179 Because of the admonition against calling expand-file-name
1180 when we have pointers into lisp strings, we accomplish this
1181 indirectly by prepending newdir to nm if necessary, and using
1182 cwd (or the wd of newdir's drive) as the new newdir. */
1183 char *adir;
1184 #ifdef WINDOWSNT
1185 const int adir_size = MAX_UTF8_PATH;
1186 #else
1187 const int adir_size = MAXPATHLEN + 1;
1188 #endif
1190 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1192 drive = (unsigned char) newdir[0];
1193 newdir += 2;
1195 if (!IS_DIRECTORY_SEP (nm[0]))
1197 ptrdiff_t nmlen = nmlim - nm;
1198 ptrdiff_t newdirlen = newdirlim - newdir;
1199 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1200 + nmlen + 1);
1201 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1202 multibyte);
1203 memcpy (tmp + dlen, nm, nmlen + 1);
1204 nm = tmp;
1205 nmlim = nm + dlen + nmlen;
1207 adir = alloca (adir_size);
1208 if (drive)
1210 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1211 strcpy (adir, "/");
1213 else
1214 getcwd (adir, adir_size);
1215 if (multibyte)
1217 Lisp_Object tem = build_string (adir);
1219 tem = DECODE_FILE (tem);
1220 newdirlim = adir + SBYTES (tem);
1221 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1223 else
1224 newdirlim = adir + strlen (adir);
1225 newdir = adir;
1228 /* Strip off drive name from prefix, if present. */
1229 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1231 drive = newdir[0];
1232 newdir += 2;
1235 /* Keep only a prefix from newdir if nm starts with slash
1236 (//server/share for UNC, nothing otherwise). */
1237 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1239 #ifdef WINDOWSNT
1240 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1241 && !IS_DIRECTORY_SEP (newdir[2]))
1243 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1244 char *p = adir + 2;
1245 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1246 p++;
1247 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1248 *p = 0;
1249 newdir = adir;
1250 newdirlim = newdir + strlen (adir);
1252 else
1253 #endif
1254 newdir = newdirlim = "";
1257 #endif /* DOS_NT */
1259 /* Ignore any slash at the end of newdir, unless newdir is
1260 just "/" or "//". */
1261 length = newdirlim - newdir;
1262 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1263 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1264 length--;
1266 /* Now concatenate the directory and name to new space in the stack frame. */
1267 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1268 eassert (tlen > file_name_as_directory_slop + 1);
1269 #ifdef DOS_NT
1270 /* Reserve space for drive specifier and escape prefix, since either
1271 or both may need to be inserted. (The Microsoft x86 compiler
1272 produces incorrect code if the following two lines are combined.) */
1273 target = alloca (tlen + 4);
1274 target += 4;
1275 #else /* not DOS_NT */
1276 target = SAFE_ALLOCA (tlen);
1277 #endif /* not DOS_NT */
1278 *target = 0;
1279 nbytes = 0;
1281 if (newdir)
1283 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1285 #ifdef DOS_NT
1286 /* If newdir is effectively "C:/", then the drive letter will have
1287 been stripped and newdir will be "/". Concatenating with an
1288 absolute directory in nm produces "//", which will then be
1289 incorrectly treated as a network share. Ignore newdir in
1290 this case (keeping the drive letter). */
1291 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1292 && newdir[1] == '\0'))
1293 #endif
1295 memcpy (target, newdir, length);
1296 target[length] = 0;
1297 nbytes = length;
1300 else
1301 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1304 memcpy (target + nbytes, nm, nmlim - nm + 1);
1306 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1307 appear. */
1309 char *p = target;
1310 char *o = target;
1312 while (*p)
1314 if (!IS_DIRECTORY_SEP (*p))
1316 *o++ = *p++;
1318 else if (p[1] == '.'
1319 && (IS_DIRECTORY_SEP (p[2])
1320 || p[2] == 0))
1322 /* If "/." is the entire filename, keep the "/". Otherwise,
1323 just delete the whole "/.". */
1324 if (o == target && p[2] == '\0')
1325 *o++ = *p;
1326 p += 2;
1328 else if (p[1] == '.' && p[2] == '.'
1329 /* `/../' is the "superroot" on certain file systems.
1330 Turned off on DOS_NT systems because they have no
1331 "superroot" and because this causes us to produce
1332 file names like "d:/../foo" which fail file-related
1333 functions of the underlying OS. (To reproduce, try a
1334 long series of "../../" in default_directory, longer
1335 than the number of levels from the root.) */
1336 #ifndef DOS_NT
1337 && o != target
1338 #endif
1339 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1341 #ifdef WINDOWSNT
1342 char *prev_o = o;
1343 #endif
1344 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1345 continue;
1346 #ifdef WINDOWSNT
1347 /* Don't go below server level in UNC filenames. */
1348 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1349 && IS_DIRECTORY_SEP (*target))
1350 o = prev_o;
1351 else
1352 #endif
1353 /* Keep initial / only if this is the whole name. */
1354 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1355 ++o;
1356 p += 3;
1358 else if (IS_DIRECTORY_SEP (p[1])
1359 && (p != target || IS_DIRECTORY_SEP (p[2])))
1360 /* Collapse multiple "/", except leave leading "//" alone. */
1361 p++;
1362 else
1364 *o++ = *p++;
1368 #ifdef DOS_NT
1369 /* At last, set drive name. */
1370 #ifdef WINDOWSNT
1371 /* Except for network file name. */
1372 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1373 #endif /* WINDOWSNT */
1375 if (!drive) emacs_abort ();
1376 target -= 2;
1377 target[0] = DRIVE_LETTER (drive);
1378 target[1] = ':';
1380 /* Reinsert the escape prefix if required. */
1381 if (is_escaped)
1383 target -= 2;
1384 target[0] = '/';
1385 target[1] = ':';
1387 result = make_specified_string (target, -1, o - target, multibyte);
1388 dostounix_filename (SSDATA (result));
1389 #ifdef WINDOWSNT
1390 if (!NILP (Vw32_downcase_file_names))
1391 result = Fdowncase (result);
1392 #endif
1393 #else /* !DOS_NT */
1394 result = make_specified_string (target, -1, o - target, multibyte);
1395 #endif /* !DOS_NT */
1398 /* Again look to see if the file name has special constructs in it
1399 and perhaps call the corresponding file handler. This is needed
1400 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1401 the ".." component gives us "/user@host:/bar/../baz" which needs
1402 to be expanded again. */
1403 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1404 if (!NILP (handler))
1406 handled_name = call3 (handler, Qexpand_file_name,
1407 result, default_directory);
1408 if (! STRINGP (handled_name))
1409 error ("Invalid handler in `file-name-handler-alist'");
1410 result = handled_name;
1413 SAFE_FREE ();
1414 return result;
1417 #if 0
1418 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1419 This is the old version of expand-file-name, before it was thoroughly
1420 rewritten for Emacs 10.31. We leave this version here commented-out,
1421 because the code is very complex and likely to have subtle bugs. If
1422 bugs _are_ found, it might be of interest to look at the old code and
1423 see what did it do in the relevant situation.
1425 Don't remove this code: it's true that it will be accessible
1426 from the repository, but a few years from deletion, people will
1427 forget it is there. */
1429 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1430 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1431 "Convert FILENAME to absolute, and canonicalize it.\n\
1432 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1433 \(does not start with slash); if DEFAULT is nil or missing,\n\
1434 the current buffer's value of default-directory is used.\n\
1435 Filenames containing `.' or `..' as components are simplified;\n\
1436 initial `~/' expands to your home directory.\n\
1437 See also the function `substitute-in-file-name'.")
1438 (name, defalt)
1439 Lisp_Object name, defalt;
1441 unsigned char *nm;
1443 register unsigned char *newdir, *p, *o;
1444 ptrdiff_t tlen;
1445 unsigned char *target;
1446 struct passwd *pw;
1448 CHECK_STRING (name);
1449 nm = SDATA (name);
1451 /* If nm is absolute, flush ...// and detect /./ and /../.
1452 If no /./ or /../ we can return right away. */
1453 if (nm[0] == '/')
1455 bool lose = 0;
1456 p = nm;
1457 while (*p)
1459 if (p[0] == '/' && p[1] == '/')
1460 nm = p + 1;
1461 if (p[0] == '/' && p[1] == '~')
1462 nm = p + 1, lose = 1;
1463 if (p[0] == '/' && p[1] == '.'
1464 && (p[2] == '/' || p[2] == 0
1465 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1466 lose = 1;
1467 p++;
1469 if (!lose)
1471 if (nm == SDATA (name))
1472 return name;
1473 return build_string (nm);
1477 /* Now determine directory to start with and put it in NEWDIR. */
1479 newdir = 0;
1481 if (nm[0] == '~') /* prefix ~ */
1482 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1484 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1485 newdir = (unsigned char *) "";
1486 nm++;
1488 else /* ~user/filename */
1490 /* Get past ~ to user. */
1491 unsigned char *user = nm + 1;
1492 /* Find end of name. */
1493 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1494 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1495 /* Copy the user name into temp storage. */
1496 o = alloca (len + 1);
1497 memcpy (o, user, len);
1498 o[len] = 0;
1500 /* Look up the user name. */
1501 block_input ();
1502 pw = (struct passwd *) getpwnam (o + 1);
1503 unblock_input ();
1504 if (!pw)
1505 error ("\"%s\" isn't a registered user", o + 1);
1507 newdir = (unsigned char *) pw->pw_dir;
1509 /* Discard the user name from NM. */
1510 nm += len;
1513 if (nm[0] != '/' && !newdir)
1515 if (NILP (defalt))
1516 defalt = current_buffer->directory;
1517 CHECK_STRING (defalt);
1518 newdir = SDATA (defalt);
1521 /* Now concatenate the directory and name to new space in the stack frame. */
1523 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1524 target = alloca (tlen);
1525 *target = 0;
1527 if (newdir)
1529 if (nm[0] == 0 || nm[0] == '/')
1530 strcpy (target, newdir);
1531 else
1532 file_name_as_directory (target, newdir);
1535 strcat (target, nm);
1537 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1539 p = target;
1540 o = target;
1542 while (*p)
1544 if (*p != '/')
1546 *o++ = *p++;
1548 else if (!strncmp (p, "//", 2)
1551 o = target;
1552 p++;
1554 else if (p[0] == '/' && p[1] == '.'
1555 && (p[2] == '/' || p[2] == 0))
1556 p += 2;
1557 else if (!strncmp (p, "/..", 3)
1558 /* `/../' is the "superroot" on certain file systems. */
1559 && o != target
1560 && (p[3] == '/' || p[3] == 0))
1562 while (o != target && *--o != '/')
1564 if (o == target && *o == '/')
1565 ++o;
1566 p += 3;
1568 else
1570 *o++ = *p++;
1574 return make_string (target, o - target);
1576 #endif
1578 /* If /~ or // appears, discard everything through first slash. */
1579 static bool
1580 file_name_absolute_p (const char *filename)
1582 return
1583 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1584 #ifdef DOS_NT
1585 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1586 && IS_DIRECTORY_SEP (filename[2]))
1587 #endif
1591 static char *
1592 search_embedded_absfilename (char *nm, char *endp)
1594 char *p, *s;
1596 for (p = nm + 1; p < endp; p++)
1598 if (IS_DIRECTORY_SEP (p[-1])
1599 && file_name_absolute_p (p)
1600 #if defined (WINDOWSNT) || defined (CYGWIN)
1601 /* // at start of file name is meaningful in Apollo,
1602 WindowsNT and Cygwin systems. */
1603 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1604 #endif /* not (WINDOWSNT || CYGWIN) */
1607 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1608 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1610 USE_SAFE_ALLOCA;
1611 char *o = SAFE_ALLOCA (s - p + 1);
1612 struct passwd *pw;
1613 memcpy (o, p, s - p);
1614 o [s - p] = 0;
1616 /* If we have ~user and `user' exists, discard
1617 everything up to ~. But if `user' does not exist, leave
1618 ~user alone, it might be a literal file name. */
1619 block_input ();
1620 pw = getpwnam (o + 1);
1621 unblock_input ();
1622 SAFE_FREE ();
1623 if (pw)
1624 return p;
1626 else
1627 return p;
1630 return NULL;
1633 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1634 Ssubstitute_in_file_name, 1, 1, 0,
1635 doc: /* Substitute environment variables referred to in FILENAME.
1636 `$FOO' where FOO is an environment variable name means to substitute
1637 the value of that variable. The variable name should be terminated
1638 with a character not a letter, digit or underscore; otherwise, enclose
1639 the entire variable name in braces.
1641 If `/~' appears, all of FILENAME through that `/' is discarded.
1642 If `//' appears, everything up to and including the first of
1643 those `/' is discarded. */)
1644 (Lisp_Object filename)
1646 char *nm, *p, *x, *endp;
1647 bool substituted = false;
1648 bool multibyte;
1649 char *xnm;
1650 Lisp_Object handler;
1652 CHECK_STRING (filename);
1654 multibyte = STRING_MULTIBYTE (filename);
1656 /* If the file name has special constructs in it,
1657 call the corresponding file handler. */
1658 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1659 if (!NILP (handler))
1661 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1662 filename);
1663 if (STRINGP (handled_name))
1664 return handled_name;
1665 error ("Invalid handler in `file-name-handler-alist'");
1668 /* Always work on a copy of the string, in case GC happens during
1669 decode of environment variables, causing the original Lisp_String
1670 data to be relocated. */
1671 USE_SAFE_ALLOCA;
1672 SAFE_ALLOCA_STRING (nm, filename);
1674 #ifdef DOS_NT
1675 dostounix_filename (nm);
1676 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1677 #endif
1678 endp = nm + SBYTES (filename);
1680 /* If /~ or // appears, discard everything through first slash. */
1681 p = search_embedded_absfilename (nm, endp);
1682 if (p)
1683 /* Start over with the new string, so we check the file-name-handler
1684 again. Important with filenames like "/home/foo//:/hello///there"
1685 which would substitute to "/:/hello///there" rather than "/there". */
1687 Lisp_Object result
1688 = (Fsubstitute_in_file_name
1689 (make_specified_string (p, -1, endp - p, multibyte)));
1690 SAFE_FREE ();
1691 return result;
1694 /* See if any variables are substituted into the string. */
1696 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1698 Lisp_Object name
1699 = (!substituted ? filename
1700 : make_specified_string (nm, -1, endp - nm, multibyte));
1701 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1702 CHECK_STRING (tmp);
1703 if (!EQ (tmp, name))
1704 substituted = true;
1705 filename = tmp;
1708 if (!substituted)
1710 #ifdef WINDOWSNT
1711 if (!NILP (Vw32_downcase_file_names))
1712 filename = Fdowncase (filename);
1713 #endif
1714 SAFE_FREE ();
1715 return filename;
1718 xnm = SSDATA (filename);
1719 x = xnm + SBYTES (filename);
1721 /* If /~ or // appears, discard everything through first slash. */
1722 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1723 /* This time we do not start over because we've already expanded envvars
1724 and replaced $$ with $. Maybe we should start over as well, but we'd
1725 need to quote some $ to $$ first. */
1726 xnm = p;
1728 #ifdef WINDOWSNT
1729 if (!NILP (Vw32_downcase_file_names))
1731 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1733 filename = Fdowncase (xname);
1735 else
1736 #endif
1737 if (xnm != SSDATA (filename))
1738 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1739 SAFE_FREE ();
1740 return filename;
1743 /* A slightly faster and more convenient way to get
1744 (directory-file-name (expand-file-name FOO)). */
1746 Lisp_Object
1747 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1749 register Lisp_Object absname;
1751 absname = Fexpand_file_name (filename, defdir);
1753 /* Remove final slash, if any (unless this is the root dir).
1754 stat behaves differently depending! */
1755 if (SCHARS (absname) > 1
1756 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1757 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1758 /* We cannot take shortcuts; they might be wrong for magic file names. */
1759 absname = Fdirectory_file_name (absname);
1760 return absname;
1763 /* Signal an error if the file ABSNAME already exists.
1764 If KNOWN_TO_EXIST, the file is known to exist.
1765 QUERYSTRING is a name for the action that is being considered
1766 to alter the file.
1767 If INTERACTIVE, ask the user whether to proceed,
1768 and bypass the error if the user says to go ahead.
1769 If QUICK, ask for y or n, not yes or no. */
1771 static void
1772 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1773 const char *querystring, bool interactive,
1774 bool quick)
1776 Lisp_Object tem, encoded_filename;
1777 struct stat statbuf;
1779 encoded_filename = ENCODE_FILE (absname);
1781 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1783 if (S_ISDIR (statbuf.st_mode))
1784 xsignal2 (Qfile_error,
1785 build_string ("File is a directory"), absname);
1786 known_to_exist = true;
1789 if (known_to_exist)
1791 if (! interactive)
1792 xsignal2 (Qfile_already_exists,
1793 build_string ("File already exists"), absname);
1794 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1795 tem = CALLN (Fformat, format, absname, build_string (querystring));
1796 if (quick)
1797 tem = call1 (intern ("y-or-n-p"), tem);
1798 else
1799 tem = do_yes_or_no_p (tem);
1800 if (NILP (tem))
1801 xsignal2 (Qfile_already_exists,
1802 build_string ("File already exists"), absname);
1806 #ifndef WINDOWSNT
1807 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1808 static bool
1809 clone_file (int dest, int source)
1811 #ifdef FICLONE
1812 return ioctl (dest, FICLONE, source) == 0;
1813 #endif
1814 return false;
1816 #endif
1818 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1819 "fCopy file: \nGCopy %s to file: \np\nP",
1820 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1821 If NEWNAME names a directory, copy FILE there.
1823 This function always sets the file modes of the output file to match
1824 the input file.
1826 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1827 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1828 signal a `file-already-exists' error without overwriting. If
1829 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1830 about overwriting; this is what happens in interactive use with M-x.
1831 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1832 existing file.
1834 Fourth arg KEEP-TIME non-nil means give the output file the same
1835 last-modified time as the old one. (This works on only some systems.)
1837 A prefix arg makes KEEP-TIME non-nil.
1839 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1840 FILE to NEWNAME.
1842 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1843 this includes the file modes, along with ACL entries and SELinux
1844 context if present. Otherwise, if NEWNAME is created its file
1845 permission bits are those of FILE, masked by the default file
1846 permissions. */)
1847 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1848 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1849 Lisp_Object preserve_permissions)
1851 Lisp_Object handler;
1852 ptrdiff_t count = SPECPDL_INDEX ();
1853 Lisp_Object encoded_file, encoded_newname;
1854 #if HAVE_LIBSELINUX
1855 security_context_t con;
1856 int conlength = 0;
1857 #endif
1858 #ifdef WINDOWSNT
1859 int result;
1860 #else
1861 bool already_exists = false;
1862 mode_t new_mask;
1863 int ifd, ofd;
1864 struct stat st;
1865 #endif
1867 file = Fexpand_file_name (file, Qnil);
1868 newname = expand_cp_target (file, newname);
1870 /* If the input file name has special constructs in it,
1871 call the corresponding file handler. */
1872 handler = Ffind_file_name_handler (file, Qcopy_file);
1873 /* Likewise for output file name. */
1874 if (NILP (handler))
1875 handler = Ffind_file_name_handler (newname, Qcopy_file);
1876 if (!NILP (handler))
1877 return call7 (handler, Qcopy_file, file, newname,
1878 ok_if_already_exists, keep_time, preserve_uid_gid,
1879 preserve_permissions);
1881 encoded_file = ENCODE_FILE (file);
1882 encoded_newname = ENCODE_FILE (newname);
1884 #ifdef WINDOWSNT
1885 if (NILP (ok_if_already_exists)
1886 || INTEGERP (ok_if_already_exists))
1887 barf_or_query_if_file_exists (newname, false, "copy to it",
1888 INTEGERP (ok_if_already_exists), false);
1890 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1891 !NILP (keep_time), !NILP (preserve_uid_gid),
1892 !NILP (preserve_permissions));
1893 switch (result)
1895 case -1:
1896 report_file_error ("Copying file", list2 (file, newname));
1897 case -2:
1898 report_file_error ("Copying permissions from", file);
1899 case -3:
1900 xsignal2 (Qfile_date_error,
1901 build_string ("Resetting file times"), newname);
1902 case -4:
1903 report_file_error ("Copying permissions to", newname);
1905 #else /* not WINDOWSNT */
1906 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1908 if (ifd < 0)
1909 report_file_error ("Opening input file", file);
1911 record_unwind_protect_int (close_file_unwind, ifd);
1913 if (fstat (ifd, &st) != 0)
1914 report_file_error ("Input file status", file);
1916 if (!NILP (preserve_permissions))
1918 #if HAVE_LIBSELINUX
1919 if (is_selinux_enabled ())
1921 conlength = fgetfilecon (ifd, &con);
1922 if (conlength == -1)
1923 report_file_error ("Doing fgetfilecon", file);
1925 #endif
1928 /* We can copy only regular files. */
1929 if (!S_ISREG (st.st_mode))
1930 report_file_errno ("Non-regular file", file,
1931 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1933 #ifndef MSDOS
1934 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1935 #else
1936 new_mask = S_IREAD | S_IWRITE;
1937 #endif
1939 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1940 new_mask);
1941 if (ofd < 0 && errno == EEXIST)
1943 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1944 barf_or_query_if_file_exists (newname, true, "copy to it",
1945 INTEGERP (ok_if_already_exists), false);
1946 already_exists = true;
1947 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1949 if (ofd < 0)
1950 report_file_error ("Opening output file", newname);
1952 record_unwind_protect_int (close_file_unwind, ofd);
1954 off_t oldsize = 0, newsize;
1956 if (already_exists)
1958 struct stat out_st;
1959 if (fstat (ofd, &out_st) != 0)
1960 report_file_error ("Output file status", newname);
1961 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1962 report_file_errno ("Input and output files are the same",
1963 list2 (file, newname), 0);
1964 if (S_ISREG (out_st.st_mode))
1965 oldsize = out_st.st_size;
1968 maybe_quit ();
1970 if (clone_file (ofd, ifd))
1971 newsize = st.st_size;
1972 else
1974 char buf[MAX_ALLOCA];
1975 ptrdiff_t n;
1976 for (newsize = 0; 0 < (n = emacs_read_quit (ifd, buf, sizeof buf));
1977 newsize += n)
1978 if (emacs_write_quit (ofd, buf, n) != n)
1979 report_file_error ("Write error", newname);
1980 if (n < 0)
1981 report_file_error ("Read error", file);
1984 /* Truncate any existing output file after writing the data. This
1985 is more likely to work than truncation before writing, if the
1986 file system is out of space or the user is over disk quota. */
1987 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
1988 report_file_error ("Truncating output file", newname);
1990 #ifndef MSDOS
1991 /* Preserve the original file permissions, and if requested, also its
1992 owner and group. */
1994 mode_t preserved_permissions = st.st_mode & 07777;
1995 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
1996 if (!NILP (preserve_uid_gid))
1998 /* Attempt to change owner and group. If that doesn't work
1999 attempt to change just the group, as that is sometimes allowed.
2000 Adjust the mode mask to eliminate setuid or setgid bits
2001 or group permissions bits that are inappropriate if the
2002 owner or group are wrong. */
2003 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2005 if (fchown (ofd, -1, st.st_gid) == 0)
2006 preserved_permissions &= ~04000;
2007 else
2009 preserved_permissions &= ~06000;
2011 /* Copy the other bits to the group bits, since the
2012 group is wrong. */
2013 preserved_permissions &= ~070;
2014 preserved_permissions |= (preserved_permissions & 7) << 3;
2015 default_permissions &= ~070;
2016 default_permissions |= (default_permissions & 7) << 3;
2021 switch (!NILP (preserve_permissions)
2022 ? qcopy_acl (SSDATA (encoded_file), ifd,
2023 SSDATA (encoded_newname), ofd,
2024 preserved_permissions)
2025 : (already_exists
2026 || (new_mask & ~realmask) == default_permissions)
2028 : fchmod (ofd, default_permissions))
2030 case -2: report_file_error ("Copying permissions from", file);
2031 case -1: report_file_error ("Copying permissions to", newname);
2034 #endif /* not MSDOS */
2036 #if HAVE_LIBSELINUX
2037 if (conlength > 0)
2039 /* Set the modified context back to the file. */
2040 bool fail = fsetfilecon (ofd, con) != 0;
2041 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2042 if (fail && errno != ENOTSUP)
2043 report_file_error ("Doing fsetfilecon", newname);
2045 freecon (con);
2047 #endif
2049 if (!NILP (keep_time))
2051 struct timespec atime = get_stat_atime (&st);
2052 struct timespec mtime = get_stat_mtime (&st);
2053 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2054 xsignal2 (Qfile_date_error,
2055 build_string ("Cannot set file date"), newname);
2058 if (emacs_close (ofd) < 0)
2059 report_file_error ("Write error", newname);
2061 emacs_close (ifd);
2063 #ifdef MSDOS
2064 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2065 and if it can't, it tells so. Otherwise, under MSDOS we usually
2066 get only the READ bit, which will make the copied file read-only,
2067 so it's better not to chmod at all. */
2068 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2069 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2070 #endif /* MSDOS */
2071 #endif /* not WINDOWSNT */
2073 /* Discard the unwind protects. */
2074 specpdl_ptr = specpdl + count;
2076 return Qnil;
2079 DEFUN ("make-directory-internal", Fmake_directory_internal,
2080 Smake_directory_internal, 1, 1, 0,
2081 doc: /* Create a new directory named DIRECTORY. */)
2082 (Lisp_Object directory)
2084 const char *dir;
2085 Lisp_Object handler;
2086 Lisp_Object encoded_dir;
2088 CHECK_STRING (directory);
2089 directory = Fexpand_file_name (directory, Qnil);
2091 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2092 if (!NILP (handler))
2093 return call2 (handler, Qmake_directory_internal, directory);
2095 encoded_dir = ENCODE_FILE (directory);
2097 dir = SSDATA (encoded_dir);
2099 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2100 report_file_error ("Creating directory", directory);
2102 return Qnil;
2105 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2106 Sdelete_directory_internal, 1, 1, 0,
2107 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2108 (Lisp_Object directory)
2110 const char *dir;
2111 Lisp_Object encoded_dir;
2113 CHECK_STRING (directory);
2114 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2115 encoded_dir = ENCODE_FILE (directory);
2116 dir = SSDATA (encoded_dir);
2118 if (rmdir (dir) != 0)
2119 report_file_error ("Removing directory", directory);
2121 return Qnil;
2124 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2125 "(list (read-file-name \
2126 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2127 \"Move file to trash: \" \"Delete file: \") \
2128 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2129 (null current-prefix-arg))",
2130 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2131 If file has multiple names, it continues to exist with the other names.
2132 TRASH non-nil means to trash the file instead of deleting, provided
2133 `delete-by-moving-to-trash' is non-nil.
2135 When called interactively, TRASH is t if no prefix argument is given.
2136 With a prefix argument, TRASH is nil. */)
2137 (Lisp_Object filename, Lisp_Object trash)
2139 Lisp_Object handler;
2140 Lisp_Object encoded_file;
2142 if (!NILP (Ffile_directory_p (filename))
2143 && NILP (Ffile_symlink_p (filename)))
2144 xsignal2 (Qfile_error,
2145 build_string ("Removing old name: is a directory"),
2146 filename);
2147 filename = Fexpand_file_name (filename, Qnil);
2149 handler = Ffind_file_name_handler (filename, Qdelete_file);
2150 if (!NILP (handler))
2151 return call3 (handler, Qdelete_file, filename, trash);
2153 if (delete_by_moving_to_trash && !NILP (trash))
2154 return call1 (Qmove_file_to_trash, filename);
2156 encoded_file = ENCODE_FILE (filename);
2158 if (unlink (SSDATA (encoded_file)) != 0 && errno != ENOENT)
2159 report_file_error ("Removing old name", filename);
2160 return Qnil;
2163 static Lisp_Object
2164 internal_delete_file_1 (Lisp_Object ignore)
2166 return Qt;
2169 /* Delete file FILENAME, returning true if successful.
2170 This ignores `delete-by-moving-to-trash'. */
2172 bool
2173 internal_delete_file (Lisp_Object filename)
2175 Lisp_Object tem;
2177 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2178 Qt, internal_delete_file_1);
2179 return NILP (tem);
2182 /* Filesystems are case-sensitive on all supported systems except
2183 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2184 case-insensitive on the first two, but they may or may not be
2185 case-insensitive on Cygwin and OS X. The following function
2186 attempts to provide a runtime test on those two systems. If the
2187 test is not conclusive, we assume case-insensitivity on Cygwin and
2188 case-sensitivity on Mac OS X.
2190 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2191 NFS-mounted Windows volumes, might be case-insensitive. Can we
2192 detect this? */
2194 static bool
2195 file_name_case_insensitive_p (const char *filename)
2197 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2198 those flags are available. As of this writing (2017-05-20),
2199 Cygwin is the only platform known to support the former (starting
2200 with Cygwin-2.6.1), and macOS is the only platform known to
2201 support the latter. */
2203 #ifdef _PC_CASE_INSENSITIVE
2204 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2205 if (res >= 0)
2206 return res > 0;
2207 #elif defined _PC_CASE_SENSITIVE
2208 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2209 if (res >= 0)
2210 return res == 0;
2211 #endif
2213 #if defined CYGWIN || defined DOS_NT
2214 return true;
2215 #else
2216 return false;
2217 #endif
2220 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2221 Sfile_name_case_insensitive_p, 1, 1, 0,
2222 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2223 The arg must be a string. */)
2224 (Lisp_Object filename)
2226 Lisp_Object handler;
2228 CHECK_STRING (filename);
2229 filename = Fexpand_file_name (filename, Qnil);
2231 /* If the file name has special constructs in it,
2232 call the corresponding file handler. */
2233 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2234 if (!NILP (handler))
2235 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2237 filename = ENCODE_FILE (filename);
2238 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2241 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2242 "fRename file: \nGRename %s to file: \np",
2243 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2244 If file has names other than FILE, it continues to have those names.
2245 Signal a `file-already-exists' error if a file NEWNAME already exists
2246 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2247 An integer third arg means request confirmation if NEWNAME already exists.
2248 This is what happens in interactive use with M-x. */)
2249 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2251 Lisp_Object handler;
2252 Lisp_Object encoded_file, encoded_newname, symlink_target;
2253 int dirp = -1;
2255 file = Fexpand_file_name (file, Qnil);
2257 /* If the filesystem is case-insensitive and the file names are
2258 identical but for case, treat it as a change-case request, and do
2259 not worry whether NEWNAME exists or whether it is a directory, as
2260 it is already another name for FILE. */
2261 bool case_only_rename = false;
2262 #if defined CYGWIN || defined DOS_NT
2263 if (!NILP (Ffile_name_case_insensitive_p (file)))
2265 newname = Fexpand_file_name (newname, Qnil);
2266 case_only_rename = !NILP (Fstring_equal (Fdowncase (file),
2267 Fdowncase (newname)));
2269 #endif
2271 if (!case_only_rename)
2272 newname = expand_cp_target (Fdirectory_file_name (file), newname);
2274 /* If the file name has special constructs in it,
2275 call the corresponding file handler. */
2276 handler = Ffind_file_name_handler (file, Qrename_file);
2277 if (NILP (handler))
2278 handler = Ffind_file_name_handler (newname, Qrename_file);
2279 if (!NILP (handler))
2280 return call4 (handler, Qrename_file,
2281 file, newname, ok_if_already_exists);
2283 encoded_file = ENCODE_FILE (file);
2284 encoded_newname = ENCODE_FILE (newname);
2286 bool plain_rename = (case_only_rename
2287 || (!NILP (ok_if_already_exists)
2288 && !INTEGERP (ok_if_already_exists)));
2289 int rename_errno;
2290 if (!plain_rename)
2292 if (renameat_noreplace (AT_FDCWD, SSDATA (encoded_file),
2293 AT_FDCWD, SSDATA (encoded_newname))
2294 == 0)
2295 return Qnil;
2297 rename_errno = errno;
2298 switch (rename_errno)
2300 case EEXIST: case EINVAL: case ENOSYS:
2301 #if ENOSYS != ENOTSUP
2302 case ENOTSUP:
2303 #endif
2304 barf_or_query_if_file_exists (newname, rename_errno == EEXIST,
2305 "rename to it",
2306 INTEGERP (ok_if_already_exists),
2307 false);
2308 plain_rename = true;
2309 break;
2313 if (plain_rename)
2315 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2316 return Qnil;
2317 rename_errno = errno;
2318 /* Don't prompt again. */
2319 ok_if_already_exists = Qt;
2321 else if (!NILP (ok_if_already_exists))
2322 ok_if_already_exists = Qt;
2324 if (rename_errno != EXDEV)
2325 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2327 symlink_target = Ffile_symlink_p (file);
2328 if (!NILP (symlink_target))
2329 Fmake_symbolic_link (symlink_target, newname, ok_if_already_exists);
2330 else
2332 if (dirp < 0)
2333 dirp = directory_like (file);
2334 if (dirp)
2335 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2336 else
2337 Fcopy_file (file, newname, ok_if_already_exists, Qt, Qt, Qt);
2340 ptrdiff_t count = SPECPDL_INDEX ();
2341 specbind (Qdelete_by_moving_to_trash, Qnil);
2342 if (dirp && NILP (symlink_target))
2343 call2 (Qdelete_directory, file, Qt);
2344 else
2345 Fdelete_file (file, Qnil);
2346 return unbind_to (count, Qnil);
2349 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2350 "fAdd name to file: \nGName to add to %s: \np",
2351 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2352 Signal a `file-already-exists' error if a file NEWNAME already exists
2353 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2354 An integer third arg means request confirmation if NEWNAME already exists.
2355 This is what happens in interactive use with M-x. */)
2356 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2358 Lisp_Object handler;
2359 Lisp_Object encoded_file, encoded_newname;
2361 file = Fexpand_file_name (file, Qnil);
2362 newname = expand_cp_target (file, newname);
2364 /* If the file name has special constructs in it,
2365 call the corresponding file handler. */
2366 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2367 if (!NILP (handler))
2368 return call4 (handler, Qadd_name_to_file, file,
2369 newname, ok_if_already_exists);
2371 /* If the new name has special constructs in it,
2372 call the corresponding file handler. */
2373 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2374 if (!NILP (handler))
2375 return call4 (handler, Qadd_name_to_file, file,
2376 newname, ok_if_already_exists);
2378 encoded_file = ENCODE_FILE (file);
2379 encoded_newname = ENCODE_FILE (newname);
2381 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2382 return Qnil;
2384 if (errno == EEXIST)
2386 if (NILP (ok_if_already_exists)
2387 || INTEGERP (ok_if_already_exists))
2388 barf_or_query_if_file_exists (newname, true, "make it a new name",
2389 INTEGERP (ok_if_already_exists), false);
2390 unlink (SSDATA (newname));
2391 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2392 return Qnil;
2395 report_file_error ("Adding new name", list2 (file, newname));
2398 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2399 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2400 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2401 Both args must be strings.
2402 Signal a `file-already-exists' error if a file LINKNAME already exists
2403 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2404 An integer third arg means request confirmation if LINKNAME already exists.
2405 This happens for interactive use with M-x. */)
2406 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2408 Lisp_Object handler;
2409 Lisp_Object encoded_target, encoded_linkname;
2411 CHECK_STRING (target);
2412 /* If the link target has a ~, we must expand it to get
2413 a truly valid file name. Otherwise, do not expand;
2414 we want to permit links to relative file names. */
2415 if (SREF (target, 0) == '~')
2416 target = Fexpand_file_name (target, Qnil);
2418 linkname = expand_cp_target (target, linkname);
2420 /* If the file name has special constructs in it,
2421 call the corresponding file handler. */
2422 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2423 if (!NILP (handler))
2424 return call4 (handler, Qmake_symbolic_link, target,
2425 linkname, ok_if_already_exists);
2427 /* If the new link name has special constructs in it,
2428 call the corresponding file handler. */
2429 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2430 if (!NILP (handler))
2431 return call4 (handler, Qmake_symbolic_link, target,
2432 linkname, ok_if_already_exists);
2434 encoded_target = ENCODE_FILE (target);
2435 encoded_linkname = ENCODE_FILE (linkname);
2437 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2438 return Qnil;
2440 if (errno == ENOSYS)
2441 xsignal1 (Qfile_error,
2442 build_string ("Symbolic links are not supported"));
2444 if (errno == EEXIST)
2446 if (NILP (ok_if_already_exists)
2447 || INTEGERP (ok_if_already_exists))
2448 barf_or_query_if_file_exists (linkname, true, "make it a link",
2449 INTEGERP (ok_if_already_exists), false);
2450 unlink (SSDATA (encoded_linkname));
2451 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2452 return Qnil;
2455 report_file_error ("Making symbolic link", list2 (target, linkname));
2459 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2460 1, 1, 0,
2461 doc: /* Return t if file FILENAME specifies an absolute file name.
2462 On Unix, this is a name starting with a `/' or a `~'. */)
2463 (Lisp_Object filename)
2465 CHECK_STRING (filename);
2466 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2469 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2470 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2471 See also `file-readable-p' and `file-attributes'.
2472 This returns nil for a symlink to a nonexistent file.
2473 Use `file-symlink-p' to test for such links. */)
2474 (Lisp_Object filename)
2476 Lisp_Object absname;
2477 Lisp_Object handler;
2479 CHECK_STRING (filename);
2480 absname = Fexpand_file_name (filename, Qnil);
2482 /* If the file name has special constructs in it,
2483 call the corresponding file handler. */
2484 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2485 if (!NILP (handler))
2487 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2488 errno = 0;
2489 return result;
2492 absname = ENCODE_FILE (absname);
2494 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2497 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2498 doc: /* Return t if FILENAME can be executed by you.
2499 For a directory, this means you can access files in that directory.
2500 \(It is generally better to use `file-accessible-directory-p' for that
2501 purpose, though.) */)
2502 (Lisp_Object filename)
2504 Lisp_Object absname;
2505 Lisp_Object handler;
2507 CHECK_STRING (filename);
2508 absname = Fexpand_file_name (filename, Qnil);
2510 /* If the file name has special constructs in it,
2511 call the corresponding file handler. */
2512 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2513 if (!NILP (handler))
2514 return call2 (handler, Qfile_executable_p, absname);
2516 absname = ENCODE_FILE (absname);
2518 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2521 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2522 doc: /* Return t if file FILENAME exists and you can read it.
2523 See also `file-exists-p' and `file-attributes'. */)
2524 (Lisp_Object filename)
2526 Lisp_Object absname;
2527 Lisp_Object handler;
2529 CHECK_STRING (filename);
2530 absname = Fexpand_file_name (filename, Qnil);
2532 /* If the file name has special constructs in it,
2533 call the corresponding file handler. */
2534 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2535 if (!NILP (handler))
2536 return call2 (handler, Qfile_readable_p, absname);
2538 absname = ENCODE_FILE (absname);
2539 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2540 ? Qt : Qnil);
2543 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2544 doc: /* Return t if file FILENAME can be written or created by you. */)
2545 (Lisp_Object filename)
2547 Lisp_Object absname, dir, encoded;
2548 Lisp_Object handler;
2550 CHECK_STRING (filename);
2551 absname = Fexpand_file_name (filename, Qnil);
2553 /* If the file name has special constructs in it,
2554 call the corresponding file handler. */
2555 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2556 if (!NILP (handler))
2557 return call2 (handler, Qfile_writable_p, absname);
2559 encoded = ENCODE_FILE (absname);
2560 if (check_writable (SSDATA (encoded), W_OK))
2561 return Qt;
2562 if (errno != ENOENT)
2563 return Qnil;
2565 dir = Ffile_name_directory (absname);
2566 eassert (!NILP (dir));
2567 #ifdef MSDOS
2568 dir = Fdirectory_file_name (dir);
2569 #endif /* MSDOS */
2571 dir = ENCODE_FILE (dir);
2572 #ifdef WINDOWSNT
2573 /* The read-only attribute of the parent directory doesn't affect
2574 whether a file or directory can be created within it. Some day we
2575 should check ACLs though, which do affect this. */
2576 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2577 #else
2578 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2579 #endif
2582 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2583 doc: /* Access file FILENAME, and get an error if that does not work.
2584 The second argument STRING is prepended to the error message.
2585 If there is no error, returns nil. */)
2586 (Lisp_Object filename, Lisp_Object string)
2588 Lisp_Object handler, encoded_filename, absname;
2590 CHECK_STRING (filename);
2591 absname = Fexpand_file_name (filename, Qnil);
2593 CHECK_STRING (string);
2595 /* If the file name has special constructs in it,
2596 call the corresponding file handler. */
2597 handler = Ffind_file_name_handler (absname, Qaccess_file);
2598 if (!NILP (handler))
2599 return call3 (handler, Qaccess_file, absname, string);
2601 encoded_filename = ENCODE_FILE (absname);
2603 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2604 report_file_error (SSDATA (string), filename);
2606 return Qnil;
2609 /* Relative to directory FD, return the symbolic link value of FILENAME.
2610 On failure, return nil. */
2611 Lisp_Object
2612 emacs_readlinkat (int fd, char const *filename)
2614 static struct allocator const emacs_norealloc_allocator =
2615 { xmalloc, NULL, xfree, memory_full };
2616 Lisp_Object val;
2617 char readlink_buf[1024];
2618 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2619 &emacs_norealloc_allocator, readlinkat);
2620 if (!buf)
2621 return Qnil;
2623 val = build_unibyte_string (buf);
2624 if (buf[0] == '/' && strchr (buf, ':'))
2626 AUTO_STRING (slash_colon, "/:");
2627 val = concat2 (slash_colon, val);
2629 if (buf != readlink_buf)
2630 xfree (buf);
2631 val = DECODE_FILE (val);
2632 return val;
2635 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2636 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2637 The value is the link target, as a string.
2638 Otherwise it returns nil.
2640 This function does not check whether the link target exists. */)
2641 (Lisp_Object filename)
2643 Lisp_Object handler;
2645 CHECK_STRING (filename);
2646 filename = Fexpand_file_name (filename, Qnil);
2648 /* If the file name has special constructs in it,
2649 call the corresponding file handler. */
2650 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2651 if (!NILP (handler))
2652 return call2 (handler, Qfile_symlink_p, filename);
2654 filename = ENCODE_FILE (filename);
2656 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2659 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2660 doc: /* Return t if FILENAME names an existing directory.
2661 Symbolic links to directories count as directories.
2662 See `file-symlink-p' to distinguish symlinks. */)
2663 (Lisp_Object filename)
2665 Lisp_Object absname;
2666 Lisp_Object handler;
2668 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2670 /* If the file name has special constructs in it,
2671 call the corresponding file handler. */
2672 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2673 if (!NILP (handler))
2674 return call2 (handler, Qfile_directory_p, absname);
2676 absname = ENCODE_FILE (absname);
2678 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2681 /* Return true if FILE is a directory or a symlink to a directory. */
2682 bool
2683 file_directory_p (char const *file)
2685 #ifdef WINDOWSNT
2686 /* This is cheaper than 'stat'. */
2687 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2688 #else
2689 struct stat st;
2690 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2691 #endif
2694 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2695 Sfile_accessible_directory_p, 1, 1, 0,
2696 doc: /* Return t if FILENAME names a directory you can open.
2697 For the value to be t, FILENAME must specify the name of a directory
2698 as a file, and the directory must allow you to open files in it. In
2699 order to use a directory as a buffer's current directory, this
2700 predicate must return true. A directory name spec may be given
2701 instead; then the value is t if the directory so specified exists and
2702 really is a readable and searchable directory. */)
2703 (Lisp_Object filename)
2705 Lisp_Object absname;
2706 Lisp_Object handler;
2708 CHECK_STRING (filename);
2709 absname = Fexpand_file_name (filename, Qnil);
2711 /* If the file name has special constructs in it,
2712 call the corresponding file handler. */
2713 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2714 if (!NILP (handler))
2716 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2718 /* Set errno in case the handler failed. EACCES might be a lie
2719 (e.g., the directory might not exist, or be a regular file),
2720 but at least it does TRT in the "usual" case of an existing
2721 directory that is not accessible by the current user, and
2722 avoids reporting "Success" for a failed operation. Perhaps
2723 someday we can fix this in a better way, by improving
2724 file-accessible-directory-p's API; see Bug#25419. */
2725 if (!EQ (r, Qt))
2726 errno = EACCES;
2728 return r;
2731 absname = ENCODE_FILE (absname);
2732 return file_accessible_directory_p (absname) ? Qt : Qnil;
2735 /* If FILE is a searchable directory or a symlink to a
2736 searchable directory, return true. Otherwise return
2737 false and set errno to an error number. */
2738 bool
2739 file_accessible_directory_p (Lisp_Object file)
2741 #ifdef DOS_NT
2742 # ifdef WINDOWSNT
2743 /* We need a special-purpose test because (a) NTFS security data is
2744 not reflected in Posix-style mode bits, and (b) the trick with
2745 accessing "DIR/.", used below on Posix hosts, doesn't work on
2746 Windows, because "DIR/." is normalized to just "DIR" before
2747 hitting the disk. */
2748 return (SBYTES (file) == 0
2749 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2750 # else /* MSDOS */
2751 return file_directory_p (SSDATA (file));
2752 # endif /* MSDOS */
2753 #else /* !DOS_NT */
2754 /* On POSIXish platforms, use just one system call; this avoids a
2755 race and is typically faster. */
2756 const char *data = SSDATA (file);
2757 ptrdiff_t len = SBYTES (file);
2758 char const *dir;
2759 bool ok;
2760 int saved_errno;
2761 USE_SAFE_ALLOCA;
2763 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2764 There are three exceptions: "", "/", and "//". Leave "" alone,
2765 as it's invalid. Append only "." to the other two exceptions as
2766 "/" and "//" are distinct on some platforms, whereas "/", "///",
2767 "////", etc. are all equivalent. */
2768 if (! len)
2769 dir = data;
2770 else
2772 /* Just check for trailing '/' when deciding whether to append '/'.
2773 That's simpler than testing the two special cases "/" and "//",
2774 and it's a safe optimization here. */
2775 char *buf = SAFE_ALLOCA (len + 3);
2776 memcpy (buf, data, len);
2777 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2778 dir = buf;
2781 ok = check_existing (dir);
2782 saved_errno = errno;
2783 SAFE_FREE ();
2784 errno = saved_errno;
2785 return ok;
2786 #endif /* !DOS_NT */
2789 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2790 doc: /* Return t if FILENAME names a regular file.
2791 This is the sort of file that holds an ordinary stream of data bytes.
2792 Symbolic links to regular files count as regular files.
2793 See `file-symlink-p' to distinguish symlinks. */)
2794 (Lisp_Object filename)
2796 register Lisp_Object absname;
2797 struct stat st;
2798 Lisp_Object handler;
2800 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2802 /* If the file name has special constructs in it,
2803 call the corresponding file handler. */
2804 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2805 if (!NILP (handler))
2806 return call2 (handler, Qfile_regular_p, absname);
2808 absname = ENCODE_FILE (absname);
2810 #ifdef WINDOWSNT
2812 int result;
2813 Lisp_Object tem = Vw32_get_true_file_attributes;
2815 /* Tell stat to use expensive method to get accurate info. */
2816 Vw32_get_true_file_attributes = Qt;
2817 result = stat (SSDATA (absname), &st);
2818 Vw32_get_true_file_attributes = tem;
2820 if (result < 0)
2821 return Qnil;
2822 return S_ISREG (st.st_mode) ? Qt : Qnil;
2824 #else
2825 if (stat (SSDATA (absname), &st) < 0)
2826 return Qnil;
2827 return S_ISREG (st.st_mode) ? Qt : Qnil;
2828 #endif
2831 DEFUN ("file-selinux-context", Ffile_selinux_context,
2832 Sfile_selinux_context, 1, 1, 0,
2833 doc: /* Return SELinux context of file named FILENAME.
2834 The return value is a list (USER ROLE TYPE RANGE), where the list
2835 elements are strings naming the user, role, type, and range of the
2836 file's SELinux security context.
2838 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2839 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2840 (Lisp_Object filename)
2842 Lisp_Object absname;
2843 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2845 Lisp_Object handler;
2846 #if HAVE_LIBSELINUX
2847 security_context_t con;
2848 int conlength;
2849 context_t context;
2850 #endif
2852 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2854 /* If the file name has special constructs in it,
2855 call the corresponding file handler. */
2856 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2857 if (!NILP (handler))
2858 return call2 (handler, Qfile_selinux_context, absname);
2860 absname = ENCODE_FILE (absname);
2862 #if HAVE_LIBSELINUX
2863 if (is_selinux_enabled ())
2865 conlength = lgetfilecon (SSDATA (absname), &con);
2866 if (conlength > 0)
2868 context = context_new (con);
2869 if (context_user_get (context))
2870 user = build_string (context_user_get (context));
2871 if (context_role_get (context))
2872 role = build_string (context_role_get (context));
2873 if (context_type_get (context))
2874 type = build_string (context_type_get (context));
2875 if (context_range_get (context))
2876 range = build_string (context_range_get (context));
2877 context_free (context);
2878 freecon (con);
2881 #endif
2883 return list4 (user, role, type, range);
2886 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2887 Sset_file_selinux_context, 2, 2, 0,
2888 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2889 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2890 elements are strings naming the components of a SELinux context.
2892 Value is t if setting of SELinux context was successful, nil otherwise.
2894 This function does nothing and returns nil if SELinux is disabled,
2895 or if Emacs was not compiled with SELinux support. */)
2896 (Lisp_Object filename, Lisp_Object context)
2898 Lisp_Object absname;
2899 Lisp_Object handler;
2900 #if HAVE_LIBSELINUX
2901 Lisp_Object encoded_absname;
2902 Lisp_Object user = CAR_SAFE (context);
2903 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2904 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2905 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2906 security_context_t con;
2907 bool fail;
2908 int conlength;
2909 context_t parsed_con;
2910 #endif
2912 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2914 /* If the file name has special constructs in it,
2915 call the corresponding file handler. */
2916 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2917 if (!NILP (handler))
2918 return call3 (handler, Qset_file_selinux_context, absname, context);
2920 #if HAVE_LIBSELINUX
2921 if (is_selinux_enabled ())
2923 /* Get current file context. */
2924 encoded_absname = ENCODE_FILE (absname);
2925 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2926 if (conlength > 0)
2928 parsed_con = context_new (con);
2929 /* Change the parts defined in the parameter.*/
2930 if (STRINGP (user))
2932 if (context_user_set (parsed_con, SSDATA (user)))
2933 error ("Doing context_user_set");
2935 if (STRINGP (role))
2937 if (context_role_set (parsed_con, SSDATA (role)))
2938 error ("Doing context_role_set");
2940 if (STRINGP (type))
2942 if (context_type_set (parsed_con, SSDATA (type)))
2943 error ("Doing context_type_set");
2945 if (STRINGP (range))
2947 if (context_range_set (parsed_con, SSDATA (range)))
2948 error ("Doing context_range_set");
2951 /* Set the modified context back to the file. */
2952 fail = (lsetfilecon (SSDATA (encoded_absname),
2953 context_str (parsed_con))
2954 != 0);
2955 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2956 if (fail && errno != ENOTSUP)
2957 report_file_error ("Doing lsetfilecon", absname);
2959 context_free (parsed_con);
2960 freecon (con);
2961 return fail ? Qnil : Qt;
2963 else
2964 report_file_error ("Doing lgetfilecon", absname);
2966 #endif
2968 return Qnil;
2971 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2972 doc: /* Return ACL entries of file named FILENAME.
2973 The entries are returned in a format suitable for use in `set-file-acl'
2974 but is otherwise undocumented and subject to change.
2975 Return nil if file does not exist or is not accessible, or if Emacs
2976 was unable to determine the ACL entries. */)
2977 (Lisp_Object filename)
2979 #if USE_ACL
2980 Lisp_Object absname;
2981 Lisp_Object handler;
2982 # ifdef HAVE_ACL_SET_FILE
2983 acl_t acl;
2984 Lisp_Object acl_string;
2985 char *str;
2986 # ifndef HAVE_ACL_TYPE_EXTENDED
2987 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2988 # endif
2989 # endif
2991 absname = expand_and_dir_to_file (filename,
2992 BVAR (current_buffer, directory));
2994 /* If the file name has special constructs in it,
2995 call the corresponding file handler. */
2996 handler = Ffind_file_name_handler (absname, Qfile_acl);
2997 if (!NILP (handler))
2998 return call2 (handler, Qfile_acl, absname);
3000 # ifdef HAVE_ACL_SET_FILE
3001 absname = ENCODE_FILE (absname);
3003 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3004 if (acl == NULL)
3005 return Qnil;
3007 str = acl_to_text (acl, NULL);
3008 if (str == NULL)
3010 acl_free (acl);
3011 return Qnil;
3014 acl_string = build_string (str);
3015 acl_free (str);
3016 acl_free (acl);
3018 return acl_string;
3019 # endif
3020 #endif
3022 return Qnil;
3025 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3026 2, 2, 0,
3027 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3028 ACL-STRING should contain the textual representation of the ACL
3029 entries in a format suitable for the platform.
3031 Value is t if setting of ACL was successful, nil otherwise.
3033 Setting ACL for local files requires Emacs to be built with ACL
3034 support. */)
3035 (Lisp_Object filename, Lisp_Object acl_string)
3037 #if USE_ACL
3038 Lisp_Object absname;
3039 Lisp_Object handler;
3040 # ifdef HAVE_ACL_SET_FILE
3041 Lisp_Object encoded_absname;
3042 acl_t acl;
3043 bool fail;
3044 # endif
3046 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3048 /* If the file name has special constructs in it,
3049 call the corresponding file handler. */
3050 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3051 if (!NILP (handler))
3052 return call3 (handler, Qset_file_acl, absname, acl_string);
3054 # ifdef HAVE_ACL_SET_FILE
3055 if (STRINGP (acl_string))
3057 acl = acl_from_text (SSDATA (acl_string));
3058 if (acl == NULL)
3060 report_file_error ("Converting ACL", absname);
3061 return Qnil;
3064 encoded_absname = ENCODE_FILE (absname);
3066 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3067 acl)
3068 != 0);
3069 if (fail && acl_errno_valid (errno))
3070 report_file_error ("Setting ACL", absname);
3072 acl_free (acl);
3073 return fail ? Qnil : Qt;
3075 # endif
3076 #endif
3078 return Qnil;
3081 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3082 doc: /* Return mode bits of file named FILENAME, as an integer.
3083 Return nil, if file does not exist or is not accessible. */)
3084 (Lisp_Object filename)
3086 Lisp_Object absname;
3087 struct stat st;
3088 Lisp_Object handler;
3090 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3092 /* If the file name has special constructs in it,
3093 call the corresponding file handler. */
3094 handler = Ffind_file_name_handler (absname, Qfile_modes);
3095 if (!NILP (handler))
3096 return call2 (handler, Qfile_modes, absname);
3098 absname = ENCODE_FILE (absname);
3100 if (stat (SSDATA (absname), &st) < 0)
3101 return Qnil;
3103 return make_number (st.st_mode & 07777);
3106 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3107 "(let ((file (read-file-name \"File: \"))) \
3108 (list file (read-file-modes nil file)))",
3109 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3110 Only the 12 low bits of MODE are used.
3112 Interactively, mode bits are read by `read-file-modes', which accepts
3113 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3114 (Lisp_Object filename, Lisp_Object mode)
3116 Lisp_Object absname, encoded_absname;
3117 Lisp_Object handler;
3119 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3120 CHECK_NUMBER (mode);
3122 /* If the file name has special constructs in it,
3123 call the corresponding file handler. */
3124 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3125 if (!NILP (handler))
3126 return call3 (handler, Qset_file_modes, absname, mode);
3128 encoded_absname = ENCODE_FILE (absname);
3130 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3131 report_file_error ("Doing chmod", absname);
3133 return Qnil;
3136 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3137 doc: /* Set the file permission bits for newly created files.
3138 The argument MODE should be an integer; only the low 9 bits are used.
3139 This setting is inherited by subprocesses. */)
3140 (Lisp_Object mode)
3142 mode_t oldrealmask, oldumask, newumask;
3143 CHECK_NUMBER (mode);
3144 oldrealmask = realmask;
3145 newumask = ~ XINT (mode) & 0777;
3147 block_input ();
3148 realmask = newumask;
3149 oldumask = umask (newumask);
3150 unblock_input ();
3152 eassert (oldumask == oldrealmask);
3153 return Qnil;
3156 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3157 doc: /* Return the default file protection for created files.
3158 The value is an integer. */)
3159 (void)
3161 Lisp_Object value;
3162 XSETINT (value, (~ realmask) & 0777);
3163 return value;
3167 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3168 doc: /* Set times of file FILENAME to TIMESTAMP.
3169 Set both access and modification times.
3170 Return t on success, else nil.
3171 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3172 `current-time'. */)
3173 (Lisp_Object filename, Lisp_Object timestamp)
3175 Lisp_Object absname, encoded_absname;
3176 Lisp_Object handler;
3177 struct timespec t = lisp_time_argument (timestamp);
3179 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3181 /* If the file name has special constructs in it,
3182 call the corresponding file handler. */
3183 handler = Ffind_file_name_handler (absname, Qset_file_times);
3184 if (!NILP (handler))
3185 return call3 (handler, Qset_file_times, absname, timestamp);
3187 encoded_absname = ENCODE_FILE (absname);
3190 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3192 #ifdef MSDOS
3193 /* Setting times on a directory always fails. */
3194 if (file_directory_p (SSDATA (encoded_absname)))
3195 return Qnil;
3196 #endif
3197 report_file_error ("Setting file times", absname);
3201 return Qt;
3204 #ifdef HAVE_SYNC
3205 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3206 doc: /* Tell Unix to finish all pending disk updates. */)
3207 (void)
3209 sync ();
3210 return Qnil;
3213 #endif /* HAVE_SYNC */
3215 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3216 doc: /* Return t if file FILE1 is newer than file FILE2.
3217 If FILE1 does not exist, the answer is nil;
3218 otherwise, if FILE2 does not exist, the answer is t. */)
3219 (Lisp_Object file1, Lisp_Object file2)
3221 Lisp_Object absname1, absname2;
3222 struct stat st1, st2;
3223 Lisp_Object handler;
3225 CHECK_STRING (file1);
3226 CHECK_STRING (file2);
3228 absname1 = Qnil;
3229 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3230 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3232 /* If the file name has special constructs in it,
3233 call the corresponding file handler. */
3234 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3235 if (NILP (handler))
3236 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3237 if (!NILP (handler))
3238 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3240 absname1 = ENCODE_FILE (absname1);
3241 absname2 = ENCODE_FILE (absname2);
3243 if (stat (SSDATA (absname1), &st1) < 0)
3244 return Qnil;
3246 if (stat (SSDATA (absname2), &st2) < 0)
3247 return Qt;
3249 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3250 ? Qt : Qnil);
3253 enum { READ_BUF_SIZE = MAX_ALLOCA };
3255 /* This function is called after Lisp functions to decide a coding
3256 system are called, or when they cause an error. Before they are
3257 called, the current buffer is set unibyte and it contains only a
3258 newly inserted text (thus the buffer was empty before the
3259 insertion).
3261 The functions may set markers, overlays, text properties, or even
3262 alter the buffer contents, change the current buffer.
3264 Here, we reset all those changes by:
3265 o set back the current buffer.
3266 o move all markers and overlays to BEG.
3267 o remove all text properties.
3268 o set back the buffer multibyteness. */
3270 static void
3271 decide_coding_unwind (Lisp_Object unwind_data)
3273 Lisp_Object multibyte, undo_list, buffer;
3275 multibyte = XCAR (unwind_data);
3276 unwind_data = XCDR (unwind_data);
3277 undo_list = XCAR (unwind_data);
3278 buffer = XCDR (unwind_data);
3280 set_buffer_internal (XBUFFER (buffer));
3281 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3282 adjust_overlays_for_delete (BEG, Z - BEG);
3283 set_buffer_intervals (current_buffer, NULL);
3284 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3286 /* Now we are safe to change the buffer's multibyteness directly. */
3287 bset_enable_multibyte_characters (current_buffer, multibyte);
3288 bset_undo_list (current_buffer, undo_list);
3291 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3292 object where slot 0 is the file descriptor, slot 1 specifies
3293 an offset to put the read bytes, and slot 2 is the maximum
3294 amount of bytes to read. Value is the number of bytes read. */
3296 static Lisp_Object
3297 read_non_regular (Lisp_Object state)
3299 int nbytes = emacs_read_quit (XSAVE_INTEGER (state, 0),
3300 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3301 + XSAVE_INTEGER (state, 1)),
3302 XSAVE_INTEGER (state, 2));
3303 /* Fast recycle this object for the likely next call. */
3304 free_misc (state);
3305 return make_number (nbytes);
3309 /* Condition-case handler used when reading from non-regular files
3310 in insert-file-contents. */
3312 static Lisp_Object
3313 read_non_regular_quit (Lisp_Object ignore)
3315 return Qnil;
3318 /* Return the file offset that VAL represents, checking for type
3319 errors and overflow. */
3320 static off_t
3321 file_offset (Lisp_Object val)
3323 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3324 return XINT (val);
3326 if (FLOATP (val))
3328 double v = XFLOAT_DATA (val);
3329 if (0 <= v && v < 1.0 + TYPE_MAXIMUM (off_t))
3331 off_t o = v;
3332 if (o == v)
3333 return o;
3337 wrong_type_argument (intern ("file-offset"), val);
3340 /* Return a special time value indicating the error number ERRNUM. */
3341 static struct timespec
3342 time_error_value (int errnum)
3344 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3345 ? NONEXISTENT_MODTIME_NSECS
3346 : UNKNOWN_MODTIME_NSECS);
3347 return make_timespec (0, ns);
3350 static Lisp_Object
3351 get_window_points_and_markers (void)
3353 Lisp_Object pt_marker = Fpoint_marker ();
3354 Lisp_Object windows
3355 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3356 Lisp_Object window_markers = windows;
3357 /* Window markers (and point) are handled specially: rather than move to
3358 just before or just after the modified text, we try to keep the
3359 markers at the same distance (bug#19161).
3360 In general, this is wrong, but for window-markers, this should be harmless
3361 and is convenient for the end user when most of the file is unmodified,
3362 except for a few minor details near the beginning and near the end. */
3363 for (; CONSP (windows); windows = XCDR (windows))
3364 if (WINDOWP (XCAR (windows)))
3366 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3367 XSETCAR (windows,
3368 Fcons (window_marker, Fmarker_position (window_marker)));
3370 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3373 static void
3374 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3375 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3377 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3378 if (CONSP (XCAR (window_markers)))
3380 Lisp_Object car = XCAR (window_markers);
3381 Lisp_Object marker = XCAR (car);
3382 Lisp_Object oldpos = XCDR (car);
3383 if (MARKERP (marker) && INTEGERP (oldpos)
3384 && XINT (oldpos) > same_at_start
3385 && XINT (oldpos) < same_at_end)
3387 ptrdiff_t oldsize = same_at_end - same_at_start;
3388 ptrdiff_t newsize = inserted;
3389 double growth = newsize / (double)oldsize;
3390 ptrdiff_t newpos
3391 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3392 Fset_marker (marker, make_number (newpos), Qnil);
3397 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3398 text as a linear C char array. */
3399 static void
3400 maybe_move_gap (struct buffer *b)
3402 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3404 struct buffer *cb = current_buffer;
3406 set_buffer_internal (b);
3407 move_gap_both (Z, Z_BYTE);
3408 set_buffer_internal (cb);
3412 /* FIXME: insert-file-contents should be split with the top-level moved to
3413 Elisp and only the core kept in C. */
3415 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3416 1, 5, 0,
3417 doc: /* Insert contents of file FILENAME after point.
3418 Returns list of absolute file name and number of characters inserted.
3419 If second argument VISIT is non-nil, the buffer's visited filename and
3420 last save file modtime are set, and it is marked unmodified. If
3421 visiting and the file does not exist, visiting is completed before the
3422 error is signaled.
3424 The optional third and fourth arguments BEG and END specify what portion
3425 of the file to insert. These arguments count bytes in the file, not
3426 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3428 If optional fifth argument REPLACE is non-nil, replace the current
3429 buffer contents (in the accessible portion) with the file contents.
3430 This is better than simply deleting and inserting the whole thing
3431 because (1) it preserves some marker positions and (2) it puts less data
3432 in the undo list. When REPLACE is non-nil, the second return value is
3433 the number of characters that replace previous buffer contents.
3435 This function does code conversion according to the value of
3436 `coding-system-for-read' or `file-coding-system-alist', and sets the
3437 variable `last-coding-system-used' to the coding system actually used.
3439 In addition, this function decodes the inserted text from known formats
3440 by calling `format-decode', which see. */)
3441 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3443 struct stat st;
3444 struct timespec mtime;
3445 int fd;
3446 ptrdiff_t inserted = 0;
3447 ptrdiff_t how_much;
3448 off_t beg_offset, end_offset;
3449 int unprocessed;
3450 ptrdiff_t count = SPECPDL_INDEX ();
3451 Lisp_Object handler, val, insval, orig_filename, old_undo;
3452 Lisp_Object p;
3453 ptrdiff_t total = 0;
3454 bool not_regular = 0;
3455 int save_errno = 0;
3456 char read_buf[READ_BUF_SIZE];
3457 struct coding_system coding;
3458 bool replace_handled = false;
3459 bool set_coding_system = false;
3460 Lisp_Object coding_system;
3461 bool read_quit = false;
3462 /* If the undo log only contains the insertion, there's no point
3463 keeping it. It's typically when we first fill a file-buffer. */
3464 bool empty_undo_list_p
3465 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3466 && BEG == Z);
3467 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3468 bool we_locked_file = false;
3469 ptrdiff_t fd_index;
3470 Lisp_Object window_markers = Qnil;
3471 /* same_at_start and same_at_end count bytes, because file access counts
3472 bytes and BEG and END count bytes. */
3473 ptrdiff_t same_at_start = BEGV_BYTE;
3474 ptrdiff_t same_at_end = ZV_BYTE;
3475 /* SAME_AT_END_CHARPOS counts characters, because
3476 restore_window_points needs the old character count. */
3477 ptrdiff_t same_at_end_charpos = ZV;
3479 if (current_buffer->base_buffer && ! NILP (visit))
3480 error ("Cannot do file visiting in an indirect buffer");
3482 if (!NILP (BVAR (current_buffer, read_only)))
3483 Fbarf_if_buffer_read_only (Qnil);
3485 val = Qnil;
3486 p = Qnil;
3487 orig_filename = Qnil;
3488 old_undo = Qnil;
3490 CHECK_STRING (filename);
3491 filename = Fexpand_file_name (filename, Qnil);
3493 /* The value Qnil means that the coding system is not yet
3494 decided. */
3495 coding_system = Qnil;
3497 /* If the file name has special constructs in it,
3498 call the corresponding file handler. */
3499 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3500 if (!NILP (handler))
3502 val = call6 (handler, Qinsert_file_contents, filename,
3503 visit, beg, end, replace);
3504 if (CONSP (val) && CONSP (XCDR (val))
3505 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3506 inserted = XINT (XCAR (XCDR (val)));
3507 goto handled;
3510 orig_filename = filename;
3511 filename = ENCODE_FILE (filename);
3513 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3514 if (fd < 0)
3516 save_errno = errno;
3517 if (NILP (visit))
3518 report_file_error ("Opening input file", orig_filename);
3519 mtime = time_error_value (save_errno);
3520 st.st_size = -1;
3521 if (!NILP (Vcoding_system_for_read))
3523 /* Don't let invalid values into buffer-file-coding-system. */
3524 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3525 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3527 goto notfound;
3530 fd_index = SPECPDL_INDEX ();
3531 record_unwind_protect_int (close_file_unwind, fd);
3533 /* Replacement should preserve point as it preserves markers. */
3534 if (!NILP (replace))
3536 window_markers = get_window_points_and_markers ();
3537 record_unwind_protect (restore_point_unwind,
3538 XCAR (XCAR (window_markers)));
3541 if (fstat (fd, &st) != 0)
3542 report_file_error ("Input file status", orig_filename);
3543 mtime = get_stat_mtime (&st);
3545 /* This code will need to be changed in order to work on named
3546 pipes, and it's probably just not worth it. So we should at
3547 least signal an error. */
3548 if (!S_ISREG (st.st_mode))
3550 not_regular = 1;
3552 if (! NILP (visit))
3553 goto notfound;
3555 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3556 xsignal2 (Qfile_error,
3557 build_string ("not a regular file"), orig_filename);
3560 if (!NILP (visit))
3562 if (!NILP (beg) || !NILP (end))
3563 error ("Attempt to visit less than an entire file");
3564 if (BEG < Z && NILP (replace))
3565 error ("Cannot do file visiting in a non-empty buffer");
3568 if (!NILP (beg))
3569 beg_offset = file_offset (beg);
3570 else
3571 beg_offset = 0;
3573 if (!NILP (end))
3574 end_offset = file_offset (end);
3575 else
3577 if (not_regular)
3578 end_offset = TYPE_MAXIMUM (off_t);
3579 else
3581 end_offset = st.st_size;
3583 /* A negative size can happen on a platform that allows file
3584 sizes greater than the maximum off_t value. */
3585 if (end_offset < 0)
3586 buffer_overflow ();
3588 /* The file size returned from stat may be zero, but data
3589 may be readable nonetheless, for example when this is a
3590 file in the /proc filesystem. */
3591 if (end_offset == 0)
3592 end_offset = READ_BUF_SIZE;
3596 /* Check now whether the buffer will become too large,
3597 in the likely case where the file's length is not changing.
3598 This saves a lot of needless work before a buffer overflow. */
3599 if (! not_regular)
3601 /* The likely offset where we will stop reading. We could read
3602 more (or less), if the file grows (or shrinks) as we read it. */
3603 off_t likely_end = min (end_offset, st.st_size);
3605 if (beg_offset < likely_end)
3607 ptrdiff_t buf_bytes
3608 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3609 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3610 off_t likely_growth = likely_end - beg_offset;
3611 if (buf_growth_max < likely_growth)
3612 buffer_overflow ();
3616 /* Prevent redisplay optimizations. */
3617 current_buffer->clip_changed = true;
3619 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3621 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3622 setup_coding_system (coding_system, &coding);
3623 /* Ensure we set Vlast_coding_system_used. */
3624 set_coding_system = true;
3626 else if (BEG < Z)
3628 /* Decide the coding system to use for reading the file now
3629 because we can't use an optimized method for handling
3630 `coding:' tag if the current buffer is not empty. */
3631 if (!NILP (Vcoding_system_for_read))
3632 coding_system = Vcoding_system_for_read;
3633 else
3635 /* Don't try looking inside a file for a coding system
3636 specification if it is not seekable. */
3637 if (! not_regular && ! NILP (Vset_auto_coding_function))
3639 /* Find a coding system specified in the heading two
3640 lines or in the tailing several lines of the file.
3641 We assume that the 1K-byte and 3K-byte for heading
3642 and tailing respectively are sufficient for this
3643 purpose. */
3644 int nread;
3646 if (st.st_size <= (1024 * 4))
3647 nread = emacs_read_quit (fd, read_buf, 1024 * 4);
3648 else
3650 nread = emacs_read_quit (fd, read_buf, 1024);
3651 if (nread == 1024)
3653 int ntail;
3654 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3655 report_file_error ("Setting file position",
3656 orig_filename);
3657 ntail = emacs_read_quit (fd, read_buf + nread, 1024 * 3);
3658 nread = ntail < 0 ? ntail : nread + ntail;
3662 if (nread < 0)
3663 report_file_error ("Read error", orig_filename);
3664 else if (nread > 0)
3666 AUTO_STRING (name, " *code-converting-work*");
3667 struct buffer *prev = current_buffer;
3668 Lisp_Object workbuf;
3669 struct buffer *buf;
3671 record_unwind_current_buffer ();
3673 workbuf = Fget_buffer_create (name);
3674 buf = XBUFFER (workbuf);
3676 delete_all_overlays (buf);
3677 bset_directory (buf, BVAR (current_buffer, directory));
3678 bset_read_only (buf, Qnil);
3679 bset_filename (buf, Qnil);
3680 bset_undo_list (buf, Qt);
3681 eassert (buf->overlays_before == NULL);
3682 eassert (buf->overlays_after == NULL);
3684 set_buffer_internal (buf);
3685 Ferase_buffer ();
3686 bset_enable_multibyte_characters (buf, Qnil);
3688 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3689 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3690 coding_system = call2 (Vset_auto_coding_function,
3691 filename, make_number (nread));
3692 set_buffer_internal (prev);
3694 /* Discard the unwind protect for recovering the
3695 current buffer. */
3696 specpdl_ptr--;
3698 /* Rewind the file for the actual read done later. */
3699 if (lseek (fd, 0, SEEK_SET) < 0)
3700 report_file_error ("Setting file position", orig_filename);
3704 if (NILP (coding_system))
3706 /* If we have not yet decided a coding system, check
3707 file-coding-system-alist. */
3708 coding_system = CALLN (Ffind_operation_coding_system,
3709 Qinsert_file_contents, orig_filename,
3710 visit, beg, end, replace);
3711 if (CONSP (coding_system))
3712 coding_system = XCAR (coding_system);
3716 if (NILP (coding_system))
3717 coding_system = Qundecided;
3718 else
3719 CHECK_CODING_SYSTEM (coding_system);
3721 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3722 /* We must suppress all character code conversion except for
3723 end-of-line conversion. */
3724 coding_system = raw_text_coding_system (coding_system);
3726 setup_coding_system (coding_system, &coding);
3727 /* Ensure we set Vlast_coding_system_used. */
3728 set_coding_system = true;
3731 /* If requested, replace the accessible part of the buffer
3732 with the file contents. Avoid replacing text at the
3733 beginning or end of the buffer that matches the file contents;
3734 that preserves markers pointing to the unchanged parts.
3736 Here we implement this feature in an optimized way
3737 for the case where code conversion is NOT needed.
3738 The following if-statement handles the case of conversion
3739 in a less optimal way.
3741 If the code conversion is "automatic" then we try using this
3742 method and hope for the best.
3743 But if we discover the need for conversion, we give up on this method
3744 and let the following if-statement handle the replace job. */
3745 if (!NILP (replace)
3746 && BEGV < ZV
3747 && (NILP (coding_system)
3748 || ! CODING_REQUIRE_DECODING (&coding)))
3750 ptrdiff_t overlap;
3751 /* There is still a possibility we will find the need to do code
3752 conversion. If that happens, set this variable to
3753 give up on handling REPLACE in the optimized way. */
3754 bool giveup_match_end = false;
3756 if (beg_offset != 0)
3758 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3759 report_file_error ("Setting file position", orig_filename);
3762 /* Count how many chars at the start of the file
3763 match the text at the beginning of the buffer. */
3764 while (true)
3766 int nread = emacs_read_quit (fd, read_buf, sizeof read_buf);
3767 if (nread < 0)
3768 report_file_error ("Read error", orig_filename);
3769 else if (nread == 0)
3770 break;
3772 if (CODING_REQUIRE_DETECTION (&coding))
3774 coding_system = detect_coding_system ((unsigned char *) read_buf,
3775 nread, nread, 1, 0,
3776 coding_system);
3777 setup_coding_system (coding_system, &coding);
3780 if (CODING_REQUIRE_DECODING (&coding))
3781 /* We found that the file should be decoded somehow.
3782 Let's give up here. */
3784 giveup_match_end = true;
3785 break;
3788 int bufpos = 0;
3789 while (bufpos < nread && same_at_start < ZV_BYTE
3790 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3791 same_at_start++, bufpos++;
3792 /* If we found a discrepancy, stop the scan.
3793 Otherwise loop around and scan the next bufferful. */
3794 if (bufpos != nread)
3795 break;
3797 /* If the file matches the buffer completely,
3798 there's no need to replace anything. */
3799 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3801 emacs_close (fd);
3802 clear_unwind_protect (fd_index);
3804 /* Truncate the buffer to the size of the file. */
3805 del_range_1 (same_at_start, same_at_end, 0, 0);
3806 goto handled;
3809 /* Count how many chars at the end of the file
3810 match the text at the end of the buffer. But, if we have
3811 already found that decoding is necessary, don't waste time. */
3812 while (!giveup_match_end)
3814 int total_read, nread, bufpos, trial;
3815 off_t curpos;
3817 /* At what file position are we now scanning? */
3818 curpos = end_offset - (ZV_BYTE - same_at_end);
3819 /* If the entire file matches the buffer tail, stop the scan. */
3820 if (curpos == 0)
3821 break;
3822 /* How much can we scan in the next step? */
3823 trial = min (curpos, sizeof read_buf);
3824 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3825 report_file_error ("Setting file position", orig_filename);
3827 total_read = nread = 0;
3828 while (total_read < trial)
3830 nread = emacs_read_quit (fd, read_buf + total_read,
3831 trial - total_read);
3832 if (nread < 0)
3833 report_file_error ("Read error", orig_filename);
3834 else if (nread == 0)
3835 break;
3836 total_read += nread;
3839 /* Scan this bufferful from the end, comparing with
3840 the Emacs buffer. */
3841 bufpos = total_read;
3843 /* Compare with same_at_start to avoid counting some buffer text
3844 as matching both at the file's beginning and at the end. */
3845 while (bufpos > 0 && same_at_end > same_at_start
3846 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3847 same_at_end--, bufpos--;
3849 /* If we found a discrepancy, stop the scan.
3850 Otherwise loop around and scan the preceding bufferful. */
3851 if (bufpos != 0)
3853 /* If this discrepancy is because of code conversion,
3854 we cannot use this method; giveup and try the other. */
3855 if (same_at_end > same_at_start
3856 && FETCH_BYTE (same_at_end - 1) >= 0200
3857 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3858 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3859 giveup_match_end = true;
3860 break;
3863 if (nread == 0)
3864 break;
3867 if (! giveup_match_end)
3869 ptrdiff_t temp;
3870 ptrdiff_t this_count = SPECPDL_INDEX ();
3872 /* We win! We can handle REPLACE the optimized way. */
3874 /* Extend the start of non-matching text area to multibyte
3875 character boundary. */
3876 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3877 while (same_at_start > BEGV_BYTE
3878 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3879 same_at_start--;
3881 /* Extend the end of non-matching text area to multibyte
3882 character boundary. */
3883 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3884 while (same_at_end < ZV_BYTE
3885 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3886 same_at_end++;
3888 /* Don't try to reuse the same piece of text twice. */
3889 overlap = (same_at_start - BEGV_BYTE
3890 - (same_at_end
3891 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3892 if (overlap > 0)
3893 same_at_end += overlap;
3894 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3896 /* Arrange to read only the nonmatching middle part of the file. */
3897 beg_offset += same_at_start - BEGV_BYTE;
3898 end_offset -= ZV_BYTE - same_at_end;
3900 /* This binding is to avoid ask-user-about-supersession-threat
3901 being called in insert_from_buffer or del_range_bytes (via
3902 prepare_to_modify_buffer).
3903 AFAICT we could avoid ask-user-about-supersession-threat by setting
3904 current_buffer->modtime earlier, but we could still end up calling
3905 ask-user-about-supersession-threat if the file is modified while
3906 we read it, so we bind buffer-file-name instead. */
3907 specbind (intern ("buffer-file-name"), Qnil);
3908 del_range_byte (same_at_start, same_at_end);
3909 /* Insert from the file at the proper position. */
3910 temp = BYTE_TO_CHAR (same_at_start);
3911 SET_PT_BOTH (temp, same_at_start);
3912 unbind_to (this_count, Qnil);
3914 /* If display currently starts at beginning of line,
3915 keep it that way. */
3916 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3917 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3919 replace_handled = true;
3923 /* If requested, replace the accessible part of the buffer
3924 with the file contents. Avoid replacing text at the
3925 beginning or end of the buffer that matches the file contents;
3926 that preserves markers pointing to the unchanged parts.
3928 Here we implement this feature for the case where code conversion
3929 is needed, in a simple way that needs a lot of memory.
3930 The preceding if-statement handles the case of no conversion
3931 in a more optimized way. */
3932 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3934 ptrdiff_t same_at_start_charpos;
3935 ptrdiff_t inserted_chars;
3936 ptrdiff_t overlap;
3937 ptrdiff_t bufpos;
3938 unsigned char *decoded;
3939 ptrdiff_t temp;
3940 ptrdiff_t this = 0;
3941 ptrdiff_t this_count = SPECPDL_INDEX ();
3942 bool multibyte
3943 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3944 Lisp_Object conversion_buffer;
3946 conversion_buffer = code_conversion_save (1, multibyte);
3948 /* First read the whole file, performing code conversion into
3949 CONVERSION_BUFFER. */
3951 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3952 report_file_error ("Setting file position", orig_filename);
3954 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3955 unprocessed = 0; /* Bytes not processed in previous loop. */
3957 while (true)
3959 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3960 quitting while reading a huge file. */
3962 this = emacs_read_quit (fd, read_buf + unprocessed,
3963 READ_BUF_SIZE - unprocessed);
3964 if (this <= 0)
3965 break;
3967 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3968 BUF_Z (XBUFFER (conversion_buffer)));
3969 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3970 unprocessed + this, conversion_buffer);
3971 unprocessed = coding.carryover_bytes;
3972 if (coding.carryover_bytes > 0)
3973 memcpy (read_buf, coding.carryover, unprocessed);
3976 if (this < 0)
3977 report_file_error ("Read error", orig_filename);
3978 emacs_close (fd);
3979 clear_unwind_protect (fd_index);
3981 if (unprocessed > 0)
3983 coding.mode |= CODING_MODE_LAST_BLOCK;
3984 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3985 unprocessed, conversion_buffer);
3986 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3989 coding_system = CODING_ID_NAME (coding.id);
3990 set_coding_system = true;
3991 maybe_move_gap (XBUFFER (conversion_buffer));
3992 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3993 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3994 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3996 /* Compare the beginning of the converted string with the buffer
3997 text. */
3999 bufpos = 0;
4000 while (bufpos < inserted && same_at_start < same_at_end
4001 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4002 same_at_start++, bufpos++;
4004 /* If the file matches the head of buffer completely,
4005 there's no need to replace anything. */
4007 if (bufpos == inserted)
4009 /* Truncate the buffer to the size of the file. */
4010 if (same_at_start != same_at_end)
4012 /* See previous specbind for the reason behind this. */
4013 specbind (intern ("buffer-file-name"), Qnil);
4014 del_range_byte (same_at_start, same_at_end);
4016 inserted = 0;
4018 unbind_to (this_count, Qnil);
4019 goto handled;
4022 /* Extend the start of non-matching text area to the previous
4023 multibyte character boundary. */
4024 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4025 while (same_at_start > BEGV_BYTE
4026 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4027 same_at_start--;
4029 /* Scan this bufferful from the end, comparing with
4030 the Emacs buffer. */
4031 bufpos = inserted;
4033 /* Compare with same_at_start to avoid counting some buffer text
4034 as matching both at the file's beginning and at the end. */
4035 while (bufpos > 0 && same_at_end > same_at_start
4036 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4037 same_at_end--, bufpos--;
4039 /* Extend the end of non-matching text area to the next
4040 multibyte character boundary. */
4041 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4042 while (same_at_end < ZV_BYTE
4043 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4044 same_at_end++;
4046 /* Don't try to reuse the same piece of text twice. */
4047 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4048 if (overlap > 0)
4049 same_at_end += overlap;
4050 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4052 /* If display currently starts at beginning of line,
4053 keep it that way. */
4054 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4055 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4057 /* Replace the chars that we need to replace,
4058 and update INSERTED to equal the number of bytes
4059 we are taking from the decoded string. */
4060 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4062 /* See previous specbind for the reason behind this. */
4063 specbind (intern ("buffer-file-name"), Qnil);
4064 if (same_at_end != same_at_start)
4066 del_range_byte (same_at_start, same_at_end);
4067 temp = GPT;
4068 eassert (same_at_start == GPT_BYTE);
4069 same_at_start = GPT_BYTE;
4071 else
4073 temp = same_at_end_charpos;
4075 /* Insert from the file at the proper position. */
4076 SET_PT_BOTH (temp, same_at_start);
4077 same_at_start_charpos
4078 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4079 same_at_start - BEGV_BYTE
4080 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4081 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4082 inserted_chars
4083 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4084 same_at_start + inserted - BEGV_BYTE
4085 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4086 - same_at_start_charpos);
4087 insert_from_buffer (XBUFFER (conversion_buffer),
4088 same_at_start_charpos, inserted_chars, 0);
4089 /* Set `inserted' to the number of inserted characters. */
4090 inserted = PT - temp;
4091 /* Set point before the inserted characters. */
4092 SET_PT_BOTH (temp, same_at_start);
4094 unbind_to (this_count, Qnil);
4096 goto handled;
4099 if (! not_regular)
4100 total = end_offset - beg_offset;
4101 else
4102 /* For a special file, all we can do is guess. */
4103 total = READ_BUF_SIZE;
4105 if (NILP (visit) && total > 0)
4107 if (!NILP (BVAR (current_buffer, file_truename))
4108 /* Make binding buffer-file-name to nil effective. */
4109 && !NILP (BVAR (current_buffer, filename))
4110 && SAVE_MODIFF >= MODIFF)
4111 we_locked_file = true;
4112 prepare_to_modify_buffer (PT, PT, NULL);
4115 move_gap_both (PT, PT_BYTE);
4116 if (GAP_SIZE < total)
4117 make_gap (total - GAP_SIZE);
4119 if (beg_offset != 0 || !NILP (replace))
4121 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4122 report_file_error ("Setting file position", orig_filename);
4125 /* In the following loop, HOW_MUCH contains the total bytes read so
4126 far for a regular file, and not changed for a special file. But,
4127 before exiting the loop, it is set to a negative value if I/O
4128 error occurs. */
4129 how_much = 0;
4131 /* Total bytes inserted. */
4132 inserted = 0;
4134 /* Here, we don't do code conversion in the loop. It is done by
4135 decode_coding_gap after all data are read into the buffer. */
4137 ptrdiff_t gap_size = GAP_SIZE;
4139 while (how_much < total)
4141 /* `try' is reserved in some compilers (Microsoft C). */
4142 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4143 ptrdiff_t this;
4145 if (not_regular)
4147 Lisp_Object nbytes;
4149 /* Maybe make more room. */
4150 if (gap_size < trytry)
4152 make_gap (trytry - gap_size);
4153 gap_size = GAP_SIZE - inserted;
4156 /* Read from the file, capturing `quit'. When an
4157 error occurs, end the loop, and arrange for a quit
4158 to be signaled after decoding the text we read. */
4159 nbytes = internal_condition_case_1
4160 (read_non_regular,
4161 make_save_int_int_int (fd, inserted, trytry),
4162 Qerror, read_non_regular_quit);
4164 if (NILP (nbytes))
4166 read_quit = true;
4167 break;
4170 this = XINT (nbytes);
4172 else
4174 /* Allow quitting out of the actual I/O. We don't make text
4175 part of the buffer until all the reading is done, so a C-g
4176 here doesn't do any harm. */
4177 this = emacs_read_quit (fd,
4178 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4179 + inserted),
4180 trytry);
4183 if (this <= 0)
4185 how_much = this;
4186 break;
4189 gap_size -= this;
4191 /* For a regular file, where TOTAL is the real size,
4192 count HOW_MUCH to compare with it.
4193 For a special file, where TOTAL is just a buffer size,
4194 so don't bother counting in HOW_MUCH.
4195 (INSERTED is where we count the number of characters inserted.) */
4196 if (! not_regular)
4197 how_much += this;
4198 inserted += this;
4202 /* Now we have either read all the file data into the gap,
4203 or stop reading on I/O error or quit. If nothing was
4204 read, undo marking the buffer modified. */
4206 if (inserted == 0)
4208 if (we_locked_file)
4209 unlock_file (BVAR (current_buffer, file_truename));
4210 Vdeactivate_mark = old_Vdeactivate_mark;
4212 else
4213 Fset (Qdeactivate_mark, Qt);
4215 emacs_close (fd);
4216 clear_unwind_protect (fd_index);
4218 if (how_much < 0)
4219 report_file_error ("Read error", orig_filename);
4221 /* Make the text read part of the buffer. */
4222 GAP_SIZE -= inserted;
4223 GPT += inserted;
4224 GPT_BYTE += inserted;
4225 ZV += inserted;
4226 ZV_BYTE += inserted;
4227 Z += inserted;
4228 Z_BYTE += inserted;
4230 if (GAP_SIZE > 0)
4231 /* Put an anchor to ensure multi-byte form ends at gap. */
4232 *GPT_ADDR = 0;
4234 notfound:
4236 if (NILP (coding_system))
4238 /* The coding system is not yet decided. Decide it by an
4239 optimized method for handling `coding:' tag.
4241 Note that we can get here only if the buffer was empty
4242 before the insertion. */
4244 if (!NILP (Vcoding_system_for_read))
4245 coding_system = Vcoding_system_for_read;
4246 else
4248 /* Since we are sure that the current buffer was empty
4249 before the insertion, we can toggle
4250 enable-multibyte-characters directly here without taking
4251 care of marker adjustment. By this way, we can run Lisp
4252 program safely before decoding the inserted text. */
4253 Lisp_Object unwind_data;
4254 ptrdiff_t count1 = SPECPDL_INDEX ();
4256 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4257 Fcons (BVAR (current_buffer, undo_list),
4258 Fcurrent_buffer ()));
4259 bset_enable_multibyte_characters (current_buffer, Qnil);
4260 bset_undo_list (current_buffer, Qt);
4261 record_unwind_protect (decide_coding_unwind, unwind_data);
4263 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4265 coding_system = call2 (Vset_auto_coding_function,
4266 filename, make_number (inserted));
4269 if (NILP (coding_system))
4271 /* If the coding system is not yet decided, check
4272 file-coding-system-alist. */
4273 coding_system = CALLN (Ffind_operation_coding_system,
4274 Qinsert_file_contents, orig_filename,
4275 visit, beg, end, Qnil);
4276 if (CONSP (coding_system))
4277 coding_system = XCAR (coding_system);
4279 unbind_to (count1, Qnil);
4280 inserted = Z_BYTE - BEG_BYTE;
4283 if (NILP (coding_system))
4284 coding_system = Qundecided;
4285 else
4286 CHECK_CODING_SYSTEM (coding_system);
4288 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4289 /* We must suppress all character code conversion except for
4290 end-of-line conversion. */
4291 coding_system = raw_text_coding_system (coding_system);
4292 setup_coding_system (coding_system, &coding);
4293 /* Ensure we set Vlast_coding_system_used. */
4294 set_coding_system = true;
4297 if (!NILP (visit))
4299 /* When we visit a file by raw-text, we change the buffer to
4300 unibyte. */
4301 if (CODING_FOR_UNIBYTE (&coding)
4302 /* Can't do this if part of the buffer might be preserved. */
4303 && NILP (replace))
4305 /* Visiting a file with these coding system makes the buffer
4306 unibyte. */
4307 if (inserted > 0)
4308 bset_enable_multibyte_characters (current_buffer, Qnil);
4309 else
4310 Fset_buffer_multibyte (Qnil);
4314 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4315 if (CODING_MAY_REQUIRE_DECODING (&coding)
4316 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4318 move_gap_both (PT, PT_BYTE);
4319 GAP_SIZE += inserted;
4320 ZV_BYTE -= inserted;
4321 Z_BYTE -= inserted;
4322 ZV -= inserted;
4323 Z -= inserted;
4324 decode_coding_gap (&coding, inserted, inserted);
4325 inserted = coding.produced_char;
4326 coding_system = CODING_ID_NAME (coding.id);
4328 else if (inserted > 0)
4330 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4331 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4332 inserted);
4335 /* Call after-change hooks for the inserted text, aside from the case
4336 of normal visiting (not with REPLACE), which is done in a new buffer
4337 "before" the buffer is changed. */
4338 if (inserted > 0 && total > 0
4339 && (NILP (visit) || !NILP (replace)))
4341 signal_after_change (PT, 0, inserted);
4342 update_compositions (PT, PT, CHECK_BORDER);
4345 /* Now INSERTED is measured in characters. */
4347 handled:
4349 if (inserted > 0)
4350 restore_window_points (window_markers, inserted,
4351 BYTE_TO_CHAR (same_at_start),
4352 same_at_end_charpos);
4354 if (!NILP (visit))
4356 if (empty_undo_list_p)
4357 bset_undo_list (current_buffer, Qnil);
4359 if (NILP (handler))
4361 current_buffer->modtime = mtime;
4362 current_buffer->modtime_size = st.st_size;
4363 bset_filename (current_buffer, orig_filename);
4366 SAVE_MODIFF = MODIFF;
4367 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4368 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4369 if (NILP (handler))
4371 if (!NILP (BVAR (current_buffer, file_truename)))
4372 unlock_file (BVAR (current_buffer, file_truename));
4373 unlock_file (filename);
4375 if (not_regular)
4376 xsignal2 (Qfile_error,
4377 build_string ("not a regular file"), orig_filename);
4380 if (set_coding_system)
4381 Vlast_coding_system_used = coding_system;
4383 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4385 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4386 visit);
4387 if (! NILP (insval))
4389 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4390 wrong_type_argument (intern ("inserted-chars"), insval);
4391 inserted = XFASTINT (insval);
4395 /* Decode file format. */
4396 if (inserted > 0)
4398 /* Don't run point motion or modification hooks when decoding. */
4399 ptrdiff_t count1 = SPECPDL_INDEX ();
4400 ptrdiff_t old_inserted = inserted;
4401 specbind (Qinhibit_point_motion_hooks, Qt);
4402 specbind (Qinhibit_modification_hooks, Qt);
4404 /* Save old undo list and don't record undo for decoding. */
4405 old_undo = BVAR (current_buffer, undo_list);
4406 bset_undo_list (current_buffer, Qt);
4408 if (NILP (replace))
4410 insval = call3 (Qformat_decode,
4411 Qnil, make_number (inserted), visit);
4412 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4413 wrong_type_argument (intern ("inserted-chars"), insval);
4414 inserted = XFASTINT (insval);
4416 else
4418 /* If REPLACE is non-nil and we succeeded in not replacing the
4419 beginning or end of the buffer text with the file's contents,
4420 call format-decode with `point' positioned at the beginning
4421 of the buffer and `inserted' equaling the number of
4422 characters in the buffer. Otherwise, format-decode might
4423 fail to correctly analyze the beginning or end of the buffer.
4424 Hence we temporarily save `point' and `inserted' here and
4425 restore `point' iff format-decode did not insert or delete
4426 any text. Otherwise we leave `point' at point-min. */
4427 ptrdiff_t opoint = PT;
4428 ptrdiff_t opoint_byte = PT_BYTE;
4429 ptrdiff_t oinserted = ZV - BEGV;
4430 EMACS_INT ochars_modiff = CHARS_MODIFF;
4432 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4433 insval = call3 (Qformat_decode,
4434 Qnil, make_number (oinserted), visit);
4435 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4436 wrong_type_argument (intern ("inserted-chars"), insval);
4437 if (ochars_modiff == CHARS_MODIFF)
4438 /* format_decode didn't modify buffer's characters => move
4439 point back to position before inserted text and leave
4440 value of inserted alone. */
4441 SET_PT_BOTH (opoint, opoint_byte);
4442 else
4443 /* format_decode modified buffer's characters => consider
4444 entire buffer changed and leave point at point-min. */
4445 inserted = XFASTINT (insval);
4448 /* For consistency with format-decode call these now iff inserted > 0
4449 (martin 2007-06-28). */
4450 p = Vafter_insert_file_functions;
4451 while (CONSP (p))
4453 if (NILP (replace))
4455 insval = call1 (XCAR (p), make_number (inserted));
4456 if (!NILP (insval))
4458 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4459 wrong_type_argument (intern ("inserted-chars"), insval);
4460 inserted = XFASTINT (insval);
4463 else
4465 /* For the rationale of this see the comment on
4466 format-decode above. */
4467 ptrdiff_t opoint = PT;
4468 ptrdiff_t opoint_byte = PT_BYTE;
4469 ptrdiff_t oinserted = ZV - BEGV;
4470 EMACS_INT ochars_modiff = CHARS_MODIFF;
4472 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4473 insval = call1 (XCAR (p), make_number (oinserted));
4474 if (!NILP (insval))
4476 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4477 wrong_type_argument (intern ("inserted-chars"), insval);
4478 if (ochars_modiff == CHARS_MODIFF)
4479 /* after_insert_file_functions didn't modify
4480 buffer's characters => move point back to
4481 position before inserted text and leave value of
4482 inserted alone. */
4483 SET_PT_BOTH (opoint, opoint_byte);
4484 else
4485 /* after_insert_file_functions did modify buffer's
4486 characters => consider entire buffer changed and
4487 leave point at point-min. */
4488 inserted = XFASTINT (insval);
4492 maybe_quit ();
4493 p = XCDR (p);
4496 if (!empty_undo_list_p)
4498 bset_undo_list (current_buffer, old_undo);
4499 if (CONSP (old_undo) && inserted != old_inserted)
4501 /* Adjust the last undo record for the size change during
4502 the format conversion. */
4503 Lisp_Object tem = XCAR (old_undo);
4504 if (CONSP (tem) && INTEGERP (XCAR (tem))
4505 && INTEGERP (XCDR (tem))
4506 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4507 XSETCDR (tem, make_number (PT + inserted));
4510 else
4511 /* If undo_list was Qt before, keep it that way.
4512 Otherwise start with an empty undo_list. */
4513 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4515 unbind_to (count1, Qnil);
4518 if (!NILP (visit)
4519 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4521 /* If visiting nonexistent file, return nil. */
4522 report_file_errno ("Opening input file", orig_filename, save_errno);
4525 /* We made a lot of deletions and insertions above, so invalidate
4526 the newline cache for the entire region of the inserted
4527 characters. */
4528 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4529 invalidate_region_cache (current_buffer->base_buffer,
4530 current_buffer->base_buffer->newline_cache,
4531 PT - BEG, Z - PT - inserted);
4532 else if (current_buffer->newline_cache)
4533 invalidate_region_cache (current_buffer,
4534 current_buffer->newline_cache,
4535 PT - BEG, Z - PT - inserted);
4537 if (read_quit)
4538 quit ();
4540 /* Retval needs to be dealt with in all cases consistently. */
4541 if (NILP (val))
4542 val = list2 (orig_filename, make_number (inserted));
4544 return unbind_to (count, val);
4547 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4549 static void
4550 build_annotations_unwind (Lisp_Object arg)
4552 Vwrite_region_annotation_buffers = arg;
4555 /* Decide the coding-system to encode the data with. */
4557 static Lisp_Object
4558 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4559 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4560 struct coding_system *coding)
4562 Lisp_Object val;
4563 Lisp_Object eol_parent = Qnil;
4565 if (auto_saving
4566 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4567 BVAR (current_buffer, auto_save_file_name))))
4569 val = Qutf_8_emacs;
4570 eol_parent = Qunix;
4572 else if (!NILP (Vcoding_system_for_write))
4574 val = Vcoding_system_for_write;
4575 if (coding_system_require_warning
4576 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4577 /* Confirm that VAL can surely encode the current region. */
4578 val = call5 (Vselect_safe_coding_system_function,
4579 start, end, list2 (Qt, val),
4580 Qnil, filename);
4582 else
4584 /* If the variable `buffer-file-coding-system' is set locally,
4585 it means that the file was read with some kind of code
4586 conversion or the variable is explicitly set by users. We
4587 had better write it out with the same coding system even if
4588 `enable-multibyte-characters' is nil.
4590 If it is not set locally, we anyway have to convert EOL
4591 format if the default value of `buffer-file-coding-system'
4592 tells that it is not Unix-like (LF only) format. */
4593 bool using_default_coding = 0;
4594 bool force_raw_text = 0;
4596 val = BVAR (current_buffer, buffer_file_coding_system);
4597 if (NILP (val)
4598 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4600 val = Qnil;
4601 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4602 force_raw_text = 1;
4605 if (NILP (val))
4607 /* Check file-coding-system-alist. */
4608 Lisp_Object coding_systems
4609 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4610 filename, append, visit, lockname);
4611 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4612 val = XCDR (coding_systems);
4615 if (NILP (val))
4617 /* If we still have not decided a coding system, use the
4618 current buffer's value of buffer-file-coding-system. */
4619 val = BVAR (current_buffer, buffer_file_coding_system);
4620 using_default_coding = 1;
4623 if (! NILP (val) && ! force_raw_text)
4625 Lisp_Object spec, attrs;
4627 CHECK_CODING_SYSTEM (val);
4628 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4629 attrs = AREF (spec, 0);
4630 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4631 force_raw_text = 1;
4634 if (!force_raw_text
4635 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4637 /* Confirm that VAL can surely encode the current region. */
4638 val = call5 (Vselect_safe_coding_system_function,
4639 start, end, val, Qnil, filename);
4640 /* As the function specified by select-safe-coding-system-function
4641 is out of our control, make sure we are not fed by bogus
4642 values. */
4643 if (!NILP (val))
4644 CHECK_CODING_SYSTEM (val);
4647 /* If the decided coding-system doesn't specify end-of-line
4648 format, we use that of `buffer-file-coding-system'. */
4649 if (! using_default_coding)
4651 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4653 if (! NILP (dflt))
4654 val = coding_inherit_eol_type (val, dflt);
4657 /* If we decide not to encode text, use `raw-text' or one of its
4658 subsidiaries. */
4659 if (force_raw_text)
4660 val = raw_text_coding_system (val);
4663 val = coding_inherit_eol_type (val, eol_parent);
4664 setup_coding_system (val, coding);
4666 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4667 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4668 return val;
4671 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4672 "r\nFWrite region to file: \ni\ni\ni\np",
4673 doc: /* Write current region into specified file.
4674 When called from a program, requires three arguments:
4675 START, END and FILENAME. START and END are normally buffer positions
4676 specifying the part of the buffer to write.
4677 If START is nil, that means to use the entire buffer contents; END is
4678 ignored.
4679 If START is a string, then output that string to the file
4680 instead of any buffer contents; END is ignored.
4682 Optional fourth argument APPEND if non-nil means
4683 append to existing file contents (if any). If it is a number,
4684 seek to that offset in the file before writing.
4685 Optional fifth argument VISIT, if t or a string, means
4686 set the last-save-file-modtime of buffer to this file's modtime
4687 and mark buffer not modified.
4688 If VISIT is a string, it is a second file name;
4689 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4690 VISIT is also the file name to lock and unlock for clash detection.
4691 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4692 do not display the \"Wrote file\" message.
4693 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4694 use for locking and unlocking, overriding FILENAME and VISIT.
4695 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4696 for an existing file with the same name. If MUSTBENEW is `excl',
4697 that means to get an error if the file already exists; never overwrite.
4698 If MUSTBENEW is neither nil nor `excl', that means ask for
4699 confirmation before overwriting, but do go ahead and overwrite the file
4700 if the user confirms.
4702 This does code conversion according to the value of
4703 `coding-system-for-write', `buffer-file-coding-system', or
4704 `file-coding-system-alist', and sets the variable
4705 `last-coding-system-used' to the coding system actually used.
4707 This calls `write-region-annotate-functions' at the start, and
4708 `write-region-post-annotation-function' at the end. */)
4709 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4710 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4712 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4713 -1);
4716 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4717 descriptor for FILENAME, so do not open or close FILENAME. */
4719 Lisp_Object
4720 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4721 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4722 Lisp_Object mustbenew, int desc)
4724 int open_flags;
4725 int mode;
4726 off_t offset UNINIT;
4727 bool open_and_close_file = desc < 0;
4728 bool ok;
4729 int save_errno = 0;
4730 const char *fn;
4731 struct stat st;
4732 struct timespec modtime;
4733 ptrdiff_t count = SPECPDL_INDEX ();
4734 ptrdiff_t count1 UNINIT;
4735 Lisp_Object handler;
4736 Lisp_Object visit_file;
4737 Lisp_Object annotations;
4738 Lisp_Object encoded_filename;
4739 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4740 bool quietly = !NILP (visit);
4741 bool file_locked = 0;
4742 struct buffer *given_buffer;
4743 struct coding_system coding;
4745 if (current_buffer->base_buffer && visiting)
4746 error ("Cannot do file visiting in an indirect buffer");
4748 if (!NILP (start) && !STRINGP (start))
4749 validate_region (&start, &end);
4751 visit_file = Qnil;
4753 filename = Fexpand_file_name (filename, Qnil);
4755 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4756 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4758 if (STRINGP (visit))
4759 visit_file = Fexpand_file_name (visit, Qnil);
4760 else
4761 visit_file = filename;
4763 if (NILP (lockname))
4764 lockname = visit_file;
4766 annotations = Qnil;
4768 /* If the file name has special constructs in it,
4769 call the corresponding file handler. */
4770 handler = Ffind_file_name_handler (filename, Qwrite_region);
4771 /* If FILENAME has no handler, see if VISIT has one. */
4772 if (NILP (handler) && STRINGP (visit))
4773 handler = Ffind_file_name_handler (visit, Qwrite_region);
4775 if (!NILP (handler))
4777 Lisp_Object val;
4778 val = call8 (handler, Qwrite_region, start, end,
4779 filename, append, visit, lockname, mustbenew);
4781 if (visiting)
4783 SAVE_MODIFF = MODIFF;
4784 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4785 bset_filename (current_buffer, visit_file);
4788 return val;
4791 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4793 /* Special kludge to simplify auto-saving. */
4794 if (NILP (start))
4796 /* Do it later, so write-region-annotate-function can work differently
4797 if we save "the buffer" vs "a region".
4798 This is useful in tar-mode. --Stef
4799 XSETFASTINT (start, BEG);
4800 XSETFASTINT (end, Z); */
4801 Fwiden ();
4804 record_unwind_protect (build_annotations_unwind,
4805 Vwrite_region_annotation_buffers);
4806 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4808 given_buffer = current_buffer;
4810 if (!STRINGP (start))
4812 annotations = build_annotations (start, end);
4814 if (current_buffer != given_buffer)
4816 XSETFASTINT (start, BEGV);
4817 XSETFASTINT (end, ZV);
4821 if (NILP (start))
4823 XSETFASTINT (start, BEGV);
4824 XSETFASTINT (end, ZV);
4827 /* Decide the coding-system to encode the data with.
4828 We used to make this choice before calling build_annotations, but that
4829 leads to problems when a write-annotate-function takes care of
4830 unsavable chars (as was the case with X-Symbol). */
4831 Vlast_coding_system_used
4832 = choose_write_coding_system (start, end, filename,
4833 append, visit, lockname, &coding);
4835 if (open_and_close_file && !auto_saving)
4837 lock_file (lockname);
4838 file_locked = 1;
4841 encoded_filename = ENCODE_FILE (filename);
4842 fn = SSDATA (encoded_filename);
4843 open_flags = O_WRONLY | O_CREAT;
4844 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4845 if (NUMBERP (append))
4846 offset = file_offset (append);
4847 else if (!NILP (append))
4848 open_flags |= O_APPEND;
4849 #ifdef DOS_NT
4850 mode = S_IREAD | S_IWRITE;
4851 #else
4852 mode = auto_saving ? auto_save_mode_bits : 0666;
4853 #endif
4855 if (open_and_close_file)
4857 desc = emacs_open (fn, open_flags, mode);
4858 if (desc < 0)
4860 int open_errno = errno;
4861 if (file_locked)
4862 unlock_file (lockname);
4863 report_file_errno ("Opening output file", filename, open_errno);
4866 count1 = SPECPDL_INDEX ();
4867 record_unwind_protect_int (close_file_unwind, desc);
4870 if (NUMBERP (append))
4872 off_t ret = lseek (desc, offset, SEEK_SET);
4873 if (ret < 0)
4875 int lseek_errno = errno;
4876 if (file_locked)
4877 unlock_file (lockname);
4878 report_file_errno ("Lseek error", filename, lseek_errno);
4882 if (STRINGP (start))
4883 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4884 else if (XINT (start) != XINT (end))
4885 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4886 &annotations, &coding);
4887 else
4889 /* If file was empty, still need to write the annotations. */
4890 coding.mode |= CODING_MODE_LAST_BLOCK;
4891 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4893 save_errno = errno;
4895 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4896 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4898 /* We have to flush out a data. */
4899 coding.mode |= CODING_MODE_LAST_BLOCK;
4900 ok = e_write (desc, Qnil, 1, 1, &coding);
4901 save_errno = errno;
4904 /* fsync is not crucial for temporary files. Nor for auto-save
4905 files, since they might lose some work anyway. */
4906 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4908 /* Transfer data and metadata to disk, retrying if interrupted.
4909 fsync can report a write failure here, e.g., due to disk full
4910 under NFS. But ignore EINVAL, which means fsync is not
4911 supported on this file. */
4912 while (fsync (desc) != 0)
4913 if (errno != EINTR)
4915 if (errno != EINVAL)
4916 ok = 0, save_errno = errno;
4917 break;
4921 modtime = invalid_timespec ();
4922 if (visiting)
4924 if (fstat (desc, &st) == 0)
4925 modtime = get_stat_mtime (&st);
4926 else
4927 ok = 0, save_errno = errno;
4930 if (open_and_close_file)
4932 /* NFS can report a write failure now. */
4933 if (emacs_close (desc) < 0)
4934 ok = 0, save_errno = errno;
4936 /* Discard the unwind protect for close_file_unwind. */
4937 specpdl_ptr = specpdl + count1;
4940 /* Some file systems have a bug where st_mtime is not updated
4941 properly after a write. For example, CIFS might not see the
4942 st_mtime change until after the file is opened again.
4944 Attempt to detect this file system bug, and update MODTIME to the
4945 newer st_mtime if the bug appears to be present. This introduces
4946 a race condition, so to avoid most instances of the race condition
4947 on non-buggy file systems, skip this check if the most recently
4948 encountered non-buggy file system was the current file system.
4950 A race condition can occur if some other process modifies the
4951 file between the fstat above and the fstat below, but the race is
4952 unlikely and a similar race between the last write and the fstat
4953 above cannot possibly be closed anyway. */
4955 if (timespec_valid_p (modtime)
4956 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4958 int desc1 = emacs_open (fn, O_WRONLY, 0);
4959 if (desc1 >= 0)
4961 struct stat st1;
4962 if (fstat (desc1, &st1) == 0
4963 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4965 /* Use the heuristic if it appears to be valid. With neither
4966 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4967 file, the time stamp won't change. Also, some non-POSIX
4968 systems don't update an empty file's time stamp when
4969 truncating it. Finally, file systems with 100 ns or worse
4970 resolution sometimes seem to have bugs: on a system with ns
4971 resolution, checking ns % 100 incorrectly avoids the heuristic
4972 1% of the time, but the problem should be temporary as we will
4973 try again on the next time stamp. */
4974 bool use_heuristic
4975 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4976 && st.st_size != 0
4977 && modtime.tv_nsec % 100 != 0);
4979 struct timespec modtime1 = get_stat_mtime (&st1);
4980 if (use_heuristic
4981 && timespec_cmp (modtime, modtime1) == 0
4982 && st.st_size == st1.st_size)
4984 timestamp_file_system = st.st_dev;
4985 valid_timestamp_file_system = 1;
4987 else
4989 st.st_size = st1.st_size;
4990 modtime = modtime1;
4993 emacs_close (desc1);
4997 /* Call write-region-post-annotation-function. */
4998 while (CONSP (Vwrite_region_annotation_buffers))
5000 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5001 if (!NILP (Fbuffer_live_p (buf)))
5003 Fset_buffer (buf);
5004 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5005 call0 (Vwrite_region_post_annotation_function);
5007 Vwrite_region_annotation_buffers
5008 = XCDR (Vwrite_region_annotation_buffers);
5011 unbind_to (count, Qnil);
5013 if (file_locked)
5014 unlock_file (lockname);
5016 /* Do this before reporting IO error
5017 to avoid a "file has changed on disk" warning on
5018 next attempt to save. */
5019 if (timespec_valid_p (modtime))
5021 current_buffer->modtime = modtime;
5022 current_buffer->modtime_size = st.st_size;
5025 if (! ok)
5026 report_file_errno ("Write error", filename, save_errno);
5028 bool auto_saving_into_visited_file =
5029 auto_saving
5030 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5031 BVAR (current_buffer, auto_save_file_name)));
5032 if (visiting)
5034 SAVE_MODIFF = MODIFF;
5035 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5036 bset_filename (current_buffer, visit_file);
5037 update_mode_lines = 14;
5038 if (auto_saving_into_visited_file)
5039 unlock_file (lockname);
5041 else if (quietly)
5043 if (auto_saving_into_visited_file)
5045 SAVE_MODIFF = MODIFF;
5046 unlock_file (lockname);
5049 return Qnil;
5052 if (!auto_saving && !noninteractive)
5053 message_with_string ((NUMBERP (append)
5054 ? "Updated %s"
5055 : ! NILP (append)
5056 ? "Added to %s"
5057 : "Wrote %s"),
5058 visit_file, 1);
5060 return Qnil;
5063 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5064 doc: /* Return t if (car A) is numerically less than (car B). */)
5065 (Lisp_Object a, Lisp_Object b)
5067 return arithcompare (Fcar (a), Fcar (b), ARITH_LESS);
5070 /* Build the complete list of annotations appropriate for writing out
5071 the text between START and END, by calling all the functions in
5072 write-region-annotate-functions and merging the lists they return.
5073 If one of these functions switches to a different buffer, we assume
5074 that buffer contains altered text. Therefore, the caller must
5075 make sure to restore the current buffer in all cases,
5076 as save-excursion would do. */
5078 static Lisp_Object
5079 build_annotations (Lisp_Object start, Lisp_Object end)
5081 Lisp_Object annotations;
5082 Lisp_Object p, res;
5083 Lisp_Object original_buffer;
5084 int i;
5085 bool used_global = false;
5087 XSETBUFFER (original_buffer, current_buffer);
5089 annotations = Qnil;
5090 p = Vwrite_region_annotate_functions;
5091 while (CONSP (p))
5093 struct buffer *given_buffer = current_buffer;
5094 if (EQ (Qt, XCAR (p)) && !used_global)
5095 { /* Use the global value of the hook. */
5096 used_global = true;
5097 p = CALLN (Fappend,
5098 Fdefault_value (Qwrite_region_annotate_functions),
5099 XCDR (p));
5100 continue;
5102 Vwrite_region_annotations_so_far = annotations;
5103 res = call2 (XCAR (p), start, end);
5104 /* If the function makes a different buffer current,
5105 assume that means this buffer contains altered text to be output.
5106 Reset START and END from the buffer bounds
5107 and discard all previous annotations because they should have
5108 been dealt with by this function. */
5109 if (current_buffer != given_buffer)
5111 Vwrite_region_annotation_buffers
5112 = Fcons (Fcurrent_buffer (),
5113 Vwrite_region_annotation_buffers);
5114 XSETFASTINT (start, BEGV);
5115 XSETFASTINT (end, ZV);
5116 annotations = Qnil;
5118 Flength (res); /* Check basic validity of return value */
5119 annotations = merge (annotations, res, Qcar_less_than_car);
5120 p = XCDR (p);
5123 /* Now do the same for annotation functions implied by the file-format */
5124 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5125 p = BVAR (current_buffer, auto_save_file_format);
5126 else
5127 p = BVAR (current_buffer, file_format);
5128 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5130 struct buffer *given_buffer = current_buffer;
5132 Vwrite_region_annotations_so_far = annotations;
5134 /* Value is either a list of annotations or nil if the function
5135 has written annotations to a temporary buffer, which is now
5136 current. */
5137 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5138 original_buffer, make_number (i));
5139 if (current_buffer != given_buffer)
5141 XSETFASTINT (start, BEGV);
5142 XSETFASTINT (end, ZV);
5143 annotations = Qnil;
5146 if (CONSP (res))
5147 annotations = merge (annotations, res, Qcar_less_than_car);
5150 return annotations;
5154 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5155 If STRING is nil, POS is the character position in the current buffer.
5156 Intersperse with them the annotations from *ANNOT
5157 which fall within the range of POS to POS + NCHARS,
5158 each at its appropriate position.
5160 We modify *ANNOT by discarding elements as we use them up.
5162 Return true if successful. */
5164 static bool
5165 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5166 ptrdiff_t nchars, Lisp_Object *annot,
5167 struct coding_system *coding)
5169 Lisp_Object tem;
5170 ptrdiff_t nextpos;
5171 ptrdiff_t lastpos = pos + nchars;
5173 while (NILP (*annot) || CONSP (*annot))
5175 tem = Fcar_safe (Fcar (*annot));
5176 nextpos = pos - 1;
5177 if (INTEGERP (tem))
5178 nextpos = XFASTINT (tem);
5180 /* If there are no more annotations in this range,
5181 output the rest of the range all at once. */
5182 if (! (nextpos >= pos && nextpos <= lastpos))
5183 return e_write (desc, string, pos, lastpos, coding);
5185 /* Output buffer text up to the next annotation's position. */
5186 if (nextpos > pos)
5188 if (!e_write (desc, string, pos, nextpos, coding))
5189 return 0;
5190 pos = nextpos;
5192 /* Output the annotation. */
5193 tem = Fcdr (Fcar (*annot));
5194 if (STRINGP (tem))
5196 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5197 return 0;
5199 *annot = Fcdr (*annot);
5201 return 1;
5204 /* Maximum number of characters that the next
5205 function encodes per one loop iteration. */
5207 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5209 /* Write text in the range START and END into descriptor DESC,
5210 encoding them with coding system CODING. If STRING is nil, START
5211 and END are character positions of the current buffer, else they
5212 are indexes to the string STRING. Return true if successful. */
5214 static bool
5215 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5216 struct coding_system *coding)
5218 if (STRINGP (string))
5220 start = 0;
5221 end = SCHARS (string);
5224 /* We used to have a code for handling selective display here. But,
5225 now it is handled within encode_coding. */
5227 while (start < end)
5229 if (STRINGP (string))
5231 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5232 if (CODING_REQUIRE_ENCODING (coding))
5234 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5236 /* Avoid creating huge Lisp string in encode_coding_object. */
5237 if (nchars == E_WRITE_MAX)
5238 coding->raw_destination = 1;
5240 encode_coding_object
5241 (coding, string, start, string_char_to_byte (string, start),
5242 start + nchars, string_char_to_byte (string, start + nchars),
5243 Qt);
5245 else
5247 coding->dst_object = string;
5248 coding->consumed_char = SCHARS (string);
5249 coding->produced = SBYTES (string);
5252 else
5254 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5255 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5257 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5258 if (CODING_REQUIRE_ENCODING (coding))
5260 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5262 /* Likewise. */
5263 if (nchars == E_WRITE_MAX)
5264 coding->raw_destination = 1;
5266 encode_coding_object
5267 (coding, Fcurrent_buffer (), start, start_byte,
5268 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5270 else
5272 coding->dst_object = Qnil;
5273 coding->dst_pos_byte = start_byte;
5274 if (start >= GPT || end <= GPT)
5276 coding->consumed_char = end - start;
5277 coding->produced = end_byte - start_byte;
5279 else
5281 coding->consumed_char = GPT - start;
5282 coding->produced = GPT_BYTE - start_byte;
5287 if (coding->produced > 0)
5289 char *buf = (coding->raw_destination ? (char *) coding->destination
5290 : (STRINGP (coding->dst_object)
5291 ? SSDATA (coding->dst_object)
5292 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5293 coding->produced -= emacs_write_quit (desc, buf, coding->produced);
5295 if (coding->raw_destination)
5297 /* We're responsible for freeing this, see
5298 encode_coding_object to check why. */
5299 xfree (coding->destination);
5300 coding->raw_destination = 0;
5302 if (coding->produced)
5303 return 0;
5305 start += coding->consumed_char;
5308 return 1;
5311 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5312 Sverify_visited_file_modtime, 0, 1, 0,
5313 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5314 This means that the file has not been changed since it was visited or saved.
5315 If BUF is omitted or nil, it defaults to the current buffer.
5316 See Info node `(elisp)Modification Time' for more details. */)
5317 (Lisp_Object buf)
5319 struct buffer *b = decode_buffer (buf);
5320 struct stat st;
5321 Lisp_Object handler;
5322 Lisp_Object filename;
5323 struct timespec mtime;
5325 if (!STRINGP (BVAR (b, filename))) return Qt;
5326 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5328 /* If the file name has special constructs in it,
5329 call the corresponding file handler. */
5330 handler = Ffind_file_name_handler (BVAR (b, filename),
5331 Qverify_visited_file_modtime);
5332 if (!NILP (handler))
5333 return call2 (handler, Qverify_visited_file_modtime, buf);
5335 filename = ENCODE_FILE (BVAR (b, filename));
5337 mtime = (stat (SSDATA (filename), &st) == 0
5338 ? get_stat_mtime (&st)
5339 : time_error_value (errno));
5340 if (timespec_cmp (mtime, b->modtime) == 0
5341 && (b->modtime_size < 0
5342 || st.st_size == b->modtime_size))
5343 return Qt;
5344 return Qnil;
5347 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5348 Svisited_file_modtime, 0, 0, 0,
5349 doc: /* Return the current buffer's recorded visited file modification time.
5350 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5351 `file-attributes' returns. If the current buffer has no recorded file
5352 modification time, this function returns 0. If the visited file
5353 doesn't exist, return -1.
5354 See Info node `(elisp)Modification Time' for more details. */)
5355 (void)
5357 int ns = current_buffer->modtime.tv_nsec;
5358 if (ns < 0)
5359 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5360 return make_lisp_time (current_buffer->modtime);
5363 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5364 Sset_visited_file_modtime, 0, 1, 0,
5365 doc: /* Update buffer's recorded modification time from the visited file's time.
5366 Useful if the buffer was not read from the file normally
5367 or if the file itself has been changed for some known benign reason.
5368 An argument specifies the modification time value to use
5369 \(instead of that of the visited file), in the form of a list
5370 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5371 `visited-file-modtime'. */)
5372 (Lisp_Object time_flag)
5374 if (!NILP (time_flag))
5376 struct timespec mtime;
5377 if (INTEGERP (time_flag))
5379 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5380 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5382 else
5383 mtime = lisp_time_argument (time_flag);
5385 current_buffer->modtime = mtime;
5386 current_buffer->modtime_size = -1;
5388 else
5390 register Lisp_Object filename;
5391 struct stat st;
5392 Lisp_Object handler;
5394 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5396 /* If the file name has special constructs in it,
5397 call the corresponding file handler. */
5398 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5399 if (!NILP (handler))
5400 /* The handler can find the file name the same way we did. */
5401 return call2 (handler, Qset_visited_file_modtime, Qnil);
5403 filename = ENCODE_FILE (filename);
5405 if (stat (SSDATA (filename), &st) >= 0)
5407 current_buffer->modtime = get_stat_mtime (&st);
5408 current_buffer->modtime_size = st.st_size;
5412 return Qnil;
5415 static Lisp_Object
5416 auto_save_error (Lisp_Object error_val)
5418 auto_save_error_occurred = 1;
5420 ring_bell (XFRAME (selected_frame));
5422 AUTO_STRING (format, "Auto-saving %s: %s");
5423 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5424 Ferror_message_string (error_val));
5425 call3 (intern ("display-warning"),
5426 intern ("auto-save"), msg, intern ("error"));
5428 return Qnil;
5431 static Lisp_Object
5432 auto_save_1 (void)
5434 struct stat st;
5435 Lisp_Object modes;
5437 auto_save_mode_bits = 0666;
5439 /* Get visited file's mode to become the auto save file's mode. */
5440 if (! NILP (BVAR (current_buffer, filename)))
5442 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5443 /* But make sure we can overwrite it later! */
5444 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5445 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5446 INTEGERP (modes))
5447 /* Remote files don't cooperate with stat. */
5448 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5451 return
5452 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5453 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5454 Qnil, Qnil);
5457 struct auto_save_unwind
5459 FILE *stream;
5460 bool auto_raise;
5463 static void
5464 do_auto_save_unwind (void *arg)
5466 struct auto_save_unwind *p = arg;
5467 FILE *stream = p->stream;
5468 minibuffer_auto_raise = p->auto_raise;
5469 auto_saving = 0;
5470 if (stream != NULL)
5472 block_input ();
5473 fclose (stream);
5474 unblock_input ();
5478 static Lisp_Object
5479 do_auto_save_make_dir (Lisp_Object dir)
5481 Lisp_Object result;
5483 auto_saving_dir_umask = 077;
5484 result = call2 (Qmake_directory, dir, Qt);
5485 auto_saving_dir_umask = 0;
5486 return result;
5489 static Lisp_Object
5490 do_auto_save_eh (Lisp_Object ignore)
5492 auto_saving_dir_umask = 0;
5493 return Qnil;
5496 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5497 doc: /* Auto-save all buffers that need it.
5498 This is all buffers that have auto-saving enabled
5499 and are changed since last auto-saved.
5500 Auto-saving writes the buffer into a file
5501 so that your editing is not lost if the system crashes.
5502 This file is not the file you visited; that changes only when you save.
5503 Normally, run the normal hook `auto-save-hook' before saving.
5505 A non-nil NO-MESSAGE argument means do not print any message if successful.
5506 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5507 (Lisp_Object no_message, Lisp_Object current_only)
5509 struct buffer *old = current_buffer, *b;
5510 Lisp_Object tail, buf, hook;
5511 bool auto_saved = 0;
5512 int do_handled_files;
5513 Lisp_Object oquit;
5514 FILE *stream = NULL;
5515 ptrdiff_t count = SPECPDL_INDEX ();
5516 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5517 bool old_message_p = 0;
5518 struct auto_save_unwind auto_save_unwind;
5520 if (max_specpdl_size < specpdl_size + 40)
5521 max_specpdl_size = specpdl_size + 40;
5523 if (minibuf_level)
5524 no_message = Qt;
5526 if (NILP (no_message))
5528 old_message_p = push_message ();
5529 record_unwind_protect_void (pop_message_unwind);
5532 /* Ordinarily don't quit within this function,
5533 but don't make it impossible to quit (in case we get hung in I/O). */
5534 oquit = Vquit_flag;
5535 Vquit_flag = Qnil;
5537 hook = intern ("auto-save-hook");
5538 safe_run_hooks (hook);
5540 if (STRINGP (Vauto_save_list_file_name))
5542 Lisp_Object listfile;
5544 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5546 /* Don't try to create the directory when shutting down Emacs,
5547 because creating the directory might signal an error, and
5548 that would leave Emacs in a strange state. */
5549 if (!NILP (Vrun_hooks))
5551 Lisp_Object dir;
5552 dir = Ffile_name_directory (listfile);
5553 if (NILP (Ffile_directory_p (dir)))
5554 internal_condition_case_1 (do_auto_save_make_dir,
5555 dir, Qt,
5556 do_auto_save_eh);
5559 stream = emacs_fopen (SSDATA (listfile), "w");
5562 auto_save_unwind.stream = stream;
5563 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5564 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5565 minibuffer_auto_raise = 0;
5566 auto_saving = 1;
5567 auto_save_error_occurred = 0;
5569 /* On first pass, save all files that don't have handlers.
5570 On second pass, save all files that do have handlers.
5572 If Emacs is crashing, the handlers may tweak what is causing
5573 Emacs to crash in the first place, and it would be a shame if
5574 Emacs failed to autosave perfectly ordinary files because it
5575 couldn't handle some ange-ftp'd file. */
5577 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5578 FOR_EACH_LIVE_BUFFER (tail, buf)
5580 b = XBUFFER (buf);
5582 /* Record all the buffers that have auto save mode
5583 in the special file that lists them. For each of these buffers,
5584 Record visited name (if any) and auto save name. */
5585 if (STRINGP (BVAR (b, auto_save_file_name))
5586 && stream != NULL && do_handled_files == 0)
5588 block_input ();
5589 if (!NILP (BVAR (b, filename)))
5590 fwrite_unlocked (SDATA (BVAR (b, filename)), 1,
5591 SBYTES (BVAR (b, filename)), stream);
5592 putc_unlocked ('\n', stream);
5593 fwrite_unlocked (SDATA (BVAR (b, auto_save_file_name)), 1,
5594 SBYTES (BVAR (b, auto_save_file_name)), stream);
5595 putc_unlocked ('\n', stream);
5596 unblock_input ();
5599 if (!NILP (current_only)
5600 && b != current_buffer)
5601 continue;
5603 /* Don't auto-save indirect buffers.
5604 The base buffer takes care of it. */
5605 if (b->base_buffer)
5606 continue;
5608 /* Check for auto save enabled
5609 and file changed since last auto save
5610 and file changed since last real save. */
5611 if (STRINGP (BVAR (b, auto_save_file_name))
5612 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5613 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5614 /* -1 means we've turned off autosaving for a while--see below. */
5615 && XINT (BVAR (b, save_length)) >= 0
5616 && (do_handled_files
5617 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5618 Qwrite_region))))
5620 struct timespec before_time = current_timespec ();
5621 struct timespec after_time;
5623 /* If we had a failure, don't try again for 20 minutes. */
5624 if (b->auto_save_failure_time > 0
5625 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5626 continue;
5628 set_buffer_internal (b);
5629 if (NILP (Vauto_save_include_big_deletions)
5630 && (XFASTINT (BVAR (b, save_length)) * 10
5631 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5632 /* A short file is likely to change a large fraction;
5633 spare the user annoying messages. */
5634 && XFASTINT (BVAR (b, save_length)) > 5000
5635 /* These messages are frequent and annoying for `*mail*'. */
5636 && !EQ (BVAR (b, filename), Qnil)
5637 && NILP (no_message))
5639 /* It has shrunk too much; turn off auto-saving here. */
5640 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5641 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5642 BVAR (b, name), 1);
5643 minibuffer_auto_raise = 0;
5644 /* Turn off auto-saving until there's a real save,
5645 and prevent any more warnings. */
5646 XSETINT (BVAR (b, save_length), -1);
5647 Fsleep_for (make_number (1), Qnil);
5648 continue;
5650 if (!auto_saved && NILP (no_message))
5651 message1 ("Auto-saving...");
5652 internal_condition_case (auto_save_1, Qt, auto_save_error);
5653 auto_saved = 1;
5654 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5655 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5656 set_buffer_internal (old);
5658 after_time = current_timespec ();
5660 /* If auto-save took more than 60 seconds,
5661 assume it was an NFS failure that got a timeout. */
5662 if (after_time.tv_sec - before_time.tv_sec > 60)
5663 b->auto_save_failure_time = after_time.tv_sec;
5667 /* Prevent another auto save till enough input events come in. */
5668 record_auto_save ();
5670 if (auto_saved && NILP (no_message))
5672 if (old_message_p)
5674 /* If we are going to restore an old message,
5675 give time to read ours. */
5676 sit_for (make_number (1), 0, 0);
5677 restore_message ();
5679 else if (!auto_save_error_occurred)
5680 /* Don't overwrite the error message if an error occurred.
5681 If we displayed a message and then restored a state
5682 with no message, leave a "done" message on the screen. */
5683 message1 ("Auto-saving...done");
5686 Vquit_flag = oquit;
5688 /* This restores the message-stack status. */
5689 unbind_to (count, Qnil);
5690 return Qnil;
5693 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5694 Sset_buffer_auto_saved, 0, 0, 0,
5695 doc: /* Mark current buffer as auto-saved with its current text.
5696 No auto-save file will be written until the buffer changes again. */)
5697 (void)
5699 /* FIXME: This should not be called in indirect buffers, since
5700 they're not autosaved. */
5701 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5702 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5703 current_buffer->auto_save_failure_time = 0;
5704 return Qnil;
5707 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5708 Sclear_buffer_auto_save_failure, 0, 0, 0,
5709 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5710 (void)
5712 current_buffer->auto_save_failure_time = 0;
5713 return Qnil;
5716 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5717 0, 0, 0,
5718 doc: /* Return t if current buffer has been auto-saved recently.
5719 More precisely, if it has been auto-saved since last read from or saved
5720 in the visited file. If the buffer has no visited file,
5721 then any auto-save counts as "recent". */)
5722 (void)
5724 /* FIXME: maybe we should return nil for indirect buffers since
5725 they're never autosaved. */
5726 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5729 /* Reading and completing file names. */
5731 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5732 Snext_read_file_uses_dialog_p, 0, 0, 0,
5733 doc: /* Return t if a call to `read-file-name' will use a dialog.
5734 The return value is only relevant for a call to `read-file-name' that happens
5735 before any other event (mouse or keypress) is handled. */)
5736 (void)
5738 #if (defined USE_GTK || defined USE_MOTIF \
5739 || defined HAVE_NS || defined HAVE_NTGUI)
5740 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5741 && use_dialog_box
5742 && use_file_dialog
5743 && window_system_available (SELECTED_FRAME ()))
5744 return Qt;
5745 #endif
5746 return Qnil;
5750 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5751 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5752 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5753 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5754 it to text mode.
5756 As a side effect, this function flushes any pending STREAM's data.
5758 Value is the previous value of STREAM's I/O mode, nil for text mode,
5759 non-nil for binary mode.
5761 On MS-Windows and MS-DOS, binary mode is needed to read or write
5762 arbitrary binary data, and for disabling translation between CR-LF
5763 pairs and a single newline character. Examples include generation
5764 of text files with Unix-style end-of-line format using `princ' in
5765 batch mode, with standard output redirected to a file.
5767 On Posix systems, this function always returns non-nil, and has no
5768 effect except for flushing STREAM's data. */)
5769 (Lisp_Object stream, Lisp_Object mode)
5771 FILE *fp = NULL;
5772 int binmode;
5774 CHECK_SYMBOL (stream);
5775 if (EQ (stream, Qstdin))
5776 fp = stdin;
5777 else if (EQ (stream, Qstdout))
5778 fp = stdout;
5779 else if (EQ (stream, Qstderr))
5780 fp = stderr;
5781 else
5782 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5784 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5785 if (fp != stdin)
5786 fflush_unlocked (fp);
5788 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5791 void
5792 init_fileio (void)
5794 realmask = umask (0);
5795 umask (realmask);
5797 valid_timestamp_file_system = 0;
5799 /* fsync can be a significant performance hit. Often it doesn't
5800 suffice to make the file-save operation survive a crash. For
5801 batch scripts, which are typically part of larger shell commands
5802 that don't fsync other files, its effect on performance can be
5803 significant so its utility is particularly questionable.
5804 Hence, for now by default fsync is used only when interactive.
5806 For more on why fsync often fails to work on today's hardware, see:
5807 Zheng M et al. Understanding the robustness of SSDs under power fault.
5808 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5809 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5811 For more on why fsync does not suffice even if it works properly, see:
5812 Roche X. Necessary step(s) to synchronize filename operations on disk.
5813 Austin Group Defect 672, 2013-03-19
5814 http://austingroupbugs.net/view.php?id=672 */
5815 write_region_inhibit_fsync = noninteractive;
5818 void
5819 syms_of_fileio (void)
5821 /* Property name of a file name handler,
5822 which gives a list of operations it handles. */
5823 DEFSYM (Qoperations, "operations");
5825 DEFSYM (Qexpand_file_name, "expand-file-name");
5826 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5827 DEFSYM (Qdirectory_file_name, "directory-file-name");
5828 DEFSYM (Qfile_name_directory, "file-name-directory");
5829 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5830 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5831 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5832 DEFSYM (Qcopy_file, "copy-file");
5833 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5834 DEFSYM (Qmake_directory, "make-directory");
5835 DEFSYM (Qdelete_file, "delete-file");
5836 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5837 DEFSYM (Qrename_file, "rename-file");
5838 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5839 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5840 DEFSYM (Qfile_exists_p, "file-exists-p");
5841 DEFSYM (Qfile_executable_p, "file-executable-p");
5842 DEFSYM (Qfile_readable_p, "file-readable-p");
5843 DEFSYM (Qfile_writable_p, "file-writable-p");
5844 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5845 DEFSYM (Qaccess_file, "access-file");
5846 DEFSYM (Qfile_directory_p, "file-directory-p");
5847 DEFSYM (Qfile_regular_p, "file-regular-p");
5848 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5849 DEFSYM (Qfile_modes, "file-modes");
5850 DEFSYM (Qset_file_modes, "set-file-modes");
5851 DEFSYM (Qset_file_times, "set-file-times");
5852 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5853 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5854 DEFSYM (Qfile_acl, "file-acl");
5855 DEFSYM (Qset_file_acl, "set-file-acl");
5856 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5857 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5858 DEFSYM (Qwrite_region, "write-region");
5859 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5860 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5862 /* The symbol bound to coding-system-for-read when
5863 insert-file-contents is called for recovering a file. This is not
5864 an actual coding system name, but just an indicator to tell
5865 insert-file-contents to use `emacs-mule' with a special flag for
5866 auto saving and recovering a file. */
5867 DEFSYM (Qauto_save_coding, "auto-save-coding");
5869 DEFSYM (Qfile_name_history, "file-name-history");
5870 Fset (Qfile_name_history, Qnil);
5872 DEFSYM (Qfile_error, "file-error");
5873 DEFSYM (Qfile_already_exists, "file-already-exists");
5874 DEFSYM (Qfile_date_error, "file-date-error");
5875 DEFSYM (Qfile_missing, "file-missing");
5876 DEFSYM (Qfile_notify_error, "file-notify-error");
5877 DEFSYM (Qexcl, "excl");
5879 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5880 doc: /* Coding system for encoding file names.
5881 If it is nil, `default-file-name-coding-system' (which see) is used.
5883 On MS-Windows, the value of this variable is largely ignored if
5884 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5885 behaves as if file names were encoded in `utf-8'. */);
5886 Vfile_name_coding_system = Qnil;
5888 DEFVAR_LISP ("default-file-name-coding-system",
5889 Vdefault_file_name_coding_system,
5890 doc: /* Default coding system for encoding file names.
5891 This variable is used only when `file-name-coding-system' is nil.
5893 This variable is set/changed by the command `set-language-environment'.
5894 User should not set this variable manually,
5895 instead use `file-name-coding-system' to get a constant encoding
5896 of file names regardless of the current language environment.
5898 On MS-Windows, the value of this variable is largely ignored if
5899 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5900 behaves as if file names were encoded in `utf-8'. */);
5901 Vdefault_file_name_coding_system = Qnil;
5903 /* Lisp functions for translating file formats. */
5904 DEFSYM (Qformat_decode, "format-decode");
5905 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5907 /* Lisp function for setting buffer-file-coding-system and the
5908 multibyteness of the current buffer after inserting a file. */
5909 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5911 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5913 Fput (Qfile_error, Qerror_conditions,
5914 Fpurecopy (list2 (Qfile_error, Qerror)));
5915 Fput (Qfile_error, Qerror_message,
5916 build_pure_c_string ("File error"));
5918 Fput (Qfile_already_exists, Qerror_conditions,
5919 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5920 Fput (Qfile_already_exists, Qerror_message,
5921 build_pure_c_string ("File already exists"));
5923 Fput (Qfile_date_error, Qerror_conditions,
5924 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5925 Fput (Qfile_date_error, Qerror_message,
5926 build_pure_c_string ("Cannot set file date"));
5928 Fput (Qfile_missing, Qerror_conditions,
5929 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
5930 Fput (Qfile_missing, Qerror_message,
5931 build_pure_c_string ("File is missing"));
5933 Fput (Qfile_notify_error, Qerror_conditions,
5934 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5935 Fput (Qfile_notify_error, Qerror_message,
5936 build_pure_c_string ("File notification error"));
5938 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5939 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5940 If a file name matches REGEXP, all I/O on that file is done by calling
5941 HANDLER. If a file name matches more than one handler, the handler
5942 whose match starts last in the file name gets precedence. The
5943 function `find-file-name-handler' checks this list for a handler for
5944 its argument.
5946 HANDLER should be a function. The first argument given to it is the
5947 name of the I/O primitive to be handled; the remaining arguments are
5948 the arguments that were passed to that primitive. For example, if you
5949 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5950 HANDLER is called like this:
5952 (funcall HANDLER \\='file-exists-p FILENAME)
5954 Note that HANDLER must be able to handle all I/O primitives; if it has
5955 nothing special to do for a primitive, it should reinvoke the
5956 primitive to handle the operation \"the usual way\".
5957 See Info node `(elisp)Magic File Names' for more details. */);
5958 Vfile_name_handler_alist = Qnil;
5960 DEFVAR_LISP ("set-auto-coding-function",
5961 Vset_auto_coding_function,
5962 doc: /* If non-nil, a function to call to decide a coding system of file.
5963 Two arguments are passed to this function: the file name
5964 and the length of a file contents following the point.
5965 This function should return a coding system to decode the file contents.
5966 It should check the file name against `auto-coding-alist'.
5967 If no coding system is decided, it should check a coding system
5968 specified in the heading lines with the format:
5969 -*- ... coding: CODING-SYSTEM; ... -*-
5970 or local variable spec of the tailing lines with `coding:' tag. */);
5971 Vset_auto_coding_function = Qnil;
5973 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5974 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5975 Each is passed one argument, the number of characters inserted,
5976 with point at the start of the inserted text. Each function
5977 should leave point the same, and return the new character count.
5978 If `insert-file-contents' is intercepted by a handler from
5979 `file-name-handler-alist', that handler is responsible for calling the
5980 functions in `after-insert-file-functions' if appropriate. */);
5981 Vafter_insert_file_functions = Qnil;
5983 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5984 doc: /* A list of functions to be called at the start of `write-region'.
5985 Each is passed two arguments, START and END as for `write-region'.
5986 These are usually two numbers but not always; see the documentation
5987 for `write-region'. The function should return a list of pairs
5988 of the form (POSITION . STRING), consisting of strings to be effectively
5989 inserted at the specified positions of the file being written (1 means to
5990 insert before the first byte written). The POSITIONs must be sorted into
5991 increasing order.
5993 If there are several annotation functions, the lists returned by these
5994 functions are merged destructively. As each annotation function runs,
5995 the variable `write-region-annotations-so-far' contains a list of all
5996 annotations returned by previous annotation functions.
5998 An annotation function can return with a different buffer current.
5999 Doing so removes the annotations returned by previous functions, and
6000 resets START and END to `point-min' and `point-max' of the new buffer.
6002 After `write-region' completes, Emacs calls the function stored in
6003 `write-region-post-annotation-function', once for each buffer that was
6004 current when building the annotations (i.e., at least once), with that
6005 buffer current. */);
6006 Vwrite_region_annotate_functions = Qnil;
6007 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6009 DEFVAR_LISP ("write-region-post-annotation-function",
6010 Vwrite_region_post_annotation_function,
6011 doc: /* Function to call after `write-region' completes.
6012 The function is called with no arguments. If one or more of the
6013 annotation functions in `write-region-annotate-functions' changed the
6014 current buffer, the function stored in this variable is called for
6015 each of those additional buffers as well, in addition to the original
6016 buffer. The relevant buffer is current during each function call. */);
6017 Vwrite_region_post_annotation_function = Qnil;
6018 staticpro (&Vwrite_region_annotation_buffers);
6020 DEFVAR_LISP ("write-region-annotations-so-far",
6021 Vwrite_region_annotations_so_far,
6022 doc: /* When an annotation function is called, this holds the previous annotations.
6023 These are the annotations made by other annotation functions
6024 that were already called. See also `write-region-annotate-functions'. */);
6025 Vwrite_region_annotations_so_far = Qnil;
6027 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6028 doc: /* A list of file name handlers that temporarily should not be used.
6029 This applies only to the operation `inhibit-file-name-operation'. */);
6030 Vinhibit_file_name_handlers = Qnil;
6032 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6033 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6034 Vinhibit_file_name_operation = Qnil;
6036 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6037 doc: /* File name in which to write a list of all auto save file names.
6038 This variable is initialized automatically from `auto-save-list-file-prefix'
6039 shortly after Emacs reads your init file, if you have not yet given it
6040 a non-nil value. */);
6041 Vauto_save_list_file_name = Qnil;
6043 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6044 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6045 Normally auto-save files are written under other names. */);
6046 Vauto_save_visited_file_name = Qnil;
6048 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6049 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6050 If nil, deleting a substantial portion of the text disables auto-save
6051 in the buffer; this is the default behavior, because the auto-save
6052 file is usually more useful if it contains the deleted text. */);
6053 Vauto_save_include_big_deletions = Qnil;
6055 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6056 doc: /* Non-nil means don't call fsync in `write-region'.
6057 This variable affects calls to `write-region' as well as save commands.
6058 Setting this to nil may avoid data loss if the system loses power or
6059 the operating system crashes. By default, it is non-nil in batch mode. */);
6060 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6062 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6063 doc: /* Specifies whether to use the system's trash can.
6064 When non-nil, certain file deletion commands use the function
6065 `move-file-to-trash' instead of deleting files outright.
6066 This includes interactive calls to `delete-file' and
6067 `delete-directory' and the Dired deletion commands. */);
6068 delete_by_moving_to_trash = 0;
6069 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6071 /* Lisp function for moving files to trash. */
6072 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6074 /* Lisp function for recursively copying directories. */
6075 DEFSYM (Qcopy_directory, "copy-directory");
6077 /* Lisp function for recursively deleting directories. */
6078 DEFSYM (Qdelete_directory, "delete-directory");
6080 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6081 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6083 DEFSYM (Qstdin, "stdin");
6084 DEFSYM (Qstdout, "stdout");
6085 DEFSYM (Qstderr, "stderr");
6087 defsubr (&Sfind_file_name_handler);
6088 defsubr (&Sfile_name_directory);
6089 defsubr (&Sfile_name_nondirectory);
6090 defsubr (&Sunhandled_file_name_directory);
6091 defsubr (&Sfile_name_as_directory);
6092 defsubr (&Sdirectory_name_p);
6093 defsubr (&Sdirectory_file_name);
6094 defsubr (&Smake_temp_file_internal);
6095 defsubr (&Smake_temp_name);
6096 defsubr (&Sexpand_file_name);
6097 defsubr (&Ssubstitute_in_file_name);
6098 defsubr (&Scopy_file);
6099 defsubr (&Smake_directory_internal);
6100 defsubr (&Sdelete_directory_internal);
6101 defsubr (&Sdelete_file);
6102 defsubr (&Sfile_name_case_insensitive_p);
6103 defsubr (&Srename_file);
6104 defsubr (&Sadd_name_to_file);
6105 defsubr (&Smake_symbolic_link);
6106 defsubr (&Sfile_name_absolute_p);
6107 defsubr (&Sfile_exists_p);
6108 defsubr (&Sfile_executable_p);
6109 defsubr (&Sfile_readable_p);
6110 defsubr (&Sfile_writable_p);
6111 defsubr (&Saccess_file);
6112 defsubr (&Sfile_symlink_p);
6113 defsubr (&Sfile_directory_p);
6114 defsubr (&Sfile_accessible_directory_p);
6115 defsubr (&Sfile_regular_p);
6116 defsubr (&Sfile_modes);
6117 defsubr (&Sset_file_modes);
6118 defsubr (&Sset_file_times);
6119 defsubr (&Sfile_selinux_context);
6120 defsubr (&Sfile_acl);
6121 defsubr (&Sset_file_acl);
6122 defsubr (&Sset_file_selinux_context);
6123 defsubr (&Sset_default_file_modes);
6124 defsubr (&Sdefault_file_modes);
6125 defsubr (&Sfile_newer_than_file_p);
6126 defsubr (&Sinsert_file_contents);
6127 defsubr (&Swrite_region);
6128 defsubr (&Scar_less_than_car);
6129 defsubr (&Sverify_visited_file_modtime);
6130 defsubr (&Svisited_file_modtime);
6131 defsubr (&Sset_visited_file_modtime);
6132 defsubr (&Sdo_auto_save);
6133 defsubr (&Sset_buffer_auto_saved);
6134 defsubr (&Sclear_buffer_auto_save_failure);
6135 defsubr (&Srecent_auto_save_p);
6137 defsubr (&Snext_read_file_uses_dialog_p);
6139 defsubr (&Sset_binary_mode);
6141 #ifdef HAVE_SYNC
6142 defsubr (&Sunix_sync);
6143 #endif