Use Gnulib 'tempname' on MS-Windows
[emacs.git] / src / fileio.c
blob8506a198fe3bc9125db3d723502ad468f54dc8ca
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>
101 #include <binary-io.h>
103 #ifdef HPUX
104 #include <netio.h>
105 #endif
107 #include "commands.h"
109 /* True during writing of auto-save files. */
110 static bool auto_saving;
112 /* Emacs's real umask. */
113 static mode_t realmask;
115 /* Nonzero umask during creation of auto-save directories. */
116 static mode_t auto_saving_dir_umask;
118 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
119 a new file with the same mode as the original. */
120 static mode_t auto_save_mode_bits;
122 /* Set by auto_save_1 if an error occurred during the last auto-save. */
123 static bool auto_save_error_occurred;
125 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
126 number of a file system where time stamps were observed to to work. */
127 static bool valid_timestamp_file_system;
128 static dev_t timestamp_file_system;
130 /* Each time an annotation function changes the buffer, the new buffer
131 is added here. */
132 static Lisp_Object Vwrite_region_annotation_buffers;
134 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
135 Lisp_Object *, struct coding_system *);
136 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
137 struct coding_system *);
140 /* Return true if FILENAME exists. */
142 static bool
143 check_existing (const char *filename)
145 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
148 /* Return true if file FILENAME exists and can be executed. */
150 static bool
151 check_executable (char *filename)
153 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
156 /* Return true if file FILENAME exists and can be accessed
157 according to AMODE, which should include W_OK.
158 On failure, return false and set errno. */
160 static bool
161 check_writable (const char *filename, int amode)
163 #ifdef MSDOS
164 /* FIXME: an faccessat implementation should be added to the
165 DOS/Windows ports and this #ifdef branch should be removed. */
166 struct stat st;
167 if (stat (filename, &st) < 0)
168 return 0;
169 errno = EPERM;
170 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
171 #else /* not MSDOS */
172 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
173 #ifdef CYGWIN
174 /* faccessat may have returned failure because Cygwin couldn't
175 determine the file's UID or GID; if so, we return success. */
176 if (!res)
178 int faccessat_errno = errno;
179 struct stat st;
180 if (stat (filename, &st) < 0)
181 return 0;
182 res = (st.st_uid == -1 || st.st_gid == -1);
183 errno = faccessat_errno;
185 #endif /* CYGWIN */
186 return res;
187 #endif /* not MSDOS */
190 /* Signal a file-access failure. STRING describes the failure,
191 NAME the file involved, and ERRORNO the errno value.
193 If NAME is neither null nor a pair, package it up as a singleton
194 list before reporting it; this saves report_file_errno's caller the
195 trouble of preserving errno before calling list1. */
197 void
198 report_file_errno (char const *string, Lisp_Object name, int errorno)
200 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
201 char *str = emacs_strerror (errorno);
202 AUTO_STRING (unibyte_str, str);
203 Lisp_Object errstring
204 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
205 Lisp_Object errdata = Fcons (errstring, data);
207 if (errorno == EEXIST)
208 xsignal (Qfile_already_exists, errdata);
209 else
210 xsignal (errorno == ENOENT ? Qfile_missing : Qfile_error,
211 Fcons (build_string (string), errdata));
214 /* Signal a file-access failure that set errno. STRING describes the
215 failure, NAME the file involved. When invoking this function, take
216 care to not use arguments such as build_string ("foo") that involve
217 side effects that may set errno. */
219 void
220 report_file_error (char const *string, Lisp_Object name)
222 report_file_errno (string, name, errno);
225 /* Like report_file_error, but reports a file-notify-error instead. */
227 void
228 report_file_notify_error (const char *string, Lisp_Object name)
230 char *str = emacs_strerror (errno);
231 AUTO_STRING (unibyte_str, str);
232 Lisp_Object errstring
233 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
234 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
235 Lisp_Object errdata = Fcons (errstring, data);
237 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
240 void
241 close_file_unwind (int fd)
243 emacs_close (fd);
246 void
247 fclose_unwind (void *arg)
249 FILE *stream = arg;
250 fclose (stream);
253 /* Restore point, having saved it as a marker. */
255 void
256 restore_point_unwind (Lisp_Object location)
258 Fgoto_char (location);
259 unchain_marker (XMARKER (location));
263 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
264 Sfind_file_name_handler, 2, 2, 0,
265 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
266 Otherwise, return nil.
267 A file name is handled if one of the regular expressions in
268 `file-name-handler-alist' matches it.
270 If OPERATION equals `inhibit-file-name-operation', then ignore
271 any handlers that are members of `inhibit-file-name-handlers',
272 but still do run any other handlers. This lets handlers
273 use the standard functions without calling themselves recursively. */)
274 (Lisp_Object filename, Lisp_Object operation)
276 /* This function must not munge the match data. */
277 Lisp_Object chain, inhibited_handlers, result;
278 ptrdiff_t pos = -1;
280 result = Qnil;
281 CHECK_STRING (filename);
283 if (EQ (operation, Vinhibit_file_name_operation))
284 inhibited_handlers = Vinhibit_file_name_handlers;
285 else
286 inhibited_handlers = Qnil;
288 for (chain = Vfile_name_handler_alist; CONSP (chain);
289 chain = XCDR (chain))
291 Lisp_Object elt;
292 elt = XCAR (chain);
293 if (CONSP (elt))
295 Lisp_Object string = XCAR (elt);
296 ptrdiff_t match_pos;
297 Lisp_Object handler = XCDR (elt);
298 Lisp_Object operations = Qnil;
300 if (SYMBOLP (handler))
301 operations = Fget (handler, Qoperations);
303 if (STRINGP (string)
304 && (match_pos = fast_string_match (string, filename)) > pos
305 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
307 Lisp_Object tem;
309 handler = XCDR (elt);
310 tem = Fmemq (handler, inhibited_handlers);
311 if (NILP (tem))
313 result = handler;
314 pos = match_pos;
319 maybe_quit ();
321 return result;
324 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
325 1, 1, 0,
326 doc: /* Return the directory component in file name FILENAME.
327 Return nil if FILENAME does not include a directory.
328 Otherwise return a directory name.
329 Given a Unix syntax file name, returns a string ending in slash. */)
330 (Lisp_Object filename)
332 Lisp_Object handler;
334 CHECK_STRING (filename);
336 /* If the file name has special constructs in it,
337 call the corresponding file handler. */
338 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
339 if (!NILP (handler))
341 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
342 filename);
343 return STRINGP (handled_name) ? handled_name : Qnil;
346 char *beg = SSDATA (filename);
347 char const *p = beg + SBYTES (filename);
349 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
350 #ifdef DOS_NT
351 /* only recognize drive specifier at the beginning */
352 && !(p[-1] == ':'
353 /* handle the "/:d:foo" and "/:foo" cases correctly */
354 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
355 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
356 #endif
357 ) p--;
359 if (p == beg)
360 return Qnil;
361 #ifdef DOS_NT
362 /* Expansion of "c:" to drive and default directory. */
363 Lisp_Object tem_fn;
364 USE_SAFE_ALLOCA;
365 SAFE_ALLOCA_STRING (beg, filename);
366 p = beg + (p - SSDATA (filename));
368 if (p[-1] == ':')
370 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
371 char *res = alloca (MAXPATHLEN + 1);
372 char *r = res;
374 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
376 memcpy (res, beg, 2);
377 beg += 2;
378 r += 2;
381 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
383 size_t l = strlen (res);
385 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
386 strcat (res, "/");
387 beg = res;
388 p = beg + strlen (beg);
389 dostounix_filename (beg);
390 tem_fn = make_specified_string (beg, -1, p - beg,
391 STRING_MULTIBYTE (filename));
393 else
394 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
395 STRING_MULTIBYTE (filename));
397 else if (STRING_MULTIBYTE (filename))
399 tem_fn = make_specified_string (beg, -1, p - beg, 1);
400 dostounix_filename (SSDATA (tem_fn));
401 #ifdef WINDOWSNT
402 if (!NILP (Vw32_downcase_file_names))
403 tem_fn = Fdowncase (tem_fn);
404 #endif
406 else
408 dostounix_filename (beg);
409 tem_fn = make_specified_string (beg, -1, p - beg, 0);
411 SAFE_FREE ();
412 return tem_fn;
413 #else /* DOS_NT */
414 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
415 #endif /* DOS_NT */
418 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
419 Sfile_name_nondirectory, 1, 1, 0,
420 doc: /* Return file name FILENAME sans its directory.
421 For example, in a Unix-syntax file name,
422 this is everything after the last slash,
423 or the entire name if it contains no slash. */)
424 (Lisp_Object filename)
426 register const char *beg, *p, *end;
427 Lisp_Object handler;
429 CHECK_STRING (filename);
431 /* If the file name has special constructs in it,
432 call the corresponding file handler. */
433 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
434 if (!NILP (handler))
436 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
437 filename);
438 if (STRINGP (handled_name))
439 return handled_name;
440 error ("Invalid handler in `file-name-handler-alist'");
443 beg = SSDATA (filename);
444 end = p = beg + SBYTES (filename);
446 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
447 #ifdef DOS_NT
448 /* only recognize drive specifier at beginning */
449 && !(p[-1] == ':'
450 /* handle the "/:d:foo" case correctly */
451 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
452 #endif
454 p--;
456 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
459 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
460 Sunhandled_file_name_directory, 1, 1, 0,
461 doc: /* Return a directly usable directory name somehow associated with FILENAME.
462 A `directly usable' directory name is one that may be used without the
463 intervention of any file handler.
464 If FILENAME is a directly usable file itself, return
465 \(file-name-as-directory FILENAME).
466 If FILENAME refers to a file which is not accessible from a local process,
467 then this should return nil.
468 The `call-process' and `start-process' functions use this function to
469 get a current directory to run processes in. */)
470 (Lisp_Object filename)
472 Lisp_Object handler;
474 /* If the file name has special constructs in it,
475 call the corresponding file handler. */
476 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
477 if (!NILP (handler))
479 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
480 filename);
481 return STRINGP (handled_name) ? handled_name : Qnil;
484 return Ffile_name_as_directory (filename);
487 /* Maximum number of bytes that DST will be longer than SRC
488 in file_name_as_directory. This occurs when SRCLEN == 0. */
489 enum { file_name_as_directory_slop = 2 };
491 /* Convert from file name SRC of length SRCLEN to directory name in
492 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
493 string. On UNIX, just make sure there is a terminating /. Return
494 the length of DST in bytes. */
496 static ptrdiff_t
497 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
498 bool multibyte)
500 if (srclen == 0)
502 dst[0] = '.';
503 dst[1] = '/';
504 dst[2] = '\0';
505 return 2;
508 memcpy (dst, src, srclen);
509 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
510 dst[srclen++] = DIRECTORY_SEP;
511 dst[srclen] = 0;
512 #ifdef DOS_NT
513 dostounix_filename (dst);
514 #endif
515 return srclen;
518 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
519 Sfile_name_as_directory, 1, 1, 0,
520 doc: /* Return a string representing the file name FILE interpreted as a directory.
521 This operation exists because a directory is also a file, but its name as
522 a directory is different from its name as a file.
523 The result can be used as the value of `default-directory'
524 or passed as second argument to `expand-file-name'.
525 For a Unix-syntax file name, just appends a slash unless a trailing slash
526 is already present. */)
527 (Lisp_Object file)
529 char *buf;
530 ptrdiff_t length;
531 Lisp_Object handler, val;
532 USE_SAFE_ALLOCA;
534 CHECK_STRING (file);
536 /* If the file name has special constructs in it,
537 call the corresponding file handler. */
538 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
539 if (!NILP (handler))
541 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
542 file);
543 if (STRINGP (handled_name))
544 return handled_name;
545 error ("Invalid handler in `file-name-handler-alist'");
548 #ifdef WINDOWSNT
549 if (!NILP (Vw32_downcase_file_names))
550 file = Fdowncase (file);
551 #endif
552 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
553 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
554 STRING_MULTIBYTE (file));
555 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
556 SAFE_FREE ();
557 return val;
560 /* Convert from directory name SRC of length SRCLEN to file name in
561 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
562 string. On UNIX, just make sure there isn't a terminating /.
563 Return the length of DST in bytes. */
565 static ptrdiff_t
566 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
568 /* Process as Unix format: just remove any final slash.
569 But leave "/" and "//" unchanged. */
570 while (srclen > 1
571 #ifdef DOS_NT
572 && !IS_ANY_SEP (src[srclen - 2])
573 #endif
574 && IS_DIRECTORY_SEP (src[srclen - 1])
575 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
576 srclen--;
578 memcpy (dst, src, srclen);
579 dst[srclen] = 0;
580 #ifdef DOS_NT
581 dostounix_filename (dst);
582 #endif
583 return srclen;
586 DEFUN ("directory-name-p", Fdirectory_name_p, Sdirectory_name_p, 1, 1, 0,
587 doc: /* Return non-nil if NAME ends with a directory separator character. */)
588 (Lisp_Object name)
590 CHECK_STRING (name);
591 ptrdiff_t namelen = SBYTES (name);
592 unsigned char c = namelen ? SREF (name, namelen - 1) : 0;
593 return IS_DIRECTORY_SEP (c) ? Qt : Qnil;
596 /* Return true if NAME must be that of a directory if it exists.
597 When NAME is a directory name, this avoids system calls compared to
598 just calling Ffile_directory_p. */
600 static bool
601 directory_like (Lisp_Object name)
603 return !NILP (Fdirectory_name_p (name)) || !NILP (Ffile_directory_p (name));
606 /* Return the expansion of NEWNAME, except that if NEWNAME is like a
607 directory then return the expansion of FILE's basename under
608 NEWNAME. This is like how 'cp FILE NEWNAME' works. */
610 static Lisp_Object
611 expand_cp_target (Lisp_Object file, Lisp_Object newname)
613 return (directory_like (newname)
614 ? Fexpand_file_name (Ffile_name_nondirectory (file), newname)
615 : Fexpand_file_name (newname, Qnil));
618 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
619 1, 1, 0,
620 doc: /* Returns the file name of the directory named DIRECTORY.
621 This is the name of the file that holds the data for the directory DIRECTORY.
622 This operation exists because a directory is also a file, but its name as
623 a directory is different from its name as a file.
624 In Unix-syntax, this function just removes the final slash. */)
625 (Lisp_Object directory)
627 char *buf;
628 ptrdiff_t length;
629 Lisp_Object handler, val;
630 USE_SAFE_ALLOCA;
632 CHECK_STRING (directory);
634 /* If the file name has special constructs in it,
635 call the corresponding file handler. */
636 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
637 if (!NILP (handler))
639 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
640 directory);
641 if (STRINGP (handled_name))
642 return handled_name;
643 error ("Invalid handler in `file-name-handler-alist'");
646 #ifdef WINDOWSNT
647 if (!NILP (Vw32_downcase_file_names))
648 directory = Fdowncase (directory);
649 #endif
650 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
651 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
652 STRING_MULTIBYTE (directory));
653 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
654 SAFE_FREE ();
655 return val;
658 static const char make_temp_name_tbl[64] =
660 'A','B','C','D','E','F','G','H',
661 'I','J','K','L','M','N','O','P',
662 'Q','R','S','T','U','V','W','X',
663 'Y','Z','a','b','c','d','e','f',
664 'g','h','i','j','k','l','m','n',
665 'o','p','q','r','s','t','u','v',
666 'w','x','y','z','0','1','2','3',
667 '4','5','6','7','8','9','-','_'
670 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
672 /* Value is a temporary file name starting with PREFIX, a string.
674 The Emacs process number forms part of the result, so there is
675 no danger of generating a name being used by another process.
676 In addition, this function makes an attempt to choose a name
677 which has no existing file. To make this work, PREFIX should be
678 an absolute file name.
680 BASE64_P means add the pid as 3 characters in base64
681 encoding. In this case, 6 characters will be added to PREFIX to
682 form the file name. Otherwise, if Emacs is running on a system
683 with long file names, add the pid as a decimal number.
685 This function signals an error if no unique file name could be
686 generated. */
688 Lisp_Object
689 make_temp_name (Lisp_Object prefix, bool base64_p)
691 Lisp_Object val, encoded_prefix;
692 ptrdiff_t len;
693 printmax_t pid;
694 char *p, *data;
695 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
696 int pidlen;
698 CHECK_STRING (prefix);
700 /* VAL is created by adding 6 characters to PREFIX. The first
701 three are the PID of this process, in base 64, and the second
702 three are incremented if the file already exists. This ensures
703 262144 unique file names per PID per PREFIX. */
705 pid = getpid ();
707 if (base64_p)
709 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
710 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
711 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
712 pidlen = 3;
714 else
716 #ifdef HAVE_LONG_FILE_NAMES
717 pidlen = sprintf (pidbuf, "%"pMd, pid);
718 #else
719 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
720 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
721 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
722 pidlen = 3;
723 #endif
726 encoded_prefix = ENCODE_FILE (prefix);
727 len = SBYTES (encoded_prefix);
728 val = make_uninit_string (len + 3 + pidlen);
729 data = SSDATA (val);
730 memcpy (data, SSDATA (encoded_prefix), len);
731 p = data + len;
733 memcpy (p, pidbuf, pidlen);
734 p += pidlen;
736 /* Here we try to minimize useless stat'ing when this function is
737 invoked many times successively with the same PREFIX. We achieve
738 this by initializing count to a random value, and incrementing it
739 afterwards.
741 We don't want make-temp-name to be called while dumping,
742 because then make_temp_name_count_initialized_p would get set
743 and then make_temp_name_count would not be set when Emacs starts. */
745 if (!make_temp_name_count_initialized_p)
747 make_temp_name_count = time (NULL);
748 make_temp_name_count_initialized_p = 1;
751 while (1)
753 unsigned num = make_temp_name_count;
755 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
756 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
757 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
759 /* Poor man's congruential RN generator. Replace with
760 ++make_temp_name_count for debugging. */
761 make_temp_name_count += 25229;
762 make_temp_name_count %= 225307;
764 if (!check_existing (data))
766 /* We want to return only if errno is ENOENT. */
767 if (errno == ENOENT)
768 return DECODE_FILE (val);
769 else
770 /* The error here is dubious, but there is little else we
771 can do. The alternatives are to return nil, which is
772 as bad as (and in many cases worse than) throwing the
773 error, or to ignore the error, which will likely result
774 in looping through 225307 stat's, which is not only
775 dog-slow, but also useless since eventually nil would
776 have to be returned anyway. */
777 report_file_error ("Cannot create temporary name for prefix",
778 prefix);
779 /* not reached */
785 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
786 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
787 The Emacs process number forms part of the result, so there is no
788 danger of generating a name being used by another Emacs process
789 \(so long as only a single host can access the containing directory...).
791 This function tries to choose a name that has no existing file.
792 For this to work, PREFIX should be an absolute file name, and PREFIX
793 and the returned string should both be non-magic.
795 There is a race condition between calling `make-temp-name' and creating the
796 file, which opens all kinds of security holes. For that reason, you should
797 normally use `make-temp-file' instead. */)
798 (Lisp_Object prefix)
800 return make_temp_name (prefix, 0);
803 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
804 doc: /* Convert filename NAME to absolute, and canonicalize it.
805 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
806 \(does not start with slash or tilde); both the directory name and
807 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
808 missing, the current buffer's value of `default-directory' is used.
809 NAME should be a string that is a valid file name for the underlying
810 filesystem.
811 File name components that are `.' are removed, and
812 so are file name components followed by `..', along with the `..' itself;
813 note that these simplifications are done without checking the resulting
814 file names in the file system.
815 Multiple consecutive slashes are collapsed into a single slash,
816 except at the beginning of the file name when they are significant (e.g.,
817 UNC file names on MS-Windows.)
818 An initial `~/' expands to your home directory.
819 An initial `~USER/' expands to USER's home directory.
820 See also the function `substitute-in-file-name'.
822 For technical reasons, this function can return correct but
823 non-intuitive results for the root directory; for instance,
824 \(expand-file-name ".." "/") returns "/..". For this reason, use
825 \(directory-file-name (file-name-directory dirname)) to traverse a
826 filesystem tree, not (expand-file-name ".." dirname). */)
827 (Lisp_Object name, Lisp_Object default_directory)
829 /* These point to SDATA and need to be careful with string-relocation
830 during GC (via DECODE_FILE). */
831 char *nm;
832 char *nmlim;
833 const char *newdir;
834 const char *newdirlim;
835 /* This should only point to alloca'd data. */
836 char *target;
838 ptrdiff_t tlen;
839 struct passwd *pw;
840 #ifdef DOS_NT
841 int drive = 0;
842 bool collapse_newdir = true;
843 bool is_escaped = 0;
844 #endif /* DOS_NT */
845 ptrdiff_t length, nbytes;
846 Lisp_Object handler, result, handled_name;
847 bool multibyte;
848 Lisp_Object hdir;
849 USE_SAFE_ALLOCA;
851 CHECK_STRING (name);
853 /* If the file name has special constructs in it,
854 call the corresponding file handler. */
855 handler = Ffind_file_name_handler (name, Qexpand_file_name);
856 if (!NILP (handler))
858 handled_name = call3 (handler, Qexpand_file_name,
859 name, default_directory);
860 if (STRINGP (handled_name))
861 return handled_name;
862 error ("Invalid handler in `file-name-handler-alist'");
866 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
867 if (NILP (default_directory))
868 default_directory = BVAR (current_buffer, directory);
869 if (! STRINGP (default_directory))
871 #ifdef DOS_NT
872 /* "/" is not considered a root directory on DOS_NT, so using "/"
873 here causes an infinite recursion in, e.g., the following:
875 (let (default-directory)
876 (expand-file-name "a"))
878 To avoid this, we set default_directory to the root of the
879 current drive. */
880 default_directory = build_string (emacs_root_dir ());
881 #else
882 default_directory = build_string ("/");
883 #endif
886 if (!NILP (default_directory))
888 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
889 if (!NILP (handler))
891 handled_name = call3 (handler, Qexpand_file_name,
892 name, default_directory);
893 if (STRINGP (handled_name))
894 return handled_name;
895 error ("Invalid handler in `file-name-handler-alist'");
900 char *o = SSDATA (default_directory);
902 /* Make sure DEFAULT_DIRECTORY is properly expanded.
903 It would be better to do this down below where we actually use
904 default_directory. Unfortunately, calling Fexpand_file_name recursively
905 could invoke GC, and the strings might be relocated. This would
906 be annoying because we have pointers into strings lying around
907 that would need adjusting, and people would add new pointers to
908 the code and forget to adjust them, resulting in intermittent bugs.
909 Putting this call here avoids all that crud.
911 The EQ test avoids infinite recursion. */
912 if (! NILP (default_directory) && !EQ (default_directory, name)
913 /* Save time in some common cases - as long as default_directory
914 is not relative, it can be canonicalized with name below (if it
915 is needed at all) without requiring it to be expanded now. */
916 #ifdef DOS_NT
917 /* Detect MSDOS file names with drive specifiers. */
918 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
919 && IS_DIRECTORY_SEP (o[2]))
920 /* Detect escaped file names without drive spec after "/:".
921 These should not be recursively expanded, to avoid
922 including the default directory twice in the expanded
923 result. */
924 && ! (o[0] == '/' && o[1] == ':')
925 #ifdef WINDOWSNT
926 /* Detect Windows file names in UNC format. */
927 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
928 #endif
929 #else /* not DOS_NT */
930 /* Detect Unix absolute file names (/... alone is not absolute on
931 DOS or Windows). */
932 && ! (IS_DIRECTORY_SEP (o[0]))
933 #endif /* not DOS_NT */
936 default_directory = Fexpand_file_name (default_directory, Qnil);
939 multibyte = STRING_MULTIBYTE (name);
940 if (multibyte != STRING_MULTIBYTE (default_directory))
942 if (multibyte)
944 unsigned char *p = SDATA (name);
946 while (*p && ASCII_CHAR_P (*p))
947 p++;
948 if (*p == '\0')
950 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
951 unibyte. Do not convert DEFAULT_DIRECTORY to
952 multibyte; instead, convert NAME to a unibyte string,
953 so that the result of this function is also a unibyte
954 string. This is needed during bootstrapping and
955 dumping, when Emacs cannot decode file names, because
956 the locale environment is not set up. */
957 name = make_unibyte_string (SSDATA (name), SBYTES (name));
958 multibyte = 0;
960 else
961 default_directory = string_to_multibyte (default_directory);
963 else
965 name = string_to_multibyte (name);
966 multibyte = 1;
970 #ifdef WINDOWSNT
971 if (!NILP (Vw32_downcase_file_names))
972 default_directory = Fdowncase (default_directory);
973 #endif
975 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
976 SAFE_ALLOCA_STRING (nm, name);
977 nmlim = nm + SBYTES (name);
979 #ifdef DOS_NT
980 /* Note if special escape prefix is present, but remove for now. */
981 if (nm[0] == '/' && nm[1] == ':')
983 is_escaped = 1;
984 nm += 2;
987 /* Find and remove drive specifier if present; this makes nm absolute
988 even if the rest of the name appears to be relative. Only look for
989 drive specifier at the beginning. */
990 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
992 drive = (unsigned char) nm[0];
993 nm += 2;
996 #ifdef WINDOWSNT
997 /* If we see "c://somedir", we want to strip the first slash after the
998 colon when stripping the drive letter. Otherwise, this expands to
999 "//somedir". */
1000 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1001 nm++;
1003 /* Discard any previous drive specifier if nm is now in UNC format. */
1004 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1005 && !IS_DIRECTORY_SEP (nm[2]))
1006 drive = 0;
1007 #endif /* WINDOWSNT */
1008 #endif /* DOS_NT */
1010 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
1011 none are found, we can probably return right away. We will avoid
1012 allocating a new string if name is already fully expanded. */
1013 if (
1014 IS_DIRECTORY_SEP (nm[0])
1015 #ifdef MSDOS
1016 && drive && !is_escaped
1017 #endif
1018 #ifdef WINDOWSNT
1019 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
1020 #endif
1023 /* If it turns out that the filename we want to return is just a
1024 suffix of FILENAME, we don't need to go through and edit
1025 things; we just need to construct a new string using data
1026 starting at the middle of FILENAME. If we set LOSE, that
1027 means we've discovered that we can't do that cool trick. */
1028 bool lose = 0;
1029 char *p = nm;
1031 while (*p)
1033 /* Since we know the name is absolute, we can assume that each
1034 element starts with a "/". */
1036 /* "." and ".." are hairy. */
1037 if (IS_DIRECTORY_SEP (p[0])
1038 && p[1] == '.'
1039 && (IS_DIRECTORY_SEP (p[2])
1040 || p[2] == 0
1041 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1042 || p[3] == 0))))
1043 lose = 1;
1044 /* Replace multiple slashes with a single one, except
1045 leave leading "//" alone. */
1046 else if (IS_DIRECTORY_SEP (p[0])
1047 && IS_DIRECTORY_SEP (p[1])
1048 && (p != nm || IS_DIRECTORY_SEP (p[2])))
1049 lose = 1;
1050 p++;
1052 if (!lose)
1054 #ifdef DOS_NT
1055 /* Make sure directories are all separated with /, but
1056 avoid allocation of a new string when not required. */
1057 dostounix_filename (nm);
1058 #ifdef WINDOWSNT
1059 if (IS_DIRECTORY_SEP (nm[1]))
1061 if (strcmp (nm, SSDATA (name)) != 0)
1062 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1064 else
1065 #endif
1066 /* Drive must be set, so this is okay. */
1067 if (strcmp (nm - 2, SSDATA (name)) != 0)
1069 name = make_specified_string (nm, -1, p - nm, multibyte);
1070 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1071 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1072 name = concat2 (drive_prefix, name);
1074 #ifdef WINDOWSNT
1075 if (!NILP (Vw32_downcase_file_names))
1076 name = Fdowncase (name);
1077 #endif
1078 #else /* not DOS_NT */
1079 if (strcmp (nm, SSDATA (name)) != 0)
1080 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1081 #endif /* not DOS_NT */
1082 SAFE_FREE ();
1083 return name;
1087 /* At this point, nm might or might not be an absolute file name. We
1088 need to expand ~ or ~user if present, otherwise prefix nm with
1089 default_directory if nm is not absolute, and finally collapse /./
1090 and /foo/../ sequences.
1092 We set newdir to be the appropriate prefix if one is needed:
1093 - the relevant user directory if nm starts with ~ or ~user
1094 - the specified drive's working dir (DOS/NT only) if nm does not
1095 start with /
1096 - the value of default_directory.
1098 Note that these prefixes are not guaranteed to be absolute (except
1099 for the working dir of a drive). Therefore, to ensure we always
1100 return an absolute name, if the final prefix is not absolute we
1101 append it to the current working directory. */
1103 newdir = newdirlim = 0;
1105 if (nm[0] == '~' /* prefix ~ */
1106 #ifdef DOS_NT
1107 && !is_escaped /* don't expand ~ in escaped file names */
1108 #endif
1111 if (IS_DIRECTORY_SEP (nm[1])
1112 || nm[1] == 0) /* ~ by itself */
1114 Lisp_Object tem;
1116 if (!(newdir = egetenv ("HOME")))
1117 newdir = newdirlim = "";
1118 nm++;
1119 #ifdef WINDOWSNT
1120 if (newdir[0])
1122 char newdir_utf8[MAX_UTF8_PATH];
1124 filename_from_ansi (newdir, newdir_utf8);
1125 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1126 newdir = SSDATA (tem);
1128 else
1129 #endif
1130 tem = build_string (newdir);
1131 newdirlim = newdir + SBYTES (tem);
1132 /* `egetenv' may return a unibyte string, which will bite us
1133 if we expect the directory to be multibyte. */
1134 if (multibyte && !STRING_MULTIBYTE (tem))
1136 hdir = DECODE_FILE (tem);
1137 newdir = SSDATA (hdir);
1138 newdirlim = newdir + SBYTES (hdir);
1140 #ifdef DOS_NT
1141 collapse_newdir = false;
1142 #endif
1144 else /* ~user/filename */
1146 char *o, *p;
1147 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1148 continue;
1149 o = SAFE_ALLOCA (p - nm + 1);
1150 memcpy (o, nm, p - nm);
1151 o[p - nm] = 0;
1153 block_input ();
1154 pw = getpwnam (o + 1);
1155 unblock_input ();
1156 if (pw)
1158 Lisp_Object tem;
1160 newdir = pw->pw_dir;
1161 /* `getpwnam' may return a unibyte string, which will
1162 bite us when we expect the directory to be multibyte. */
1163 tem = make_unibyte_string (newdir, strlen (newdir));
1164 newdirlim = newdir + SBYTES (tem);
1165 if (multibyte && !STRING_MULTIBYTE (tem))
1167 hdir = DECODE_FILE (tem);
1168 newdir = SSDATA (hdir);
1169 newdirlim = newdir + SBYTES (hdir);
1171 nm = p;
1172 #ifdef DOS_NT
1173 collapse_newdir = false;
1174 #endif
1177 /* If we don't find a user of that name, leave the name
1178 unchanged; don't move nm forward to p. */
1182 #ifdef DOS_NT
1183 /* On DOS and Windows, nm is absolute if a drive name was specified;
1184 use the drive's current directory as the prefix if needed. */
1185 if (!newdir && drive)
1187 /* Get default directory if needed to make nm absolute. */
1188 char *adir = NULL;
1189 if (!IS_DIRECTORY_SEP (nm[0]))
1191 adir = alloca (MAXPATHLEN + 1);
1192 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1193 adir = NULL;
1194 else if (multibyte)
1196 Lisp_Object tem = build_string (adir);
1198 tem = DECODE_FILE (tem);
1199 newdirlim = adir + SBYTES (tem);
1200 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1202 else
1203 newdirlim = adir + strlen (adir);
1205 if (!adir)
1207 /* Either nm starts with /, or drive isn't mounted. */
1208 adir = alloca (4);
1209 adir[0] = DRIVE_LETTER (drive);
1210 adir[1] = ':';
1211 adir[2] = '/';
1212 adir[3] = 0;
1213 newdirlim = adir + 3;
1215 newdir = adir;
1217 #endif /* DOS_NT */
1219 /* Finally, if no prefix has been specified and nm is not absolute,
1220 then it must be expanded relative to default_directory. */
1222 if (1
1223 #ifndef DOS_NT
1224 /* /... alone is not absolute on DOS and Windows. */
1225 && !IS_DIRECTORY_SEP (nm[0])
1226 #endif
1227 #ifdef WINDOWSNT
1228 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1229 && !IS_DIRECTORY_SEP (nm[2]))
1230 #endif
1231 && !newdir)
1233 newdir = SSDATA (default_directory);
1234 newdirlim = newdir + SBYTES (default_directory);
1235 #ifdef DOS_NT
1236 /* Note if special escape prefix is present, but remove for now. */
1237 if (newdir[0] == '/' && newdir[1] == ':')
1239 is_escaped = 1;
1240 newdir += 2;
1242 #endif
1245 #ifdef DOS_NT
1246 if (newdir)
1248 /* First ensure newdir is an absolute name. */
1249 if (
1250 /* Detect MSDOS file names with drive specifiers. */
1251 ! (IS_DRIVE (newdir[0])
1252 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1253 #ifdef WINDOWSNT
1254 /* Detect Windows file names in UNC format. */
1255 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1256 && !IS_DIRECTORY_SEP (newdir[2]))
1257 #endif
1260 /* Effectively, let newdir be (expand-file-name newdir cwd).
1261 Because of the admonition against calling expand-file-name
1262 when we have pointers into lisp strings, we accomplish this
1263 indirectly by prepending newdir to nm if necessary, and using
1264 cwd (or the wd of newdir's drive) as the new newdir. */
1265 char *adir;
1266 #ifdef WINDOWSNT
1267 const int adir_size = MAX_UTF8_PATH;
1268 #else
1269 const int adir_size = MAXPATHLEN + 1;
1270 #endif
1272 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1274 drive = (unsigned char) newdir[0];
1275 newdir += 2;
1277 if (!IS_DIRECTORY_SEP (nm[0]))
1279 ptrdiff_t nmlen = nmlim - nm;
1280 ptrdiff_t newdirlen = newdirlim - newdir;
1281 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1282 + nmlen + 1);
1283 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1284 multibyte);
1285 memcpy (tmp + dlen, nm, nmlen + 1);
1286 nm = tmp;
1287 nmlim = nm + dlen + nmlen;
1289 adir = alloca (adir_size);
1290 if (drive)
1292 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1293 strcpy (adir, "/");
1295 else
1296 getcwd (adir, adir_size);
1297 if (multibyte)
1299 Lisp_Object tem = build_string (adir);
1301 tem = DECODE_FILE (tem);
1302 newdirlim = adir + SBYTES (tem);
1303 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1305 else
1306 newdirlim = adir + strlen (adir);
1307 newdir = adir;
1310 /* Strip off drive name from prefix, if present. */
1311 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1313 drive = newdir[0];
1314 newdir += 2;
1317 /* Keep only a prefix from newdir if nm starts with slash
1318 (//server/share for UNC, nothing otherwise). */
1319 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1321 #ifdef WINDOWSNT
1322 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1323 && !IS_DIRECTORY_SEP (newdir[2]))
1325 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1326 char *p = adir + 2;
1327 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1328 p++;
1329 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1330 *p = 0;
1331 newdir = adir;
1332 newdirlim = newdir + strlen (adir);
1334 else
1335 #endif
1336 newdir = newdirlim = "";
1339 #endif /* DOS_NT */
1341 /* Ignore any slash at the end of newdir, unless newdir is
1342 just "/" or "//". */
1343 length = newdirlim - newdir;
1344 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1345 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1346 length--;
1348 /* Now concatenate the directory and name to new space in the stack frame. */
1349 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1350 eassert (tlen > file_name_as_directory_slop + 1);
1351 #ifdef DOS_NT
1352 /* Reserve space for drive specifier and escape prefix, since either
1353 or both may need to be inserted. (The Microsoft x86 compiler
1354 produces incorrect code if the following two lines are combined.) */
1355 target = alloca (tlen + 4);
1356 target += 4;
1357 #else /* not DOS_NT */
1358 target = SAFE_ALLOCA (tlen);
1359 #endif /* not DOS_NT */
1360 *target = 0;
1361 nbytes = 0;
1363 if (newdir)
1365 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1367 #ifdef DOS_NT
1368 /* If newdir is effectively "C:/", then the drive letter will have
1369 been stripped and newdir will be "/". Concatenating with an
1370 absolute directory in nm produces "//", which will then be
1371 incorrectly treated as a network share. Ignore newdir in
1372 this case (keeping the drive letter). */
1373 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1374 && newdir[1] == '\0'))
1375 #endif
1377 memcpy (target, newdir, length);
1378 target[length] = 0;
1379 nbytes = length;
1382 else
1383 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1386 memcpy (target + nbytes, nm, nmlim - nm + 1);
1388 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1389 appear. */
1391 char *p = target;
1392 char *o = target;
1394 while (*p)
1396 if (!IS_DIRECTORY_SEP (*p))
1398 *o++ = *p++;
1400 else if (p[1] == '.'
1401 && (IS_DIRECTORY_SEP (p[2])
1402 || p[2] == 0))
1404 /* If "/." is the entire filename, keep the "/". Otherwise,
1405 just delete the whole "/.". */
1406 if (o == target && p[2] == '\0')
1407 *o++ = *p;
1408 p += 2;
1410 else if (p[1] == '.' && p[2] == '.'
1411 /* `/../' is the "superroot" on certain file systems.
1412 Turned off on DOS_NT systems because they have no
1413 "superroot" and because this causes us to produce
1414 file names like "d:/../foo" which fail file-related
1415 functions of the underlying OS. (To reproduce, try a
1416 long series of "../../" in default_directory, longer
1417 than the number of levels from the root.) */
1418 #ifndef DOS_NT
1419 && o != target
1420 #endif
1421 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1423 #ifdef WINDOWSNT
1424 char *prev_o = o;
1425 #endif
1426 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1427 continue;
1428 #ifdef WINDOWSNT
1429 /* Don't go below server level in UNC filenames. */
1430 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1431 && IS_DIRECTORY_SEP (*target))
1432 o = prev_o;
1433 else
1434 #endif
1435 /* Keep initial / only if this is the whole name. */
1436 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1437 ++o;
1438 p += 3;
1440 else if (IS_DIRECTORY_SEP (p[1])
1441 && (p != target || IS_DIRECTORY_SEP (p[2])))
1442 /* Collapse multiple "/", except leave leading "//" alone. */
1443 p++;
1444 else
1446 *o++ = *p++;
1450 #ifdef DOS_NT
1451 /* At last, set drive name. */
1452 #ifdef WINDOWSNT
1453 /* Except for network file name. */
1454 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1455 #endif /* WINDOWSNT */
1457 if (!drive) emacs_abort ();
1458 target -= 2;
1459 target[0] = DRIVE_LETTER (drive);
1460 target[1] = ':';
1462 /* Reinsert the escape prefix if required. */
1463 if (is_escaped)
1465 target -= 2;
1466 target[0] = '/';
1467 target[1] = ':';
1469 result = make_specified_string (target, -1, o - target, multibyte);
1470 dostounix_filename (SSDATA (result));
1471 #ifdef WINDOWSNT
1472 if (!NILP (Vw32_downcase_file_names))
1473 result = Fdowncase (result);
1474 #endif
1475 #else /* !DOS_NT */
1476 result = make_specified_string (target, -1, o - target, multibyte);
1477 #endif /* !DOS_NT */
1480 /* Again look to see if the file name has special constructs in it
1481 and perhaps call the corresponding file handler. This is needed
1482 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1483 the ".." component gives us "/user@host:/bar/../baz" which needs
1484 to be expanded again. */
1485 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1486 if (!NILP (handler))
1488 handled_name = call3 (handler, Qexpand_file_name,
1489 result, default_directory);
1490 if (! STRINGP (handled_name))
1491 error ("Invalid handler in `file-name-handler-alist'");
1492 result = handled_name;
1495 SAFE_FREE ();
1496 return result;
1499 #if 0
1500 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1501 This is the old version of expand-file-name, before it was thoroughly
1502 rewritten for Emacs 10.31. We leave this version here commented-out,
1503 because the code is very complex and likely to have subtle bugs. If
1504 bugs _are_ found, it might be of interest to look at the old code and
1505 see what did it do in the relevant situation.
1507 Don't remove this code: it's true that it will be accessible
1508 from the repository, but a few years from deletion, people will
1509 forget it is there. */
1511 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1512 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1513 "Convert FILENAME to absolute, and canonicalize it.\n\
1514 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1515 \(does not start with slash); if DEFAULT is nil or missing,\n\
1516 the current buffer's value of default-directory is used.\n\
1517 Filenames containing `.' or `..' as components are simplified;\n\
1518 initial `~/' expands to your home directory.\n\
1519 See also the function `substitute-in-file-name'.")
1520 (name, defalt)
1521 Lisp_Object name, defalt;
1523 unsigned char *nm;
1525 register unsigned char *newdir, *p, *o;
1526 ptrdiff_t tlen;
1527 unsigned char *target;
1528 struct passwd *pw;
1530 CHECK_STRING (name);
1531 nm = SDATA (name);
1533 /* If nm is absolute, flush ...// and detect /./ and /../.
1534 If no /./ or /../ we can return right away. */
1535 if (nm[0] == '/')
1537 bool lose = 0;
1538 p = nm;
1539 while (*p)
1541 if (p[0] == '/' && p[1] == '/')
1542 nm = p + 1;
1543 if (p[0] == '/' && p[1] == '~')
1544 nm = p + 1, lose = 1;
1545 if (p[0] == '/' && p[1] == '.'
1546 && (p[2] == '/' || p[2] == 0
1547 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1548 lose = 1;
1549 p++;
1551 if (!lose)
1553 if (nm == SDATA (name))
1554 return name;
1555 return build_string (nm);
1559 /* Now determine directory to start with and put it in NEWDIR. */
1561 newdir = 0;
1563 if (nm[0] == '~') /* prefix ~ */
1564 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1566 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1567 newdir = (unsigned char *) "";
1568 nm++;
1570 else /* ~user/filename */
1572 /* Get past ~ to user. */
1573 unsigned char *user = nm + 1;
1574 /* Find end of name. */
1575 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1576 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1577 /* Copy the user name into temp storage. */
1578 o = alloca (len + 1);
1579 memcpy (o, user, len);
1580 o[len] = 0;
1582 /* Look up the user name. */
1583 block_input ();
1584 pw = (struct passwd *) getpwnam (o + 1);
1585 unblock_input ();
1586 if (!pw)
1587 error ("\"%s\" isn't a registered user", o + 1);
1589 newdir = (unsigned char *) pw->pw_dir;
1591 /* Discard the user name from NM. */
1592 nm += len;
1595 if (nm[0] != '/' && !newdir)
1597 if (NILP (defalt))
1598 defalt = current_buffer->directory;
1599 CHECK_STRING (defalt);
1600 newdir = SDATA (defalt);
1603 /* Now concatenate the directory and name to new space in the stack frame. */
1605 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1606 target = alloca (tlen);
1607 *target = 0;
1609 if (newdir)
1611 if (nm[0] == 0 || nm[0] == '/')
1612 strcpy (target, newdir);
1613 else
1614 file_name_as_directory (target, newdir);
1617 strcat (target, nm);
1619 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1621 p = target;
1622 o = target;
1624 while (*p)
1626 if (*p != '/')
1628 *o++ = *p++;
1630 else if (!strncmp (p, "//", 2)
1633 o = target;
1634 p++;
1636 else if (p[0] == '/' && p[1] == '.'
1637 && (p[2] == '/' || p[2] == 0))
1638 p += 2;
1639 else if (!strncmp (p, "/..", 3)
1640 /* `/../' is the "superroot" on certain file systems. */
1641 && o != target
1642 && (p[3] == '/' || p[3] == 0))
1644 while (o != target && *--o != '/')
1646 if (o == target && *o == '/')
1647 ++o;
1648 p += 3;
1650 else
1652 *o++ = *p++;
1656 return make_string (target, o - target);
1658 #endif
1660 /* If /~ or // appears, discard everything through first slash. */
1661 static bool
1662 file_name_absolute_p (const char *filename)
1664 return
1665 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1666 #ifdef DOS_NT
1667 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1668 && IS_DIRECTORY_SEP (filename[2]))
1669 #endif
1673 static char *
1674 search_embedded_absfilename (char *nm, char *endp)
1676 char *p, *s;
1678 for (p = nm + 1; p < endp; p++)
1680 if (IS_DIRECTORY_SEP (p[-1])
1681 && file_name_absolute_p (p)
1682 #if defined (WINDOWSNT) || defined (CYGWIN)
1683 /* // at start of file name is meaningful in Apollo,
1684 WindowsNT and Cygwin systems. */
1685 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1686 #endif /* not (WINDOWSNT || CYGWIN) */
1689 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1690 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1692 USE_SAFE_ALLOCA;
1693 char *o = SAFE_ALLOCA (s - p + 1);
1694 struct passwd *pw;
1695 memcpy (o, p, s - p);
1696 o [s - p] = 0;
1698 /* If we have ~user and `user' exists, discard
1699 everything up to ~. But if `user' does not exist, leave
1700 ~user alone, it might be a literal file name. */
1701 block_input ();
1702 pw = getpwnam (o + 1);
1703 unblock_input ();
1704 SAFE_FREE ();
1705 if (pw)
1706 return p;
1708 else
1709 return p;
1712 return NULL;
1715 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1716 Ssubstitute_in_file_name, 1, 1, 0,
1717 doc: /* Substitute environment variables referred to in FILENAME.
1718 `$FOO' where FOO is an environment variable name means to substitute
1719 the value of that variable. The variable name should be terminated
1720 with a character not a letter, digit or underscore; otherwise, enclose
1721 the entire variable name in braces.
1723 If `/~' appears, all of FILENAME through that `/' is discarded.
1724 If `//' appears, everything up to and including the first of
1725 those `/' is discarded. */)
1726 (Lisp_Object filename)
1728 char *nm, *p, *x, *endp;
1729 bool substituted = false;
1730 bool multibyte;
1731 char *xnm;
1732 Lisp_Object handler;
1734 CHECK_STRING (filename);
1736 multibyte = STRING_MULTIBYTE (filename);
1738 /* If the file name has special constructs in it,
1739 call the corresponding file handler. */
1740 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1741 if (!NILP (handler))
1743 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1744 filename);
1745 if (STRINGP (handled_name))
1746 return handled_name;
1747 error ("Invalid handler in `file-name-handler-alist'");
1750 /* Always work on a copy of the string, in case GC happens during
1751 decode of environment variables, causing the original Lisp_String
1752 data to be relocated. */
1753 USE_SAFE_ALLOCA;
1754 SAFE_ALLOCA_STRING (nm, filename);
1756 #ifdef DOS_NT
1757 dostounix_filename (nm);
1758 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1759 #endif
1760 endp = nm + SBYTES (filename);
1762 /* If /~ or // appears, discard everything through first slash. */
1763 p = search_embedded_absfilename (nm, endp);
1764 if (p)
1765 /* Start over with the new string, so we check the file-name-handler
1766 again. Important with filenames like "/home/foo//:/hello///there"
1767 which would substitute to "/:/hello///there" rather than "/there". */
1769 Lisp_Object result
1770 = (Fsubstitute_in_file_name
1771 (make_specified_string (p, -1, endp - p, multibyte)));
1772 SAFE_FREE ();
1773 return result;
1776 /* See if any variables are substituted into the string. */
1778 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1780 Lisp_Object name
1781 = (!substituted ? filename
1782 : make_specified_string (nm, -1, endp - nm, multibyte));
1783 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1784 CHECK_STRING (tmp);
1785 if (!EQ (tmp, name))
1786 substituted = true;
1787 filename = tmp;
1790 if (!substituted)
1792 #ifdef WINDOWSNT
1793 if (!NILP (Vw32_downcase_file_names))
1794 filename = Fdowncase (filename);
1795 #endif
1796 SAFE_FREE ();
1797 return filename;
1800 xnm = SSDATA (filename);
1801 x = xnm + SBYTES (filename);
1803 /* If /~ or // appears, discard everything through first slash. */
1804 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1805 /* This time we do not start over because we've already expanded envvars
1806 and replaced $$ with $. Maybe we should start over as well, but we'd
1807 need to quote some $ to $$ first. */
1808 xnm = p;
1810 #ifdef WINDOWSNT
1811 if (!NILP (Vw32_downcase_file_names))
1813 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1815 filename = Fdowncase (xname);
1817 else
1818 #endif
1819 if (xnm != SSDATA (filename))
1820 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1821 SAFE_FREE ();
1822 return filename;
1825 /* A slightly faster and more convenient way to get
1826 (directory-file-name (expand-file-name FOO)). */
1828 Lisp_Object
1829 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1831 register Lisp_Object absname;
1833 absname = Fexpand_file_name (filename, defdir);
1835 /* Remove final slash, if any (unless this is the root dir).
1836 stat behaves differently depending! */
1837 if (SCHARS (absname) > 1
1838 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1839 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1840 /* We cannot take shortcuts; they might be wrong for magic file names. */
1841 absname = Fdirectory_file_name (absname);
1842 return absname;
1845 /* Signal an error if the file ABSNAME already exists.
1846 If KNOWN_TO_EXIST, the file is known to exist.
1847 QUERYSTRING is a name for the action that is being considered
1848 to alter the file.
1849 If INTERACTIVE, ask the user whether to proceed,
1850 and bypass the error if the user says to go ahead.
1851 If QUICK, ask for y or n, not yes or no. */
1853 static void
1854 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1855 const char *querystring, bool interactive,
1856 bool quick)
1858 Lisp_Object tem, encoded_filename;
1859 struct stat statbuf;
1861 encoded_filename = ENCODE_FILE (absname);
1863 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1865 if (S_ISDIR (statbuf.st_mode))
1866 xsignal2 (Qfile_error,
1867 build_string ("File is a directory"), absname);
1868 known_to_exist = true;
1871 if (known_to_exist)
1873 if (! interactive)
1874 xsignal2 (Qfile_already_exists,
1875 build_string ("File already exists"), absname);
1876 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1877 tem = CALLN (Fformat, format, absname, build_string (querystring));
1878 if (quick)
1879 tem = call1 (intern ("y-or-n-p"), tem);
1880 else
1881 tem = do_yes_or_no_p (tem);
1882 if (NILP (tem))
1883 xsignal2 (Qfile_already_exists,
1884 build_string ("File already exists"), absname);
1888 #ifndef WINDOWSNT
1889 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1890 static bool
1891 clone_file (int dest, int source)
1893 #ifdef FICLONE
1894 return ioctl (dest, FICLONE, source) == 0;
1895 #endif
1896 return false;
1898 #endif
1900 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1901 "fCopy file: \nGCopy %s to file: \np\nP",
1902 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1903 If NEWNAME names a directory, copy FILE there.
1905 This function always sets the file modes of the output file to match
1906 the input file.
1908 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1909 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1910 signal a `file-already-exists' error without overwriting. If
1911 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1912 about overwriting; this is what happens in interactive use with M-x.
1913 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1914 existing file.
1916 Fourth arg KEEP-TIME non-nil means give the output file the same
1917 last-modified time as the old one. (This works on only some systems.)
1919 A prefix arg makes KEEP-TIME non-nil.
1921 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1922 FILE to NEWNAME.
1924 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1925 this includes the file modes, along with ACL entries and SELinux
1926 context if present. Otherwise, if NEWNAME is created its file
1927 permission bits are those of FILE, masked by the default file
1928 permissions. */)
1929 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1930 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1931 Lisp_Object preserve_permissions)
1933 Lisp_Object handler;
1934 ptrdiff_t count = SPECPDL_INDEX ();
1935 Lisp_Object encoded_file, encoded_newname;
1936 #if HAVE_LIBSELINUX
1937 security_context_t con;
1938 int conlength = 0;
1939 #endif
1940 #ifdef WINDOWSNT
1941 int result;
1942 #else
1943 bool already_exists = false;
1944 mode_t new_mask;
1945 int ifd, ofd;
1946 struct stat st;
1947 #endif
1949 file = Fexpand_file_name (file, Qnil);
1950 newname = expand_cp_target (file, newname);
1952 /* If the input file name has special constructs in it,
1953 call the corresponding file handler. */
1954 handler = Ffind_file_name_handler (file, Qcopy_file);
1955 /* Likewise for output file name. */
1956 if (NILP (handler))
1957 handler = Ffind_file_name_handler (newname, Qcopy_file);
1958 if (!NILP (handler))
1959 return call7 (handler, Qcopy_file, file, newname,
1960 ok_if_already_exists, keep_time, preserve_uid_gid,
1961 preserve_permissions);
1963 encoded_file = ENCODE_FILE (file);
1964 encoded_newname = ENCODE_FILE (newname);
1966 #ifdef WINDOWSNT
1967 if (NILP (ok_if_already_exists)
1968 || INTEGERP (ok_if_already_exists))
1969 barf_or_query_if_file_exists (newname, false, "copy to it",
1970 INTEGERP (ok_if_already_exists), false);
1972 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1973 !NILP (keep_time), !NILP (preserve_uid_gid),
1974 !NILP (preserve_permissions));
1975 switch (result)
1977 case -1:
1978 report_file_error ("Copying file", list2 (file, newname));
1979 case -2:
1980 report_file_error ("Copying permissions from", file);
1981 case -3:
1982 xsignal2 (Qfile_date_error,
1983 build_string ("Resetting file times"), newname);
1984 case -4:
1985 report_file_error ("Copying permissions to", newname);
1987 #else /* not WINDOWSNT */
1988 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1990 if (ifd < 0)
1991 report_file_error ("Opening input file", file);
1993 record_unwind_protect_int (close_file_unwind, ifd);
1995 if (fstat (ifd, &st) != 0)
1996 report_file_error ("Input file status", file);
1998 if (!NILP (preserve_permissions))
2000 #if HAVE_LIBSELINUX
2001 if (is_selinux_enabled ())
2003 conlength = fgetfilecon (ifd, &con);
2004 if (conlength == -1)
2005 report_file_error ("Doing fgetfilecon", file);
2007 #endif
2010 /* We can copy only regular files. */
2011 if (!S_ISREG (st.st_mode))
2012 report_file_errno ("Non-regular file", file,
2013 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
2015 #ifndef MSDOS
2016 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
2017 #else
2018 new_mask = S_IREAD | S_IWRITE;
2019 #endif
2021 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
2022 new_mask);
2023 if (ofd < 0 && errno == EEXIST)
2025 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
2026 barf_or_query_if_file_exists (newname, true, "copy to it",
2027 INTEGERP (ok_if_already_exists), false);
2028 already_exists = true;
2029 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
2031 if (ofd < 0)
2032 report_file_error ("Opening output file", newname);
2034 record_unwind_protect_int (close_file_unwind, ofd);
2036 off_t oldsize = 0, newsize;
2038 if (already_exists)
2040 struct stat out_st;
2041 if (fstat (ofd, &out_st) != 0)
2042 report_file_error ("Output file status", newname);
2043 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2044 report_file_errno ("Input and output files are the same",
2045 list2 (file, newname), 0);
2046 if (S_ISREG (out_st.st_mode))
2047 oldsize = out_st.st_size;
2050 maybe_quit ();
2052 if (clone_file (ofd, ifd))
2053 newsize = st.st_size;
2054 else
2056 char buf[MAX_ALLOCA];
2057 ptrdiff_t n;
2058 for (newsize = 0; 0 < (n = emacs_read_quit (ifd, buf, sizeof buf));
2059 newsize += n)
2060 if (emacs_write_quit (ofd, buf, n) != n)
2061 report_file_error ("Write error", newname);
2062 if (n < 0)
2063 report_file_error ("Read error", file);
2066 /* Truncate any existing output file after writing the data. This
2067 is more likely to work than truncation before writing, if the
2068 file system is out of space or the user is over disk quota. */
2069 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2070 report_file_error ("Truncating output file", newname);
2072 #ifndef MSDOS
2073 /* Preserve the original file permissions, and if requested, also its
2074 owner and group. */
2076 mode_t preserved_permissions = st.st_mode & 07777;
2077 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2078 if (!NILP (preserve_uid_gid))
2080 /* Attempt to change owner and group. If that doesn't work
2081 attempt to change just the group, as that is sometimes allowed.
2082 Adjust the mode mask to eliminate setuid or setgid bits
2083 or group permissions bits that are inappropriate if the
2084 owner or group are wrong. */
2085 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2087 if (fchown (ofd, -1, st.st_gid) == 0)
2088 preserved_permissions &= ~04000;
2089 else
2091 preserved_permissions &= ~06000;
2093 /* Copy the other bits to the group bits, since the
2094 group is wrong. */
2095 preserved_permissions &= ~070;
2096 preserved_permissions |= (preserved_permissions & 7) << 3;
2097 default_permissions &= ~070;
2098 default_permissions |= (default_permissions & 7) << 3;
2103 switch (!NILP (preserve_permissions)
2104 ? qcopy_acl (SSDATA (encoded_file), ifd,
2105 SSDATA (encoded_newname), ofd,
2106 preserved_permissions)
2107 : (already_exists
2108 || (new_mask & ~realmask) == default_permissions)
2110 : fchmod (ofd, default_permissions))
2112 case -2: report_file_error ("Copying permissions from", file);
2113 case -1: report_file_error ("Copying permissions to", newname);
2116 #endif /* not MSDOS */
2118 #if HAVE_LIBSELINUX
2119 if (conlength > 0)
2121 /* Set the modified context back to the file. */
2122 bool fail = fsetfilecon (ofd, con) != 0;
2123 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2124 if (fail && errno != ENOTSUP)
2125 report_file_error ("Doing fsetfilecon", newname);
2127 freecon (con);
2129 #endif
2131 if (!NILP (keep_time))
2133 struct timespec atime = get_stat_atime (&st);
2134 struct timespec mtime = get_stat_mtime (&st);
2135 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2136 xsignal2 (Qfile_date_error,
2137 build_string ("Cannot set file date"), newname);
2140 if (emacs_close (ofd) < 0)
2141 report_file_error ("Write error", newname);
2143 emacs_close (ifd);
2145 #ifdef MSDOS
2146 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2147 and if it can't, it tells so. Otherwise, under MSDOS we usually
2148 get only the READ bit, which will make the copied file read-only,
2149 so it's better not to chmod at all. */
2150 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2151 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2152 #endif /* MSDOS */
2153 #endif /* not WINDOWSNT */
2155 /* Discard the unwind protects. */
2156 specpdl_ptr = specpdl + count;
2158 return Qnil;
2161 DEFUN ("make-directory-internal", Fmake_directory_internal,
2162 Smake_directory_internal, 1, 1, 0,
2163 doc: /* Create a new directory named DIRECTORY. */)
2164 (Lisp_Object directory)
2166 const char *dir;
2167 Lisp_Object handler;
2168 Lisp_Object encoded_dir;
2170 CHECK_STRING (directory);
2171 directory = Fexpand_file_name (directory, Qnil);
2173 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2174 if (!NILP (handler))
2175 return call2 (handler, Qmake_directory_internal, directory);
2177 encoded_dir = ENCODE_FILE (directory);
2179 dir = SSDATA (encoded_dir);
2181 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2182 report_file_error ("Creating directory", directory);
2184 return Qnil;
2187 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2188 Sdelete_directory_internal, 1, 1, 0,
2189 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2190 (Lisp_Object directory)
2192 const char *dir;
2193 Lisp_Object encoded_dir;
2195 CHECK_STRING (directory);
2196 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2197 encoded_dir = ENCODE_FILE (directory);
2198 dir = SSDATA (encoded_dir);
2200 if (rmdir (dir) != 0)
2201 report_file_error ("Removing directory", directory);
2203 return Qnil;
2206 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2207 "(list (read-file-name \
2208 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2209 \"Move file to trash: \" \"Delete file: \") \
2210 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2211 (null current-prefix-arg))",
2212 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2213 If file has multiple names, it continues to exist with the other names.
2214 TRASH non-nil means to trash the file instead of deleting, provided
2215 `delete-by-moving-to-trash' is non-nil.
2217 When called interactively, TRASH is t if no prefix argument is given.
2218 With a prefix argument, TRASH is nil. */)
2219 (Lisp_Object filename, Lisp_Object trash)
2221 Lisp_Object handler;
2222 Lisp_Object encoded_file;
2224 if (!NILP (Ffile_directory_p (filename))
2225 && NILP (Ffile_symlink_p (filename)))
2226 xsignal2 (Qfile_error,
2227 build_string ("Removing old name: is a directory"),
2228 filename);
2229 filename = Fexpand_file_name (filename, Qnil);
2231 handler = Ffind_file_name_handler (filename, Qdelete_file);
2232 if (!NILP (handler))
2233 return call3 (handler, Qdelete_file, filename, trash);
2235 if (delete_by_moving_to_trash && !NILP (trash))
2236 return call1 (Qmove_file_to_trash, filename);
2238 encoded_file = ENCODE_FILE (filename);
2240 if (unlink (SSDATA (encoded_file)) != 0 && errno != ENOENT)
2241 report_file_error ("Removing old name", filename);
2242 return Qnil;
2245 static Lisp_Object
2246 internal_delete_file_1 (Lisp_Object ignore)
2248 return Qt;
2251 /* Delete file FILENAME, returning true if successful.
2252 This ignores `delete-by-moving-to-trash'. */
2254 bool
2255 internal_delete_file (Lisp_Object filename)
2257 Lisp_Object tem;
2259 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2260 Qt, internal_delete_file_1);
2261 return NILP (tem);
2264 /* Filesystems are case-sensitive on all supported systems except
2265 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2266 case-insensitive on the first two, but they may or may not be
2267 case-insensitive on Cygwin and OS X. The following function
2268 attempts to provide a runtime test on those two systems. If the
2269 test is not conclusive, we assume case-insensitivity on Cygwin and
2270 case-sensitivity on Mac OS X.
2272 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2273 NFS-mounted Windows volumes, might be case-insensitive. Can we
2274 detect this? */
2276 static bool
2277 file_name_case_insensitive_p (const char *filename)
2279 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2280 those flags are available. As of this writing (2017-05-20),
2281 Cygwin is the only platform known to support the former (starting
2282 with Cygwin-2.6.1), and macOS is the only platform known to
2283 support the latter. */
2285 #ifdef _PC_CASE_INSENSITIVE
2286 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2287 if (res >= 0)
2288 return res > 0;
2289 #elif defined _PC_CASE_SENSITIVE
2290 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2291 if (res >= 0)
2292 return res == 0;
2293 #endif
2295 #if defined CYGWIN || defined DOS_NT
2296 return true;
2297 #else
2298 return false;
2299 #endif
2302 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2303 Sfile_name_case_insensitive_p, 1, 1, 0,
2304 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2305 The arg must be a string. */)
2306 (Lisp_Object filename)
2308 Lisp_Object handler;
2310 CHECK_STRING (filename);
2311 filename = Fexpand_file_name (filename, Qnil);
2313 /* If the file name has special constructs in it,
2314 call the corresponding file handler. */
2315 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2316 if (!NILP (handler))
2317 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2319 filename = ENCODE_FILE (filename);
2320 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2323 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2324 "fRename file: \nGRename %s to file: \np",
2325 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2326 If file has names other than FILE, it continues to have those names.
2327 Signal a `file-already-exists' error if a file NEWNAME already exists
2328 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2329 An integer third arg means request confirmation if NEWNAME already exists.
2330 This is what happens in interactive use with M-x. */)
2331 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2333 Lisp_Object handler;
2334 Lisp_Object encoded_file, encoded_newname, symlink_target;
2335 int dirp = -1;
2337 file = Fexpand_file_name (file, Qnil);
2339 /* If the filesystem is case-insensitive and the file names are
2340 identical but for case, treat it as a change-case request, and do
2341 not worry whether NEWNAME exists or whether it is a directory, as
2342 it is already another name for FILE. */
2343 bool case_only_rename = false;
2344 if (!NILP (Ffile_name_case_insensitive_p (file)))
2346 newname = Fexpand_file_name (newname, Qnil);
2347 case_only_rename = !NILP (Fstring_equal (Fdowncase (file),
2348 Fdowncase (newname)));
2351 if (!case_only_rename)
2352 newname = expand_cp_target (Fdirectory_file_name (file), newname);
2354 /* If the file name has special constructs in it,
2355 call the corresponding file handler. */
2356 handler = Ffind_file_name_handler (file, Qrename_file);
2357 if (NILP (handler))
2358 handler = Ffind_file_name_handler (newname, Qrename_file);
2359 if (!NILP (handler))
2360 return call4 (handler, Qrename_file,
2361 file, newname, ok_if_already_exists);
2363 encoded_file = ENCODE_FILE (file);
2364 encoded_newname = ENCODE_FILE (newname);
2366 bool plain_rename = (case_only_rename
2367 || (!NILP (ok_if_already_exists)
2368 && !INTEGERP (ok_if_already_exists)));
2369 int rename_errno;
2370 if (!plain_rename)
2372 if (renameat_noreplace (AT_FDCWD, SSDATA (encoded_file),
2373 AT_FDCWD, SSDATA (encoded_newname))
2374 == 0)
2375 return Qnil;
2377 rename_errno = errno;
2378 switch (rename_errno)
2380 case EEXIST: case EINVAL: case ENOSYS:
2381 barf_or_query_if_file_exists (newname, rename_errno == EEXIST,
2382 "rename to it",
2383 INTEGERP (ok_if_already_exists),
2384 false);
2385 plain_rename = true;
2386 break;
2390 if (plain_rename)
2392 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2393 return Qnil;
2394 rename_errno = errno;
2395 /* Don't prompt again. */
2396 ok_if_already_exists = Qt;
2398 else if (!NILP (ok_if_already_exists))
2399 ok_if_already_exists = Qt;
2401 if (rename_errno != EXDEV)
2402 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2404 symlink_target = Ffile_symlink_p (file);
2405 if (!NILP (symlink_target))
2406 Fmake_symbolic_link (symlink_target, newname, ok_if_already_exists);
2407 else
2409 if (dirp < 0)
2410 dirp = directory_like (file);
2411 if (dirp)
2412 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2413 else
2414 Fcopy_file (file, newname, ok_if_already_exists, Qt, Qt, Qt);
2417 ptrdiff_t count = SPECPDL_INDEX ();
2418 specbind (Qdelete_by_moving_to_trash, Qnil);
2419 if (dirp && NILP (symlink_target))
2420 call2 (Qdelete_directory, file, Qt);
2421 else
2422 Fdelete_file (file, Qnil);
2423 return unbind_to (count, Qnil);
2426 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2427 "fAdd name to file: \nGName to add to %s: \np",
2428 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2429 Signal a `file-already-exists' error if a file NEWNAME already exists
2430 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2431 An integer third arg means request confirmation if NEWNAME already exists.
2432 This is what happens in interactive use with M-x. */)
2433 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2435 Lisp_Object handler;
2436 Lisp_Object encoded_file, encoded_newname;
2438 file = Fexpand_file_name (file, Qnil);
2439 newname = expand_cp_target (file, newname);
2441 /* If the file name has special constructs in it,
2442 call the corresponding file handler. */
2443 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2444 if (!NILP (handler))
2445 return call4 (handler, Qadd_name_to_file, file,
2446 newname, ok_if_already_exists);
2448 /* If the new name has special constructs in it,
2449 call the corresponding file handler. */
2450 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2451 if (!NILP (handler))
2452 return call4 (handler, Qadd_name_to_file, file,
2453 newname, ok_if_already_exists);
2455 encoded_file = ENCODE_FILE (file);
2456 encoded_newname = ENCODE_FILE (newname);
2458 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2459 return Qnil;
2461 if (errno == EEXIST)
2463 if (NILP (ok_if_already_exists)
2464 || INTEGERP (ok_if_already_exists))
2465 barf_or_query_if_file_exists (newname, true, "make it a new name",
2466 INTEGERP (ok_if_already_exists), false);
2467 unlink (SSDATA (newname));
2468 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
2469 return Qnil;
2472 report_file_error ("Adding new name", list2 (file, newname));
2475 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2476 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2477 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2478 Both args must be strings.
2479 Signal a `file-already-exists' error if a file LINKNAME already exists
2480 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2481 An integer third arg means request confirmation if LINKNAME already exists.
2482 This happens for interactive use with M-x. */)
2483 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2485 Lisp_Object handler;
2486 Lisp_Object encoded_target, encoded_linkname;
2488 CHECK_STRING (target);
2489 /* If the link target has a ~, we must expand it to get
2490 a truly valid file name. Otherwise, do not expand;
2491 we want to permit links to relative file names. */
2492 if (SREF (target, 0) == '~')
2493 target = Fexpand_file_name (target, Qnil);
2495 linkname = expand_cp_target (target, linkname);
2497 /* If the file name has special constructs in it,
2498 call the corresponding file handler. */
2499 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2500 if (!NILP (handler))
2501 return call4 (handler, Qmake_symbolic_link, target,
2502 linkname, ok_if_already_exists);
2504 /* If the new link name has special constructs in it,
2505 call the corresponding file handler. */
2506 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2507 if (!NILP (handler))
2508 return call4 (handler, Qmake_symbolic_link, target,
2509 linkname, ok_if_already_exists);
2511 encoded_target = ENCODE_FILE (target);
2512 encoded_linkname = ENCODE_FILE (linkname);
2514 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2515 return Qnil;
2517 if (errno == ENOSYS)
2518 xsignal1 (Qfile_error,
2519 build_string ("Symbolic links are not supported"));
2521 if (errno == EEXIST)
2523 if (NILP (ok_if_already_exists)
2524 || INTEGERP (ok_if_already_exists))
2525 barf_or_query_if_file_exists (linkname, true, "make it a link",
2526 INTEGERP (ok_if_already_exists), false);
2527 unlink (SSDATA (encoded_linkname));
2528 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) == 0)
2529 return Qnil;
2532 report_file_error ("Making symbolic link", list2 (target, linkname));
2536 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2537 1, 1, 0,
2538 doc: /* Return t if file FILENAME specifies an absolute file name.
2539 On Unix, this is a name starting with a `/' or a `~'. */)
2540 (Lisp_Object filename)
2542 CHECK_STRING (filename);
2543 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2546 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2547 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2548 See also `file-readable-p' and `file-attributes'.
2549 This returns nil for a symlink to a nonexistent file.
2550 Use `file-symlink-p' to test for such links. */)
2551 (Lisp_Object filename)
2553 Lisp_Object absname;
2554 Lisp_Object handler;
2556 CHECK_STRING (filename);
2557 absname = Fexpand_file_name (filename, Qnil);
2559 /* If the file name has special constructs in it,
2560 call the corresponding file handler. */
2561 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2562 if (!NILP (handler))
2564 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2565 errno = 0;
2566 return result;
2569 absname = ENCODE_FILE (absname);
2571 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2574 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2575 doc: /* Return t if FILENAME can be executed by you.
2576 For a directory, this means you can access files in that directory.
2577 \(It is generally better to use `file-accessible-directory-p' for that
2578 purpose, though.) */)
2579 (Lisp_Object filename)
2581 Lisp_Object absname;
2582 Lisp_Object handler;
2584 CHECK_STRING (filename);
2585 absname = Fexpand_file_name (filename, Qnil);
2587 /* If the file name has special constructs in it,
2588 call the corresponding file handler. */
2589 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2590 if (!NILP (handler))
2591 return call2 (handler, Qfile_executable_p, absname);
2593 absname = ENCODE_FILE (absname);
2595 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2598 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2599 doc: /* Return t if file FILENAME exists and you can read it.
2600 See also `file-exists-p' and `file-attributes'. */)
2601 (Lisp_Object filename)
2603 Lisp_Object absname;
2604 Lisp_Object handler;
2606 CHECK_STRING (filename);
2607 absname = Fexpand_file_name (filename, Qnil);
2609 /* If the file name has special constructs in it,
2610 call the corresponding file handler. */
2611 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2612 if (!NILP (handler))
2613 return call2 (handler, Qfile_readable_p, absname);
2615 absname = ENCODE_FILE (absname);
2616 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2617 ? Qt : Qnil);
2620 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2621 doc: /* Return t if file FILENAME can be written or created by you. */)
2622 (Lisp_Object filename)
2624 Lisp_Object absname, dir, encoded;
2625 Lisp_Object handler;
2627 CHECK_STRING (filename);
2628 absname = Fexpand_file_name (filename, Qnil);
2630 /* If the file name has special constructs in it,
2631 call the corresponding file handler. */
2632 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2633 if (!NILP (handler))
2634 return call2 (handler, Qfile_writable_p, absname);
2636 encoded = ENCODE_FILE (absname);
2637 if (check_writable (SSDATA (encoded), W_OK))
2638 return Qt;
2639 if (errno != ENOENT)
2640 return Qnil;
2642 dir = Ffile_name_directory (absname);
2643 eassert (!NILP (dir));
2644 #ifdef MSDOS
2645 dir = Fdirectory_file_name (dir);
2646 #endif /* MSDOS */
2648 dir = ENCODE_FILE (dir);
2649 #ifdef WINDOWSNT
2650 /* The read-only attribute of the parent directory doesn't affect
2651 whether a file or directory can be created within it. Some day we
2652 should check ACLs though, which do affect this. */
2653 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2654 #else
2655 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2656 #endif
2659 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2660 doc: /* Access file FILENAME, and get an error if that does not work.
2661 The second argument STRING is prepended to the error message.
2662 If there is no error, returns nil. */)
2663 (Lisp_Object filename, Lisp_Object string)
2665 Lisp_Object handler, encoded_filename, absname;
2667 CHECK_STRING (filename);
2668 absname = Fexpand_file_name (filename, Qnil);
2670 CHECK_STRING (string);
2672 /* If the file name has special constructs in it,
2673 call the corresponding file handler. */
2674 handler = Ffind_file_name_handler (absname, Qaccess_file);
2675 if (!NILP (handler))
2676 return call3 (handler, Qaccess_file, absname, string);
2678 encoded_filename = ENCODE_FILE (absname);
2680 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2681 report_file_error (SSDATA (string), filename);
2683 return Qnil;
2686 /* Relative to directory FD, return the symbolic link value of FILENAME.
2687 On failure, return nil. */
2688 Lisp_Object
2689 emacs_readlinkat (int fd, char const *filename)
2691 static struct allocator const emacs_norealloc_allocator =
2692 { xmalloc, NULL, xfree, memory_full };
2693 Lisp_Object val;
2694 char readlink_buf[1024];
2695 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2696 &emacs_norealloc_allocator, readlinkat);
2697 if (!buf)
2698 return Qnil;
2700 val = build_unibyte_string (buf);
2701 if (buf[0] == '/' && strchr (buf, ':'))
2703 AUTO_STRING (slash_colon, "/:");
2704 val = concat2 (slash_colon, val);
2706 if (buf != readlink_buf)
2707 xfree (buf);
2708 val = DECODE_FILE (val);
2709 return val;
2712 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2713 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2714 The value is the link target, as a string.
2715 Otherwise it returns nil.
2717 This function does not check whether the link target exists. */)
2718 (Lisp_Object filename)
2720 Lisp_Object handler;
2722 CHECK_STRING (filename);
2723 filename = Fexpand_file_name (filename, Qnil);
2725 /* If the file name has special constructs in it,
2726 call the corresponding file handler. */
2727 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2728 if (!NILP (handler))
2729 return call2 (handler, Qfile_symlink_p, filename);
2731 filename = ENCODE_FILE (filename);
2733 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2736 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2737 doc: /* Return t if FILENAME names an existing directory.
2738 Symbolic links to directories count as directories.
2739 See `file-symlink-p' to distinguish symlinks. */)
2740 (Lisp_Object filename)
2742 Lisp_Object absname;
2743 Lisp_Object handler;
2745 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2747 /* If the file name has special constructs in it,
2748 call the corresponding file handler. */
2749 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2750 if (!NILP (handler))
2751 return call2 (handler, Qfile_directory_p, absname);
2753 absname = ENCODE_FILE (absname);
2755 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2758 /* Return true if FILE is a directory or a symlink to a directory. */
2759 bool
2760 file_directory_p (char const *file)
2762 #ifdef WINDOWSNT
2763 /* This is cheaper than 'stat'. */
2764 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2765 #else
2766 struct stat st;
2767 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2768 #endif
2771 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2772 Sfile_accessible_directory_p, 1, 1, 0,
2773 doc: /* Return t if FILENAME names a directory you can open.
2774 For the value to be t, FILENAME must specify the name of a directory
2775 as a file, and the directory must allow you to open files in it. In
2776 order to use a directory as a buffer's current directory, this
2777 predicate must return true. A directory name spec may be given
2778 instead; then the value is t if the directory so specified exists and
2779 really is a readable and searchable directory. */)
2780 (Lisp_Object filename)
2782 Lisp_Object absname;
2783 Lisp_Object handler;
2785 CHECK_STRING (filename);
2786 absname = Fexpand_file_name (filename, Qnil);
2788 /* If the file name has special constructs in it,
2789 call the corresponding file handler. */
2790 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2791 if (!NILP (handler))
2793 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2795 /* Set errno in case the handler failed. EACCES might be a lie
2796 (e.g., the directory might not exist, or be a regular file),
2797 but at least it does TRT in the "usual" case of an existing
2798 directory that is not accessible by the current user, and
2799 avoids reporting "Success" for a failed operation. Perhaps
2800 someday we can fix this in a better way, by improving
2801 file-accessible-directory-p's API; see Bug#25419. */
2802 if (!EQ (r, Qt))
2803 errno = EACCES;
2805 return r;
2808 absname = ENCODE_FILE (absname);
2809 return file_accessible_directory_p (absname) ? Qt : Qnil;
2812 /* If FILE is a searchable directory or a symlink to a
2813 searchable directory, return true. Otherwise return
2814 false and set errno to an error number. */
2815 bool
2816 file_accessible_directory_p (Lisp_Object file)
2818 #ifdef DOS_NT
2819 # ifdef WINDOWSNT
2820 /* We need a special-purpose test because (a) NTFS security data is
2821 not reflected in Posix-style mode bits, and (b) the trick with
2822 accessing "DIR/.", used below on Posix hosts, doesn't work on
2823 Windows, because "DIR/." is normalized to just "DIR" before
2824 hitting the disk. */
2825 return (SBYTES (file) == 0
2826 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2827 # else /* MSDOS */
2828 return file_directory_p (SSDATA (file));
2829 # endif /* MSDOS */
2830 #else /* !DOS_NT */
2831 /* On POSIXish platforms, use just one system call; this avoids a
2832 race and is typically faster. */
2833 const char *data = SSDATA (file);
2834 ptrdiff_t len = SBYTES (file);
2835 char const *dir;
2836 bool ok;
2837 int saved_errno;
2838 USE_SAFE_ALLOCA;
2840 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2841 There are three exceptions: "", "/", and "//". Leave "" alone,
2842 as it's invalid. Append only "." to the other two exceptions as
2843 "/" and "//" are distinct on some platforms, whereas "/", "///",
2844 "////", etc. are all equivalent. */
2845 if (! len)
2846 dir = data;
2847 else
2849 /* Just check for trailing '/' when deciding whether to append '/'.
2850 That's simpler than testing the two special cases "/" and "//",
2851 and it's a safe optimization here. */
2852 char *buf = SAFE_ALLOCA (len + 3);
2853 memcpy (buf, data, len);
2854 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2855 dir = buf;
2858 ok = check_existing (dir);
2859 saved_errno = errno;
2860 SAFE_FREE ();
2861 errno = saved_errno;
2862 return ok;
2863 #endif /* !DOS_NT */
2866 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2867 doc: /* Return t if FILENAME names a regular file.
2868 This is the sort of file that holds an ordinary stream of data bytes.
2869 Symbolic links to regular files count as regular files.
2870 See `file-symlink-p' to distinguish symlinks. */)
2871 (Lisp_Object filename)
2873 register Lisp_Object absname;
2874 struct stat st;
2875 Lisp_Object handler;
2877 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2879 /* If the file name has special constructs in it,
2880 call the corresponding file handler. */
2881 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2882 if (!NILP (handler))
2883 return call2 (handler, Qfile_regular_p, absname);
2885 absname = ENCODE_FILE (absname);
2887 #ifdef WINDOWSNT
2889 int result;
2890 Lisp_Object tem = Vw32_get_true_file_attributes;
2892 /* Tell stat to use expensive method to get accurate info. */
2893 Vw32_get_true_file_attributes = Qt;
2894 result = stat (SSDATA (absname), &st);
2895 Vw32_get_true_file_attributes = tem;
2897 if (result < 0)
2898 return Qnil;
2899 return S_ISREG (st.st_mode) ? Qt : Qnil;
2901 #else
2902 if (stat (SSDATA (absname), &st) < 0)
2903 return Qnil;
2904 return S_ISREG (st.st_mode) ? Qt : Qnil;
2905 #endif
2908 DEFUN ("file-selinux-context", Ffile_selinux_context,
2909 Sfile_selinux_context, 1, 1, 0,
2910 doc: /* Return SELinux context of file named FILENAME.
2911 The return value is a list (USER ROLE TYPE RANGE), where the list
2912 elements are strings naming the user, role, type, and range of the
2913 file's SELinux security context.
2915 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2916 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2917 (Lisp_Object filename)
2919 Lisp_Object absname;
2920 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2922 Lisp_Object handler;
2923 #if HAVE_LIBSELINUX
2924 security_context_t con;
2925 int conlength;
2926 context_t context;
2927 #endif
2929 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2931 /* If the file name has special constructs in it,
2932 call the corresponding file handler. */
2933 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2934 if (!NILP (handler))
2935 return call2 (handler, Qfile_selinux_context, absname);
2937 absname = ENCODE_FILE (absname);
2939 #if HAVE_LIBSELINUX
2940 if (is_selinux_enabled ())
2942 conlength = lgetfilecon (SSDATA (absname), &con);
2943 if (conlength > 0)
2945 context = context_new (con);
2946 if (context_user_get (context))
2947 user = build_string (context_user_get (context));
2948 if (context_role_get (context))
2949 role = build_string (context_role_get (context));
2950 if (context_type_get (context))
2951 type = build_string (context_type_get (context));
2952 if (context_range_get (context))
2953 range = build_string (context_range_get (context));
2954 context_free (context);
2955 freecon (con);
2958 #endif
2960 return list4 (user, role, type, range);
2963 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2964 Sset_file_selinux_context, 2, 2, 0,
2965 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2966 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2967 elements are strings naming the components of a SELinux context.
2969 Value is t if setting of SELinux context was successful, nil otherwise.
2971 This function does nothing and returns nil if SELinux is disabled,
2972 or if Emacs was not compiled with SELinux support. */)
2973 (Lisp_Object filename, Lisp_Object context)
2975 Lisp_Object absname;
2976 Lisp_Object handler;
2977 #if HAVE_LIBSELINUX
2978 Lisp_Object encoded_absname;
2979 Lisp_Object user = CAR_SAFE (context);
2980 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2981 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2982 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2983 security_context_t con;
2984 bool fail;
2985 int conlength;
2986 context_t parsed_con;
2987 #endif
2989 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2991 /* If the file name has special constructs in it,
2992 call the corresponding file handler. */
2993 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2994 if (!NILP (handler))
2995 return call3 (handler, Qset_file_selinux_context, absname, context);
2997 #if HAVE_LIBSELINUX
2998 if (is_selinux_enabled ())
3000 /* Get current file context. */
3001 encoded_absname = ENCODE_FILE (absname);
3002 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
3003 if (conlength > 0)
3005 parsed_con = context_new (con);
3006 /* Change the parts defined in the parameter.*/
3007 if (STRINGP (user))
3009 if (context_user_set (parsed_con, SSDATA (user)))
3010 error ("Doing context_user_set");
3012 if (STRINGP (role))
3014 if (context_role_set (parsed_con, SSDATA (role)))
3015 error ("Doing context_role_set");
3017 if (STRINGP (type))
3019 if (context_type_set (parsed_con, SSDATA (type)))
3020 error ("Doing context_type_set");
3022 if (STRINGP (range))
3024 if (context_range_set (parsed_con, SSDATA (range)))
3025 error ("Doing context_range_set");
3028 /* Set the modified context back to the file. */
3029 fail = (lsetfilecon (SSDATA (encoded_absname),
3030 context_str (parsed_con))
3031 != 0);
3032 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
3033 if (fail && errno != ENOTSUP)
3034 report_file_error ("Doing lsetfilecon", absname);
3036 context_free (parsed_con);
3037 freecon (con);
3038 return fail ? Qnil : Qt;
3040 else
3041 report_file_error ("Doing lgetfilecon", absname);
3043 #endif
3045 return Qnil;
3048 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
3049 doc: /* Return ACL entries of file named FILENAME.
3050 The entries are returned in a format suitable for use in `set-file-acl'
3051 but is otherwise undocumented and subject to change.
3052 Return nil if file does not exist or is not accessible, or if Emacs
3053 was unable to determine the ACL entries. */)
3054 (Lisp_Object filename)
3056 #if USE_ACL
3057 Lisp_Object absname;
3058 Lisp_Object handler;
3059 # ifdef HAVE_ACL_SET_FILE
3060 acl_t acl;
3061 Lisp_Object acl_string;
3062 char *str;
3063 # ifndef HAVE_ACL_TYPE_EXTENDED
3064 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
3065 # endif
3066 # endif
3068 absname = expand_and_dir_to_file (filename,
3069 BVAR (current_buffer, directory));
3071 /* If the file name has special constructs in it,
3072 call the corresponding file handler. */
3073 handler = Ffind_file_name_handler (absname, Qfile_acl);
3074 if (!NILP (handler))
3075 return call2 (handler, Qfile_acl, absname);
3077 # ifdef HAVE_ACL_SET_FILE
3078 absname = ENCODE_FILE (absname);
3080 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3081 if (acl == NULL)
3082 return Qnil;
3084 str = acl_to_text (acl, NULL);
3085 if (str == NULL)
3087 acl_free (acl);
3088 return Qnil;
3091 acl_string = build_string (str);
3092 acl_free (str);
3093 acl_free (acl);
3095 return acl_string;
3096 # endif
3097 #endif
3099 return Qnil;
3102 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3103 2, 2, 0,
3104 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3105 ACL-STRING should contain the textual representation of the ACL
3106 entries in a format suitable for the platform.
3108 Value is t if setting of ACL was successful, nil otherwise.
3110 Setting ACL for local files requires Emacs to be built with ACL
3111 support. */)
3112 (Lisp_Object filename, Lisp_Object acl_string)
3114 #if USE_ACL
3115 Lisp_Object absname;
3116 Lisp_Object handler;
3117 # ifdef HAVE_ACL_SET_FILE
3118 Lisp_Object encoded_absname;
3119 acl_t acl;
3120 bool fail;
3121 # endif
3123 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3125 /* If the file name has special constructs in it,
3126 call the corresponding file handler. */
3127 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3128 if (!NILP (handler))
3129 return call3 (handler, Qset_file_acl, absname, acl_string);
3131 # ifdef HAVE_ACL_SET_FILE
3132 if (STRINGP (acl_string))
3134 acl = acl_from_text (SSDATA (acl_string));
3135 if (acl == NULL)
3137 report_file_error ("Converting ACL", absname);
3138 return Qnil;
3141 encoded_absname = ENCODE_FILE (absname);
3143 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3144 acl)
3145 != 0);
3146 if (fail && acl_errno_valid (errno))
3147 report_file_error ("Setting ACL", absname);
3149 acl_free (acl);
3150 return fail ? Qnil : Qt;
3152 # endif
3153 #endif
3155 return Qnil;
3158 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3159 doc: /* Return mode bits of file named FILENAME, as an integer.
3160 Return nil, if file does not exist or is not accessible. */)
3161 (Lisp_Object filename)
3163 Lisp_Object absname;
3164 struct stat st;
3165 Lisp_Object handler;
3167 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3169 /* If the file name has special constructs in it,
3170 call the corresponding file handler. */
3171 handler = Ffind_file_name_handler (absname, Qfile_modes);
3172 if (!NILP (handler))
3173 return call2 (handler, Qfile_modes, absname);
3175 absname = ENCODE_FILE (absname);
3177 if (stat (SSDATA (absname), &st) < 0)
3178 return Qnil;
3180 return make_number (st.st_mode & 07777);
3183 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3184 "(let ((file (read-file-name \"File: \"))) \
3185 (list file (read-file-modes nil file)))",
3186 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3187 Only the 12 low bits of MODE are used.
3189 Interactively, mode bits are read by `read-file-modes', which accepts
3190 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3191 (Lisp_Object filename, Lisp_Object mode)
3193 Lisp_Object absname, encoded_absname;
3194 Lisp_Object handler;
3196 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3197 CHECK_NUMBER (mode);
3199 /* If the file name has special constructs in it,
3200 call the corresponding file handler. */
3201 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3202 if (!NILP (handler))
3203 return call3 (handler, Qset_file_modes, absname, mode);
3205 encoded_absname = ENCODE_FILE (absname);
3207 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3208 report_file_error ("Doing chmod", absname);
3210 return Qnil;
3213 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3214 doc: /* Set the file permission bits for newly created files.
3215 The argument MODE should be an integer; only the low 9 bits are used.
3216 This setting is inherited by subprocesses. */)
3217 (Lisp_Object mode)
3219 mode_t oldrealmask, oldumask, newumask;
3220 CHECK_NUMBER (mode);
3221 oldrealmask = realmask;
3222 newumask = ~ XINT (mode) & 0777;
3224 block_input ();
3225 realmask = newumask;
3226 oldumask = umask (newumask);
3227 unblock_input ();
3229 eassert (oldumask == oldrealmask);
3230 return Qnil;
3233 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3234 doc: /* Return the default file protection for created files.
3235 The value is an integer. */)
3236 (void)
3238 Lisp_Object value;
3239 XSETINT (value, (~ realmask) & 0777);
3240 return value;
3244 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3245 doc: /* Set times of file FILENAME to TIMESTAMP.
3246 Set both access and modification times.
3247 Return t on success, else nil.
3248 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3249 `current-time'. */)
3250 (Lisp_Object filename, Lisp_Object timestamp)
3252 Lisp_Object absname, encoded_absname;
3253 Lisp_Object handler;
3254 struct timespec t = lisp_time_argument (timestamp);
3256 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3258 /* If the file name has special constructs in it,
3259 call the corresponding file handler. */
3260 handler = Ffind_file_name_handler (absname, Qset_file_times);
3261 if (!NILP (handler))
3262 return call3 (handler, Qset_file_times, absname, timestamp);
3264 encoded_absname = ENCODE_FILE (absname);
3267 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3269 #ifdef MSDOS
3270 /* Setting times on a directory always fails. */
3271 if (file_directory_p (SSDATA (encoded_absname)))
3272 return Qnil;
3273 #endif
3274 report_file_error ("Setting file times", absname);
3278 return Qt;
3281 #ifdef HAVE_SYNC
3282 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3283 doc: /* Tell Unix to finish all pending disk updates. */)
3284 (void)
3286 sync ();
3287 return Qnil;
3290 #endif /* HAVE_SYNC */
3292 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3293 doc: /* Return t if file FILE1 is newer than file FILE2.
3294 If FILE1 does not exist, the answer is nil;
3295 otherwise, if FILE2 does not exist, the answer is t. */)
3296 (Lisp_Object file1, Lisp_Object file2)
3298 Lisp_Object absname1, absname2;
3299 struct stat st1, st2;
3300 Lisp_Object handler;
3302 CHECK_STRING (file1);
3303 CHECK_STRING (file2);
3305 absname1 = Qnil;
3306 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3307 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3309 /* If the file name has special constructs in it,
3310 call the corresponding file handler. */
3311 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3312 if (NILP (handler))
3313 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3314 if (!NILP (handler))
3315 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3317 absname1 = ENCODE_FILE (absname1);
3318 absname2 = ENCODE_FILE (absname2);
3320 if (stat (SSDATA (absname1), &st1) < 0)
3321 return Qnil;
3323 if (stat (SSDATA (absname2), &st2) < 0)
3324 return Qt;
3326 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3327 ? Qt : Qnil);
3330 enum { READ_BUF_SIZE = MAX_ALLOCA };
3332 /* This function is called after Lisp functions to decide a coding
3333 system are called, or when they cause an error. Before they are
3334 called, the current buffer is set unibyte and it contains only a
3335 newly inserted text (thus the buffer was empty before the
3336 insertion).
3338 The functions may set markers, overlays, text properties, or even
3339 alter the buffer contents, change the current buffer.
3341 Here, we reset all those changes by:
3342 o set back the current buffer.
3343 o move all markers and overlays to BEG.
3344 o remove all text properties.
3345 o set back the buffer multibyteness. */
3347 static void
3348 decide_coding_unwind (Lisp_Object unwind_data)
3350 Lisp_Object multibyte, undo_list, buffer;
3352 multibyte = XCAR (unwind_data);
3353 unwind_data = XCDR (unwind_data);
3354 undo_list = XCAR (unwind_data);
3355 buffer = XCDR (unwind_data);
3357 set_buffer_internal (XBUFFER (buffer));
3358 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3359 adjust_overlays_for_delete (BEG, Z - BEG);
3360 set_buffer_intervals (current_buffer, NULL);
3361 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3363 /* Now we are safe to change the buffer's multibyteness directly. */
3364 bset_enable_multibyte_characters (current_buffer, multibyte);
3365 bset_undo_list (current_buffer, undo_list);
3368 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3369 object where slot 0 is the file descriptor, slot 1 specifies
3370 an offset to put the read bytes, and slot 2 is the maximum
3371 amount of bytes to read. Value is the number of bytes read. */
3373 static Lisp_Object
3374 read_non_regular (Lisp_Object state)
3376 int nbytes = emacs_read_quit (XSAVE_INTEGER (state, 0),
3377 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3378 + XSAVE_INTEGER (state, 1)),
3379 XSAVE_INTEGER (state, 2));
3380 /* Fast recycle this object for the likely next call. */
3381 free_misc (state);
3382 return make_number (nbytes);
3386 /* Condition-case handler used when reading from non-regular files
3387 in insert-file-contents. */
3389 static Lisp_Object
3390 read_non_regular_quit (Lisp_Object ignore)
3392 return Qnil;
3395 /* Return the file offset that VAL represents, checking for type
3396 errors and overflow. */
3397 static off_t
3398 file_offset (Lisp_Object val)
3400 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3401 return XINT (val);
3403 if (FLOATP (val))
3405 double v = XFLOAT_DATA (val);
3406 if (0 <= v && v < 1.0 + TYPE_MAXIMUM (off_t))
3408 off_t o = v;
3409 if (o == v)
3410 return o;
3414 wrong_type_argument (intern ("file-offset"), val);
3417 /* Return a special time value indicating the error number ERRNUM. */
3418 static struct timespec
3419 time_error_value (int errnum)
3421 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3422 ? NONEXISTENT_MODTIME_NSECS
3423 : UNKNOWN_MODTIME_NSECS);
3424 return make_timespec (0, ns);
3427 static Lisp_Object
3428 get_window_points_and_markers (void)
3430 Lisp_Object pt_marker = Fpoint_marker ();
3431 Lisp_Object windows
3432 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3433 Lisp_Object window_markers = windows;
3434 /* Window markers (and point) are handled specially: rather than move to
3435 just before or just after the modified text, we try to keep the
3436 markers at the same distance (bug#19161).
3437 In general, this is wrong, but for window-markers, this should be harmless
3438 and is convenient for the end user when most of the file is unmodified,
3439 except for a few minor details near the beginning and near the end. */
3440 for (; CONSP (windows); windows = XCDR (windows))
3441 if (WINDOWP (XCAR (windows)))
3443 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3444 XSETCAR (windows,
3445 Fcons (window_marker, Fmarker_position (window_marker)));
3447 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3450 static void
3451 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3452 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3454 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3455 if (CONSP (XCAR (window_markers)))
3457 Lisp_Object car = XCAR (window_markers);
3458 Lisp_Object marker = XCAR (car);
3459 Lisp_Object oldpos = XCDR (car);
3460 if (MARKERP (marker) && INTEGERP (oldpos)
3461 && XINT (oldpos) > same_at_start
3462 && XINT (oldpos) < same_at_end)
3464 ptrdiff_t oldsize = same_at_end - same_at_start;
3465 ptrdiff_t newsize = inserted;
3466 double growth = newsize / (double)oldsize;
3467 ptrdiff_t newpos
3468 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3469 Fset_marker (marker, make_number (newpos), Qnil);
3474 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3475 text as a linear C char array. */
3476 static void
3477 maybe_move_gap (struct buffer *b)
3479 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3481 struct buffer *cb = current_buffer;
3483 set_buffer_internal (b);
3484 move_gap_both (Z, Z_BYTE);
3485 set_buffer_internal (cb);
3489 /* FIXME: insert-file-contents should be split with the top-level moved to
3490 Elisp and only the core kept in C. */
3492 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3493 1, 5, 0,
3494 doc: /* Insert contents of file FILENAME after point.
3495 Returns list of absolute file name and number of characters inserted.
3496 If second argument VISIT is non-nil, the buffer's visited filename and
3497 last save file modtime are set, and it is marked unmodified. If
3498 visiting and the file does not exist, visiting is completed before the
3499 error is signaled.
3501 The optional third and fourth arguments BEG and END specify what portion
3502 of the file to insert. These arguments count bytes in the file, not
3503 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3505 If optional fifth argument REPLACE is non-nil, replace the current
3506 buffer contents (in the accessible portion) with the file contents.
3507 This is better than simply deleting and inserting the whole thing
3508 because (1) it preserves some marker positions and (2) it puts less data
3509 in the undo list. When REPLACE is non-nil, the second return value is
3510 the number of characters that replace previous buffer contents.
3512 This function does code conversion according to the value of
3513 `coding-system-for-read' or `file-coding-system-alist', and sets the
3514 variable `last-coding-system-used' to the coding system actually used.
3516 In addition, this function decodes the inserted text from known formats
3517 by calling `format-decode', which see. */)
3518 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3520 struct stat st;
3521 struct timespec mtime;
3522 int fd;
3523 ptrdiff_t inserted = 0;
3524 ptrdiff_t how_much;
3525 off_t beg_offset, end_offset;
3526 int unprocessed;
3527 ptrdiff_t count = SPECPDL_INDEX ();
3528 Lisp_Object handler, val, insval, orig_filename, old_undo;
3529 Lisp_Object p;
3530 ptrdiff_t total = 0;
3531 bool not_regular = 0;
3532 int save_errno = 0;
3533 char read_buf[READ_BUF_SIZE];
3534 struct coding_system coding;
3535 bool replace_handled = false;
3536 bool set_coding_system = false;
3537 Lisp_Object coding_system;
3538 bool read_quit = false;
3539 /* If the undo log only contains the insertion, there's no point
3540 keeping it. It's typically when we first fill a file-buffer. */
3541 bool empty_undo_list_p
3542 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3543 && BEG == Z);
3544 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3545 bool we_locked_file = false;
3546 ptrdiff_t fd_index;
3547 Lisp_Object window_markers = Qnil;
3548 /* same_at_start and same_at_end count bytes, because file access counts
3549 bytes and BEG and END count bytes. */
3550 ptrdiff_t same_at_start = BEGV_BYTE;
3551 ptrdiff_t same_at_end = ZV_BYTE;
3552 /* SAME_AT_END_CHARPOS counts characters, because
3553 restore_window_points needs the old character count. */
3554 ptrdiff_t same_at_end_charpos = ZV;
3556 if (current_buffer->base_buffer && ! NILP (visit))
3557 error ("Cannot do file visiting in an indirect buffer");
3559 if (!NILP (BVAR (current_buffer, read_only)))
3560 Fbarf_if_buffer_read_only (Qnil);
3562 val = Qnil;
3563 p = Qnil;
3564 orig_filename = Qnil;
3565 old_undo = Qnil;
3567 CHECK_STRING (filename);
3568 filename = Fexpand_file_name (filename, Qnil);
3570 /* The value Qnil means that the coding system is not yet
3571 decided. */
3572 coding_system = Qnil;
3574 /* If the file name has special constructs in it,
3575 call the corresponding file handler. */
3576 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3577 if (!NILP (handler))
3579 val = call6 (handler, Qinsert_file_contents, filename,
3580 visit, beg, end, replace);
3581 if (CONSP (val) && CONSP (XCDR (val))
3582 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3583 inserted = XINT (XCAR (XCDR (val)));
3584 goto handled;
3587 orig_filename = filename;
3588 filename = ENCODE_FILE (filename);
3590 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3591 if (fd < 0)
3593 save_errno = errno;
3594 if (NILP (visit))
3595 report_file_error ("Opening input file", orig_filename);
3596 mtime = time_error_value (save_errno);
3597 st.st_size = -1;
3598 if (!NILP (Vcoding_system_for_read))
3600 /* Don't let invalid values into buffer-file-coding-system. */
3601 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3602 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3604 goto notfound;
3607 fd_index = SPECPDL_INDEX ();
3608 record_unwind_protect_int (close_file_unwind, fd);
3610 /* Replacement should preserve point as it preserves markers. */
3611 if (!NILP (replace))
3613 window_markers = get_window_points_and_markers ();
3614 record_unwind_protect (restore_point_unwind,
3615 XCAR (XCAR (window_markers)));
3618 if (fstat (fd, &st) != 0)
3619 report_file_error ("Input file status", orig_filename);
3620 mtime = get_stat_mtime (&st);
3622 /* This code will need to be changed in order to work on named
3623 pipes, and it's probably just not worth it. So we should at
3624 least signal an error. */
3625 if (!S_ISREG (st.st_mode))
3627 not_regular = 1;
3629 if (! NILP (visit))
3630 goto notfound;
3632 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3633 xsignal2 (Qfile_error,
3634 build_string ("not a regular file"), orig_filename);
3637 if (!NILP (visit))
3639 if (!NILP (beg) || !NILP (end))
3640 error ("Attempt to visit less than an entire file");
3641 if (BEG < Z && NILP (replace))
3642 error ("Cannot do file visiting in a non-empty buffer");
3645 if (!NILP (beg))
3646 beg_offset = file_offset (beg);
3647 else
3648 beg_offset = 0;
3650 if (!NILP (end))
3651 end_offset = file_offset (end);
3652 else
3654 if (not_regular)
3655 end_offset = TYPE_MAXIMUM (off_t);
3656 else
3658 end_offset = st.st_size;
3660 /* A negative size can happen on a platform that allows file
3661 sizes greater than the maximum off_t value. */
3662 if (end_offset < 0)
3663 buffer_overflow ();
3665 /* The file size returned from stat may be zero, but data
3666 may be readable nonetheless, for example when this is a
3667 file in the /proc filesystem. */
3668 if (end_offset == 0)
3669 end_offset = READ_BUF_SIZE;
3673 /* Check now whether the buffer will become too large,
3674 in the likely case where the file's length is not changing.
3675 This saves a lot of needless work before a buffer overflow. */
3676 if (! not_regular)
3678 /* The likely offset where we will stop reading. We could read
3679 more (or less), if the file grows (or shrinks) as we read it. */
3680 off_t likely_end = min (end_offset, st.st_size);
3682 if (beg_offset < likely_end)
3684 ptrdiff_t buf_bytes
3685 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3686 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3687 off_t likely_growth = likely_end - beg_offset;
3688 if (buf_growth_max < likely_growth)
3689 buffer_overflow ();
3693 /* Prevent redisplay optimizations. */
3694 current_buffer->clip_changed = true;
3696 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3698 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3699 setup_coding_system (coding_system, &coding);
3700 /* Ensure we set Vlast_coding_system_used. */
3701 set_coding_system = true;
3703 else if (BEG < Z)
3705 /* Decide the coding system to use for reading the file now
3706 because we can't use an optimized method for handling
3707 `coding:' tag if the current buffer is not empty. */
3708 if (!NILP (Vcoding_system_for_read))
3709 coding_system = Vcoding_system_for_read;
3710 else
3712 /* Don't try looking inside a file for a coding system
3713 specification if it is not seekable. */
3714 if (! not_regular && ! NILP (Vset_auto_coding_function))
3716 /* Find a coding system specified in the heading two
3717 lines or in the tailing several lines of the file.
3718 We assume that the 1K-byte and 3K-byte for heading
3719 and tailing respectively are sufficient for this
3720 purpose. */
3721 int nread;
3723 if (st.st_size <= (1024 * 4))
3724 nread = emacs_read_quit (fd, read_buf, 1024 * 4);
3725 else
3727 nread = emacs_read_quit (fd, read_buf, 1024);
3728 if (nread == 1024)
3730 int ntail;
3731 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3732 report_file_error ("Setting file position",
3733 orig_filename);
3734 ntail = emacs_read_quit (fd, read_buf + nread, 1024 * 3);
3735 nread = ntail < 0 ? ntail : nread + ntail;
3739 if (nread < 0)
3740 report_file_error ("Read error", orig_filename);
3741 else if (nread > 0)
3743 AUTO_STRING (name, " *code-converting-work*");
3744 struct buffer *prev = current_buffer;
3745 Lisp_Object workbuf;
3746 struct buffer *buf;
3748 record_unwind_current_buffer ();
3750 workbuf = Fget_buffer_create (name);
3751 buf = XBUFFER (workbuf);
3753 delete_all_overlays (buf);
3754 bset_directory (buf, BVAR (current_buffer, directory));
3755 bset_read_only (buf, Qnil);
3756 bset_filename (buf, Qnil);
3757 bset_undo_list (buf, Qt);
3758 eassert (buf->overlays_before == NULL);
3759 eassert (buf->overlays_after == NULL);
3761 set_buffer_internal (buf);
3762 Ferase_buffer ();
3763 bset_enable_multibyte_characters (buf, Qnil);
3765 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3766 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3767 coding_system = call2 (Vset_auto_coding_function,
3768 filename, make_number (nread));
3769 set_buffer_internal (prev);
3771 /* Discard the unwind protect for recovering the
3772 current buffer. */
3773 specpdl_ptr--;
3775 /* Rewind the file for the actual read done later. */
3776 if (lseek (fd, 0, SEEK_SET) < 0)
3777 report_file_error ("Setting file position", orig_filename);
3781 if (NILP (coding_system))
3783 /* If we have not yet decided a coding system, check
3784 file-coding-system-alist. */
3785 coding_system = CALLN (Ffind_operation_coding_system,
3786 Qinsert_file_contents, orig_filename,
3787 visit, beg, end, replace);
3788 if (CONSP (coding_system))
3789 coding_system = XCAR (coding_system);
3793 if (NILP (coding_system))
3794 coding_system = Qundecided;
3795 else
3796 CHECK_CODING_SYSTEM (coding_system);
3798 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3799 /* We must suppress all character code conversion except for
3800 end-of-line conversion. */
3801 coding_system = raw_text_coding_system (coding_system);
3803 setup_coding_system (coding_system, &coding);
3804 /* Ensure we set Vlast_coding_system_used. */
3805 set_coding_system = true;
3808 /* If requested, replace the accessible part of the buffer
3809 with the file contents. Avoid replacing text at the
3810 beginning or end of the buffer that matches the file contents;
3811 that preserves markers pointing to the unchanged parts.
3813 Here we implement this feature in an optimized way
3814 for the case where code conversion is NOT needed.
3815 The following if-statement handles the case of conversion
3816 in a less optimal way.
3818 If the code conversion is "automatic" then we try using this
3819 method and hope for the best.
3820 But if we discover the need for conversion, we give up on this method
3821 and let the following if-statement handle the replace job. */
3822 if (!NILP (replace)
3823 && BEGV < ZV
3824 && (NILP (coding_system)
3825 || ! CODING_REQUIRE_DECODING (&coding)))
3827 ptrdiff_t overlap;
3828 /* There is still a possibility we will find the need to do code
3829 conversion. If that happens, set this variable to
3830 give up on handling REPLACE in the optimized way. */
3831 bool giveup_match_end = false;
3833 if (beg_offset != 0)
3835 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3836 report_file_error ("Setting file position", orig_filename);
3839 /* Count how many chars at the start of the file
3840 match the text at the beginning of the buffer. */
3841 while (true)
3843 int nread = emacs_read_quit (fd, read_buf, sizeof read_buf);
3844 if (nread < 0)
3845 report_file_error ("Read error", orig_filename);
3846 else if (nread == 0)
3847 break;
3849 if (CODING_REQUIRE_DETECTION (&coding))
3851 coding_system = detect_coding_system ((unsigned char *) read_buf,
3852 nread, nread, 1, 0,
3853 coding_system);
3854 setup_coding_system (coding_system, &coding);
3857 if (CODING_REQUIRE_DECODING (&coding))
3858 /* We found that the file should be decoded somehow.
3859 Let's give up here. */
3861 giveup_match_end = true;
3862 break;
3865 int bufpos = 0;
3866 while (bufpos < nread && same_at_start < ZV_BYTE
3867 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3868 same_at_start++, bufpos++;
3869 /* If we found a discrepancy, stop the scan.
3870 Otherwise loop around and scan the next bufferful. */
3871 if (bufpos != nread)
3872 break;
3874 /* If the file matches the buffer completely,
3875 there's no need to replace anything. */
3876 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3878 emacs_close (fd);
3879 clear_unwind_protect (fd_index);
3881 /* Truncate the buffer to the size of the file. */
3882 del_range_1 (same_at_start, same_at_end, 0, 0);
3883 goto handled;
3886 /* Count how many chars at the end of the file
3887 match the text at the end of the buffer. But, if we have
3888 already found that decoding is necessary, don't waste time. */
3889 while (!giveup_match_end)
3891 int total_read, nread, bufpos, trial;
3892 off_t curpos;
3894 /* At what file position are we now scanning? */
3895 curpos = end_offset - (ZV_BYTE - same_at_end);
3896 /* If the entire file matches the buffer tail, stop the scan. */
3897 if (curpos == 0)
3898 break;
3899 /* How much can we scan in the next step? */
3900 trial = min (curpos, sizeof read_buf);
3901 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3902 report_file_error ("Setting file position", orig_filename);
3904 total_read = nread = 0;
3905 while (total_read < trial)
3907 nread = emacs_read_quit (fd, read_buf + total_read,
3908 trial - total_read);
3909 if (nread < 0)
3910 report_file_error ("Read error", orig_filename);
3911 else if (nread == 0)
3912 break;
3913 total_read += nread;
3916 /* Scan this bufferful from the end, comparing with
3917 the Emacs buffer. */
3918 bufpos = total_read;
3920 /* Compare with same_at_start to avoid counting some buffer text
3921 as matching both at the file's beginning and at the end. */
3922 while (bufpos > 0 && same_at_end > same_at_start
3923 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3924 same_at_end--, bufpos--;
3926 /* If we found a discrepancy, stop the scan.
3927 Otherwise loop around and scan the preceding bufferful. */
3928 if (bufpos != 0)
3930 /* If this discrepancy is because of code conversion,
3931 we cannot use this method; giveup and try the other. */
3932 if (same_at_end > same_at_start
3933 && FETCH_BYTE (same_at_end - 1) >= 0200
3934 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3935 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3936 giveup_match_end = true;
3937 break;
3940 if (nread == 0)
3941 break;
3944 if (! giveup_match_end)
3946 ptrdiff_t temp;
3947 ptrdiff_t this_count = SPECPDL_INDEX ();
3949 /* We win! We can handle REPLACE the optimized way. */
3951 /* Extend the start of non-matching text area to multibyte
3952 character boundary. */
3953 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3954 while (same_at_start > BEGV_BYTE
3955 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3956 same_at_start--;
3958 /* Extend the end of non-matching text area to multibyte
3959 character boundary. */
3960 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3961 while (same_at_end < ZV_BYTE
3962 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3963 same_at_end++;
3965 /* Don't try to reuse the same piece of text twice. */
3966 overlap = (same_at_start - BEGV_BYTE
3967 - (same_at_end
3968 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3969 if (overlap > 0)
3970 same_at_end += overlap;
3971 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3973 /* Arrange to read only the nonmatching middle part of the file. */
3974 beg_offset += same_at_start - BEGV_BYTE;
3975 end_offset -= ZV_BYTE - same_at_end;
3977 /* This binding is to avoid ask-user-about-supersession-threat
3978 being called in insert_from_buffer or del_range_bytes (via
3979 prepare_to_modify_buffer).
3980 AFAICT we could avoid ask-user-about-supersession-threat by setting
3981 current_buffer->modtime earlier, but we could still end up calling
3982 ask-user-about-supersession-threat if the file is modified while
3983 we read it, so we bind buffer-file-name instead. */
3984 specbind (intern ("buffer-file-name"), Qnil);
3985 del_range_byte (same_at_start, same_at_end);
3986 /* Insert from the file at the proper position. */
3987 temp = BYTE_TO_CHAR (same_at_start);
3988 SET_PT_BOTH (temp, same_at_start);
3989 unbind_to (this_count, Qnil);
3991 /* If display currently starts at beginning of line,
3992 keep it that way. */
3993 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3994 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3996 replace_handled = true;
4000 /* If requested, replace the accessible part of the buffer
4001 with the file contents. Avoid replacing text at the
4002 beginning or end of the buffer that matches the file contents;
4003 that preserves markers pointing to the unchanged parts.
4005 Here we implement this feature for the case where code conversion
4006 is needed, in a simple way that needs a lot of memory.
4007 The preceding if-statement handles the case of no conversion
4008 in a more optimized way. */
4009 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
4011 ptrdiff_t same_at_start_charpos;
4012 ptrdiff_t inserted_chars;
4013 ptrdiff_t overlap;
4014 ptrdiff_t bufpos;
4015 unsigned char *decoded;
4016 ptrdiff_t temp;
4017 ptrdiff_t this = 0;
4018 ptrdiff_t this_count = SPECPDL_INDEX ();
4019 bool multibyte
4020 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4021 Lisp_Object conversion_buffer;
4023 conversion_buffer = code_conversion_save (1, multibyte);
4025 /* First read the whole file, performing code conversion into
4026 CONVERSION_BUFFER. */
4028 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4029 report_file_error ("Setting file position", orig_filename);
4031 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
4032 unprocessed = 0; /* Bytes not processed in previous loop. */
4034 while (true)
4036 /* Read at most READ_BUF_SIZE bytes at a time, to allow
4037 quitting while reading a huge file. */
4039 this = emacs_read_quit (fd, read_buf + unprocessed,
4040 READ_BUF_SIZE - unprocessed);
4041 if (this <= 0)
4042 break;
4044 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
4045 BUF_Z (XBUFFER (conversion_buffer)));
4046 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4047 unprocessed + this, conversion_buffer);
4048 unprocessed = coding.carryover_bytes;
4049 if (coding.carryover_bytes > 0)
4050 memcpy (read_buf, coding.carryover, unprocessed);
4053 if (this < 0)
4054 report_file_error ("Read error", orig_filename);
4055 emacs_close (fd);
4056 clear_unwind_protect (fd_index);
4058 if (unprocessed > 0)
4060 coding.mode |= CODING_MODE_LAST_BLOCK;
4061 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4062 unprocessed, conversion_buffer);
4063 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4066 coding_system = CODING_ID_NAME (coding.id);
4067 set_coding_system = true;
4068 maybe_move_gap (XBUFFER (conversion_buffer));
4069 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
4070 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4071 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4073 /* Compare the beginning of the converted string with the buffer
4074 text. */
4076 bufpos = 0;
4077 while (bufpos < inserted && same_at_start < same_at_end
4078 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4079 same_at_start++, bufpos++;
4081 /* If the file matches the head of buffer completely,
4082 there's no need to replace anything. */
4084 if (bufpos == inserted)
4086 /* Truncate the buffer to the size of the file. */
4087 if (same_at_start != same_at_end)
4089 /* See previous specbind for the reason behind this. */
4090 specbind (intern ("buffer-file-name"), Qnil);
4091 del_range_byte (same_at_start, same_at_end);
4093 inserted = 0;
4095 unbind_to (this_count, Qnil);
4096 goto handled;
4099 /* Extend the start of non-matching text area to the previous
4100 multibyte character boundary. */
4101 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4102 while (same_at_start > BEGV_BYTE
4103 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4104 same_at_start--;
4106 /* Scan this bufferful from the end, comparing with
4107 the Emacs buffer. */
4108 bufpos = inserted;
4110 /* Compare with same_at_start to avoid counting some buffer text
4111 as matching both at the file's beginning and at the end. */
4112 while (bufpos > 0 && same_at_end > same_at_start
4113 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4114 same_at_end--, bufpos--;
4116 /* Extend the end of non-matching text area to the next
4117 multibyte character boundary. */
4118 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4119 while (same_at_end < ZV_BYTE
4120 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4121 same_at_end++;
4123 /* Don't try to reuse the same piece of text twice. */
4124 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4125 if (overlap > 0)
4126 same_at_end += overlap;
4127 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4129 /* If display currently starts at beginning of line,
4130 keep it that way. */
4131 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4132 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4134 /* Replace the chars that we need to replace,
4135 and update INSERTED to equal the number of bytes
4136 we are taking from the decoded string. */
4137 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4139 /* See previous specbind for the reason behind this. */
4140 specbind (intern ("buffer-file-name"), Qnil);
4141 if (same_at_end != same_at_start)
4143 del_range_byte (same_at_start, same_at_end);
4144 temp = GPT;
4145 eassert (same_at_start == GPT_BYTE);
4146 same_at_start = GPT_BYTE;
4148 else
4150 temp = same_at_end_charpos;
4152 /* Insert from the file at the proper position. */
4153 SET_PT_BOTH (temp, same_at_start);
4154 same_at_start_charpos
4155 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4156 same_at_start - BEGV_BYTE
4157 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4158 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4159 inserted_chars
4160 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4161 same_at_start + inserted - BEGV_BYTE
4162 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4163 - same_at_start_charpos);
4164 insert_from_buffer (XBUFFER (conversion_buffer),
4165 same_at_start_charpos, inserted_chars, 0);
4166 /* Set `inserted' to the number of inserted characters. */
4167 inserted = PT - temp;
4168 /* Set point before the inserted characters. */
4169 SET_PT_BOTH (temp, same_at_start);
4171 unbind_to (this_count, Qnil);
4173 goto handled;
4176 if (! not_regular)
4177 total = end_offset - beg_offset;
4178 else
4179 /* For a special file, all we can do is guess. */
4180 total = READ_BUF_SIZE;
4182 if (NILP (visit) && total > 0)
4184 if (!NILP (BVAR (current_buffer, file_truename))
4185 /* Make binding buffer-file-name to nil effective. */
4186 && !NILP (BVAR (current_buffer, filename))
4187 && SAVE_MODIFF >= MODIFF)
4188 we_locked_file = true;
4189 prepare_to_modify_buffer (PT, PT, NULL);
4192 move_gap_both (PT, PT_BYTE);
4193 if (GAP_SIZE < total)
4194 make_gap (total - GAP_SIZE);
4196 if (beg_offset != 0 || !NILP (replace))
4198 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4199 report_file_error ("Setting file position", orig_filename);
4202 /* In the following loop, HOW_MUCH contains the total bytes read so
4203 far for a regular file, and not changed for a special file. But,
4204 before exiting the loop, it is set to a negative value if I/O
4205 error occurs. */
4206 how_much = 0;
4208 /* Total bytes inserted. */
4209 inserted = 0;
4211 /* Here, we don't do code conversion in the loop. It is done by
4212 decode_coding_gap after all data are read into the buffer. */
4214 ptrdiff_t gap_size = GAP_SIZE;
4216 while (how_much < total)
4218 /* `try' is reserved in some compilers (Microsoft C). */
4219 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4220 ptrdiff_t this;
4222 if (not_regular)
4224 Lisp_Object nbytes;
4226 /* Maybe make more room. */
4227 if (gap_size < trytry)
4229 make_gap (trytry - gap_size);
4230 gap_size = GAP_SIZE - inserted;
4233 /* Read from the file, capturing `quit'. When an
4234 error occurs, end the loop, and arrange for a quit
4235 to be signaled after decoding the text we read. */
4236 nbytes = internal_condition_case_1
4237 (read_non_regular,
4238 make_save_int_int_int (fd, inserted, trytry),
4239 Qerror, read_non_regular_quit);
4241 if (NILP (nbytes))
4243 read_quit = true;
4244 break;
4247 this = XINT (nbytes);
4249 else
4251 /* Allow quitting out of the actual I/O. We don't make text
4252 part of the buffer until all the reading is done, so a C-g
4253 here doesn't do any harm. */
4254 this = emacs_read_quit (fd,
4255 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4256 + inserted),
4257 trytry);
4260 if (this <= 0)
4262 how_much = this;
4263 break;
4266 gap_size -= this;
4268 /* For a regular file, where TOTAL is the real size,
4269 count HOW_MUCH to compare with it.
4270 For a special file, where TOTAL is just a buffer size,
4271 so don't bother counting in HOW_MUCH.
4272 (INSERTED is where we count the number of characters inserted.) */
4273 if (! not_regular)
4274 how_much += this;
4275 inserted += this;
4279 /* Now we have either read all the file data into the gap,
4280 or stop reading on I/O error or quit. If nothing was
4281 read, undo marking the buffer modified. */
4283 if (inserted == 0)
4285 if (we_locked_file)
4286 unlock_file (BVAR (current_buffer, file_truename));
4287 Vdeactivate_mark = old_Vdeactivate_mark;
4289 else
4290 Fset (Qdeactivate_mark, Qt);
4292 emacs_close (fd);
4293 clear_unwind_protect (fd_index);
4295 if (how_much < 0)
4296 report_file_error ("Read error", orig_filename);
4298 /* Make the text read part of the buffer. */
4299 GAP_SIZE -= inserted;
4300 GPT += inserted;
4301 GPT_BYTE += inserted;
4302 ZV += inserted;
4303 ZV_BYTE += inserted;
4304 Z += inserted;
4305 Z_BYTE += inserted;
4307 if (GAP_SIZE > 0)
4308 /* Put an anchor to ensure multi-byte form ends at gap. */
4309 *GPT_ADDR = 0;
4311 notfound:
4313 if (NILP (coding_system))
4315 /* The coding system is not yet decided. Decide it by an
4316 optimized method for handling `coding:' tag.
4318 Note that we can get here only if the buffer was empty
4319 before the insertion. */
4321 if (!NILP (Vcoding_system_for_read))
4322 coding_system = Vcoding_system_for_read;
4323 else
4325 /* Since we are sure that the current buffer was empty
4326 before the insertion, we can toggle
4327 enable-multibyte-characters directly here without taking
4328 care of marker adjustment. By this way, we can run Lisp
4329 program safely before decoding the inserted text. */
4330 Lisp_Object unwind_data;
4331 ptrdiff_t count1 = SPECPDL_INDEX ();
4333 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4334 Fcons (BVAR (current_buffer, undo_list),
4335 Fcurrent_buffer ()));
4336 bset_enable_multibyte_characters (current_buffer, Qnil);
4337 bset_undo_list (current_buffer, Qt);
4338 record_unwind_protect (decide_coding_unwind, unwind_data);
4340 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4342 coding_system = call2 (Vset_auto_coding_function,
4343 filename, make_number (inserted));
4346 if (NILP (coding_system))
4348 /* If the coding system is not yet decided, check
4349 file-coding-system-alist. */
4350 coding_system = CALLN (Ffind_operation_coding_system,
4351 Qinsert_file_contents, orig_filename,
4352 visit, beg, end, Qnil);
4353 if (CONSP (coding_system))
4354 coding_system = XCAR (coding_system);
4356 unbind_to (count1, Qnil);
4357 inserted = Z_BYTE - BEG_BYTE;
4360 if (NILP (coding_system))
4361 coding_system = Qundecided;
4362 else
4363 CHECK_CODING_SYSTEM (coding_system);
4365 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4366 /* We must suppress all character code conversion except for
4367 end-of-line conversion. */
4368 coding_system = raw_text_coding_system (coding_system);
4369 setup_coding_system (coding_system, &coding);
4370 /* Ensure we set Vlast_coding_system_used. */
4371 set_coding_system = true;
4374 if (!NILP (visit))
4376 /* When we visit a file by raw-text, we change the buffer to
4377 unibyte. */
4378 if (CODING_FOR_UNIBYTE (&coding)
4379 /* Can't do this if part of the buffer might be preserved. */
4380 && NILP (replace))
4382 /* Visiting a file with these coding system makes the buffer
4383 unibyte. */
4384 if (inserted > 0)
4385 bset_enable_multibyte_characters (current_buffer, Qnil);
4386 else
4387 Fset_buffer_multibyte (Qnil);
4391 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4392 if (CODING_MAY_REQUIRE_DECODING (&coding)
4393 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4395 move_gap_both (PT, PT_BYTE);
4396 GAP_SIZE += inserted;
4397 ZV_BYTE -= inserted;
4398 Z_BYTE -= inserted;
4399 ZV -= inserted;
4400 Z -= inserted;
4401 decode_coding_gap (&coding, inserted, inserted);
4402 inserted = coding.produced_char;
4403 coding_system = CODING_ID_NAME (coding.id);
4405 else if (inserted > 0)
4407 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4408 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4409 inserted);
4412 /* Call after-change hooks for the inserted text, aside from the case
4413 of normal visiting (not with REPLACE), which is done in a new buffer
4414 "before" the buffer is changed. */
4415 if (inserted > 0 && total > 0
4416 && (NILP (visit) || !NILP (replace)))
4418 signal_after_change (PT, 0, inserted);
4419 update_compositions (PT, PT, CHECK_BORDER);
4422 /* Now INSERTED is measured in characters. */
4424 handled:
4426 if (inserted > 0)
4427 restore_window_points (window_markers, inserted,
4428 BYTE_TO_CHAR (same_at_start),
4429 same_at_end_charpos);
4431 if (!NILP (visit))
4433 if (empty_undo_list_p)
4434 bset_undo_list (current_buffer, Qnil);
4436 if (NILP (handler))
4438 current_buffer->modtime = mtime;
4439 current_buffer->modtime_size = st.st_size;
4440 bset_filename (current_buffer, orig_filename);
4443 SAVE_MODIFF = MODIFF;
4444 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4445 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4446 if (NILP (handler))
4448 if (!NILP (BVAR (current_buffer, file_truename)))
4449 unlock_file (BVAR (current_buffer, file_truename));
4450 unlock_file (filename);
4452 if (not_regular)
4453 xsignal2 (Qfile_error,
4454 build_string ("not a regular file"), orig_filename);
4457 if (set_coding_system)
4458 Vlast_coding_system_used = coding_system;
4460 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4462 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4463 visit);
4464 if (! NILP (insval))
4466 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4467 wrong_type_argument (intern ("inserted-chars"), insval);
4468 inserted = XFASTINT (insval);
4472 /* Decode file format. */
4473 if (inserted > 0)
4475 /* Don't run point motion or modification hooks when decoding. */
4476 ptrdiff_t count1 = SPECPDL_INDEX ();
4477 ptrdiff_t old_inserted = inserted;
4478 specbind (Qinhibit_point_motion_hooks, Qt);
4479 specbind (Qinhibit_modification_hooks, Qt);
4481 /* Save old undo list and don't record undo for decoding. */
4482 old_undo = BVAR (current_buffer, undo_list);
4483 bset_undo_list (current_buffer, Qt);
4485 if (NILP (replace))
4487 insval = call3 (Qformat_decode,
4488 Qnil, make_number (inserted), visit);
4489 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4490 wrong_type_argument (intern ("inserted-chars"), insval);
4491 inserted = XFASTINT (insval);
4493 else
4495 /* If REPLACE is non-nil and we succeeded in not replacing the
4496 beginning or end of the buffer text with the file's contents,
4497 call format-decode with `point' positioned at the beginning
4498 of the buffer and `inserted' equaling the number of
4499 characters in the buffer. Otherwise, format-decode might
4500 fail to correctly analyze the beginning or end of the buffer.
4501 Hence we temporarily save `point' and `inserted' here and
4502 restore `point' iff format-decode did not insert or delete
4503 any text. Otherwise we leave `point' at point-min. */
4504 ptrdiff_t opoint = PT;
4505 ptrdiff_t opoint_byte = PT_BYTE;
4506 ptrdiff_t oinserted = ZV - BEGV;
4507 EMACS_INT ochars_modiff = CHARS_MODIFF;
4509 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4510 insval = call3 (Qformat_decode,
4511 Qnil, make_number (oinserted), visit);
4512 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4513 wrong_type_argument (intern ("inserted-chars"), insval);
4514 if (ochars_modiff == CHARS_MODIFF)
4515 /* format_decode didn't modify buffer's characters => move
4516 point back to position before inserted text and leave
4517 value of inserted alone. */
4518 SET_PT_BOTH (opoint, opoint_byte);
4519 else
4520 /* format_decode modified buffer's characters => consider
4521 entire buffer changed and leave point at point-min. */
4522 inserted = XFASTINT (insval);
4525 /* For consistency with format-decode call these now iff inserted > 0
4526 (martin 2007-06-28). */
4527 p = Vafter_insert_file_functions;
4528 while (CONSP (p))
4530 if (NILP (replace))
4532 insval = call1 (XCAR (p), make_number (inserted));
4533 if (!NILP (insval))
4535 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4536 wrong_type_argument (intern ("inserted-chars"), insval);
4537 inserted = XFASTINT (insval);
4540 else
4542 /* For the rationale of this see the comment on
4543 format-decode above. */
4544 ptrdiff_t opoint = PT;
4545 ptrdiff_t opoint_byte = PT_BYTE;
4546 ptrdiff_t oinserted = ZV - BEGV;
4547 EMACS_INT ochars_modiff = CHARS_MODIFF;
4549 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4550 insval = call1 (XCAR (p), make_number (oinserted));
4551 if (!NILP (insval))
4553 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4554 wrong_type_argument (intern ("inserted-chars"), insval);
4555 if (ochars_modiff == CHARS_MODIFF)
4556 /* after_insert_file_functions didn't modify
4557 buffer's characters => move point back to
4558 position before inserted text and leave value of
4559 inserted alone. */
4560 SET_PT_BOTH (opoint, opoint_byte);
4561 else
4562 /* after_insert_file_functions did modify buffer's
4563 characters => consider entire buffer changed and
4564 leave point at point-min. */
4565 inserted = XFASTINT (insval);
4569 maybe_quit ();
4570 p = XCDR (p);
4573 if (!empty_undo_list_p)
4575 bset_undo_list (current_buffer, old_undo);
4576 if (CONSP (old_undo) && inserted != old_inserted)
4578 /* Adjust the last undo record for the size change during
4579 the format conversion. */
4580 Lisp_Object tem = XCAR (old_undo);
4581 if (CONSP (tem) && INTEGERP (XCAR (tem))
4582 && INTEGERP (XCDR (tem))
4583 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4584 XSETCDR (tem, make_number (PT + inserted));
4587 else
4588 /* If undo_list was Qt before, keep it that way.
4589 Otherwise start with an empty undo_list. */
4590 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4592 unbind_to (count1, Qnil);
4595 if (!NILP (visit)
4596 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4598 /* If visiting nonexistent file, return nil. */
4599 report_file_errno ("Opening input file", orig_filename, save_errno);
4602 /* We made a lot of deletions and insertions above, so invalidate
4603 the newline cache for the entire region of the inserted
4604 characters. */
4605 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4606 invalidate_region_cache (current_buffer->base_buffer,
4607 current_buffer->base_buffer->newline_cache,
4608 PT - BEG, Z - PT - inserted);
4609 else if (current_buffer->newline_cache)
4610 invalidate_region_cache (current_buffer,
4611 current_buffer->newline_cache,
4612 PT - BEG, Z - PT - inserted);
4614 if (read_quit)
4615 quit ();
4617 /* Retval needs to be dealt with in all cases consistently. */
4618 if (NILP (val))
4619 val = list2 (orig_filename, make_number (inserted));
4621 return unbind_to (count, val);
4624 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4626 static void
4627 build_annotations_unwind (Lisp_Object arg)
4629 Vwrite_region_annotation_buffers = arg;
4632 /* Decide the coding-system to encode the data with. */
4634 static Lisp_Object
4635 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4636 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4637 struct coding_system *coding)
4639 Lisp_Object val;
4640 Lisp_Object eol_parent = Qnil;
4642 if (auto_saving
4643 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4644 BVAR (current_buffer, auto_save_file_name))))
4646 val = Qutf_8_emacs;
4647 eol_parent = Qunix;
4649 else if (!NILP (Vcoding_system_for_write))
4651 val = Vcoding_system_for_write;
4652 if (coding_system_require_warning
4653 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4654 /* Confirm that VAL can surely encode the current region. */
4655 val = call5 (Vselect_safe_coding_system_function,
4656 start, end, list2 (Qt, val),
4657 Qnil, filename);
4659 else
4661 /* If the variable `buffer-file-coding-system' is set locally,
4662 it means that the file was read with some kind of code
4663 conversion or the variable is explicitly set by users. We
4664 had better write it out with the same coding system even if
4665 `enable-multibyte-characters' is nil.
4667 If it is not set locally, we anyway have to convert EOL
4668 format if the default value of `buffer-file-coding-system'
4669 tells that it is not Unix-like (LF only) format. */
4670 bool using_default_coding = 0;
4671 bool force_raw_text = 0;
4673 val = BVAR (current_buffer, buffer_file_coding_system);
4674 if (NILP (val)
4675 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4677 val = Qnil;
4678 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4679 force_raw_text = 1;
4682 if (NILP (val))
4684 /* Check file-coding-system-alist. */
4685 Lisp_Object coding_systems
4686 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4687 filename, append, visit, lockname);
4688 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4689 val = XCDR (coding_systems);
4692 if (NILP (val))
4694 /* If we still have not decided a coding system, use the
4695 current buffer's value of buffer-file-coding-system. */
4696 val = BVAR (current_buffer, buffer_file_coding_system);
4697 using_default_coding = 1;
4700 if (! NILP (val) && ! force_raw_text)
4702 Lisp_Object spec, attrs;
4704 CHECK_CODING_SYSTEM (val);
4705 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4706 attrs = AREF (spec, 0);
4707 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4708 force_raw_text = 1;
4711 if (!force_raw_text
4712 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4714 /* Confirm that VAL can surely encode the current region. */
4715 val = call5 (Vselect_safe_coding_system_function,
4716 start, end, val, Qnil, filename);
4717 /* As the function specified by select-safe-coding-system-function
4718 is out of our control, make sure we are not fed by bogus
4719 values. */
4720 if (!NILP (val))
4721 CHECK_CODING_SYSTEM (val);
4724 /* If the decided coding-system doesn't specify end-of-line
4725 format, we use that of `buffer-file-coding-system'. */
4726 if (! using_default_coding)
4728 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4730 if (! NILP (dflt))
4731 val = coding_inherit_eol_type (val, dflt);
4734 /* If we decide not to encode text, use `raw-text' or one of its
4735 subsidiaries. */
4736 if (force_raw_text)
4737 val = raw_text_coding_system (val);
4740 val = coding_inherit_eol_type (val, eol_parent);
4741 setup_coding_system (val, coding);
4743 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4744 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4745 return val;
4748 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4749 "r\nFWrite region to file: \ni\ni\ni\np",
4750 doc: /* Write current region into specified file.
4751 When called from a program, requires three arguments:
4752 START, END and FILENAME. START and END are normally buffer positions
4753 specifying the part of the buffer to write.
4754 If START is nil, that means to use the entire buffer contents; END is
4755 ignored.
4756 If START is a string, then output that string to the file
4757 instead of any buffer contents; END is ignored.
4759 Optional fourth argument APPEND if non-nil means
4760 append to existing file contents (if any). If it is a number,
4761 seek to that offset in the file before writing.
4762 Optional fifth argument VISIT, if t or a string, means
4763 set the last-save-file-modtime of buffer to this file's modtime
4764 and mark buffer not modified.
4765 If VISIT is a string, it is a second file name;
4766 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4767 VISIT is also the file name to lock and unlock for clash detection.
4768 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4769 do not display the \"Wrote file\" message.
4770 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4771 use for locking and unlocking, overriding FILENAME and VISIT.
4772 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4773 for an existing file with the same name. If MUSTBENEW is `excl',
4774 that means to get an error if the file already exists; never overwrite.
4775 If MUSTBENEW is neither nil nor `excl', that means ask for
4776 confirmation before overwriting, but do go ahead and overwrite the file
4777 if the user confirms.
4779 This does code conversion according to the value of
4780 `coding-system-for-write', `buffer-file-coding-system', or
4781 `file-coding-system-alist', and sets the variable
4782 `last-coding-system-used' to the coding system actually used.
4784 This calls `write-region-annotate-functions' at the start, and
4785 `write-region-post-annotation-function' at the end. */)
4786 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4787 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4789 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4790 -1);
4793 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4794 descriptor for FILENAME, so do not open or close FILENAME. */
4796 Lisp_Object
4797 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4798 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4799 Lisp_Object mustbenew, int desc)
4801 int open_flags;
4802 int mode;
4803 off_t offset UNINIT;
4804 bool open_and_close_file = desc < 0;
4805 bool ok;
4806 int save_errno = 0;
4807 const char *fn;
4808 struct stat st;
4809 struct timespec modtime;
4810 ptrdiff_t count = SPECPDL_INDEX ();
4811 ptrdiff_t count1 UNINIT;
4812 Lisp_Object handler;
4813 Lisp_Object visit_file;
4814 Lisp_Object annotations;
4815 Lisp_Object encoded_filename;
4816 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4817 bool quietly = !NILP (visit);
4818 bool file_locked = 0;
4819 struct buffer *given_buffer;
4820 struct coding_system coding;
4822 if (current_buffer->base_buffer && visiting)
4823 error ("Cannot do file visiting in an indirect buffer");
4825 if (!NILP (start) && !STRINGP (start))
4826 validate_region (&start, &end);
4828 visit_file = Qnil;
4830 filename = Fexpand_file_name (filename, Qnil);
4832 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4833 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4835 if (STRINGP (visit))
4836 visit_file = Fexpand_file_name (visit, Qnil);
4837 else
4838 visit_file = filename;
4840 if (NILP (lockname))
4841 lockname = visit_file;
4843 annotations = Qnil;
4845 /* If the file name has special constructs in it,
4846 call the corresponding file handler. */
4847 handler = Ffind_file_name_handler (filename, Qwrite_region);
4848 /* If FILENAME has no handler, see if VISIT has one. */
4849 if (NILP (handler) && STRINGP (visit))
4850 handler = Ffind_file_name_handler (visit, Qwrite_region);
4852 if (!NILP (handler))
4854 Lisp_Object val;
4855 val = call6 (handler, Qwrite_region, start, end,
4856 filename, append, visit);
4858 if (visiting)
4860 SAVE_MODIFF = MODIFF;
4861 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4862 bset_filename (current_buffer, visit_file);
4865 return val;
4868 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4870 /* Special kludge to simplify auto-saving. */
4871 if (NILP (start))
4873 /* Do it later, so write-region-annotate-function can work differently
4874 if we save "the buffer" vs "a region".
4875 This is useful in tar-mode. --Stef
4876 XSETFASTINT (start, BEG);
4877 XSETFASTINT (end, Z); */
4878 Fwiden ();
4881 record_unwind_protect (build_annotations_unwind,
4882 Vwrite_region_annotation_buffers);
4883 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4885 given_buffer = current_buffer;
4887 if (!STRINGP (start))
4889 annotations = build_annotations (start, end);
4891 if (current_buffer != given_buffer)
4893 XSETFASTINT (start, BEGV);
4894 XSETFASTINT (end, ZV);
4898 if (NILP (start))
4900 XSETFASTINT (start, BEGV);
4901 XSETFASTINT (end, ZV);
4904 /* Decide the coding-system to encode the data with.
4905 We used to make this choice before calling build_annotations, but that
4906 leads to problems when a write-annotate-function takes care of
4907 unsavable chars (as was the case with X-Symbol). */
4908 Vlast_coding_system_used
4909 = choose_write_coding_system (start, end, filename,
4910 append, visit, lockname, &coding);
4912 if (open_and_close_file && !auto_saving)
4914 lock_file (lockname);
4915 file_locked = 1;
4918 encoded_filename = ENCODE_FILE (filename);
4919 fn = SSDATA (encoded_filename);
4920 open_flags = O_WRONLY | O_CREAT;
4921 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4922 if (NUMBERP (append))
4923 offset = file_offset (append);
4924 else if (!NILP (append))
4925 open_flags |= O_APPEND;
4926 #ifdef DOS_NT
4927 mode = S_IREAD | S_IWRITE;
4928 #else
4929 mode = auto_saving ? auto_save_mode_bits : 0666;
4930 #endif
4932 if (open_and_close_file)
4934 desc = emacs_open (fn, open_flags, mode);
4935 if (desc < 0)
4937 int open_errno = errno;
4938 if (file_locked)
4939 unlock_file (lockname);
4940 report_file_errno ("Opening output file", filename, open_errno);
4943 count1 = SPECPDL_INDEX ();
4944 record_unwind_protect_int (close_file_unwind, desc);
4947 if (NUMBERP (append))
4949 off_t ret = lseek (desc, offset, SEEK_SET);
4950 if (ret < 0)
4952 int lseek_errno = errno;
4953 if (file_locked)
4954 unlock_file (lockname);
4955 report_file_errno ("Lseek error", filename, lseek_errno);
4959 if (STRINGP (start))
4960 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4961 else if (XINT (start) != XINT (end))
4962 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4963 &annotations, &coding);
4964 else
4966 /* If file was empty, still need to write the annotations. */
4967 coding.mode |= CODING_MODE_LAST_BLOCK;
4968 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4970 save_errno = errno;
4972 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4973 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4975 /* We have to flush out a data. */
4976 coding.mode |= CODING_MODE_LAST_BLOCK;
4977 ok = e_write (desc, Qnil, 1, 1, &coding);
4978 save_errno = errno;
4981 /* fsync is not crucial for temporary files. Nor for auto-save
4982 files, since they might lose some work anyway. */
4983 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4985 /* Transfer data and metadata to disk, retrying if interrupted.
4986 fsync can report a write failure here, e.g., due to disk full
4987 under NFS. But ignore EINVAL, which means fsync is not
4988 supported on this file. */
4989 while (fsync (desc) != 0)
4990 if (errno != EINTR)
4992 if (errno != EINVAL)
4993 ok = 0, save_errno = errno;
4994 break;
4998 modtime = invalid_timespec ();
4999 if (visiting)
5001 if (fstat (desc, &st) == 0)
5002 modtime = get_stat_mtime (&st);
5003 else
5004 ok = 0, save_errno = errno;
5007 if (open_and_close_file)
5009 /* NFS can report a write failure now. */
5010 if (emacs_close (desc) < 0)
5011 ok = 0, save_errno = errno;
5013 /* Discard the unwind protect for close_file_unwind. */
5014 specpdl_ptr = specpdl + count1;
5017 /* Some file systems have a bug where st_mtime is not updated
5018 properly after a write. For example, CIFS might not see the
5019 st_mtime change until after the file is opened again.
5021 Attempt to detect this file system bug, and update MODTIME to the
5022 newer st_mtime if the bug appears to be present. This introduces
5023 a race condition, so to avoid most instances of the race condition
5024 on non-buggy file systems, skip this check if the most recently
5025 encountered non-buggy file system was the current file system.
5027 A race condition can occur if some other process modifies the
5028 file between the fstat above and the fstat below, but the race is
5029 unlikely and a similar race between the last write and the fstat
5030 above cannot possibly be closed anyway. */
5032 if (timespec_valid_p (modtime)
5033 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
5035 int desc1 = emacs_open (fn, O_WRONLY, 0);
5036 if (desc1 >= 0)
5038 struct stat st1;
5039 if (fstat (desc1, &st1) == 0
5040 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
5042 /* Use the heuristic if it appears to be valid. With neither
5043 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
5044 file, the time stamp won't change. Also, some non-POSIX
5045 systems don't update an empty file's time stamp when
5046 truncating it. Finally, file systems with 100 ns or worse
5047 resolution sometimes seem to have bugs: on a system with ns
5048 resolution, checking ns % 100 incorrectly avoids the heuristic
5049 1% of the time, but the problem should be temporary as we will
5050 try again on the next time stamp. */
5051 bool use_heuristic
5052 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
5053 && st.st_size != 0
5054 && modtime.tv_nsec % 100 != 0);
5056 struct timespec modtime1 = get_stat_mtime (&st1);
5057 if (use_heuristic
5058 && timespec_cmp (modtime, modtime1) == 0
5059 && st.st_size == st1.st_size)
5061 timestamp_file_system = st.st_dev;
5062 valid_timestamp_file_system = 1;
5064 else
5066 st.st_size = st1.st_size;
5067 modtime = modtime1;
5070 emacs_close (desc1);
5074 /* Call write-region-post-annotation-function. */
5075 while (CONSP (Vwrite_region_annotation_buffers))
5077 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5078 if (!NILP (Fbuffer_live_p (buf)))
5080 Fset_buffer (buf);
5081 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5082 call0 (Vwrite_region_post_annotation_function);
5084 Vwrite_region_annotation_buffers
5085 = XCDR (Vwrite_region_annotation_buffers);
5088 unbind_to (count, Qnil);
5090 if (file_locked)
5091 unlock_file (lockname);
5093 /* Do this before reporting IO error
5094 to avoid a "file has changed on disk" warning on
5095 next attempt to save. */
5096 if (timespec_valid_p (modtime))
5098 current_buffer->modtime = modtime;
5099 current_buffer->modtime_size = st.st_size;
5102 if (! ok)
5103 report_file_errno ("Write error", filename, save_errno);
5105 bool auto_saving_into_visited_file =
5106 auto_saving
5107 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5108 BVAR (current_buffer, auto_save_file_name)));
5109 if (visiting)
5111 SAVE_MODIFF = MODIFF;
5112 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5113 bset_filename (current_buffer, visit_file);
5114 update_mode_lines = 14;
5115 if (auto_saving_into_visited_file)
5116 unlock_file (lockname);
5118 else if (quietly)
5120 if (auto_saving_into_visited_file)
5122 SAVE_MODIFF = MODIFF;
5123 unlock_file (lockname);
5126 return Qnil;
5129 if (!auto_saving && !noninteractive)
5130 message_with_string ((NUMBERP (append)
5131 ? "Updated %s"
5132 : ! NILP (append)
5133 ? "Added to %s"
5134 : "Wrote %s"),
5135 visit_file, 1);
5137 return Qnil;
5140 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5141 doc: /* Return t if (car A) is numerically less than (car B). */)
5142 (Lisp_Object a, Lisp_Object b)
5144 return arithcompare (Fcar (a), Fcar (b), ARITH_LESS);
5147 /* Build the complete list of annotations appropriate for writing out
5148 the text between START and END, by calling all the functions in
5149 write-region-annotate-functions and merging the lists they return.
5150 If one of these functions switches to a different buffer, we assume
5151 that buffer contains altered text. Therefore, the caller must
5152 make sure to restore the current buffer in all cases,
5153 as save-excursion would do. */
5155 static Lisp_Object
5156 build_annotations (Lisp_Object start, Lisp_Object end)
5158 Lisp_Object annotations;
5159 Lisp_Object p, res;
5160 Lisp_Object original_buffer;
5161 int i;
5162 bool used_global = false;
5164 XSETBUFFER (original_buffer, current_buffer);
5166 annotations = Qnil;
5167 p = Vwrite_region_annotate_functions;
5168 while (CONSP (p))
5170 struct buffer *given_buffer = current_buffer;
5171 if (EQ (Qt, XCAR (p)) && !used_global)
5172 { /* Use the global value of the hook. */
5173 used_global = true;
5174 p = CALLN (Fappend,
5175 Fdefault_value (Qwrite_region_annotate_functions),
5176 XCDR (p));
5177 continue;
5179 Vwrite_region_annotations_so_far = annotations;
5180 res = call2 (XCAR (p), start, end);
5181 /* If the function makes a different buffer current,
5182 assume that means this buffer contains altered text to be output.
5183 Reset START and END from the buffer bounds
5184 and discard all previous annotations because they should have
5185 been dealt with by this function. */
5186 if (current_buffer != given_buffer)
5188 Vwrite_region_annotation_buffers
5189 = Fcons (Fcurrent_buffer (),
5190 Vwrite_region_annotation_buffers);
5191 XSETFASTINT (start, BEGV);
5192 XSETFASTINT (end, ZV);
5193 annotations = Qnil;
5195 Flength (res); /* Check basic validity of return value */
5196 annotations = merge (annotations, res, Qcar_less_than_car);
5197 p = XCDR (p);
5200 /* Now do the same for annotation functions implied by the file-format */
5201 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5202 p = BVAR (current_buffer, auto_save_file_format);
5203 else
5204 p = BVAR (current_buffer, file_format);
5205 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5207 struct buffer *given_buffer = current_buffer;
5209 Vwrite_region_annotations_so_far = annotations;
5211 /* Value is either a list of annotations or nil if the function
5212 has written annotations to a temporary buffer, which is now
5213 current. */
5214 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5215 original_buffer, make_number (i));
5216 if (current_buffer != given_buffer)
5218 XSETFASTINT (start, BEGV);
5219 XSETFASTINT (end, ZV);
5220 annotations = Qnil;
5223 if (CONSP (res))
5224 annotations = merge (annotations, res, Qcar_less_than_car);
5227 return annotations;
5231 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5232 If STRING is nil, POS is the character position in the current buffer.
5233 Intersperse with them the annotations from *ANNOT
5234 which fall within the range of POS to POS + NCHARS,
5235 each at its appropriate position.
5237 We modify *ANNOT by discarding elements as we use them up.
5239 Return true if successful. */
5241 static bool
5242 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5243 ptrdiff_t nchars, Lisp_Object *annot,
5244 struct coding_system *coding)
5246 Lisp_Object tem;
5247 ptrdiff_t nextpos;
5248 ptrdiff_t lastpos = pos + nchars;
5250 while (NILP (*annot) || CONSP (*annot))
5252 tem = Fcar_safe (Fcar (*annot));
5253 nextpos = pos - 1;
5254 if (INTEGERP (tem))
5255 nextpos = XFASTINT (tem);
5257 /* If there are no more annotations in this range,
5258 output the rest of the range all at once. */
5259 if (! (nextpos >= pos && nextpos <= lastpos))
5260 return e_write (desc, string, pos, lastpos, coding);
5262 /* Output buffer text up to the next annotation's position. */
5263 if (nextpos > pos)
5265 if (!e_write (desc, string, pos, nextpos, coding))
5266 return 0;
5267 pos = nextpos;
5269 /* Output the annotation. */
5270 tem = Fcdr (Fcar (*annot));
5271 if (STRINGP (tem))
5273 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5274 return 0;
5276 *annot = Fcdr (*annot);
5278 return 1;
5281 /* Maximum number of characters that the next
5282 function encodes per one loop iteration. */
5284 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5286 /* Write text in the range START and END into descriptor DESC,
5287 encoding them with coding system CODING. If STRING is nil, START
5288 and END are character positions of the current buffer, else they
5289 are indexes to the string STRING. Return true if successful. */
5291 static bool
5292 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5293 struct coding_system *coding)
5295 if (STRINGP (string))
5297 start = 0;
5298 end = SCHARS (string);
5301 /* We used to have a code for handling selective display here. But,
5302 now it is handled within encode_coding. */
5304 while (start < end)
5306 if (STRINGP (string))
5308 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5309 if (CODING_REQUIRE_ENCODING (coding))
5311 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5313 /* Avoid creating huge Lisp string in encode_coding_object. */
5314 if (nchars == E_WRITE_MAX)
5315 coding->raw_destination = 1;
5317 encode_coding_object
5318 (coding, string, start, string_char_to_byte (string, start),
5319 start + nchars, string_char_to_byte (string, start + nchars),
5320 Qt);
5322 else
5324 coding->dst_object = string;
5325 coding->consumed_char = SCHARS (string);
5326 coding->produced = SBYTES (string);
5329 else
5331 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5332 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5334 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5335 if (CODING_REQUIRE_ENCODING (coding))
5337 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5339 /* Likewise. */
5340 if (nchars == E_WRITE_MAX)
5341 coding->raw_destination = 1;
5343 encode_coding_object
5344 (coding, Fcurrent_buffer (), start, start_byte,
5345 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5347 else
5349 coding->dst_object = Qnil;
5350 coding->dst_pos_byte = start_byte;
5351 if (start >= GPT || end <= GPT)
5353 coding->consumed_char = end - start;
5354 coding->produced = end_byte - start_byte;
5356 else
5358 coding->consumed_char = GPT - start;
5359 coding->produced = GPT_BYTE - start_byte;
5364 if (coding->produced > 0)
5366 char *buf = (coding->raw_destination ? (char *) coding->destination
5367 : (STRINGP (coding->dst_object)
5368 ? SSDATA (coding->dst_object)
5369 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5370 coding->produced -= emacs_write_quit (desc, buf, coding->produced);
5372 if (coding->raw_destination)
5374 /* We're responsible for freeing this, see
5375 encode_coding_object to check why. */
5376 xfree (coding->destination);
5377 coding->raw_destination = 0;
5379 if (coding->produced)
5380 return 0;
5382 start += coding->consumed_char;
5385 return 1;
5388 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5389 Sverify_visited_file_modtime, 0, 1, 0,
5390 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5391 This means that the file has not been changed since it was visited or saved.
5392 If BUF is omitted or nil, it defaults to the current buffer.
5393 See Info node `(elisp)Modification Time' for more details. */)
5394 (Lisp_Object buf)
5396 struct buffer *b = decode_buffer (buf);
5397 struct stat st;
5398 Lisp_Object handler;
5399 Lisp_Object filename;
5400 struct timespec mtime;
5402 if (!STRINGP (BVAR (b, filename))) return Qt;
5403 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5405 /* If the file name has special constructs in it,
5406 call the corresponding file handler. */
5407 handler = Ffind_file_name_handler (BVAR (b, filename),
5408 Qverify_visited_file_modtime);
5409 if (!NILP (handler))
5410 return call2 (handler, Qverify_visited_file_modtime, buf);
5412 filename = ENCODE_FILE (BVAR (b, filename));
5414 mtime = (stat (SSDATA (filename), &st) == 0
5415 ? get_stat_mtime (&st)
5416 : time_error_value (errno));
5417 if (timespec_cmp (mtime, b->modtime) == 0
5418 && (b->modtime_size < 0
5419 || st.st_size == b->modtime_size))
5420 return Qt;
5421 return Qnil;
5424 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5425 Svisited_file_modtime, 0, 0, 0,
5426 doc: /* Return the current buffer's recorded visited file modification time.
5427 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5428 `file-attributes' returns. If the current buffer has no recorded file
5429 modification time, this function returns 0. If the visited file
5430 doesn't exist, return -1.
5431 See Info node `(elisp)Modification Time' for more details. */)
5432 (void)
5434 int ns = current_buffer->modtime.tv_nsec;
5435 if (ns < 0)
5436 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5437 return make_lisp_time (current_buffer->modtime);
5440 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5441 Sset_visited_file_modtime, 0, 1, 0,
5442 doc: /* Update buffer's recorded modification time from the visited file's time.
5443 Useful if the buffer was not read from the file normally
5444 or if the file itself has been changed for some known benign reason.
5445 An argument specifies the modification time value to use
5446 \(instead of that of the visited file), in the form of a list
5447 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5448 `visited-file-modtime'. */)
5449 (Lisp_Object time_flag)
5451 if (!NILP (time_flag))
5453 struct timespec mtime;
5454 if (INTEGERP (time_flag))
5456 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5457 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5459 else
5460 mtime = lisp_time_argument (time_flag);
5462 current_buffer->modtime = mtime;
5463 current_buffer->modtime_size = -1;
5465 else
5467 register Lisp_Object filename;
5468 struct stat st;
5469 Lisp_Object handler;
5471 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5473 /* If the file name has special constructs in it,
5474 call the corresponding file handler. */
5475 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5476 if (!NILP (handler))
5477 /* The handler can find the file name the same way we did. */
5478 return call2 (handler, Qset_visited_file_modtime, Qnil);
5480 filename = ENCODE_FILE (filename);
5482 if (stat (SSDATA (filename), &st) >= 0)
5484 current_buffer->modtime = get_stat_mtime (&st);
5485 current_buffer->modtime_size = st.st_size;
5489 return Qnil;
5492 static Lisp_Object
5493 auto_save_error (Lisp_Object error_val)
5495 auto_save_error_occurred = 1;
5497 ring_bell (XFRAME (selected_frame));
5499 AUTO_STRING (format, "Auto-saving %s: %s");
5500 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5501 Ferror_message_string (error_val));
5502 call3 (intern ("display-warning"),
5503 intern ("auto-save"), msg, intern ("error"));
5505 return Qnil;
5508 static Lisp_Object
5509 auto_save_1 (void)
5511 struct stat st;
5512 Lisp_Object modes;
5514 auto_save_mode_bits = 0666;
5516 /* Get visited file's mode to become the auto save file's mode. */
5517 if (! NILP (BVAR (current_buffer, filename)))
5519 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5520 /* But make sure we can overwrite it later! */
5521 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5522 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5523 INTEGERP (modes))
5524 /* Remote files don't cooperate with stat. */
5525 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5528 return
5529 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5530 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5531 Qnil, Qnil);
5534 struct auto_save_unwind
5536 FILE *stream;
5537 bool auto_raise;
5540 static void
5541 do_auto_save_unwind (void *arg)
5543 struct auto_save_unwind *p = arg;
5544 FILE *stream = p->stream;
5545 minibuffer_auto_raise = p->auto_raise;
5546 auto_saving = 0;
5547 if (stream != NULL)
5549 block_input ();
5550 fclose (stream);
5551 unblock_input ();
5555 static Lisp_Object
5556 do_auto_save_make_dir (Lisp_Object dir)
5558 Lisp_Object result;
5560 auto_saving_dir_umask = 077;
5561 result = call2 (Qmake_directory, dir, Qt);
5562 auto_saving_dir_umask = 0;
5563 return result;
5566 static Lisp_Object
5567 do_auto_save_eh (Lisp_Object ignore)
5569 auto_saving_dir_umask = 0;
5570 return Qnil;
5573 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5574 doc: /* Auto-save all buffers that need it.
5575 This is all buffers that have auto-saving enabled
5576 and are changed since last auto-saved.
5577 Auto-saving writes the buffer into a file
5578 so that your editing is not lost if the system crashes.
5579 This file is not the file you visited; that changes only when you save.
5580 Normally, run the normal hook `auto-save-hook' before saving.
5582 A non-nil NO-MESSAGE argument means do not print any message if successful.
5583 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5584 (Lisp_Object no_message, Lisp_Object current_only)
5586 struct buffer *old = current_buffer, *b;
5587 Lisp_Object tail, buf, hook;
5588 bool auto_saved = 0;
5589 int do_handled_files;
5590 Lisp_Object oquit;
5591 FILE *stream = NULL;
5592 ptrdiff_t count = SPECPDL_INDEX ();
5593 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5594 bool old_message_p = 0;
5595 struct auto_save_unwind auto_save_unwind;
5597 if (max_specpdl_size < specpdl_size + 40)
5598 max_specpdl_size = specpdl_size + 40;
5600 if (minibuf_level)
5601 no_message = Qt;
5603 if (NILP (no_message))
5605 old_message_p = push_message ();
5606 record_unwind_protect_void (pop_message_unwind);
5609 /* Ordinarily don't quit within this function,
5610 but don't make it impossible to quit (in case we get hung in I/O). */
5611 oquit = Vquit_flag;
5612 Vquit_flag = Qnil;
5614 hook = intern ("auto-save-hook");
5615 safe_run_hooks (hook);
5617 if (STRINGP (Vauto_save_list_file_name))
5619 Lisp_Object listfile;
5621 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5623 /* Don't try to create the directory when shutting down Emacs,
5624 because creating the directory might signal an error, and
5625 that would leave Emacs in a strange state. */
5626 if (!NILP (Vrun_hooks))
5628 Lisp_Object dir;
5629 dir = Ffile_name_directory (listfile);
5630 if (NILP (Ffile_directory_p (dir)))
5631 internal_condition_case_1 (do_auto_save_make_dir,
5632 dir, Qt,
5633 do_auto_save_eh);
5636 stream = emacs_fopen (SSDATA (listfile), "w");
5639 auto_save_unwind.stream = stream;
5640 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5641 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5642 minibuffer_auto_raise = 0;
5643 auto_saving = 1;
5644 auto_save_error_occurred = 0;
5646 /* On first pass, save all files that don't have handlers.
5647 On second pass, save all files that do have handlers.
5649 If Emacs is crashing, the handlers may tweak what is causing
5650 Emacs to crash in the first place, and it would be a shame if
5651 Emacs failed to autosave perfectly ordinary files because it
5652 couldn't handle some ange-ftp'd file. */
5654 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5655 FOR_EACH_LIVE_BUFFER (tail, buf)
5657 b = XBUFFER (buf);
5659 /* Record all the buffers that have auto save mode
5660 in the special file that lists them. For each of these buffers,
5661 Record visited name (if any) and auto save name. */
5662 if (STRINGP (BVAR (b, auto_save_file_name))
5663 && stream != NULL && do_handled_files == 0)
5665 block_input ();
5666 if (!NILP (BVAR (b, filename)))
5667 fwrite_unlocked (SDATA (BVAR (b, filename)), 1,
5668 SBYTES (BVAR (b, filename)), stream);
5669 putc_unlocked ('\n', stream);
5670 fwrite_unlocked (SDATA (BVAR (b, auto_save_file_name)), 1,
5671 SBYTES (BVAR (b, auto_save_file_name)), stream);
5672 putc_unlocked ('\n', stream);
5673 unblock_input ();
5676 if (!NILP (current_only)
5677 && b != current_buffer)
5678 continue;
5680 /* Don't auto-save indirect buffers.
5681 The base buffer takes care of it. */
5682 if (b->base_buffer)
5683 continue;
5685 /* Check for auto save enabled
5686 and file changed since last auto save
5687 and file changed since last real save. */
5688 if (STRINGP (BVAR (b, auto_save_file_name))
5689 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5690 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5691 /* -1 means we've turned off autosaving for a while--see below. */
5692 && XINT (BVAR (b, save_length)) >= 0
5693 && (do_handled_files
5694 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5695 Qwrite_region))))
5697 struct timespec before_time = current_timespec ();
5698 struct timespec after_time;
5700 /* If we had a failure, don't try again for 20 minutes. */
5701 if (b->auto_save_failure_time > 0
5702 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5703 continue;
5705 set_buffer_internal (b);
5706 if (NILP (Vauto_save_include_big_deletions)
5707 && (XFASTINT (BVAR (b, save_length)) * 10
5708 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5709 /* A short file is likely to change a large fraction;
5710 spare the user annoying messages. */
5711 && XFASTINT (BVAR (b, save_length)) > 5000
5712 /* These messages are frequent and annoying for `*mail*'. */
5713 && !EQ (BVAR (b, filename), Qnil)
5714 && NILP (no_message))
5716 /* It has shrunk too much; turn off auto-saving here. */
5717 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5718 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5719 BVAR (b, name), 1);
5720 minibuffer_auto_raise = 0;
5721 /* Turn off auto-saving until there's a real save,
5722 and prevent any more warnings. */
5723 XSETINT (BVAR (b, save_length), -1);
5724 Fsleep_for (make_number (1), Qnil);
5725 continue;
5727 if (!auto_saved && NILP (no_message))
5728 message1 ("Auto-saving...");
5729 internal_condition_case (auto_save_1, Qt, auto_save_error);
5730 auto_saved = 1;
5731 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5732 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5733 set_buffer_internal (old);
5735 after_time = current_timespec ();
5737 /* If auto-save took more than 60 seconds,
5738 assume it was an NFS failure that got a timeout. */
5739 if (after_time.tv_sec - before_time.tv_sec > 60)
5740 b->auto_save_failure_time = after_time.tv_sec;
5744 /* Prevent another auto save till enough input events come in. */
5745 record_auto_save ();
5747 if (auto_saved && NILP (no_message))
5749 if (old_message_p)
5751 /* If we are going to restore an old message,
5752 give time to read ours. */
5753 sit_for (make_number (1), 0, 0);
5754 restore_message ();
5756 else if (!auto_save_error_occurred)
5757 /* Don't overwrite the error message if an error occurred.
5758 If we displayed a message and then restored a state
5759 with no message, leave a "done" message on the screen. */
5760 message1 ("Auto-saving...done");
5763 Vquit_flag = oquit;
5765 /* This restores the message-stack status. */
5766 unbind_to (count, Qnil);
5767 return Qnil;
5770 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5771 Sset_buffer_auto_saved, 0, 0, 0,
5772 doc: /* Mark current buffer as auto-saved with its current text.
5773 No auto-save file will be written until the buffer changes again. */)
5774 (void)
5776 /* FIXME: This should not be called in indirect buffers, since
5777 they're not autosaved. */
5778 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5779 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5780 current_buffer->auto_save_failure_time = 0;
5781 return Qnil;
5784 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5785 Sclear_buffer_auto_save_failure, 0, 0, 0,
5786 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5787 (void)
5789 current_buffer->auto_save_failure_time = 0;
5790 return Qnil;
5793 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5794 0, 0, 0,
5795 doc: /* Return t if current buffer has been auto-saved recently.
5796 More precisely, if it has been auto-saved since last read from or saved
5797 in the visited file. If the buffer has no visited file,
5798 then any auto-save counts as "recent". */)
5799 (void)
5801 /* FIXME: maybe we should return nil for indirect buffers since
5802 they're never autosaved. */
5803 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5806 /* Reading and completing file names. */
5808 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5809 Snext_read_file_uses_dialog_p, 0, 0, 0,
5810 doc: /* Return t if a call to `read-file-name' will use a dialog.
5811 The return value is only relevant for a call to `read-file-name' that happens
5812 before any other event (mouse or keypress) is handled. */)
5813 (void)
5815 #if (defined USE_GTK || defined USE_MOTIF \
5816 || defined HAVE_NS || defined HAVE_NTGUI)
5817 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5818 && use_dialog_box
5819 && use_file_dialog
5820 && window_system_available (SELECTED_FRAME ()))
5821 return Qt;
5822 #endif
5823 return Qnil;
5827 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5828 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5829 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5830 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5831 it to text mode.
5833 As a side effect, this function flushes any pending STREAM's data.
5835 Value is the previous value of STREAM's I/O mode, nil for text mode,
5836 non-nil for binary mode.
5838 On MS-Windows and MS-DOS, binary mode is needed to read or write
5839 arbitrary binary data, and for disabling translation between CR-LF
5840 pairs and a single newline character. Examples include generation
5841 of text files with Unix-style end-of-line format using `princ' in
5842 batch mode, with standard output redirected to a file.
5844 On Posix systems, this function always returns non-nil, and has no
5845 effect except for flushing STREAM's data. */)
5846 (Lisp_Object stream, Lisp_Object mode)
5848 FILE *fp = NULL;
5849 int binmode;
5851 CHECK_SYMBOL (stream);
5852 if (EQ (stream, Qstdin))
5853 fp = stdin;
5854 else if (EQ (stream, Qstdout))
5855 fp = stdout;
5856 else if (EQ (stream, Qstderr))
5857 fp = stderr;
5858 else
5859 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5861 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5862 if (fp != stdin)
5863 fflush_unlocked (fp);
5865 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5868 void
5869 init_fileio (void)
5871 realmask = umask (0);
5872 umask (realmask);
5874 valid_timestamp_file_system = 0;
5876 /* fsync can be a significant performance hit. Often it doesn't
5877 suffice to make the file-save operation survive a crash. For
5878 batch scripts, which are typically part of larger shell commands
5879 that don't fsync other files, its effect on performance can be
5880 significant so its utility is particularly questionable.
5881 Hence, for now by default fsync is used only when interactive.
5883 For more on why fsync often fails to work on today's hardware, see:
5884 Zheng M et al. Understanding the robustness of SSDs under power fault.
5885 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5886 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5888 For more on why fsync does not suffice even if it works properly, see:
5889 Roche X. Necessary step(s) to synchronize filename operations on disk.
5890 Austin Group Defect 672, 2013-03-19
5891 http://austingroupbugs.net/view.php?id=672 */
5892 write_region_inhibit_fsync = noninteractive;
5895 void
5896 syms_of_fileio (void)
5898 /* Property name of a file name handler,
5899 which gives a list of operations it handles. */
5900 DEFSYM (Qoperations, "operations");
5902 DEFSYM (Qexpand_file_name, "expand-file-name");
5903 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5904 DEFSYM (Qdirectory_file_name, "directory-file-name");
5905 DEFSYM (Qfile_name_directory, "file-name-directory");
5906 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5907 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5908 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5909 DEFSYM (Qcopy_file, "copy-file");
5910 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5911 DEFSYM (Qmake_directory, "make-directory");
5912 DEFSYM (Qdelete_file, "delete-file");
5913 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5914 DEFSYM (Qrename_file, "rename-file");
5915 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5916 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5917 DEFSYM (Qfile_exists_p, "file-exists-p");
5918 DEFSYM (Qfile_executable_p, "file-executable-p");
5919 DEFSYM (Qfile_readable_p, "file-readable-p");
5920 DEFSYM (Qfile_writable_p, "file-writable-p");
5921 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5922 DEFSYM (Qaccess_file, "access-file");
5923 DEFSYM (Qfile_directory_p, "file-directory-p");
5924 DEFSYM (Qfile_regular_p, "file-regular-p");
5925 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5926 DEFSYM (Qfile_modes, "file-modes");
5927 DEFSYM (Qset_file_modes, "set-file-modes");
5928 DEFSYM (Qset_file_times, "set-file-times");
5929 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5930 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5931 DEFSYM (Qfile_acl, "file-acl");
5932 DEFSYM (Qset_file_acl, "set-file-acl");
5933 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5934 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5935 DEFSYM (Qwrite_region, "write-region");
5936 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5937 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5939 /* The symbol bound to coding-system-for-read when
5940 insert-file-contents is called for recovering a file. This is not
5941 an actual coding system name, but just an indicator to tell
5942 insert-file-contents to use `emacs-mule' with a special flag for
5943 auto saving and recovering a file. */
5944 DEFSYM (Qauto_save_coding, "auto-save-coding");
5946 DEFSYM (Qfile_name_history, "file-name-history");
5947 Fset (Qfile_name_history, Qnil);
5949 DEFSYM (Qfile_error, "file-error");
5950 DEFSYM (Qfile_already_exists, "file-already-exists");
5951 DEFSYM (Qfile_date_error, "file-date-error");
5952 DEFSYM (Qfile_missing, "file-missing");
5953 DEFSYM (Qfile_notify_error, "file-notify-error");
5954 DEFSYM (Qexcl, "excl");
5956 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5957 doc: /* Coding system for encoding file names.
5958 If it is nil, `default-file-name-coding-system' (which see) is used.
5960 On MS-Windows, the value of this variable is largely ignored if
5961 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5962 behaves as if file names were encoded in `utf-8'. */);
5963 Vfile_name_coding_system = Qnil;
5965 DEFVAR_LISP ("default-file-name-coding-system",
5966 Vdefault_file_name_coding_system,
5967 doc: /* Default coding system for encoding file names.
5968 This variable is used only when `file-name-coding-system' is nil.
5970 This variable is set/changed by the command `set-language-environment'.
5971 User should not set this variable manually,
5972 instead use `file-name-coding-system' to get a constant encoding
5973 of file names regardless of the current language environment.
5975 On MS-Windows, the value of this variable is largely ignored if
5976 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5977 behaves as if file names were encoded in `utf-8'. */);
5978 Vdefault_file_name_coding_system = Qnil;
5980 /* Lisp functions for translating file formats. */
5981 DEFSYM (Qformat_decode, "format-decode");
5982 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5984 /* Lisp function for setting buffer-file-coding-system and the
5985 multibyteness of the current buffer after inserting a file. */
5986 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5988 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5990 Fput (Qfile_error, Qerror_conditions,
5991 Fpurecopy (list2 (Qfile_error, Qerror)));
5992 Fput (Qfile_error, Qerror_message,
5993 build_pure_c_string ("File error"));
5995 Fput (Qfile_already_exists, Qerror_conditions,
5996 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5997 Fput (Qfile_already_exists, Qerror_message,
5998 build_pure_c_string ("File already exists"));
6000 Fput (Qfile_date_error, Qerror_conditions,
6001 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
6002 Fput (Qfile_date_error, Qerror_message,
6003 build_pure_c_string ("Cannot set file date"));
6005 Fput (Qfile_missing, Qerror_conditions,
6006 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
6007 Fput (Qfile_missing, Qerror_message,
6008 build_pure_c_string ("File is missing"));
6010 Fput (Qfile_notify_error, Qerror_conditions,
6011 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
6012 Fput (Qfile_notify_error, Qerror_message,
6013 build_pure_c_string ("File notification error"));
6015 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
6016 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
6017 If a file name matches REGEXP, all I/O on that file is done by calling
6018 HANDLER. If a file name matches more than one handler, the handler
6019 whose match starts last in the file name gets precedence. The
6020 function `find-file-name-handler' checks this list for a handler for
6021 its argument.
6023 HANDLER should be a function. The first argument given to it is the
6024 name of the I/O primitive to be handled; the remaining arguments are
6025 the arguments that were passed to that primitive. For example, if you
6026 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
6027 HANDLER is called like this:
6029 (funcall HANDLER \\='file-exists-p FILENAME)
6031 Note that HANDLER must be able to handle all I/O primitives; if it has
6032 nothing special to do for a primitive, it should reinvoke the
6033 primitive to handle the operation \"the usual way\".
6034 See Info node `(elisp)Magic File Names' for more details. */);
6035 Vfile_name_handler_alist = Qnil;
6037 DEFVAR_LISP ("set-auto-coding-function",
6038 Vset_auto_coding_function,
6039 doc: /* If non-nil, a function to call to decide a coding system of file.
6040 Two arguments are passed to this function: the file name
6041 and the length of a file contents following the point.
6042 This function should return a coding system to decode the file contents.
6043 It should check the file name against `auto-coding-alist'.
6044 If no coding system is decided, it should check a coding system
6045 specified in the heading lines with the format:
6046 -*- ... coding: CODING-SYSTEM; ... -*-
6047 or local variable spec of the tailing lines with `coding:' tag. */);
6048 Vset_auto_coding_function = Qnil;
6050 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
6051 doc: /* A list of functions to be called at the end of `insert-file-contents'.
6052 Each is passed one argument, the number of characters inserted,
6053 with point at the start of the inserted text. Each function
6054 should leave point the same, and return the new character count.
6055 If `insert-file-contents' is intercepted by a handler from
6056 `file-name-handler-alist', that handler is responsible for calling the
6057 functions in `after-insert-file-functions' if appropriate. */);
6058 Vafter_insert_file_functions = Qnil;
6060 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
6061 doc: /* A list of functions to be called at the start of `write-region'.
6062 Each is passed two arguments, START and END as for `write-region'.
6063 These are usually two numbers but not always; see the documentation
6064 for `write-region'. The function should return a list of pairs
6065 of the form (POSITION . STRING), consisting of strings to be effectively
6066 inserted at the specified positions of the file being written (1 means to
6067 insert before the first byte written). The POSITIONs must be sorted into
6068 increasing order.
6070 If there are several annotation functions, the lists returned by these
6071 functions are merged destructively. As each annotation function runs,
6072 the variable `write-region-annotations-so-far' contains a list of all
6073 annotations returned by previous annotation functions.
6075 An annotation function can return with a different buffer current.
6076 Doing so removes the annotations returned by previous functions, and
6077 resets START and END to `point-min' and `point-max' of the new buffer.
6079 After `write-region' completes, Emacs calls the function stored in
6080 `write-region-post-annotation-function', once for each buffer that was
6081 current when building the annotations (i.e., at least once), with that
6082 buffer current. */);
6083 Vwrite_region_annotate_functions = Qnil;
6084 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6086 DEFVAR_LISP ("write-region-post-annotation-function",
6087 Vwrite_region_post_annotation_function,
6088 doc: /* Function to call after `write-region' completes.
6089 The function is called with no arguments. If one or more of the
6090 annotation functions in `write-region-annotate-functions' changed the
6091 current buffer, the function stored in this variable is called for
6092 each of those additional buffers as well, in addition to the original
6093 buffer. The relevant buffer is current during each function call. */);
6094 Vwrite_region_post_annotation_function = Qnil;
6095 staticpro (&Vwrite_region_annotation_buffers);
6097 DEFVAR_LISP ("write-region-annotations-so-far",
6098 Vwrite_region_annotations_so_far,
6099 doc: /* When an annotation function is called, this holds the previous annotations.
6100 These are the annotations made by other annotation functions
6101 that were already called. See also `write-region-annotate-functions'. */);
6102 Vwrite_region_annotations_so_far = Qnil;
6104 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6105 doc: /* A list of file name handlers that temporarily should not be used.
6106 This applies only to the operation `inhibit-file-name-operation'. */);
6107 Vinhibit_file_name_handlers = Qnil;
6109 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6110 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6111 Vinhibit_file_name_operation = Qnil;
6113 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6114 doc: /* File name in which to write a list of all auto save file names.
6115 This variable is initialized automatically from `auto-save-list-file-prefix'
6116 shortly after Emacs reads your init file, if you have not yet given it
6117 a non-nil value. */);
6118 Vauto_save_list_file_name = Qnil;
6120 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6121 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6122 Normally auto-save files are written under other names. */);
6123 Vauto_save_visited_file_name = Qnil;
6125 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6126 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6127 If nil, deleting a substantial portion of the text disables auto-save
6128 in the buffer; this is the default behavior, because the auto-save
6129 file is usually more useful if it contains the deleted text. */);
6130 Vauto_save_include_big_deletions = Qnil;
6132 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6133 doc: /* Non-nil means don't call fsync in `write-region'.
6134 This variable affects calls to `write-region' as well as save commands.
6135 Setting this to nil may avoid data loss if the system loses power or
6136 the operating system crashes. By default, it is non-nil in batch mode. */);
6137 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6139 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6140 doc: /* Specifies whether to use the system's trash can.
6141 When non-nil, certain file deletion commands use the function
6142 `move-file-to-trash' instead of deleting files outright.
6143 This includes interactive calls to `delete-file' and
6144 `delete-directory' and the Dired deletion commands. */);
6145 delete_by_moving_to_trash = 0;
6146 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6148 /* Lisp function for moving files to trash. */
6149 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6151 /* Lisp function for recursively copying directories. */
6152 DEFSYM (Qcopy_directory, "copy-directory");
6154 /* Lisp function for recursively deleting directories. */
6155 DEFSYM (Qdelete_directory, "delete-directory");
6157 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6158 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6160 DEFSYM (Qstdin, "stdin");
6161 DEFSYM (Qstdout, "stdout");
6162 DEFSYM (Qstderr, "stderr");
6164 defsubr (&Sfind_file_name_handler);
6165 defsubr (&Sfile_name_directory);
6166 defsubr (&Sfile_name_nondirectory);
6167 defsubr (&Sunhandled_file_name_directory);
6168 defsubr (&Sfile_name_as_directory);
6169 defsubr (&Sdirectory_name_p);
6170 defsubr (&Sdirectory_file_name);
6171 defsubr (&Smake_temp_name);
6172 defsubr (&Sexpand_file_name);
6173 defsubr (&Ssubstitute_in_file_name);
6174 defsubr (&Scopy_file);
6175 defsubr (&Smake_directory_internal);
6176 defsubr (&Sdelete_directory_internal);
6177 defsubr (&Sdelete_file);
6178 defsubr (&Sfile_name_case_insensitive_p);
6179 defsubr (&Srename_file);
6180 defsubr (&Sadd_name_to_file);
6181 defsubr (&Smake_symbolic_link);
6182 defsubr (&Sfile_name_absolute_p);
6183 defsubr (&Sfile_exists_p);
6184 defsubr (&Sfile_executable_p);
6185 defsubr (&Sfile_readable_p);
6186 defsubr (&Sfile_writable_p);
6187 defsubr (&Saccess_file);
6188 defsubr (&Sfile_symlink_p);
6189 defsubr (&Sfile_directory_p);
6190 defsubr (&Sfile_accessible_directory_p);
6191 defsubr (&Sfile_regular_p);
6192 defsubr (&Sfile_modes);
6193 defsubr (&Sset_file_modes);
6194 defsubr (&Sset_file_times);
6195 defsubr (&Sfile_selinux_context);
6196 defsubr (&Sfile_acl);
6197 defsubr (&Sset_file_acl);
6198 defsubr (&Sset_file_selinux_context);
6199 defsubr (&Sset_default_file_modes);
6200 defsubr (&Sdefault_file_modes);
6201 defsubr (&Sfile_newer_than_file_p);
6202 defsubr (&Sinsert_file_contents);
6203 defsubr (&Swrite_region);
6204 defsubr (&Scar_less_than_car);
6205 defsubr (&Sverify_visited_file_modtime);
6206 defsubr (&Svisited_file_modtime);
6207 defsubr (&Sset_visited_file_modtime);
6208 defsubr (&Sdo_auto_save);
6209 defsubr (&Sset_buffer_auto_saved);
6210 defsubr (&Sclear_buffer_auto_save_failure);
6211 defsubr (&Srecent_auto_save_p);
6213 defsubr (&Snext_read_file_uses_dialog_p);
6215 defsubr (&Sset_binary_mode);
6217 #ifdef HAVE_SYNC
6218 defsubr (&Sunix_sync);
6219 #endif