Add seq-set-equal-p to test for set equality
[emacs.git] / src / fileio.c
blob7f65cf5aaea43c4b2733743dd125d37568b990ec
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 we ignore
271 any handlers that are members of `inhibit-file-name-handlers',
272 but we 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-file-name", Fdirectory_file_name, Sdirectory_file_name,
587 1, 1, 0,
588 doc: /* Returns the file name of the directory named DIRECTORY.
589 This is the name of the file that holds the data for the directory DIRECTORY.
590 This operation exists because a directory is also a file, but its name as
591 a directory is different from its name as a file.
592 In Unix-syntax, this function just removes the final slash. */)
593 (Lisp_Object directory)
595 char *buf;
596 ptrdiff_t length;
597 Lisp_Object handler, val;
598 USE_SAFE_ALLOCA;
600 CHECK_STRING (directory);
602 /* If the file name has special constructs in it,
603 call the corresponding file handler. */
604 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
605 if (!NILP (handler))
607 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
608 directory);
609 if (STRINGP (handled_name))
610 return handled_name;
611 error ("Invalid handler in `file-name-handler-alist'");
614 #ifdef WINDOWSNT
615 if (!NILP (Vw32_downcase_file_names))
616 directory = Fdowncase (directory);
617 #endif
618 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
619 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
620 STRING_MULTIBYTE (directory));
621 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
622 SAFE_FREE ();
623 return val;
626 static const char make_temp_name_tbl[64] =
628 'A','B','C','D','E','F','G','H',
629 'I','J','K','L','M','N','O','P',
630 'Q','R','S','T','U','V','W','X',
631 'Y','Z','a','b','c','d','e','f',
632 'g','h','i','j','k','l','m','n',
633 'o','p','q','r','s','t','u','v',
634 'w','x','y','z','0','1','2','3',
635 '4','5','6','7','8','9','-','_'
638 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
640 /* Value is a temporary file name starting with PREFIX, a string.
642 The Emacs process number forms part of the result, so there is
643 no danger of generating a name being used by another process.
644 In addition, this function makes an attempt to choose a name
645 which has no existing file. To make this work, PREFIX should be
646 an absolute file name.
648 BASE64_P means add the pid as 3 characters in base64
649 encoding. In this case, 6 characters will be added to PREFIX to
650 form the file name. Otherwise, if Emacs is running on a system
651 with long file names, add the pid as a decimal number.
653 This function signals an error if no unique file name could be
654 generated. */
656 Lisp_Object
657 make_temp_name (Lisp_Object prefix, bool base64_p)
659 Lisp_Object val, encoded_prefix;
660 ptrdiff_t len;
661 printmax_t pid;
662 char *p, *data;
663 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
664 int pidlen;
666 CHECK_STRING (prefix);
668 /* VAL is created by adding 6 characters to PREFIX. The first
669 three are the PID of this process, in base 64, and the second
670 three are incremented if the file already exists. This ensures
671 262144 unique file names per PID per PREFIX. */
673 pid = getpid ();
675 if (base64_p)
677 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
678 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
679 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
680 pidlen = 3;
682 else
684 #ifdef HAVE_LONG_FILE_NAMES
685 pidlen = sprintf (pidbuf, "%"pMd, pid);
686 #else
687 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
688 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
689 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
690 pidlen = 3;
691 #endif
694 encoded_prefix = ENCODE_FILE (prefix);
695 len = SBYTES (encoded_prefix);
696 val = make_uninit_string (len + 3 + pidlen);
697 data = SSDATA (val);
698 memcpy (data, SSDATA (encoded_prefix), len);
699 p = data + len;
701 memcpy (p, pidbuf, pidlen);
702 p += pidlen;
704 /* Here we try to minimize useless stat'ing when this function is
705 invoked many times successively with the same PREFIX. We achieve
706 this by initializing count to a random value, and incrementing it
707 afterwards.
709 We don't want make-temp-name to be called while dumping,
710 because then make_temp_name_count_initialized_p would get set
711 and then make_temp_name_count would not be set when Emacs starts. */
713 if (!make_temp_name_count_initialized_p)
715 make_temp_name_count = time (NULL);
716 make_temp_name_count_initialized_p = 1;
719 while (1)
721 unsigned num = make_temp_name_count;
723 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
724 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
725 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
727 /* Poor man's congruential RN generator. Replace with
728 ++make_temp_name_count for debugging. */
729 make_temp_name_count += 25229;
730 make_temp_name_count %= 225307;
732 if (!check_existing (data))
734 /* We want to return only if errno is ENOENT. */
735 if (errno == ENOENT)
736 return DECODE_FILE (val);
737 else
738 /* The error here is dubious, but there is little else we
739 can do. The alternatives are to return nil, which is
740 as bad as (and in many cases worse than) throwing the
741 error, or to ignore the error, which will likely result
742 in looping through 225307 stat's, which is not only
743 dog-slow, but also useless since eventually nil would
744 have to be returned anyway. */
745 report_file_error ("Cannot create temporary name for prefix",
746 prefix);
747 /* not reached */
753 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
754 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
755 The Emacs process number forms part of the result, so there is no
756 danger of generating a name being used by another Emacs process
757 \(so long as only a single host can access the containing directory...).
759 This function tries to choose a name that has no existing file.
760 For this to work, PREFIX should be an absolute file name.
762 There is a race condition between calling `make-temp-name' and creating the
763 file, which opens all kinds of security holes. For that reason, you should
764 normally use `make-temp-file' instead. */)
765 (Lisp_Object prefix)
767 return make_temp_name (prefix, 0);
770 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
771 doc: /* Convert filename NAME to absolute, and canonicalize it.
772 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
773 \(does not start with slash or tilde); both the directory name and
774 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
775 missing, the current buffer's value of `default-directory' is used.
776 NAME should be a string that is a valid file name for the underlying
777 filesystem.
778 File name components that are `.' are removed, and
779 so are file name components followed by `..', along with the `..' itself;
780 note that these simplifications are done without checking the resulting
781 file names in the file system.
782 Multiple consecutive slashes are collapsed into a single slash,
783 except at the beginning of the file name when they are significant (e.g.,
784 UNC file names on MS-Windows.)
785 An initial `~/' expands to your home directory.
786 An initial `~USER/' expands to USER's home directory.
787 See also the function `substitute-in-file-name'.
789 For technical reasons, this function can return correct but
790 non-intuitive results for the root directory; for instance,
791 \(expand-file-name ".." "/") returns "/..". For this reason, use
792 \(directory-file-name (file-name-directory dirname)) to traverse a
793 filesystem tree, not (expand-file-name ".." dirname). */)
794 (Lisp_Object name, Lisp_Object default_directory)
796 /* These point to SDATA and need to be careful with string-relocation
797 during GC (via DECODE_FILE). */
798 char *nm;
799 char *nmlim;
800 const char *newdir;
801 const char *newdirlim;
802 /* This should only point to alloca'd data. */
803 char *target;
805 ptrdiff_t tlen;
806 struct passwd *pw;
807 #ifdef DOS_NT
808 int drive = 0;
809 bool collapse_newdir = true;
810 bool is_escaped = 0;
811 #endif /* DOS_NT */
812 ptrdiff_t length, nbytes;
813 Lisp_Object handler, result, handled_name;
814 bool multibyte;
815 Lisp_Object hdir;
816 USE_SAFE_ALLOCA;
818 CHECK_STRING (name);
820 /* If the file name has special constructs in it,
821 call the corresponding file handler. */
822 handler = Ffind_file_name_handler (name, Qexpand_file_name);
823 if (!NILP (handler))
825 handled_name = call3 (handler, Qexpand_file_name,
826 name, default_directory);
827 if (STRINGP (handled_name))
828 return handled_name;
829 error ("Invalid handler in `file-name-handler-alist'");
833 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
834 if (NILP (default_directory))
835 default_directory = BVAR (current_buffer, directory);
836 if (! STRINGP (default_directory))
838 #ifdef DOS_NT
839 /* "/" is not considered a root directory on DOS_NT, so using "/"
840 here causes an infinite recursion in, e.g., the following:
842 (let (default-directory)
843 (expand-file-name "a"))
845 To avoid this, we set default_directory to the root of the
846 current drive. */
847 default_directory = build_string (emacs_root_dir ());
848 #else
849 default_directory = build_string ("/");
850 #endif
853 if (!NILP (default_directory))
855 handler = Ffind_file_name_handler (default_directory, 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'");
867 char *o = SSDATA (default_directory);
869 /* Make sure DEFAULT_DIRECTORY is properly expanded.
870 It would be better to do this down below where we actually use
871 default_directory. Unfortunately, calling Fexpand_file_name recursively
872 could invoke GC, and the strings might be relocated. This would
873 be annoying because we have pointers into strings lying around
874 that would need adjusting, and people would add new pointers to
875 the code and forget to adjust them, resulting in intermittent bugs.
876 Putting this call here avoids all that crud.
878 The EQ test avoids infinite recursion. */
879 if (! NILP (default_directory) && !EQ (default_directory, name)
880 /* Save time in some common cases - as long as default_directory
881 is not relative, it can be canonicalized with name below (if it
882 is needed at all) without requiring it to be expanded now. */
883 #ifdef DOS_NT
884 /* Detect MSDOS file names with drive specifiers. */
885 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
886 && IS_DIRECTORY_SEP (o[2]))
887 /* Detect escaped file names without drive spec after "/:".
888 These should not be recursively expanded, to avoid
889 including the default directory twice in the expanded
890 result. */
891 && ! (o[0] == '/' && o[1] == ':')
892 #ifdef WINDOWSNT
893 /* Detect Windows file names in UNC format. */
894 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
895 #endif
896 #else /* not DOS_NT */
897 /* Detect Unix absolute file names (/... alone is not absolute on
898 DOS or Windows). */
899 && ! (IS_DIRECTORY_SEP (o[0]))
900 #endif /* not DOS_NT */
903 default_directory = Fexpand_file_name (default_directory, Qnil);
906 multibyte = STRING_MULTIBYTE (name);
907 if (multibyte != STRING_MULTIBYTE (default_directory))
909 if (multibyte)
911 unsigned char *p = SDATA (name);
913 while (*p && ASCII_CHAR_P (*p))
914 p++;
915 if (*p == '\0')
917 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
918 unibyte. Do not convert DEFAULT_DIRECTORY to
919 multibyte; instead, convert NAME to a unibyte string,
920 so that the result of this function is also a unibyte
921 string. This is needed during bootstrapping and
922 dumping, when Emacs cannot decode file names, because
923 the locale environment is not set up. */
924 name = make_unibyte_string (SSDATA (name), SBYTES (name));
925 multibyte = 0;
927 else
928 default_directory = string_to_multibyte (default_directory);
930 else
932 name = string_to_multibyte (name);
933 multibyte = 1;
937 #ifdef WINDOWSNT
938 if (!NILP (Vw32_downcase_file_names))
939 default_directory = Fdowncase (default_directory);
940 #endif
942 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
943 SAFE_ALLOCA_STRING (nm, name);
944 nmlim = nm + SBYTES (name);
946 #ifdef DOS_NT
947 /* Note if special escape prefix is present, but remove for now. */
948 if (nm[0] == '/' && nm[1] == ':')
950 is_escaped = 1;
951 nm += 2;
954 /* Find and remove drive specifier if present; this makes nm absolute
955 even if the rest of the name appears to be relative. Only look for
956 drive specifier at the beginning. */
957 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
959 drive = (unsigned char) nm[0];
960 nm += 2;
963 #ifdef WINDOWSNT
964 /* If we see "c://somedir", we want to strip the first slash after the
965 colon when stripping the drive letter. Otherwise, this expands to
966 "//somedir". */
967 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
968 nm++;
970 /* Discard any previous drive specifier if nm is now in UNC format. */
971 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
972 && !IS_DIRECTORY_SEP (nm[2]))
973 drive = 0;
974 #endif /* WINDOWSNT */
975 #endif /* DOS_NT */
977 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
978 none are found, we can probably return right away. We will avoid
979 allocating a new string if name is already fully expanded. */
980 if (
981 IS_DIRECTORY_SEP (nm[0])
982 #ifdef MSDOS
983 && drive && !is_escaped
984 #endif
985 #ifdef WINDOWSNT
986 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
987 #endif
990 /* If it turns out that the filename we want to return is just a
991 suffix of FILENAME, we don't need to go through and edit
992 things; we just need to construct a new string using data
993 starting at the middle of FILENAME. If we set LOSE, that
994 means we've discovered that we can't do that cool trick. */
995 bool lose = 0;
996 char *p = nm;
998 while (*p)
1000 /* Since we know the name is absolute, we can assume that each
1001 element starts with a "/". */
1003 /* "." and ".." are hairy. */
1004 if (IS_DIRECTORY_SEP (p[0])
1005 && p[1] == '.'
1006 && (IS_DIRECTORY_SEP (p[2])
1007 || p[2] == 0
1008 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1009 || p[3] == 0))))
1010 lose = 1;
1011 /* Replace multiple slashes with a single one, except
1012 leave leading "//" alone. */
1013 else if (IS_DIRECTORY_SEP (p[0])
1014 && IS_DIRECTORY_SEP (p[1])
1015 && (p != nm || IS_DIRECTORY_SEP (p[2])))
1016 lose = 1;
1017 p++;
1019 if (!lose)
1021 #ifdef DOS_NT
1022 /* Make sure directories are all separated with /, but
1023 avoid allocation of a new string when not required. */
1024 dostounix_filename (nm);
1025 #ifdef WINDOWSNT
1026 if (IS_DIRECTORY_SEP (nm[1]))
1028 if (strcmp (nm, SSDATA (name)) != 0)
1029 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1031 else
1032 #endif
1033 /* Drive must be set, so this is okay. */
1034 if (strcmp (nm - 2, SSDATA (name)) != 0)
1036 name = make_specified_string (nm, -1, p - nm, multibyte);
1037 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1038 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1039 name = concat2 (drive_prefix, name);
1041 #ifdef WINDOWSNT
1042 if (!NILP (Vw32_downcase_file_names))
1043 name = Fdowncase (name);
1044 #endif
1045 #else /* not DOS_NT */
1046 if (strcmp (nm, SSDATA (name)) != 0)
1047 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1048 #endif /* not DOS_NT */
1049 SAFE_FREE ();
1050 return name;
1054 /* At this point, nm might or might not be an absolute file name. We
1055 need to expand ~ or ~user if present, otherwise prefix nm with
1056 default_directory if nm is not absolute, and finally collapse /./
1057 and /foo/../ sequences.
1059 We set newdir to be the appropriate prefix if one is needed:
1060 - the relevant user directory if nm starts with ~ or ~user
1061 - the specified drive's working dir (DOS/NT only) if nm does not
1062 start with /
1063 - the value of default_directory.
1065 Note that these prefixes are not guaranteed to be absolute (except
1066 for the working dir of a drive). Therefore, to ensure we always
1067 return an absolute name, if the final prefix is not absolute we
1068 append it to the current working directory. */
1070 newdir = newdirlim = 0;
1072 if (nm[0] == '~' /* prefix ~ */
1073 #ifdef DOS_NT
1074 && !is_escaped /* don't expand ~ in escaped file names */
1075 #endif
1078 if (IS_DIRECTORY_SEP (nm[1])
1079 || nm[1] == 0) /* ~ by itself */
1081 Lisp_Object tem;
1083 if (!(newdir = egetenv ("HOME")))
1084 newdir = newdirlim = "";
1085 nm++;
1086 #ifdef WINDOWSNT
1087 if (newdir[0])
1089 char newdir_utf8[MAX_UTF8_PATH];
1091 filename_from_ansi (newdir, newdir_utf8);
1092 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1093 newdir = SSDATA (tem);
1095 else
1096 #endif
1097 tem = build_string (newdir);
1098 newdirlim = newdir + SBYTES (tem);
1099 /* `egetenv' may return a unibyte string, which will bite us
1100 if we expect the directory to be multibyte. */
1101 if (multibyte && !STRING_MULTIBYTE (tem))
1103 hdir = DECODE_FILE (tem);
1104 newdir = SSDATA (hdir);
1105 newdirlim = newdir + SBYTES (hdir);
1107 #ifdef DOS_NT
1108 collapse_newdir = false;
1109 #endif
1111 else /* ~user/filename */
1113 char *o, *p;
1114 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1115 continue;
1116 o = SAFE_ALLOCA (p - nm + 1);
1117 memcpy (o, nm, p - nm);
1118 o[p - nm] = 0;
1120 block_input ();
1121 pw = getpwnam (o + 1);
1122 unblock_input ();
1123 if (pw)
1125 Lisp_Object tem;
1127 newdir = pw->pw_dir;
1128 /* `getpwnam' may return a unibyte string, which will
1129 bite us when we expect the directory to be multibyte. */
1130 tem = make_unibyte_string (newdir, strlen (newdir));
1131 newdirlim = newdir + SBYTES (tem);
1132 if (multibyte && !STRING_MULTIBYTE (tem))
1134 hdir = DECODE_FILE (tem);
1135 newdir = SSDATA (hdir);
1136 newdirlim = newdir + SBYTES (hdir);
1138 nm = p;
1139 #ifdef DOS_NT
1140 collapse_newdir = false;
1141 #endif
1144 /* If we don't find a user of that name, leave the name
1145 unchanged; don't move nm forward to p. */
1149 #ifdef DOS_NT
1150 /* On DOS and Windows, nm is absolute if a drive name was specified;
1151 use the drive's current directory as the prefix if needed. */
1152 if (!newdir && drive)
1154 /* Get default directory if needed to make nm absolute. */
1155 char *adir = NULL;
1156 if (!IS_DIRECTORY_SEP (nm[0]))
1158 adir = alloca (MAXPATHLEN + 1);
1159 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1160 adir = NULL;
1161 else if (multibyte)
1163 Lisp_Object tem = build_string (adir);
1165 tem = DECODE_FILE (tem);
1166 newdirlim = adir + SBYTES (tem);
1167 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1169 else
1170 newdirlim = adir + strlen (adir);
1172 if (!adir)
1174 /* Either nm starts with /, or drive isn't mounted. */
1175 adir = alloca (4);
1176 adir[0] = DRIVE_LETTER (drive);
1177 adir[1] = ':';
1178 adir[2] = '/';
1179 adir[3] = 0;
1180 newdirlim = adir + 3;
1182 newdir = adir;
1184 #endif /* DOS_NT */
1186 /* Finally, if no prefix has been specified and nm is not absolute,
1187 then it must be expanded relative to default_directory. */
1189 if (1
1190 #ifndef DOS_NT
1191 /* /... alone is not absolute on DOS and Windows. */
1192 && !IS_DIRECTORY_SEP (nm[0])
1193 #endif
1194 #ifdef WINDOWSNT
1195 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1196 && !IS_DIRECTORY_SEP (nm[2]))
1197 #endif
1198 && !newdir)
1200 newdir = SSDATA (default_directory);
1201 newdirlim = newdir + SBYTES (default_directory);
1202 #ifdef DOS_NT
1203 /* Note if special escape prefix is present, but remove for now. */
1204 if (newdir[0] == '/' && newdir[1] == ':')
1206 is_escaped = 1;
1207 newdir += 2;
1209 #endif
1212 #ifdef DOS_NT
1213 if (newdir)
1215 /* First ensure newdir is an absolute name. */
1216 if (
1217 /* Detect MSDOS file names with drive specifiers. */
1218 ! (IS_DRIVE (newdir[0])
1219 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1220 #ifdef WINDOWSNT
1221 /* Detect Windows file names in UNC format. */
1222 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1223 && !IS_DIRECTORY_SEP (newdir[2]))
1224 #endif
1227 /* Effectively, let newdir be (expand-file-name newdir cwd).
1228 Because of the admonition against calling expand-file-name
1229 when we have pointers into lisp strings, we accomplish this
1230 indirectly by prepending newdir to nm if necessary, and using
1231 cwd (or the wd of newdir's drive) as the new newdir. */
1232 char *adir;
1233 #ifdef WINDOWSNT
1234 const int adir_size = MAX_UTF8_PATH;
1235 #else
1236 const int adir_size = MAXPATHLEN + 1;
1237 #endif
1239 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1241 drive = (unsigned char) newdir[0];
1242 newdir += 2;
1244 if (!IS_DIRECTORY_SEP (nm[0]))
1246 ptrdiff_t nmlen = nmlim - nm;
1247 ptrdiff_t newdirlen = newdirlim - newdir;
1248 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1249 + nmlen + 1);
1250 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1251 multibyte);
1252 memcpy (tmp + dlen, nm, nmlen + 1);
1253 nm = tmp;
1254 nmlim = nm + dlen + nmlen;
1256 adir = alloca (adir_size);
1257 if (drive)
1259 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1260 strcpy (adir, "/");
1262 else
1263 getcwd (adir, adir_size);
1264 if (multibyte)
1266 Lisp_Object tem = build_string (adir);
1268 tem = DECODE_FILE (tem);
1269 newdirlim = adir + SBYTES (tem);
1270 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1272 else
1273 newdirlim = adir + strlen (adir);
1274 newdir = adir;
1277 /* Strip off drive name from prefix, if present. */
1278 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1280 drive = newdir[0];
1281 newdir += 2;
1284 /* Keep only a prefix from newdir if nm starts with slash
1285 (//server/share for UNC, nothing otherwise). */
1286 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1288 #ifdef WINDOWSNT
1289 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1290 && !IS_DIRECTORY_SEP (newdir[2]))
1292 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1293 char *p = adir + 2;
1294 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1295 p++;
1296 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1297 *p = 0;
1298 newdir = adir;
1299 newdirlim = newdir + strlen (adir);
1301 else
1302 #endif
1303 newdir = newdirlim = "";
1306 #endif /* DOS_NT */
1308 /* Ignore any slash at the end of newdir, unless newdir is
1309 just "/" or "//". */
1310 length = newdirlim - newdir;
1311 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1312 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1313 length--;
1315 /* Now concatenate the directory and name to new space in the stack frame. */
1316 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1317 eassert (tlen > file_name_as_directory_slop + 1);
1318 #ifdef DOS_NT
1319 /* Reserve space for drive specifier and escape prefix, since either
1320 or both may need to be inserted. (The Microsoft x86 compiler
1321 produces incorrect code if the following two lines are combined.) */
1322 target = alloca (tlen + 4);
1323 target += 4;
1324 #else /* not DOS_NT */
1325 target = SAFE_ALLOCA (tlen);
1326 #endif /* not DOS_NT */
1327 *target = 0;
1328 nbytes = 0;
1330 if (newdir)
1332 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1334 #ifdef DOS_NT
1335 /* If newdir is effectively "C:/", then the drive letter will have
1336 been stripped and newdir will be "/". Concatenating with an
1337 absolute directory in nm produces "//", which will then be
1338 incorrectly treated as a network share. Ignore newdir in
1339 this case (keeping the drive letter). */
1340 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1341 && newdir[1] == '\0'))
1342 #endif
1344 memcpy (target, newdir, length);
1345 target[length] = 0;
1346 nbytes = length;
1349 else
1350 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1353 memcpy (target + nbytes, nm, nmlim - nm + 1);
1355 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1356 appear. */
1358 char *p = target;
1359 char *o = target;
1361 while (*p)
1363 if (!IS_DIRECTORY_SEP (*p))
1365 *o++ = *p++;
1367 else if (p[1] == '.'
1368 && (IS_DIRECTORY_SEP (p[2])
1369 || p[2] == 0))
1371 /* If "/." is the entire filename, keep the "/". Otherwise,
1372 just delete the whole "/.". */
1373 if (o == target && p[2] == '\0')
1374 *o++ = *p;
1375 p += 2;
1377 else if (p[1] == '.' && p[2] == '.'
1378 /* `/../' is the "superroot" on certain file systems.
1379 Turned off on DOS_NT systems because they have no
1380 "superroot" and because this causes us to produce
1381 file names like "d:/../foo" which fail file-related
1382 functions of the underlying OS. (To reproduce, try a
1383 long series of "../../" in default_directory, longer
1384 than the number of levels from the root.) */
1385 #ifndef DOS_NT
1386 && o != target
1387 #endif
1388 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1390 #ifdef WINDOWSNT
1391 char *prev_o = o;
1392 #endif
1393 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1394 continue;
1395 #ifdef WINDOWSNT
1396 /* Don't go below server level in UNC filenames. */
1397 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1398 && IS_DIRECTORY_SEP (*target))
1399 o = prev_o;
1400 else
1401 #endif
1402 /* Keep initial / only if this is the whole name. */
1403 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1404 ++o;
1405 p += 3;
1407 else if (IS_DIRECTORY_SEP (p[1])
1408 && (p != target || IS_DIRECTORY_SEP (p[2])))
1409 /* Collapse multiple "/", except leave leading "//" alone. */
1410 p++;
1411 else
1413 *o++ = *p++;
1417 #ifdef DOS_NT
1418 /* At last, set drive name. */
1419 #ifdef WINDOWSNT
1420 /* Except for network file name. */
1421 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1422 #endif /* WINDOWSNT */
1424 if (!drive) emacs_abort ();
1425 target -= 2;
1426 target[0] = DRIVE_LETTER (drive);
1427 target[1] = ':';
1429 /* Reinsert the escape prefix if required. */
1430 if (is_escaped)
1432 target -= 2;
1433 target[0] = '/';
1434 target[1] = ':';
1436 result = make_specified_string (target, -1, o - target, multibyte);
1437 dostounix_filename (SSDATA (result));
1438 #ifdef WINDOWSNT
1439 if (!NILP (Vw32_downcase_file_names))
1440 result = Fdowncase (result);
1441 #endif
1442 #else /* !DOS_NT */
1443 result = make_specified_string (target, -1, o - target, multibyte);
1444 #endif /* !DOS_NT */
1447 /* Again look to see if the file name has special constructs in it
1448 and perhaps call the corresponding file handler. This is needed
1449 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1450 the ".." component gives us "/user@host:/bar/../baz" which needs
1451 to be expanded again. */
1452 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1453 if (!NILP (handler))
1455 handled_name = call3 (handler, Qexpand_file_name,
1456 result, default_directory);
1457 if (! STRINGP (handled_name))
1458 error ("Invalid handler in `file-name-handler-alist'");
1459 result = handled_name;
1462 SAFE_FREE ();
1463 return result;
1466 #if 0
1467 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1468 This is the old version of expand-file-name, before it was thoroughly
1469 rewritten for Emacs 10.31. We leave this version here commented-out,
1470 because the code is very complex and likely to have subtle bugs. If
1471 bugs _are_ found, it might be of interest to look at the old code and
1472 see what did it do in the relevant situation.
1474 Don't remove this code: it's true that it will be accessible
1475 from the repository, but a few years from deletion, people will
1476 forget it is there. */
1478 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1479 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1480 "Convert FILENAME to absolute, and canonicalize it.\n\
1481 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1482 \(does not start with slash); if DEFAULT is nil or missing,\n\
1483 the current buffer's value of default-directory is used.\n\
1484 Filenames containing `.' or `..' as components are simplified;\n\
1485 initial `~/' expands to your home directory.\n\
1486 See also the function `substitute-in-file-name'.")
1487 (name, defalt)
1488 Lisp_Object name, defalt;
1490 unsigned char *nm;
1492 register unsigned char *newdir, *p, *o;
1493 ptrdiff_t tlen;
1494 unsigned char *target;
1495 struct passwd *pw;
1497 CHECK_STRING (name);
1498 nm = SDATA (name);
1500 /* If nm is absolute, flush ...// and detect /./ and /../.
1501 If no /./ or /../ we can return right away. */
1502 if (nm[0] == '/')
1504 bool lose = 0;
1505 p = nm;
1506 while (*p)
1508 if (p[0] == '/' && p[1] == '/')
1509 nm = p + 1;
1510 if (p[0] == '/' && p[1] == '~')
1511 nm = p + 1, lose = 1;
1512 if (p[0] == '/' && p[1] == '.'
1513 && (p[2] == '/' || p[2] == 0
1514 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1515 lose = 1;
1516 p++;
1518 if (!lose)
1520 if (nm == SDATA (name))
1521 return name;
1522 return build_string (nm);
1526 /* Now determine directory to start with and put it in NEWDIR. */
1528 newdir = 0;
1530 if (nm[0] == '~') /* prefix ~ */
1531 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1533 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1534 newdir = (unsigned char *) "";
1535 nm++;
1537 else /* ~user/filename */
1539 /* Get past ~ to user. */
1540 unsigned char *user = nm + 1;
1541 /* Find end of name. */
1542 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1543 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1544 /* Copy the user name into temp storage. */
1545 o = alloca (len + 1);
1546 memcpy (o, user, len);
1547 o[len] = 0;
1549 /* Look up the user name. */
1550 block_input ();
1551 pw = (struct passwd *) getpwnam (o + 1);
1552 unblock_input ();
1553 if (!pw)
1554 error ("\"%s\" isn't a registered user", o + 1);
1556 newdir = (unsigned char *) pw->pw_dir;
1558 /* Discard the user name from NM. */
1559 nm += len;
1562 if (nm[0] != '/' && !newdir)
1564 if (NILP (defalt))
1565 defalt = current_buffer->directory;
1566 CHECK_STRING (defalt);
1567 newdir = SDATA (defalt);
1570 /* Now concatenate the directory and name to new space in the stack frame. */
1572 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1573 target = alloca (tlen);
1574 *target = 0;
1576 if (newdir)
1578 if (nm[0] == 0 || nm[0] == '/')
1579 strcpy (target, newdir);
1580 else
1581 file_name_as_directory (target, newdir);
1584 strcat (target, nm);
1586 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1588 p = target;
1589 o = target;
1591 while (*p)
1593 if (*p != '/')
1595 *o++ = *p++;
1597 else if (!strncmp (p, "//", 2)
1600 o = target;
1601 p++;
1603 else if (p[0] == '/' && p[1] == '.'
1604 && (p[2] == '/' || p[2] == 0))
1605 p += 2;
1606 else if (!strncmp (p, "/..", 3)
1607 /* `/../' is the "superroot" on certain file systems. */
1608 && o != target
1609 && (p[3] == '/' || p[3] == 0))
1611 while (o != target && *--o != '/')
1613 if (o == target && *o == '/')
1614 ++o;
1615 p += 3;
1617 else
1619 *o++ = *p++;
1623 return make_string (target, o - target);
1625 #endif
1627 /* If /~ or // appears, discard everything through first slash. */
1628 static bool
1629 file_name_absolute_p (const char *filename)
1631 return
1632 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1633 #ifdef DOS_NT
1634 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1635 && IS_DIRECTORY_SEP (filename[2]))
1636 #endif
1640 static char *
1641 search_embedded_absfilename (char *nm, char *endp)
1643 char *p, *s;
1645 for (p = nm + 1; p < endp; p++)
1647 if (IS_DIRECTORY_SEP (p[-1])
1648 && file_name_absolute_p (p)
1649 #if defined (WINDOWSNT) || defined (CYGWIN)
1650 /* // at start of file name is meaningful in Apollo,
1651 WindowsNT and Cygwin systems. */
1652 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1653 #endif /* not (WINDOWSNT || CYGWIN) */
1656 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1657 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1659 USE_SAFE_ALLOCA;
1660 char *o = SAFE_ALLOCA (s - p + 1);
1661 struct passwd *pw;
1662 memcpy (o, p, s - p);
1663 o [s - p] = 0;
1665 /* If we have ~user and `user' exists, discard
1666 everything up to ~. But if `user' does not exist, leave
1667 ~user alone, it might be a literal file name. */
1668 block_input ();
1669 pw = getpwnam (o + 1);
1670 unblock_input ();
1671 SAFE_FREE ();
1672 if (pw)
1673 return p;
1675 else
1676 return p;
1679 return NULL;
1682 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1683 Ssubstitute_in_file_name, 1, 1, 0,
1684 doc: /* Substitute environment variables referred to in FILENAME.
1685 `$FOO' where FOO is an environment variable name means to substitute
1686 the value of that variable. The variable name should be terminated
1687 with a character not a letter, digit or underscore; otherwise, enclose
1688 the entire variable name in braces.
1690 If `/~' appears, all of FILENAME through that `/' is discarded.
1691 If `//' appears, everything up to and including the first of
1692 those `/' is discarded. */)
1693 (Lisp_Object filename)
1695 char *nm, *p, *x, *endp;
1696 bool substituted = false;
1697 bool multibyte;
1698 char *xnm;
1699 Lisp_Object handler;
1701 CHECK_STRING (filename);
1703 multibyte = STRING_MULTIBYTE (filename);
1705 /* If the file name has special constructs in it,
1706 call the corresponding file handler. */
1707 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1708 if (!NILP (handler))
1710 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1711 filename);
1712 if (STRINGP (handled_name))
1713 return handled_name;
1714 error ("Invalid handler in `file-name-handler-alist'");
1717 /* Always work on a copy of the string, in case GC happens during
1718 decode of environment variables, causing the original Lisp_String
1719 data to be relocated. */
1720 USE_SAFE_ALLOCA;
1721 SAFE_ALLOCA_STRING (nm, filename);
1723 #ifdef DOS_NT
1724 dostounix_filename (nm);
1725 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1726 #endif
1727 endp = nm + SBYTES (filename);
1729 /* If /~ or // appears, discard everything through first slash. */
1730 p = search_embedded_absfilename (nm, endp);
1731 if (p)
1732 /* Start over with the new string, so we check the file-name-handler
1733 again. Important with filenames like "/home/foo//:/hello///there"
1734 which would substitute to "/:/hello///there" rather than "/there". */
1736 Lisp_Object result
1737 = (Fsubstitute_in_file_name
1738 (make_specified_string (p, -1, endp - p, multibyte)));
1739 SAFE_FREE ();
1740 return result;
1743 /* See if any variables are substituted into the string. */
1745 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1747 Lisp_Object name
1748 = (!substituted ? filename
1749 : make_specified_string (nm, -1, endp - nm, multibyte));
1750 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1751 CHECK_STRING (tmp);
1752 if (!EQ (tmp, name))
1753 substituted = true;
1754 filename = tmp;
1757 if (!substituted)
1759 #ifdef WINDOWSNT
1760 if (!NILP (Vw32_downcase_file_names))
1761 filename = Fdowncase (filename);
1762 #endif
1763 SAFE_FREE ();
1764 return filename;
1767 xnm = SSDATA (filename);
1768 x = xnm + SBYTES (filename);
1770 /* If /~ or // appears, discard everything through first slash. */
1771 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1772 /* This time we do not start over because we've already expanded envvars
1773 and replaced $$ with $. Maybe we should start over as well, but we'd
1774 need to quote some $ to $$ first. */
1775 xnm = p;
1777 #ifdef WINDOWSNT
1778 if (!NILP (Vw32_downcase_file_names))
1780 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1782 filename = Fdowncase (xname);
1784 else
1785 #endif
1786 if (xnm != SSDATA (filename))
1787 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1788 SAFE_FREE ();
1789 return filename;
1792 /* A slightly faster and more convenient way to get
1793 (directory-file-name (expand-file-name FOO)). */
1795 Lisp_Object
1796 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1798 register Lisp_Object absname;
1800 absname = Fexpand_file_name (filename, defdir);
1802 /* Remove final slash, if any (unless this is the root dir).
1803 stat behaves differently depending! */
1804 if (SCHARS (absname) > 1
1805 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1806 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1807 /* We cannot take shortcuts; they might be wrong for magic file names. */
1808 absname = Fdirectory_file_name (absname);
1809 return absname;
1812 /* Signal an error if the file ABSNAME already exists.
1813 If KNOWN_TO_EXIST, the file is known to exist.
1814 QUERYSTRING is a name for the action that is being considered
1815 to alter the file.
1816 If INTERACTIVE, ask the user whether to proceed,
1817 and bypass the error if the user says to go ahead.
1818 If QUICK, ask for y or n, not yes or no. */
1820 static void
1821 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1822 const char *querystring, bool interactive,
1823 bool quick)
1825 Lisp_Object tem, encoded_filename;
1826 struct stat statbuf;
1828 encoded_filename = ENCODE_FILE (absname);
1830 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1832 if (S_ISDIR (statbuf.st_mode))
1833 xsignal2 (Qfile_error,
1834 build_string ("File is a directory"), absname);
1835 known_to_exist = true;
1838 if (known_to_exist)
1840 if (! interactive)
1841 xsignal2 (Qfile_already_exists,
1842 build_string ("File already exists"), absname);
1843 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1844 tem = CALLN (Fformat, format, absname, build_string (querystring));
1845 if (quick)
1846 tem = call1 (intern ("y-or-n-p"), tem);
1847 else
1848 tem = do_yes_or_no_p (tem);
1849 if (NILP (tem))
1850 xsignal2 (Qfile_already_exists,
1851 build_string ("File already exists"), absname);
1855 #ifndef WINDOWSNT
1856 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1857 static bool
1858 clone_file (int dest, int source)
1860 #ifdef FICLONE
1861 return ioctl (dest, FICLONE, source) == 0;
1862 #endif
1863 return false;
1865 #endif
1867 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1868 "fCopy file: \nGCopy %s to file: \np\nP",
1869 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1870 If NEWNAME names a directory, copy FILE there.
1872 This function always sets the file modes of the output file to match
1873 the input file.
1875 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1876 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1877 signal a `file-already-exists' error without overwriting. If
1878 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1879 about overwriting; this is what happens in interactive use with M-x.
1880 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1881 existing file.
1883 Fourth arg KEEP-TIME non-nil means give the output file the same
1884 last-modified time as the old one. (This works on only some systems.)
1886 A prefix arg makes KEEP-TIME non-nil.
1888 If PRESERVE-UID-GID is non-nil, we try to transfer the
1889 uid and gid of FILE to NEWNAME.
1891 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1892 this includes the file modes, along with ACL entries and SELinux
1893 context if present. Otherwise, if NEWNAME is created its file
1894 permission bits are those of FILE, masked by the default file
1895 permissions. */)
1896 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1897 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1898 Lisp_Object preserve_permissions)
1900 Lisp_Object handler;
1901 ptrdiff_t count = SPECPDL_INDEX ();
1902 Lisp_Object encoded_file, encoded_newname;
1903 #if HAVE_LIBSELINUX
1904 security_context_t con;
1905 int conlength = 0;
1906 #endif
1907 #ifdef WINDOWSNT
1908 int result;
1909 #else
1910 bool already_exists = false;
1911 mode_t new_mask;
1912 int ifd, ofd;
1913 struct stat st;
1914 #endif
1916 encoded_file = encoded_newname = Qnil;
1917 CHECK_STRING (file);
1918 CHECK_STRING (newname);
1920 if (!NILP (Ffile_directory_p (newname)))
1921 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1922 else
1923 newname = Fexpand_file_name (newname, Qnil);
1925 file = Fexpand_file_name (file, Qnil);
1927 /* If the input file name has special constructs in it,
1928 call the corresponding file handler. */
1929 handler = Ffind_file_name_handler (file, Qcopy_file);
1930 /* Likewise for output file name. */
1931 if (NILP (handler))
1932 handler = Ffind_file_name_handler (newname, Qcopy_file);
1933 if (!NILP (handler))
1934 return call7 (handler, Qcopy_file, file, newname,
1935 ok_if_already_exists, keep_time, preserve_uid_gid,
1936 preserve_permissions);
1938 encoded_file = ENCODE_FILE (file);
1939 encoded_newname = ENCODE_FILE (newname);
1941 #ifdef WINDOWSNT
1942 if (NILP (ok_if_already_exists)
1943 || INTEGERP (ok_if_already_exists))
1944 barf_or_query_if_file_exists (newname, false, "copy to it",
1945 INTEGERP (ok_if_already_exists), false);
1947 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1948 !NILP (keep_time), !NILP (preserve_uid_gid),
1949 !NILP (preserve_permissions));
1950 switch (result)
1952 case -1:
1953 report_file_error ("Copying file", list2 (file, newname));
1954 case -2:
1955 report_file_error ("Copying permissions from", file);
1956 case -3:
1957 xsignal2 (Qfile_date_error,
1958 build_string ("Resetting file times"), newname);
1959 case -4:
1960 report_file_error ("Copying permissions to", newname);
1962 #else /* not WINDOWSNT */
1963 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1965 if (ifd < 0)
1966 report_file_error ("Opening input file", file);
1968 record_unwind_protect_int (close_file_unwind, ifd);
1970 if (fstat (ifd, &st) != 0)
1971 report_file_error ("Input file status", file);
1973 if (!NILP (preserve_permissions))
1975 #if HAVE_LIBSELINUX
1976 if (is_selinux_enabled ())
1978 conlength = fgetfilecon (ifd, &con);
1979 if (conlength == -1)
1980 report_file_error ("Doing fgetfilecon", file);
1982 #endif
1985 /* We can copy only regular files. */
1986 if (!S_ISREG (st.st_mode))
1987 report_file_errno ("Non-regular file", file,
1988 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1990 #ifndef MSDOS
1991 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1992 #else
1993 new_mask = S_IREAD | S_IWRITE;
1994 #endif
1996 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1997 new_mask);
1998 if (ofd < 0 && errno == EEXIST)
2000 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
2001 barf_or_query_if_file_exists (newname, true, "copy to it",
2002 INTEGERP (ok_if_already_exists), false);
2003 already_exists = true;
2004 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
2006 if (ofd < 0)
2007 report_file_error ("Opening output file", newname);
2009 record_unwind_protect_int (close_file_unwind, ofd);
2011 off_t oldsize = 0, newsize;
2013 if (already_exists)
2015 struct stat out_st;
2016 if (fstat (ofd, &out_st) != 0)
2017 report_file_error ("Output file status", newname);
2018 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2019 report_file_errno ("Input and output files are the same",
2020 list2 (file, newname), 0);
2021 if (S_ISREG (out_st.st_mode))
2022 oldsize = out_st.st_size;
2025 maybe_quit ();
2027 if (clone_file (ofd, ifd))
2028 newsize = st.st_size;
2029 else
2031 char buf[MAX_ALLOCA];
2032 ptrdiff_t n;
2033 for (newsize = 0; 0 < (n = emacs_read_quit (ifd, buf, sizeof buf));
2034 newsize += n)
2035 if (emacs_write_quit (ofd, buf, n) != n)
2036 report_file_error ("Write error", newname);
2037 if (n < 0)
2038 report_file_error ("Read error", file);
2041 /* Truncate any existing output file after writing the data. This
2042 is more likely to work than truncation before writing, if the
2043 file system is out of space or the user is over disk quota. */
2044 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2045 report_file_error ("Truncating output file", newname);
2047 #ifndef MSDOS
2048 /* Preserve the original file permissions, and if requested, also its
2049 owner and group. */
2051 mode_t preserved_permissions = st.st_mode & 07777;
2052 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2053 if (!NILP (preserve_uid_gid))
2055 /* Attempt to change owner and group. If that doesn't work
2056 attempt to change just the group, as that is sometimes allowed.
2057 Adjust the mode mask to eliminate setuid or setgid bits
2058 or group permissions bits that are inappropriate if the
2059 owner or group are wrong. */
2060 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2062 if (fchown (ofd, -1, st.st_gid) == 0)
2063 preserved_permissions &= ~04000;
2064 else
2066 preserved_permissions &= ~06000;
2068 /* Copy the other bits to the group bits, since the
2069 group is wrong. */
2070 preserved_permissions &= ~070;
2071 preserved_permissions |= (preserved_permissions & 7) << 3;
2072 default_permissions &= ~070;
2073 default_permissions |= (default_permissions & 7) << 3;
2078 switch (!NILP (preserve_permissions)
2079 ? qcopy_acl (SSDATA (encoded_file), ifd,
2080 SSDATA (encoded_newname), ofd,
2081 preserved_permissions)
2082 : (already_exists
2083 || (new_mask & ~realmask) == default_permissions)
2085 : fchmod (ofd, default_permissions))
2087 case -2: report_file_error ("Copying permissions from", file);
2088 case -1: report_file_error ("Copying permissions to", newname);
2091 #endif /* not MSDOS */
2093 #if HAVE_LIBSELINUX
2094 if (conlength > 0)
2096 /* Set the modified context back to the file. */
2097 bool fail = fsetfilecon (ofd, con) != 0;
2098 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2099 if (fail && errno != ENOTSUP)
2100 report_file_error ("Doing fsetfilecon", newname);
2102 freecon (con);
2104 #endif
2106 if (!NILP (keep_time))
2108 struct timespec atime = get_stat_atime (&st);
2109 struct timespec mtime = get_stat_mtime (&st);
2110 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2111 xsignal2 (Qfile_date_error,
2112 build_string ("Cannot set file date"), newname);
2115 if (emacs_close (ofd) < 0)
2116 report_file_error ("Write error", newname);
2118 emacs_close (ifd);
2120 #ifdef MSDOS
2121 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2122 and if it can't, it tells so. Otherwise, under MSDOS we usually
2123 get only the READ bit, which will make the copied file read-only,
2124 so it's better not to chmod at all. */
2125 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2126 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2127 #endif /* MSDOS */
2128 #endif /* not WINDOWSNT */
2130 /* Discard the unwind protects. */
2131 specpdl_ptr = specpdl + count;
2133 return Qnil;
2136 DEFUN ("make-directory-internal", Fmake_directory_internal,
2137 Smake_directory_internal, 1, 1, 0,
2138 doc: /* Create a new directory named DIRECTORY. */)
2139 (Lisp_Object directory)
2141 const char *dir;
2142 Lisp_Object handler;
2143 Lisp_Object encoded_dir;
2145 CHECK_STRING (directory);
2146 directory = Fexpand_file_name (directory, Qnil);
2148 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2149 if (!NILP (handler))
2150 return call2 (handler, Qmake_directory_internal, directory);
2152 encoded_dir = ENCODE_FILE (directory);
2154 dir = SSDATA (encoded_dir);
2156 #ifdef WINDOWSNT
2157 if (mkdir (dir) != 0)
2158 #else
2159 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2160 #endif
2161 report_file_error ("Creating directory", directory);
2163 return Qnil;
2166 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2167 Sdelete_directory_internal, 1, 1, 0,
2168 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2169 (Lisp_Object directory)
2171 const char *dir;
2172 Lisp_Object encoded_dir;
2174 CHECK_STRING (directory);
2175 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2176 encoded_dir = ENCODE_FILE (directory);
2177 dir = SSDATA (encoded_dir);
2179 if (rmdir (dir) != 0)
2180 report_file_error ("Removing directory", directory);
2182 return Qnil;
2185 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2186 "(list (read-file-name \
2187 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2188 \"Move file to trash: \" \"Delete file: \") \
2189 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2190 (null current-prefix-arg))",
2191 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2192 If file has multiple names, it continues to exist with the other names.
2193 TRASH non-nil means to trash the file instead of deleting, provided
2194 `delete-by-moving-to-trash' is non-nil.
2196 When called interactively, TRASH is t if no prefix argument is given.
2197 With a prefix argument, TRASH is nil. */)
2198 (Lisp_Object filename, Lisp_Object trash)
2200 Lisp_Object handler;
2201 Lisp_Object encoded_file;
2203 if (!NILP (Ffile_directory_p (filename))
2204 && NILP (Ffile_symlink_p (filename)))
2205 xsignal2 (Qfile_error,
2206 build_string ("Removing old name: is a directory"),
2207 filename);
2208 filename = Fexpand_file_name (filename, Qnil);
2210 handler = Ffind_file_name_handler (filename, Qdelete_file);
2211 if (!NILP (handler))
2212 return call3 (handler, Qdelete_file, filename, trash);
2214 if (delete_by_moving_to_trash && !NILP (trash))
2215 return call1 (Qmove_file_to_trash, filename);
2217 encoded_file = ENCODE_FILE (filename);
2219 if (unlink (SSDATA (encoded_file)) < 0)
2220 report_file_error ("Removing old name", filename);
2221 return Qnil;
2224 static Lisp_Object
2225 internal_delete_file_1 (Lisp_Object ignore)
2227 return Qt;
2230 /* Delete file FILENAME, returning true if successful.
2231 This ignores `delete-by-moving-to-trash'. */
2233 bool
2234 internal_delete_file (Lisp_Object filename)
2236 Lisp_Object tem;
2238 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2239 Qt, internal_delete_file_1);
2240 return NILP (tem);
2243 /* Filesystems are case-sensitive on all supported systems except
2244 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2245 case-insensitive on the first two, but they may or may not be
2246 case-insensitive on Cygwin and OS X. The following function
2247 attempts to provide a runtime test on those two systems. If the
2248 test is not conclusive, we assume case-insensitivity on Cygwin and
2249 case-sensitivity on Mac OS X.
2251 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2252 NFS-mounted Windows volumes, might be case-insensitive. Can we
2253 detect this? */
2255 static bool
2256 file_name_case_insensitive_p (const char *filename)
2258 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2259 those flags are available. As of this writing (2016-11-14),
2260 Cygwin is the only platform known to support the former (starting
2261 with Cygwin-2.6.1), and Mac OS X is the only platform known to
2262 support the latter.
2264 There have been reports that pathconf with _PC_CASE_SENSITIVE
2265 does not work reliably on Mac OS X. If you have a problem,
2266 please recompile Emacs with -D DARWIN_OS_CASE_SENSITIVE_FIXME=1 or
2267 -D DARWIN_OS_CASE_SENSITIVE_FIXME=2, and file a bug report saying
2268 whether this fixed your problem. */
2270 #ifdef _PC_CASE_INSENSITIVE
2271 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2272 if (res >= 0)
2273 return res > 0;
2274 #elif defined _PC_CASE_SENSITIVE && !defined DARWIN_OS_CASE_SENSITIVE_FIXME
2275 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2276 if (res >= 0)
2277 return res == 0;
2278 #endif
2280 #ifdef DARWIN_OS
2281 # ifndef DARWIN_OS_CASE_SENSITIVE_FIXME
2282 int DARWIN_OS_CASE_SENSITIVE_FIXME = 0;
2283 # endif
2285 if (DARWIN_OS_CASE_SENSITIVE_FIXME == 1)
2287 /* This is based on developer.apple.com's getattrlist man page. */
2288 struct attrlist alist = {.volattr = ATTR_VOL_CAPABILITIES};
2289 vol_capabilities_attr_t vcaps;
2290 if (getattrlist (filename, &alist, &vcaps, sizeof vcaps, 0) == 0)
2292 if (vcaps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE)
2293 return ! (vcaps.capabilities[VOL_CAPABILITIES_FORMAT]
2294 & VOL_CAP_FMT_CASE_SENSITIVE);
2297 else if (DARWIN_OS_CASE_SENSITIVE_FIXME == 2)
2299 /* The following is based on
2300 http://lists.apple.com/archives/darwin-dev/2007/Apr/msg00010.html. */
2301 struct attrlist alist;
2302 unsigned char buffer[sizeof (vol_capabilities_attr_t) + sizeof (size_t)];
2304 memset (&alist, 0, sizeof (alist));
2305 alist.volattr = ATTR_VOL_CAPABILITIES;
2306 if (getattrlist (filename, &alist, buffer, sizeof (buffer), 0)
2307 || !(alist.volattr & ATTR_VOL_CAPABILITIES))
2308 return 0;
2309 vol_capabilities_attr_t *vcaps = buffer;
2310 return !(vcaps->capabilities[0] & VOL_CAP_FMT_CASE_SENSITIVE);
2312 #endif /* DARWIN_OS */
2314 #if defined CYGWIN || defined DOS_NT
2315 return true;
2316 #else
2317 return false;
2318 #endif
2321 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2322 Sfile_name_case_insensitive_p, 1, 1, 0,
2323 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2324 The arg must be a string. */)
2325 (Lisp_Object filename)
2327 Lisp_Object handler;
2329 CHECK_STRING (filename);
2330 filename = Fexpand_file_name (filename, Qnil);
2332 /* If the file name has special constructs in it,
2333 call the corresponding file handler. */
2334 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2335 if (!NILP (handler))
2336 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2338 filename = ENCODE_FILE (filename);
2339 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2342 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2343 "fRename file: \nGRename %s to file: \np",
2344 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2345 If file has names other than FILE, it continues to have those names.
2346 Signals a `file-already-exists' error if a file NEWNAME already exists
2347 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2348 A number as third arg means request confirmation if NEWNAME already exists.
2349 This is what happens in interactive use with M-x. */)
2350 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2352 Lisp_Object handler;
2353 Lisp_Object encoded_file, encoded_newname, symlink_target;
2355 symlink_target = encoded_file = encoded_newname = Qnil;
2356 CHECK_STRING (file);
2357 CHECK_STRING (newname);
2358 file = Fexpand_file_name (file, Qnil);
2360 if ((!NILP (Ffile_directory_p (newname)))
2361 /* If the filesystem is case-insensitive and the file names are
2362 identical but for the case, don't attempt to move directory
2363 to itself. */
2364 && (NILP (Ffile_name_case_insensitive_p (file))
2365 || NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname)))))
2367 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2368 ? file : Fdirectory_file_name (file));
2369 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2371 else
2372 newname = Fexpand_file_name (newname, Qnil);
2374 /* If the file name has special constructs in it,
2375 call the corresponding file handler. */
2376 handler = Ffind_file_name_handler (file, Qrename_file);
2377 if (NILP (handler))
2378 handler = Ffind_file_name_handler (newname, Qrename_file);
2379 if (!NILP (handler))
2380 return call4 (handler, Qrename_file,
2381 file, newname, ok_if_already_exists);
2383 encoded_file = ENCODE_FILE (file);
2384 encoded_newname = ENCODE_FILE (newname);
2386 /* If the filesystem is case-insensitive and the file names are
2387 identical but for the case, don't ask for confirmation: they
2388 simply want to change the letter-case of the file name. */
2389 if ((!(file_name_case_insensitive_p (SSDATA (encoded_file)))
2390 || NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2391 && ((NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))))
2392 barf_or_query_if_file_exists (newname, false, "rename to it",
2393 INTEGERP (ok_if_already_exists), false);
2394 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2396 int rename_errno = errno;
2397 if (rename_errno == EXDEV)
2399 ptrdiff_t count;
2400 symlink_target = Ffile_symlink_p (file);
2401 if (! NILP (symlink_target))
2402 Fmake_symbolic_link (symlink_target, newname,
2403 NILP (ok_if_already_exists) ? Qnil : Qt);
2404 else if (!NILP (Ffile_directory_p (file)))
2405 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2406 else
2407 /* We have already prompted if it was an integer, so don't
2408 have copy-file prompt again. */
2409 Fcopy_file (file, newname,
2410 NILP (ok_if_already_exists) ? Qnil : Qt,
2411 Qt, Qt, Qt);
2413 count = SPECPDL_INDEX ();
2414 specbind (Qdelete_by_moving_to_trash, Qnil);
2416 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2417 call2 (Qdelete_directory, file, Qt);
2418 else
2419 Fdelete_file (file, Qnil);
2420 unbind_to (count, Qnil);
2422 else
2423 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2426 return Qnil;
2429 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2430 "fAdd name to file: \nGName to add to %s: \np",
2431 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2432 Signals a `file-already-exists' error if a file NEWNAME already exists
2433 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2434 A number as third arg means request confirmation if NEWNAME already exists.
2435 This is what happens in interactive use with M-x. */)
2436 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2438 Lisp_Object handler;
2439 Lisp_Object encoded_file, encoded_newname;
2441 encoded_file = encoded_newname = Qnil;
2442 CHECK_STRING (file);
2443 CHECK_STRING (newname);
2444 file = Fexpand_file_name (file, Qnil);
2446 if (!NILP (Ffile_directory_p (newname)))
2447 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2448 else
2449 newname = Fexpand_file_name (newname, Qnil);
2451 /* If the file name has special constructs in it,
2452 call the corresponding file handler. */
2453 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2454 if (!NILP (handler))
2455 return call4 (handler, Qadd_name_to_file, file,
2456 newname, ok_if_already_exists);
2458 /* If the new name has special constructs in it,
2459 call the corresponding file handler. */
2460 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2461 if (!NILP (handler))
2462 return call4 (handler, Qadd_name_to_file, file,
2463 newname, ok_if_already_exists);
2465 encoded_file = ENCODE_FILE (file);
2466 encoded_newname = ENCODE_FILE (newname);
2468 if (NILP (ok_if_already_exists)
2469 || INTEGERP (ok_if_already_exists))
2470 barf_or_query_if_file_exists (newname, false, "make it a new name",
2471 INTEGERP (ok_if_already_exists), false);
2473 unlink (SSDATA (newname));
2474 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2476 int link_errno = errno;
2477 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2480 return Qnil;
2483 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2484 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2485 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2486 Both args must be strings.
2487 Signals a `file-already-exists' error if a file LINKNAME already exists
2488 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2489 A number as third arg means request confirmation if LINKNAME already exists.
2490 This happens for interactive use with M-x. */)
2491 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2493 Lisp_Object handler;
2494 Lisp_Object encoded_target, encoded_linkname;
2496 encoded_target = encoded_linkname = Qnil;
2497 CHECK_STRING (target);
2498 CHECK_STRING (linkname);
2499 /* If the link target has a ~, we must expand it to get
2500 a truly valid file name. Otherwise, do not expand;
2501 we want to permit links to relative file names. */
2502 if (SREF (target, 0) == '~')
2503 target = Fexpand_file_name (target, Qnil);
2505 if (!NILP (Ffile_directory_p (linkname)))
2506 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2507 else
2508 linkname = Fexpand_file_name (linkname, Qnil);
2510 /* If the file name has special constructs in it,
2511 call the corresponding file handler. */
2512 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2513 if (!NILP (handler))
2514 return call4 (handler, Qmake_symbolic_link, target,
2515 linkname, ok_if_already_exists);
2517 /* If the new link name has special constructs in it,
2518 call the corresponding file handler. */
2519 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2520 if (!NILP (handler))
2521 return call4 (handler, Qmake_symbolic_link, target,
2522 linkname, ok_if_already_exists);
2524 encoded_target = ENCODE_FILE (target);
2525 encoded_linkname = ENCODE_FILE (linkname);
2527 if (NILP (ok_if_already_exists)
2528 || INTEGERP (ok_if_already_exists))
2529 barf_or_query_if_file_exists (linkname, false, "make it a link",
2530 INTEGERP (ok_if_already_exists), false);
2531 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2533 /* If we didn't complain already, silently delete existing file. */
2534 int symlink_errno;
2535 if (errno == EEXIST)
2537 unlink (SSDATA (encoded_linkname));
2538 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2539 >= 0)
2540 return Qnil;
2542 if (errno == ENOSYS)
2543 xsignal1 (Qfile_error,
2544 build_string ("Symbolic links are not supported"));
2546 symlink_errno = errno;
2547 report_file_errno ("Making symbolic link", list2 (target, linkname),
2548 symlink_errno);
2551 return Qnil;
2555 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2556 1, 1, 0,
2557 doc: /* Return t if file FILENAME specifies an absolute file name.
2558 On Unix, this is a name starting with a `/' or a `~'. */)
2559 (Lisp_Object filename)
2561 CHECK_STRING (filename);
2562 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2565 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2566 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2567 See also `file-readable-p' and `file-attributes'.
2568 This returns nil for a symlink to a nonexistent file.
2569 Use `file-symlink-p' to test for such links. */)
2570 (Lisp_Object filename)
2572 Lisp_Object absname;
2573 Lisp_Object handler;
2575 CHECK_STRING (filename);
2576 absname = Fexpand_file_name (filename, Qnil);
2578 /* If the file name has special constructs in it,
2579 call the corresponding file handler. */
2580 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2581 if (!NILP (handler))
2583 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2584 errno = 0;
2585 return result;
2588 absname = ENCODE_FILE (absname);
2590 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2593 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2594 doc: /* Return t if FILENAME can be executed by you.
2595 For a directory, this means you can access files in that directory.
2596 \(It is generally better to use `file-accessible-directory-p' for that
2597 purpose, though.) */)
2598 (Lisp_Object filename)
2600 Lisp_Object absname;
2601 Lisp_Object handler;
2603 CHECK_STRING (filename);
2604 absname = Fexpand_file_name (filename, Qnil);
2606 /* If the file name has special constructs in it,
2607 call the corresponding file handler. */
2608 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2609 if (!NILP (handler))
2610 return call2 (handler, Qfile_executable_p, absname);
2612 absname = ENCODE_FILE (absname);
2614 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2617 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2618 doc: /* Return t if file FILENAME exists and you can read it.
2619 See also `file-exists-p' and `file-attributes'. */)
2620 (Lisp_Object filename)
2622 Lisp_Object absname;
2623 Lisp_Object handler;
2625 CHECK_STRING (filename);
2626 absname = Fexpand_file_name (filename, Qnil);
2628 /* If the file name has special constructs in it,
2629 call the corresponding file handler. */
2630 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2631 if (!NILP (handler))
2632 return call2 (handler, Qfile_readable_p, absname);
2634 absname = ENCODE_FILE (absname);
2635 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2636 ? Qt : Qnil);
2639 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2640 doc: /* Return t if file FILENAME can be written or created by you. */)
2641 (Lisp_Object filename)
2643 Lisp_Object absname, dir, encoded;
2644 Lisp_Object handler;
2646 CHECK_STRING (filename);
2647 absname = Fexpand_file_name (filename, Qnil);
2649 /* If the file name has special constructs in it,
2650 call the corresponding file handler. */
2651 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2652 if (!NILP (handler))
2653 return call2 (handler, Qfile_writable_p, absname);
2655 encoded = ENCODE_FILE (absname);
2656 if (check_writable (SSDATA (encoded), W_OK))
2657 return Qt;
2658 if (errno != ENOENT)
2659 return Qnil;
2661 dir = Ffile_name_directory (absname);
2662 eassert (!NILP (dir));
2663 #ifdef MSDOS
2664 dir = Fdirectory_file_name (dir);
2665 #endif /* MSDOS */
2667 dir = ENCODE_FILE (dir);
2668 #ifdef WINDOWSNT
2669 /* The read-only attribute of the parent directory doesn't affect
2670 whether a file or directory can be created within it. Some day we
2671 should check ACLs though, which do affect this. */
2672 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2673 #else
2674 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2675 #endif
2678 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2679 doc: /* Access file FILENAME, and get an error if that does not work.
2680 The second argument STRING is prepended to the error message.
2681 If there is no error, returns nil. */)
2682 (Lisp_Object filename, Lisp_Object string)
2684 Lisp_Object handler, encoded_filename, absname;
2686 CHECK_STRING (filename);
2687 absname = Fexpand_file_name (filename, Qnil);
2689 CHECK_STRING (string);
2691 /* If the file name has special constructs in it,
2692 call the corresponding file handler. */
2693 handler = Ffind_file_name_handler (absname, Qaccess_file);
2694 if (!NILP (handler))
2695 return call3 (handler, Qaccess_file, absname, string);
2697 encoded_filename = ENCODE_FILE (absname);
2699 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2700 report_file_error (SSDATA (string), filename);
2702 return Qnil;
2705 /* Relative to directory FD, return the symbolic link value of FILENAME.
2706 On failure, return nil. */
2707 Lisp_Object
2708 emacs_readlinkat (int fd, char const *filename)
2710 static struct allocator const emacs_norealloc_allocator =
2711 { xmalloc, NULL, xfree, memory_full };
2712 Lisp_Object val;
2713 char readlink_buf[1024];
2714 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2715 &emacs_norealloc_allocator, readlinkat);
2716 if (!buf)
2717 return Qnil;
2719 val = build_unibyte_string (buf);
2720 if (buf[0] == '/' && strchr (buf, ':'))
2722 AUTO_STRING (slash_colon, "/:");
2723 val = concat2 (slash_colon, val);
2725 if (buf != readlink_buf)
2726 xfree (buf);
2727 val = DECODE_FILE (val);
2728 return val;
2731 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2732 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2733 The value is the link target, as a string.
2734 Otherwise it returns nil.
2736 This function does not check whether the link target exists. */)
2737 (Lisp_Object filename)
2739 Lisp_Object handler;
2741 CHECK_STRING (filename);
2742 filename = Fexpand_file_name (filename, Qnil);
2744 /* If the file name has special constructs in it,
2745 call the corresponding file handler. */
2746 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2747 if (!NILP (handler))
2748 return call2 (handler, Qfile_symlink_p, filename);
2750 filename = ENCODE_FILE (filename);
2752 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2755 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2756 doc: /* Return t if FILENAME names an existing directory.
2757 Symbolic links to directories count as directories.
2758 See `file-symlink-p' to distinguish symlinks. */)
2759 (Lisp_Object filename)
2761 Lisp_Object absname;
2762 Lisp_Object handler;
2764 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2766 /* If the file name has special constructs in it,
2767 call the corresponding file handler. */
2768 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2769 if (!NILP (handler))
2770 return call2 (handler, Qfile_directory_p, absname);
2772 absname = ENCODE_FILE (absname);
2774 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2777 /* Return true if FILE is a directory or a symlink to a directory. */
2778 bool
2779 file_directory_p (char const *file)
2781 #ifdef WINDOWSNT
2782 /* This is cheaper than 'stat'. */
2783 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2784 #else
2785 struct stat st;
2786 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2787 #endif
2790 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2791 Sfile_accessible_directory_p, 1, 1, 0,
2792 doc: /* Return t if FILENAME names a directory you can open.
2793 For the value to be t, FILENAME must specify the name of a directory
2794 as a file, and the directory must allow you to open files in it. In
2795 order to use a directory as a buffer's current directory, this
2796 predicate must return true. A directory name spec may be given
2797 instead; then the value is t if the directory so specified exists and
2798 really is a readable and searchable directory. */)
2799 (Lisp_Object filename)
2801 Lisp_Object absname;
2802 Lisp_Object handler;
2804 CHECK_STRING (filename);
2805 absname = Fexpand_file_name (filename, Qnil);
2807 /* If the file name has special constructs in it,
2808 call the corresponding file handler. */
2809 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2810 if (!NILP (handler))
2812 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2814 /* Set errno in case the handler failed. EACCES might be a lie
2815 (e.g., the directory might not exist, or be a regular file),
2816 but at least it does TRT in the "usual" case of an existing
2817 directory that is not accessible by the current user, and
2818 avoids reporting "Success" for a failed operation. Perhaps
2819 someday we can fix this in a better way, by improving
2820 file-accessible-directory-p's API; see Bug#25419. */
2821 if (!EQ (r, Qt))
2822 errno = EACCES;
2824 return r;
2827 absname = ENCODE_FILE (absname);
2828 return file_accessible_directory_p (absname) ? Qt : Qnil;
2831 /* If FILE is a searchable directory or a symlink to a
2832 searchable directory, return true. Otherwise return
2833 false and set errno to an error number. */
2834 bool
2835 file_accessible_directory_p (Lisp_Object file)
2837 #ifdef DOS_NT
2838 # ifdef WINDOWSNT
2839 /* We need a special-purpose test because (a) NTFS security data is
2840 not reflected in Posix-style mode bits, and (b) the trick with
2841 accessing "DIR/.", used below on Posix hosts, doesn't work on
2842 Windows, because "DIR/." is normalized to just "DIR" before
2843 hitting the disk. */
2844 return (SBYTES (file) == 0
2845 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2846 # else /* MSDOS */
2847 return file_directory_p (SSDATA (file));
2848 # endif /* MSDOS */
2849 #else /* !DOS_NT */
2850 /* On POSIXish platforms, use just one system call; this avoids a
2851 race and is typically faster. */
2852 const char *data = SSDATA (file);
2853 ptrdiff_t len = SBYTES (file);
2854 char const *dir;
2855 bool ok;
2856 int saved_errno;
2857 USE_SAFE_ALLOCA;
2859 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2860 There are three exceptions: "", "/", and "//". Leave "" alone,
2861 as it's invalid. Append only "." to the other two exceptions as
2862 "/" and "//" are distinct on some platforms, whereas "/", "///",
2863 "////", etc. are all equivalent. */
2864 if (! len)
2865 dir = data;
2866 else
2868 /* Just check for trailing '/' when deciding whether to append '/'.
2869 That's simpler than testing the two special cases "/" and "//",
2870 and it's a safe optimization here. */
2871 char *buf = SAFE_ALLOCA (len + 3);
2872 memcpy (buf, data, len);
2873 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2874 dir = buf;
2877 ok = check_existing (dir);
2878 saved_errno = errno;
2879 SAFE_FREE ();
2880 errno = saved_errno;
2881 return ok;
2882 #endif /* !DOS_NT */
2885 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2886 doc: /* Return t if FILENAME names a regular file.
2887 This is the sort of file that holds an ordinary stream of data bytes.
2888 Symbolic links to regular files count as regular files.
2889 See `file-symlink-p' to distinguish symlinks. */)
2890 (Lisp_Object filename)
2892 register Lisp_Object absname;
2893 struct stat st;
2894 Lisp_Object handler;
2896 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2898 /* If the file name has special constructs in it,
2899 call the corresponding file handler. */
2900 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2901 if (!NILP (handler))
2902 return call2 (handler, Qfile_regular_p, absname);
2904 absname = ENCODE_FILE (absname);
2906 #ifdef WINDOWSNT
2908 int result;
2909 Lisp_Object tem = Vw32_get_true_file_attributes;
2911 /* Tell stat to use expensive method to get accurate info. */
2912 Vw32_get_true_file_attributes = Qt;
2913 result = stat (SSDATA (absname), &st);
2914 Vw32_get_true_file_attributes = tem;
2916 if (result < 0)
2917 return Qnil;
2918 return S_ISREG (st.st_mode) ? Qt : Qnil;
2920 #else
2921 if (stat (SSDATA (absname), &st) < 0)
2922 return Qnil;
2923 return S_ISREG (st.st_mode) ? Qt : Qnil;
2924 #endif
2927 DEFUN ("file-selinux-context", Ffile_selinux_context,
2928 Sfile_selinux_context, 1, 1, 0,
2929 doc: /* Return SELinux context of file named FILENAME.
2930 The return value is a list (USER ROLE TYPE RANGE), where the list
2931 elements are strings naming the user, role, type, and range of the
2932 file's SELinux security context.
2934 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2935 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2936 (Lisp_Object filename)
2938 Lisp_Object absname;
2939 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2941 Lisp_Object handler;
2942 #if HAVE_LIBSELINUX
2943 security_context_t con;
2944 int conlength;
2945 context_t context;
2946 #endif
2948 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2950 /* If the file name has special constructs in it,
2951 call the corresponding file handler. */
2952 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2953 if (!NILP (handler))
2954 return call2 (handler, Qfile_selinux_context, absname);
2956 absname = ENCODE_FILE (absname);
2958 #if HAVE_LIBSELINUX
2959 if (is_selinux_enabled ())
2961 conlength = lgetfilecon (SSDATA (absname), &con);
2962 if (conlength > 0)
2964 context = context_new (con);
2965 if (context_user_get (context))
2966 user = build_string (context_user_get (context));
2967 if (context_role_get (context))
2968 role = build_string (context_role_get (context));
2969 if (context_type_get (context))
2970 type = build_string (context_type_get (context));
2971 if (context_range_get (context))
2972 range = build_string (context_range_get (context));
2973 context_free (context);
2974 freecon (con);
2977 #endif
2979 return list4 (user, role, type, range);
2982 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2983 Sset_file_selinux_context, 2, 2, 0,
2984 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2985 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2986 elements are strings naming the components of a SELinux context.
2988 Value is t if setting of SELinux context was successful, nil otherwise.
2990 This function does nothing and returns nil if SELinux is disabled,
2991 or if Emacs was not compiled with SELinux support. */)
2992 (Lisp_Object filename, Lisp_Object context)
2994 Lisp_Object absname;
2995 Lisp_Object handler;
2996 #if HAVE_LIBSELINUX
2997 Lisp_Object encoded_absname;
2998 Lisp_Object user = CAR_SAFE (context);
2999 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
3000 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
3001 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
3002 security_context_t con;
3003 bool fail;
3004 int conlength;
3005 context_t parsed_con;
3006 #endif
3008 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3010 /* If the file name has special constructs in it,
3011 call the corresponding file handler. */
3012 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
3013 if (!NILP (handler))
3014 return call3 (handler, Qset_file_selinux_context, absname, context);
3016 #if HAVE_LIBSELINUX
3017 if (is_selinux_enabled ())
3019 /* Get current file context. */
3020 encoded_absname = ENCODE_FILE (absname);
3021 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
3022 if (conlength > 0)
3024 parsed_con = context_new (con);
3025 /* Change the parts defined in the parameter.*/
3026 if (STRINGP (user))
3028 if (context_user_set (parsed_con, SSDATA (user)))
3029 error ("Doing context_user_set");
3031 if (STRINGP (role))
3033 if (context_role_set (parsed_con, SSDATA (role)))
3034 error ("Doing context_role_set");
3036 if (STRINGP (type))
3038 if (context_type_set (parsed_con, SSDATA (type)))
3039 error ("Doing context_type_set");
3041 if (STRINGP (range))
3043 if (context_range_set (parsed_con, SSDATA (range)))
3044 error ("Doing context_range_set");
3047 /* Set the modified context back to the file. */
3048 fail = (lsetfilecon (SSDATA (encoded_absname),
3049 context_str (parsed_con))
3050 != 0);
3051 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
3052 if (fail && errno != ENOTSUP)
3053 report_file_error ("Doing lsetfilecon", absname);
3055 context_free (parsed_con);
3056 freecon (con);
3057 return fail ? Qnil : Qt;
3059 else
3060 report_file_error ("Doing lgetfilecon", absname);
3062 #endif
3064 return Qnil;
3067 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
3068 doc: /* Return ACL entries of file named FILENAME.
3069 The entries are returned in a format suitable for use in `set-file-acl'
3070 but is otherwise undocumented and subject to change.
3071 Return nil if file does not exist or is not accessible, or if Emacs
3072 was unable to determine the ACL entries. */)
3073 (Lisp_Object filename)
3075 #if USE_ACL
3076 Lisp_Object absname;
3077 Lisp_Object handler;
3078 # ifdef HAVE_ACL_SET_FILE
3079 acl_t acl;
3080 Lisp_Object acl_string;
3081 char *str;
3082 # ifndef HAVE_ACL_TYPE_EXTENDED
3083 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
3084 # endif
3085 # endif
3087 absname = expand_and_dir_to_file (filename,
3088 BVAR (current_buffer, directory));
3090 /* If the file name has special constructs in it,
3091 call the corresponding file handler. */
3092 handler = Ffind_file_name_handler (absname, Qfile_acl);
3093 if (!NILP (handler))
3094 return call2 (handler, Qfile_acl, absname);
3096 # ifdef HAVE_ACL_SET_FILE
3097 absname = ENCODE_FILE (absname);
3099 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3100 if (acl == NULL)
3101 return Qnil;
3103 str = acl_to_text (acl, NULL);
3104 if (str == NULL)
3106 acl_free (acl);
3107 return Qnil;
3110 acl_string = build_string (str);
3111 acl_free (str);
3112 acl_free (acl);
3114 return acl_string;
3115 # endif
3116 #endif
3118 return Qnil;
3121 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3122 2, 2, 0,
3123 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3124 ACL-STRING should contain the textual representation of the ACL
3125 entries in a format suitable for the platform.
3127 Value is t if setting of ACL was successful, nil otherwise.
3129 Setting ACL for local files requires Emacs to be built with ACL
3130 support. */)
3131 (Lisp_Object filename, Lisp_Object acl_string)
3133 #if USE_ACL
3134 Lisp_Object absname;
3135 Lisp_Object handler;
3136 # ifdef HAVE_ACL_SET_FILE
3137 Lisp_Object encoded_absname;
3138 acl_t acl;
3139 bool fail;
3140 # endif
3142 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3144 /* If the file name has special constructs in it,
3145 call the corresponding file handler. */
3146 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3147 if (!NILP (handler))
3148 return call3 (handler, Qset_file_acl, absname, acl_string);
3150 # ifdef HAVE_ACL_SET_FILE
3151 if (STRINGP (acl_string))
3153 acl = acl_from_text (SSDATA (acl_string));
3154 if (acl == NULL)
3156 report_file_error ("Converting ACL", absname);
3157 return Qnil;
3160 encoded_absname = ENCODE_FILE (absname);
3162 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3163 acl)
3164 != 0);
3165 if (fail && acl_errno_valid (errno))
3166 report_file_error ("Setting ACL", absname);
3168 acl_free (acl);
3169 return fail ? Qnil : Qt;
3171 # endif
3172 #endif
3174 return Qnil;
3177 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3178 doc: /* Return mode bits of file named FILENAME, as an integer.
3179 Return nil, if file does not exist or is not accessible. */)
3180 (Lisp_Object filename)
3182 Lisp_Object absname;
3183 struct stat st;
3184 Lisp_Object handler;
3186 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3188 /* If the file name has special constructs in it,
3189 call the corresponding file handler. */
3190 handler = Ffind_file_name_handler (absname, Qfile_modes);
3191 if (!NILP (handler))
3192 return call2 (handler, Qfile_modes, absname);
3194 absname = ENCODE_FILE (absname);
3196 if (stat (SSDATA (absname), &st) < 0)
3197 return Qnil;
3199 return make_number (st.st_mode & 07777);
3202 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3203 "(let ((file (read-file-name \"File: \"))) \
3204 (list file (read-file-modes nil file)))",
3205 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3206 Only the 12 low bits of MODE are used.
3208 Interactively, mode bits are read by `read-file-modes', which accepts
3209 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3210 (Lisp_Object filename, Lisp_Object mode)
3212 Lisp_Object absname, encoded_absname;
3213 Lisp_Object handler;
3215 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3216 CHECK_NUMBER (mode);
3218 /* If the file name has special constructs in it,
3219 call the corresponding file handler. */
3220 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3221 if (!NILP (handler))
3222 return call3 (handler, Qset_file_modes, absname, mode);
3224 encoded_absname = ENCODE_FILE (absname);
3226 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3227 report_file_error ("Doing chmod", absname);
3229 return Qnil;
3232 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3233 doc: /* Set the file permission bits for newly created files.
3234 The argument MODE should be an integer; only the low 9 bits are used.
3235 This setting is inherited by subprocesses. */)
3236 (Lisp_Object mode)
3238 mode_t oldrealmask, oldumask, newumask;
3239 CHECK_NUMBER (mode);
3240 oldrealmask = realmask;
3241 newumask = ~ XINT (mode) & 0777;
3243 block_input ();
3244 realmask = newumask;
3245 oldumask = umask (newumask);
3246 unblock_input ();
3248 eassert (oldumask == oldrealmask);
3249 return Qnil;
3252 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3253 doc: /* Return the default file protection for created files.
3254 The value is an integer. */)
3255 (void)
3257 Lisp_Object value;
3258 XSETINT (value, (~ realmask) & 0777);
3259 return value;
3263 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3264 doc: /* Set times of file FILENAME to TIMESTAMP.
3265 Set both access and modification times.
3266 Return t on success, else nil.
3267 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3268 `current-time'. */)
3269 (Lisp_Object filename, Lisp_Object timestamp)
3271 Lisp_Object absname, encoded_absname;
3272 Lisp_Object handler;
3273 struct timespec t = lisp_time_argument (timestamp);
3275 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3277 /* If the file name has special constructs in it,
3278 call the corresponding file handler. */
3279 handler = Ffind_file_name_handler (absname, Qset_file_times);
3280 if (!NILP (handler))
3281 return call3 (handler, Qset_file_times, absname, timestamp);
3283 encoded_absname = ENCODE_FILE (absname);
3286 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3288 #ifdef MSDOS
3289 /* Setting times on a directory always fails. */
3290 if (file_directory_p (SSDATA (encoded_absname)))
3291 return Qnil;
3292 #endif
3293 report_file_error ("Setting file times", absname);
3297 return Qt;
3300 #ifdef HAVE_SYNC
3301 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3302 doc: /* Tell Unix to finish all pending disk updates. */)
3303 (void)
3305 sync ();
3306 return Qnil;
3309 #endif /* HAVE_SYNC */
3311 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3312 doc: /* Return t if file FILE1 is newer than file FILE2.
3313 If FILE1 does not exist, the answer is nil;
3314 otherwise, if FILE2 does not exist, the answer is t. */)
3315 (Lisp_Object file1, Lisp_Object file2)
3317 Lisp_Object absname1, absname2;
3318 struct stat st1, st2;
3319 Lisp_Object handler;
3321 CHECK_STRING (file1);
3322 CHECK_STRING (file2);
3324 absname1 = Qnil;
3325 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3326 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3328 /* If the file name has special constructs in it,
3329 call the corresponding file handler. */
3330 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3331 if (NILP (handler))
3332 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3333 if (!NILP (handler))
3334 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3336 absname1 = ENCODE_FILE (absname1);
3337 absname2 = ENCODE_FILE (absname2);
3339 if (stat (SSDATA (absname1), &st1) < 0)
3340 return Qnil;
3342 if (stat (SSDATA (absname2), &st2) < 0)
3343 return Qt;
3345 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3346 ? Qt : Qnil);
3349 #ifndef READ_BUF_SIZE
3350 #define READ_BUF_SIZE (64 << 10)
3351 #endif
3352 /* Some buffer offsets are stored in 'int' variables. */
3353 verify (READ_BUF_SIZE <= INT_MAX);
3355 /* This function is called after Lisp functions to decide a coding
3356 system are called, or when they cause an error. Before they are
3357 called, the current buffer is set unibyte and it contains only a
3358 newly inserted text (thus the buffer was empty before the
3359 insertion).
3361 The functions may set markers, overlays, text properties, or even
3362 alter the buffer contents, change the current buffer.
3364 Here, we reset all those changes by:
3365 o set back the current buffer.
3366 o move all markers and overlays to BEG.
3367 o remove all text properties.
3368 o set back the buffer multibyteness. */
3370 static void
3371 decide_coding_unwind (Lisp_Object unwind_data)
3373 Lisp_Object multibyte, undo_list, buffer;
3375 multibyte = XCAR (unwind_data);
3376 unwind_data = XCDR (unwind_data);
3377 undo_list = XCAR (unwind_data);
3378 buffer = XCDR (unwind_data);
3380 set_buffer_internal (XBUFFER (buffer));
3381 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3382 adjust_overlays_for_delete (BEG, Z - BEG);
3383 set_buffer_intervals (current_buffer, NULL);
3384 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3386 /* Now we are safe to change the buffer's multibyteness directly. */
3387 bset_enable_multibyte_characters (current_buffer, multibyte);
3388 bset_undo_list (current_buffer, undo_list);
3391 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3392 object where slot 0 is the file descriptor, slot 1 specifies
3393 an offset to put the read bytes, and slot 2 is the maximum
3394 amount of bytes to read. Value is the number of bytes read. */
3396 static Lisp_Object
3397 read_non_regular (Lisp_Object state)
3399 int nbytes = emacs_read_quit (XSAVE_INTEGER (state, 0),
3400 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3401 + XSAVE_INTEGER (state, 1)),
3402 XSAVE_INTEGER (state, 2));
3403 /* Fast recycle this object for the likely next call. */
3404 free_misc (state);
3405 return make_number (nbytes);
3409 /* Condition-case handler used when reading from non-regular files
3410 in insert-file-contents. */
3412 static Lisp_Object
3413 read_non_regular_quit (Lisp_Object ignore)
3415 return Qnil;
3418 /* Return the file offset that VAL represents, checking for type
3419 errors and overflow. */
3420 static off_t
3421 file_offset (Lisp_Object val)
3423 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3424 return XINT (val);
3426 if (FLOATP (val))
3428 double v = XFLOAT_DATA (val);
3429 if (0 <= v && v < 1.0 + TYPE_MAXIMUM (off_t))
3431 off_t o = v;
3432 if (o == v)
3433 return o;
3437 wrong_type_argument (intern ("file-offset"), val);
3440 /* Return a special time value indicating the error number ERRNUM. */
3441 static struct timespec
3442 time_error_value (int errnum)
3444 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3445 ? NONEXISTENT_MODTIME_NSECS
3446 : UNKNOWN_MODTIME_NSECS);
3447 return make_timespec (0, ns);
3450 static Lisp_Object
3451 get_window_points_and_markers (void)
3453 Lisp_Object pt_marker = Fpoint_marker ();
3454 Lisp_Object windows
3455 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3456 Lisp_Object window_markers = windows;
3457 /* Window markers (and point) are handled specially: rather than move to
3458 just before or just after the modified text, we try to keep the
3459 markers at the same distance (bug#19161).
3460 In general, this is wrong, but for window-markers, this should be harmless
3461 and is convenient for the end user when most of the file is unmodified,
3462 except for a few minor details near the beginning and near the end. */
3463 for (; CONSP (windows); windows = XCDR (windows))
3464 if (WINDOWP (XCAR (windows)))
3466 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3467 XSETCAR (windows,
3468 Fcons (window_marker, Fmarker_position (window_marker)));
3470 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3473 static void
3474 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3475 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3477 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3478 if (CONSP (XCAR (window_markers)))
3480 Lisp_Object car = XCAR (window_markers);
3481 Lisp_Object marker = XCAR (car);
3482 Lisp_Object oldpos = XCDR (car);
3483 if (MARKERP (marker) && INTEGERP (oldpos)
3484 && XINT (oldpos) > same_at_start
3485 && XINT (oldpos) < same_at_end)
3487 ptrdiff_t oldsize = same_at_end - same_at_start;
3488 ptrdiff_t newsize = inserted;
3489 double growth = newsize / (double)oldsize;
3490 ptrdiff_t newpos
3491 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3492 Fset_marker (marker, make_number (newpos), Qnil);
3497 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3498 text as a linear C char array. */
3499 static void
3500 maybe_move_gap (struct buffer *b)
3502 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3504 struct buffer *cb = current_buffer;
3506 set_buffer_internal (b);
3507 move_gap_both (Z, Z_BYTE);
3508 set_buffer_internal (cb);
3512 /* FIXME: insert-file-contents should be split with the top-level moved to
3513 Elisp and only the core kept in C. */
3515 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3516 1, 5, 0,
3517 doc: /* Insert contents of file FILENAME after point.
3518 Returns list of absolute file name and number of characters inserted.
3519 If second argument VISIT is non-nil, the buffer's visited filename and
3520 last save file modtime are set, and it is marked unmodified. If
3521 visiting and the file does not exist, visiting is completed before the
3522 error is signaled.
3524 The optional third and fourth arguments BEG and END specify what portion
3525 of the file to insert. These arguments count bytes in the file, not
3526 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3528 If optional fifth argument REPLACE is non-nil, replace the current
3529 buffer contents (in the accessible portion) with the file contents.
3530 This is better than simply deleting and inserting the whole thing
3531 because (1) it preserves some marker positions and (2) it puts less data
3532 in the undo list. When REPLACE is non-nil, the second return value is
3533 the number of characters that replace previous buffer contents.
3535 This function does code conversion according to the value of
3536 `coding-system-for-read' or `file-coding-system-alist', and sets the
3537 variable `last-coding-system-used' to the coding system actually used.
3539 In addition, this function decodes the inserted text from known formats
3540 by calling `format-decode', which see. */)
3541 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3543 struct stat st;
3544 struct timespec mtime;
3545 int fd;
3546 ptrdiff_t inserted = 0;
3547 ptrdiff_t how_much;
3548 off_t beg_offset, end_offset;
3549 int unprocessed;
3550 ptrdiff_t count = SPECPDL_INDEX ();
3551 Lisp_Object handler, val, insval, orig_filename, old_undo;
3552 Lisp_Object p;
3553 ptrdiff_t total = 0;
3554 bool not_regular = 0;
3555 int save_errno = 0;
3556 char read_buf[READ_BUF_SIZE];
3557 struct coding_system coding;
3558 bool replace_handled = false;
3559 bool set_coding_system = false;
3560 Lisp_Object coding_system;
3561 bool read_quit = false;
3562 /* If the undo log only contains the insertion, there's no point
3563 keeping it. It's typically when we first fill a file-buffer. */
3564 bool empty_undo_list_p
3565 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3566 && BEG == Z);
3567 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3568 bool we_locked_file = false;
3569 ptrdiff_t fd_index;
3570 Lisp_Object window_markers = Qnil;
3571 /* same_at_start and same_at_end count bytes, because file access counts
3572 bytes and BEG and END count bytes. */
3573 ptrdiff_t same_at_start = BEGV_BYTE;
3574 ptrdiff_t same_at_end = ZV_BYTE;
3575 /* SAME_AT_END_CHARPOS counts characters, because
3576 restore_window_points needs the old character count. */
3577 ptrdiff_t same_at_end_charpos = ZV;
3579 if (current_buffer->base_buffer && ! NILP (visit))
3580 error ("Cannot do file visiting in an indirect buffer");
3582 if (!NILP (BVAR (current_buffer, read_only)))
3583 Fbarf_if_buffer_read_only (Qnil);
3585 val = Qnil;
3586 p = Qnil;
3587 orig_filename = Qnil;
3588 old_undo = Qnil;
3590 CHECK_STRING (filename);
3591 filename = Fexpand_file_name (filename, Qnil);
3593 /* The value Qnil means that the coding system is not yet
3594 decided. */
3595 coding_system = Qnil;
3597 /* If the file name has special constructs in it,
3598 call the corresponding file handler. */
3599 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3600 if (!NILP (handler))
3602 val = call6 (handler, Qinsert_file_contents, filename,
3603 visit, beg, end, replace);
3604 if (CONSP (val) && CONSP (XCDR (val))
3605 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3606 inserted = XINT (XCAR (XCDR (val)));
3607 goto handled;
3610 orig_filename = filename;
3611 filename = ENCODE_FILE (filename);
3613 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3614 if (fd < 0)
3616 save_errno = errno;
3617 if (NILP (visit))
3618 report_file_error ("Opening input file", orig_filename);
3619 mtime = time_error_value (save_errno);
3620 st.st_size = -1;
3621 if (!NILP (Vcoding_system_for_read))
3623 /* Don't let invalid values into buffer-file-coding-system. */
3624 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3625 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3627 goto notfound;
3630 fd_index = SPECPDL_INDEX ();
3631 record_unwind_protect_int (close_file_unwind, fd);
3633 /* Replacement should preserve point as it preserves markers. */
3634 if (!NILP (replace))
3636 window_markers = get_window_points_and_markers ();
3637 record_unwind_protect (restore_point_unwind,
3638 XCAR (XCAR (window_markers)));
3641 if (fstat (fd, &st) != 0)
3642 report_file_error ("Input file status", orig_filename);
3643 mtime = get_stat_mtime (&st);
3645 /* This code will need to be changed in order to work on named
3646 pipes, and it's probably just not worth it. So we should at
3647 least signal an error. */
3648 if (!S_ISREG (st.st_mode))
3650 not_regular = 1;
3652 if (! NILP (visit))
3653 goto notfound;
3655 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3656 xsignal2 (Qfile_error,
3657 build_string ("not a regular file"), orig_filename);
3660 if (!NILP (visit))
3662 if (!NILP (beg) || !NILP (end))
3663 error ("Attempt to visit less than an entire file");
3664 if (BEG < Z && NILP (replace))
3665 error ("Cannot do file visiting in a non-empty buffer");
3668 if (!NILP (beg))
3669 beg_offset = file_offset (beg);
3670 else
3671 beg_offset = 0;
3673 if (!NILP (end))
3674 end_offset = file_offset (end);
3675 else
3677 if (not_regular)
3678 end_offset = TYPE_MAXIMUM (off_t);
3679 else
3681 end_offset = st.st_size;
3683 /* A negative size can happen on a platform that allows file
3684 sizes greater than the maximum off_t value. */
3685 if (end_offset < 0)
3686 buffer_overflow ();
3688 /* The file size returned from stat may be zero, but data
3689 may be readable nonetheless, for example when this is a
3690 file in the /proc filesystem. */
3691 if (end_offset == 0)
3692 end_offset = READ_BUF_SIZE;
3696 /* Check now whether the buffer will become too large,
3697 in the likely case where the file's length is not changing.
3698 This saves a lot of needless work before a buffer overflow. */
3699 if (! not_regular)
3701 /* The likely offset where we will stop reading. We could read
3702 more (or less), if the file grows (or shrinks) as we read it. */
3703 off_t likely_end = min (end_offset, st.st_size);
3705 if (beg_offset < likely_end)
3707 ptrdiff_t buf_bytes
3708 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3709 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3710 off_t likely_growth = likely_end - beg_offset;
3711 if (buf_growth_max < likely_growth)
3712 buffer_overflow ();
3716 /* Prevent redisplay optimizations. */
3717 current_buffer->clip_changed = true;
3719 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3721 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3722 setup_coding_system (coding_system, &coding);
3723 /* Ensure we set Vlast_coding_system_used. */
3724 set_coding_system = true;
3726 else if (BEG < Z)
3728 /* Decide the coding system to use for reading the file now
3729 because we can't use an optimized method for handling
3730 `coding:' tag if the current buffer is not empty. */
3731 if (!NILP (Vcoding_system_for_read))
3732 coding_system = Vcoding_system_for_read;
3733 else
3735 /* Don't try looking inside a file for a coding system
3736 specification if it is not seekable. */
3737 if (! not_regular && ! NILP (Vset_auto_coding_function))
3739 /* Find a coding system specified in the heading two
3740 lines or in the tailing several lines of the file.
3741 We assume that the 1K-byte and 3K-byte for heading
3742 and tailing respectively are sufficient for this
3743 purpose. */
3744 int nread;
3746 if (st.st_size <= (1024 * 4))
3747 nread = emacs_read_quit (fd, read_buf, 1024 * 4);
3748 else
3750 nread = emacs_read_quit (fd, read_buf, 1024);
3751 if (nread == 1024)
3753 int ntail;
3754 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3755 report_file_error ("Setting file position",
3756 orig_filename);
3757 ntail = emacs_read_quit (fd, read_buf + nread, 1024 * 3);
3758 nread = ntail < 0 ? ntail : nread + ntail;
3762 if (nread < 0)
3763 report_file_error ("Read error", orig_filename);
3764 else if (nread > 0)
3766 AUTO_STRING (name, " *code-converting-work*");
3767 struct buffer *prev = current_buffer;
3768 Lisp_Object workbuf;
3769 struct buffer *buf;
3771 record_unwind_current_buffer ();
3773 workbuf = Fget_buffer_create (name);
3774 buf = XBUFFER (workbuf);
3776 delete_all_overlays (buf);
3777 bset_directory (buf, BVAR (current_buffer, directory));
3778 bset_read_only (buf, Qnil);
3779 bset_filename (buf, Qnil);
3780 bset_undo_list (buf, Qt);
3781 eassert (buf->overlays_before == NULL);
3782 eassert (buf->overlays_after == NULL);
3784 set_buffer_internal (buf);
3785 Ferase_buffer ();
3786 bset_enable_multibyte_characters (buf, Qnil);
3788 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3789 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3790 coding_system = call2 (Vset_auto_coding_function,
3791 filename, make_number (nread));
3792 set_buffer_internal (prev);
3794 /* Discard the unwind protect for recovering the
3795 current buffer. */
3796 specpdl_ptr--;
3798 /* Rewind the file for the actual read done later. */
3799 if (lseek (fd, 0, SEEK_SET) < 0)
3800 report_file_error ("Setting file position", orig_filename);
3804 if (NILP (coding_system))
3806 /* If we have not yet decided a coding system, check
3807 file-coding-system-alist. */
3808 coding_system = CALLN (Ffind_operation_coding_system,
3809 Qinsert_file_contents, orig_filename,
3810 visit, beg, end, replace);
3811 if (CONSP (coding_system))
3812 coding_system = XCAR (coding_system);
3816 if (NILP (coding_system))
3817 coding_system = Qundecided;
3818 else
3819 CHECK_CODING_SYSTEM (coding_system);
3821 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3822 /* We must suppress all character code conversion except for
3823 end-of-line conversion. */
3824 coding_system = raw_text_coding_system (coding_system);
3826 setup_coding_system (coding_system, &coding);
3827 /* Ensure we set Vlast_coding_system_used. */
3828 set_coding_system = true;
3831 /* If requested, replace the accessible part of the buffer
3832 with the file contents. Avoid replacing text at the
3833 beginning or end of the buffer that matches the file contents;
3834 that preserves markers pointing to the unchanged parts.
3836 Here we implement this feature in an optimized way
3837 for the case where code conversion is NOT needed.
3838 The following if-statement handles the case of conversion
3839 in a less optimal way.
3841 If the code conversion is "automatic" then we try using this
3842 method and hope for the best.
3843 But if we discover the need for conversion, we give up on this method
3844 and let the following if-statement handle the replace job. */
3845 if (!NILP (replace)
3846 && BEGV < ZV
3847 && (NILP (coding_system)
3848 || ! CODING_REQUIRE_DECODING (&coding)))
3850 ptrdiff_t overlap;
3851 /* There is still a possibility we will find the need to do code
3852 conversion. If that happens, set this variable to
3853 give up on handling REPLACE in the optimized way. */
3854 bool giveup_match_end = false;
3856 if (beg_offset != 0)
3858 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3859 report_file_error ("Setting file position", orig_filename);
3862 /* Count how many chars at the start of the file
3863 match the text at the beginning of the buffer. */
3864 while (true)
3866 int nread = emacs_read_quit (fd, read_buf, sizeof read_buf);
3867 if (nread < 0)
3868 report_file_error ("Read error", orig_filename);
3869 else if (nread == 0)
3870 break;
3872 if (CODING_REQUIRE_DETECTION (&coding))
3874 coding_system = detect_coding_system ((unsigned char *) read_buf,
3875 nread, nread, 1, 0,
3876 coding_system);
3877 setup_coding_system (coding_system, &coding);
3880 if (CODING_REQUIRE_DECODING (&coding))
3881 /* We found that the file should be decoded somehow.
3882 Let's give up here. */
3884 giveup_match_end = true;
3885 break;
3888 int bufpos = 0;
3889 while (bufpos < nread && same_at_start < ZV_BYTE
3890 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3891 same_at_start++, bufpos++;
3892 /* If we found a discrepancy, stop the scan.
3893 Otherwise loop around and scan the next bufferful. */
3894 if (bufpos != nread)
3895 break;
3897 /* If the file matches the buffer completely,
3898 there's no need to replace anything. */
3899 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3901 emacs_close (fd);
3902 clear_unwind_protect (fd_index);
3904 /* Truncate the buffer to the size of the file. */
3905 del_range_1 (same_at_start, same_at_end, 0, 0);
3906 goto handled;
3909 /* Count how many chars at the end of the file
3910 match the text at the end of the buffer. But, if we have
3911 already found that decoding is necessary, don't waste time. */
3912 while (!giveup_match_end)
3914 int total_read, nread, bufpos, trial;
3915 off_t curpos;
3917 /* At what file position are we now scanning? */
3918 curpos = end_offset - (ZV_BYTE - same_at_end);
3919 /* If the entire file matches the buffer tail, stop the scan. */
3920 if (curpos == 0)
3921 break;
3922 /* How much can we scan in the next step? */
3923 trial = min (curpos, sizeof read_buf);
3924 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3925 report_file_error ("Setting file position", orig_filename);
3927 total_read = nread = 0;
3928 while (total_read < trial)
3930 nread = emacs_read_quit (fd, read_buf + total_read,
3931 trial - total_read);
3932 if (nread < 0)
3933 report_file_error ("Read error", orig_filename);
3934 else if (nread == 0)
3935 break;
3936 total_read += nread;
3939 /* Scan this bufferful from the end, comparing with
3940 the Emacs buffer. */
3941 bufpos = total_read;
3943 /* Compare with same_at_start to avoid counting some buffer text
3944 as matching both at the file's beginning and at the end. */
3945 while (bufpos > 0 && same_at_end > same_at_start
3946 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3947 same_at_end--, bufpos--;
3949 /* If we found a discrepancy, stop the scan.
3950 Otherwise loop around and scan the preceding bufferful. */
3951 if (bufpos != 0)
3953 /* If this discrepancy is because of code conversion,
3954 we cannot use this method; giveup and try the other. */
3955 if (same_at_end > same_at_start
3956 && FETCH_BYTE (same_at_end - 1) >= 0200
3957 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3958 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3959 giveup_match_end = true;
3960 break;
3963 if (nread == 0)
3964 break;
3967 if (! giveup_match_end)
3969 ptrdiff_t temp;
3970 ptrdiff_t this_count = SPECPDL_INDEX ();
3972 /* We win! We can handle REPLACE the optimized way. */
3974 /* Extend the start of non-matching text area to multibyte
3975 character boundary. */
3976 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3977 while (same_at_start > BEGV_BYTE
3978 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3979 same_at_start--;
3981 /* Extend the end of non-matching text area to multibyte
3982 character boundary. */
3983 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3984 while (same_at_end < ZV_BYTE
3985 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3986 same_at_end++;
3988 /* Don't try to reuse the same piece of text twice. */
3989 overlap = (same_at_start - BEGV_BYTE
3990 - (same_at_end
3991 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3992 if (overlap > 0)
3993 same_at_end += overlap;
3994 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3996 /* Arrange to read only the nonmatching middle part of the file. */
3997 beg_offset += same_at_start - BEGV_BYTE;
3998 end_offset -= ZV_BYTE - same_at_end;
4000 /* This binding is to avoid ask-user-about-supersession-threat
4001 being called in insert_from_buffer or del_range_bytes (via
4002 prepare_to_modify_buffer).
4003 AFAICT we could avoid ask-user-about-supersession-threat by setting
4004 current_buffer->modtime earlier, but we could still end up calling
4005 ask-user-about-supersession-threat if the file is modified while
4006 we read it, so we bind buffer-file-name instead. */
4007 specbind (intern ("buffer-file-name"), Qnil);
4008 del_range_byte (same_at_start, same_at_end);
4009 /* Insert from the file at the proper position. */
4010 temp = BYTE_TO_CHAR (same_at_start);
4011 SET_PT_BOTH (temp, same_at_start);
4012 unbind_to (this_count, Qnil);
4014 /* If display currently starts at beginning of line,
4015 keep it that way. */
4016 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4017 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4019 replace_handled = true;
4023 /* If requested, replace the accessible part of the buffer
4024 with the file contents. Avoid replacing text at the
4025 beginning or end of the buffer that matches the file contents;
4026 that preserves markers pointing to the unchanged parts.
4028 Here we implement this feature for the case where code conversion
4029 is needed, in a simple way that needs a lot of memory.
4030 The preceding if-statement handles the case of no conversion
4031 in a more optimized way. */
4032 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
4034 ptrdiff_t same_at_start_charpos;
4035 ptrdiff_t inserted_chars;
4036 ptrdiff_t overlap;
4037 ptrdiff_t bufpos;
4038 unsigned char *decoded;
4039 ptrdiff_t temp;
4040 ptrdiff_t this = 0;
4041 ptrdiff_t this_count = SPECPDL_INDEX ();
4042 bool multibyte
4043 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4044 Lisp_Object conversion_buffer;
4046 conversion_buffer = code_conversion_save (1, multibyte);
4048 /* First read the whole file, performing code conversion into
4049 CONVERSION_BUFFER. */
4051 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4052 report_file_error ("Setting file position", orig_filename);
4054 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
4055 unprocessed = 0; /* Bytes not processed in previous loop. */
4057 while (true)
4059 /* Read at most READ_BUF_SIZE bytes at a time, to allow
4060 quitting while reading a huge file. */
4062 this = emacs_read_quit (fd, read_buf + unprocessed,
4063 READ_BUF_SIZE - unprocessed);
4064 if (this <= 0)
4065 break;
4067 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
4068 BUF_Z (XBUFFER (conversion_buffer)));
4069 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4070 unprocessed + this, conversion_buffer);
4071 unprocessed = coding.carryover_bytes;
4072 if (coding.carryover_bytes > 0)
4073 memcpy (read_buf, coding.carryover, unprocessed);
4076 if (this < 0)
4077 report_file_error ("Read error", orig_filename);
4078 emacs_close (fd);
4079 clear_unwind_protect (fd_index);
4081 if (unprocessed > 0)
4083 coding.mode |= CODING_MODE_LAST_BLOCK;
4084 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4085 unprocessed, conversion_buffer);
4086 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4089 coding_system = CODING_ID_NAME (coding.id);
4090 set_coding_system = true;
4091 maybe_move_gap (XBUFFER (conversion_buffer));
4092 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
4093 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4094 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4096 /* Compare the beginning of the converted string with the buffer
4097 text. */
4099 bufpos = 0;
4100 while (bufpos < inserted && same_at_start < same_at_end
4101 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4102 same_at_start++, bufpos++;
4104 /* If the file matches the head of buffer completely,
4105 there's no need to replace anything. */
4107 if (bufpos == inserted)
4109 /* Truncate the buffer to the size of the file. */
4110 if (same_at_start != same_at_end)
4112 /* See previous specbind for the reason behind this. */
4113 specbind (intern ("buffer-file-name"), Qnil);
4114 del_range_byte (same_at_start, same_at_end);
4116 inserted = 0;
4118 unbind_to (this_count, Qnil);
4119 goto handled;
4122 /* Extend the start of non-matching text area to the previous
4123 multibyte character boundary. */
4124 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4125 while (same_at_start > BEGV_BYTE
4126 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4127 same_at_start--;
4129 /* Scan this bufferful from the end, comparing with
4130 the Emacs buffer. */
4131 bufpos = inserted;
4133 /* Compare with same_at_start to avoid counting some buffer text
4134 as matching both at the file's beginning and at the end. */
4135 while (bufpos > 0 && same_at_end > same_at_start
4136 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4137 same_at_end--, bufpos--;
4139 /* Extend the end of non-matching text area to the next
4140 multibyte character boundary. */
4141 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4142 while (same_at_end < ZV_BYTE
4143 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4144 same_at_end++;
4146 /* Don't try to reuse the same piece of text twice. */
4147 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4148 if (overlap > 0)
4149 same_at_end += overlap;
4150 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4152 /* If display currently starts at beginning of line,
4153 keep it that way. */
4154 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4155 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4157 /* Replace the chars that we need to replace,
4158 and update INSERTED to equal the number of bytes
4159 we are taking from the decoded string. */
4160 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4162 /* See previous specbind for the reason behind this. */
4163 specbind (intern ("buffer-file-name"), Qnil);
4164 if (same_at_end != same_at_start)
4166 del_range_byte (same_at_start, same_at_end);
4167 temp = GPT;
4168 eassert (same_at_start == GPT_BYTE);
4169 same_at_start = GPT_BYTE;
4171 else
4173 temp = same_at_end_charpos;
4175 /* Insert from the file at the proper position. */
4176 SET_PT_BOTH (temp, same_at_start);
4177 same_at_start_charpos
4178 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4179 same_at_start - BEGV_BYTE
4180 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4181 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4182 inserted_chars
4183 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4184 same_at_start + inserted - BEGV_BYTE
4185 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4186 - same_at_start_charpos);
4187 insert_from_buffer (XBUFFER (conversion_buffer),
4188 same_at_start_charpos, inserted_chars, 0);
4189 /* Set `inserted' to the number of inserted characters. */
4190 inserted = PT - temp;
4191 /* Set point before the inserted characters. */
4192 SET_PT_BOTH (temp, same_at_start);
4194 unbind_to (this_count, Qnil);
4196 goto handled;
4199 if (! not_regular)
4200 total = end_offset - beg_offset;
4201 else
4202 /* For a special file, all we can do is guess. */
4203 total = READ_BUF_SIZE;
4205 if (NILP (visit) && total > 0)
4207 if (!NILP (BVAR (current_buffer, file_truename))
4208 /* Make binding buffer-file-name to nil effective. */
4209 && !NILP (BVAR (current_buffer, filename))
4210 && SAVE_MODIFF >= MODIFF)
4211 we_locked_file = true;
4212 prepare_to_modify_buffer (PT, PT, NULL);
4215 move_gap_both (PT, PT_BYTE);
4216 if (GAP_SIZE < total)
4217 make_gap (total - GAP_SIZE);
4219 if (beg_offset != 0 || !NILP (replace))
4221 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4222 report_file_error ("Setting file position", orig_filename);
4225 /* In the following loop, HOW_MUCH contains the total bytes read so
4226 far for a regular file, and not changed for a special file. But,
4227 before exiting the loop, it is set to a negative value if I/O
4228 error occurs. */
4229 how_much = 0;
4231 /* Total bytes inserted. */
4232 inserted = 0;
4234 /* Here, we don't do code conversion in the loop. It is done by
4235 decode_coding_gap after all data are read into the buffer. */
4237 ptrdiff_t gap_size = GAP_SIZE;
4239 while (how_much < total)
4241 /* `try' is reserved in some compilers (Microsoft C). */
4242 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4243 ptrdiff_t this;
4245 if (not_regular)
4247 Lisp_Object nbytes;
4249 /* Maybe make more room. */
4250 if (gap_size < trytry)
4252 make_gap (trytry - gap_size);
4253 gap_size = GAP_SIZE - inserted;
4256 /* Read from the file, capturing `quit'. When an
4257 error occurs, end the loop, and arrange for a quit
4258 to be signaled after decoding the text we read. */
4259 nbytes = internal_condition_case_1
4260 (read_non_regular,
4261 make_save_int_int_int (fd, inserted, trytry),
4262 Qerror, read_non_regular_quit);
4264 if (NILP (nbytes))
4266 read_quit = true;
4267 break;
4270 this = XINT (nbytes);
4272 else
4274 /* Allow quitting out of the actual I/O. We don't make text
4275 part of the buffer until all the reading is done, so a C-g
4276 here doesn't do any harm. */
4277 this = emacs_read_quit (fd,
4278 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4279 + inserted),
4280 trytry);
4283 if (this <= 0)
4285 how_much = this;
4286 break;
4289 gap_size -= this;
4291 /* For a regular file, where TOTAL is the real size,
4292 count HOW_MUCH to compare with it.
4293 For a special file, where TOTAL is just a buffer size,
4294 so don't bother counting in HOW_MUCH.
4295 (INSERTED is where we count the number of characters inserted.) */
4296 if (! not_regular)
4297 how_much += this;
4298 inserted += this;
4302 /* Now we have either read all the file data into the gap,
4303 or stop reading on I/O error or quit. If nothing was
4304 read, undo marking the buffer modified. */
4306 if (inserted == 0)
4308 if (we_locked_file)
4309 unlock_file (BVAR (current_buffer, file_truename));
4310 Vdeactivate_mark = old_Vdeactivate_mark;
4312 else
4313 Fset (Qdeactivate_mark, Qt);
4315 emacs_close (fd);
4316 clear_unwind_protect (fd_index);
4318 if (how_much < 0)
4319 report_file_error ("Read error", orig_filename);
4321 /* Make the text read part of the buffer. */
4322 GAP_SIZE -= inserted;
4323 GPT += inserted;
4324 GPT_BYTE += inserted;
4325 ZV += inserted;
4326 ZV_BYTE += inserted;
4327 Z += inserted;
4328 Z_BYTE += inserted;
4330 if (GAP_SIZE > 0)
4331 /* Put an anchor to ensure multi-byte form ends at gap. */
4332 *GPT_ADDR = 0;
4334 notfound:
4336 if (NILP (coding_system))
4338 /* The coding system is not yet decided. Decide it by an
4339 optimized method for handling `coding:' tag.
4341 Note that we can get here only if the buffer was empty
4342 before the insertion. */
4344 if (!NILP (Vcoding_system_for_read))
4345 coding_system = Vcoding_system_for_read;
4346 else
4348 /* Since we are sure that the current buffer was empty
4349 before the insertion, we can toggle
4350 enable-multibyte-characters directly here without taking
4351 care of marker adjustment. By this way, we can run Lisp
4352 program safely before decoding the inserted text. */
4353 Lisp_Object unwind_data;
4354 ptrdiff_t count1 = SPECPDL_INDEX ();
4356 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4357 Fcons (BVAR (current_buffer, undo_list),
4358 Fcurrent_buffer ()));
4359 bset_enable_multibyte_characters (current_buffer, Qnil);
4360 bset_undo_list (current_buffer, Qt);
4361 record_unwind_protect (decide_coding_unwind, unwind_data);
4363 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4365 coding_system = call2 (Vset_auto_coding_function,
4366 filename, make_number (inserted));
4369 if (NILP (coding_system))
4371 /* If the coding system is not yet decided, check
4372 file-coding-system-alist. */
4373 coding_system = CALLN (Ffind_operation_coding_system,
4374 Qinsert_file_contents, orig_filename,
4375 visit, beg, end, Qnil);
4376 if (CONSP (coding_system))
4377 coding_system = XCAR (coding_system);
4379 unbind_to (count1, Qnil);
4380 inserted = Z_BYTE - BEG_BYTE;
4383 if (NILP (coding_system))
4384 coding_system = Qundecided;
4385 else
4386 CHECK_CODING_SYSTEM (coding_system);
4388 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4389 /* We must suppress all character code conversion except for
4390 end-of-line conversion. */
4391 coding_system = raw_text_coding_system (coding_system);
4392 setup_coding_system (coding_system, &coding);
4393 /* Ensure we set Vlast_coding_system_used. */
4394 set_coding_system = true;
4397 if (!NILP (visit))
4399 /* When we visit a file by raw-text, we change the buffer to
4400 unibyte. */
4401 if (CODING_FOR_UNIBYTE (&coding)
4402 /* Can't do this if part of the buffer might be preserved. */
4403 && NILP (replace))
4405 /* Visiting a file with these coding system makes the buffer
4406 unibyte. */
4407 if (inserted > 0)
4408 bset_enable_multibyte_characters (current_buffer, Qnil);
4409 else
4410 Fset_buffer_multibyte (Qnil);
4414 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4415 if (CODING_MAY_REQUIRE_DECODING (&coding)
4416 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4418 move_gap_both (PT, PT_BYTE);
4419 GAP_SIZE += inserted;
4420 ZV_BYTE -= inserted;
4421 Z_BYTE -= inserted;
4422 ZV -= inserted;
4423 Z -= inserted;
4424 decode_coding_gap (&coding, inserted, inserted);
4425 inserted = coding.produced_char;
4426 coding_system = CODING_ID_NAME (coding.id);
4428 else if (inserted > 0)
4430 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4431 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4432 inserted);
4435 /* Call after-change hooks for the inserted text, aside from the case
4436 of normal visiting (not with REPLACE), which is done in a new buffer
4437 "before" the buffer is changed. */
4438 if (inserted > 0 && total > 0
4439 && (NILP (visit) || !NILP (replace)))
4441 signal_after_change (PT, 0, inserted);
4442 update_compositions (PT, PT, CHECK_BORDER);
4445 /* Now INSERTED is measured in characters. */
4447 handled:
4449 if (inserted > 0)
4450 restore_window_points (window_markers, inserted,
4451 BYTE_TO_CHAR (same_at_start),
4452 same_at_end_charpos);
4454 if (!NILP (visit))
4456 if (empty_undo_list_p)
4457 bset_undo_list (current_buffer, Qnil);
4459 if (NILP (handler))
4461 current_buffer->modtime = mtime;
4462 current_buffer->modtime_size = st.st_size;
4463 bset_filename (current_buffer, orig_filename);
4466 SAVE_MODIFF = MODIFF;
4467 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4468 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4469 if (NILP (handler))
4471 if (!NILP (BVAR (current_buffer, file_truename)))
4472 unlock_file (BVAR (current_buffer, file_truename));
4473 unlock_file (filename);
4475 if (not_regular)
4476 xsignal2 (Qfile_error,
4477 build_string ("not a regular file"), orig_filename);
4480 if (set_coding_system)
4481 Vlast_coding_system_used = coding_system;
4483 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4485 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4486 visit);
4487 if (! NILP (insval))
4489 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4490 wrong_type_argument (intern ("inserted-chars"), insval);
4491 inserted = XFASTINT (insval);
4495 /* Decode file format. */
4496 if (inserted > 0)
4498 /* Don't run point motion or modification hooks when decoding. */
4499 ptrdiff_t count1 = SPECPDL_INDEX ();
4500 ptrdiff_t old_inserted = inserted;
4501 specbind (Qinhibit_point_motion_hooks, Qt);
4502 specbind (Qinhibit_modification_hooks, Qt);
4504 /* Save old undo list and don't record undo for decoding. */
4505 old_undo = BVAR (current_buffer, undo_list);
4506 bset_undo_list (current_buffer, Qt);
4508 if (NILP (replace))
4510 insval = call3 (Qformat_decode,
4511 Qnil, make_number (inserted), visit);
4512 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4513 wrong_type_argument (intern ("inserted-chars"), insval);
4514 inserted = XFASTINT (insval);
4516 else
4518 /* If REPLACE is non-nil and we succeeded in not replacing the
4519 beginning or end of the buffer text with the file's contents,
4520 call format-decode with `point' positioned at the beginning
4521 of the buffer and `inserted' equaling the number of
4522 characters in the buffer. Otherwise, format-decode might
4523 fail to correctly analyze the beginning or end of the buffer.
4524 Hence we temporarily save `point' and `inserted' here and
4525 restore `point' iff format-decode did not insert or delete
4526 any text. Otherwise we leave `point' at point-min. */
4527 ptrdiff_t opoint = PT;
4528 ptrdiff_t opoint_byte = PT_BYTE;
4529 ptrdiff_t oinserted = ZV - BEGV;
4530 EMACS_INT ochars_modiff = CHARS_MODIFF;
4532 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4533 insval = call3 (Qformat_decode,
4534 Qnil, make_number (oinserted), visit);
4535 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4536 wrong_type_argument (intern ("inserted-chars"), insval);
4537 if (ochars_modiff == CHARS_MODIFF)
4538 /* format_decode didn't modify buffer's characters => move
4539 point back to position before inserted text and leave
4540 value of inserted alone. */
4541 SET_PT_BOTH (opoint, opoint_byte);
4542 else
4543 /* format_decode modified buffer's characters => consider
4544 entire buffer changed and leave point at point-min. */
4545 inserted = XFASTINT (insval);
4548 /* For consistency with format-decode call these now iff inserted > 0
4549 (martin 2007-06-28). */
4550 p = Vafter_insert_file_functions;
4551 while (CONSP (p))
4553 if (NILP (replace))
4555 insval = call1 (XCAR (p), make_number (inserted));
4556 if (!NILP (insval))
4558 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4559 wrong_type_argument (intern ("inserted-chars"), insval);
4560 inserted = XFASTINT (insval);
4563 else
4565 /* For the rationale of this see the comment on
4566 format-decode above. */
4567 ptrdiff_t opoint = PT;
4568 ptrdiff_t opoint_byte = PT_BYTE;
4569 ptrdiff_t oinserted = ZV - BEGV;
4570 EMACS_INT ochars_modiff = CHARS_MODIFF;
4572 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4573 insval = call1 (XCAR (p), make_number (oinserted));
4574 if (!NILP (insval))
4576 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4577 wrong_type_argument (intern ("inserted-chars"), insval);
4578 if (ochars_modiff == CHARS_MODIFF)
4579 /* after_insert_file_functions didn't modify
4580 buffer's characters => move point back to
4581 position before inserted text and leave value of
4582 inserted alone. */
4583 SET_PT_BOTH (opoint, opoint_byte);
4584 else
4585 /* after_insert_file_functions did modify buffer's
4586 characters => consider entire buffer changed and
4587 leave point at point-min. */
4588 inserted = XFASTINT (insval);
4592 maybe_quit ();
4593 p = XCDR (p);
4596 if (!empty_undo_list_p)
4598 bset_undo_list (current_buffer, old_undo);
4599 if (CONSP (old_undo) && inserted != old_inserted)
4601 /* Adjust the last undo record for the size change during
4602 the format conversion. */
4603 Lisp_Object tem = XCAR (old_undo);
4604 if (CONSP (tem) && INTEGERP (XCAR (tem))
4605 && INTEGERP (XCDR (tem))
4606 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4607 XSETCDR (tem, make_number (PT + inserted));
4610 else
4611 /* If undo_list was Qt before, keep it that way.
4612 Otherwise start with an empty undo_list. */
4613 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4615 unbind_to (count1, Qnil);
4618 if (!NILP (visit)
4619 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4621 /* If visiting nonexistent file, return nil. */
4622 report_file_errno ("Opening input file", orig_filename, save_errno);
4625 /* We made a lot of deletions and insertions above, so invalidate
4626 the newline cache for the entire region of the inserted
4627 characters. */
4628 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4629 invalidate_region_cache (current_buffer->base_buffer,
4630 current_buffer->base_buffer->newline_cache,
4631 PT - BEG, Z - PT - inserted);
4632 else if (current_buffer->newline_cache)
4633 invalidate_region_cache (current_buffer,
4634 current_buffer->newline_cache,
4635 PT - BEG, Z - PT - inserted);
4637 if (read_quit)
4638 quit ();
4640 /* Retval needs to be dealt with in all cases consistently. */
4641 if (NILP (val))
4642 val = list2 (orig_filename, make_number (inserted));
4644 return unbind_to (count, val);
4647 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4649 static void
4650 build_annotations_unwind (Lisp_Object arg)
4652 Vwrite_region_annotation_buffers = arg;
4655 /* Decide the coding-system to encode the data with. */
4657 static Lisp_Object
4658 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4659 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4660 struct coding_system *coding)
4662 Lisp_Object val;
4663 Lisp_Object eol_parent = Qnil;
4665 if (auto_saving
4666 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4667 BVAR (current_buffer, auto_save_file_name))))
4669 val = Qutf_8_emacs;
4670 eol_parent = Qunix;
4672 else if (!NILP (Vcoding_system_for_write))
4674 val = Vcoding_system_for_write;
4675 if (coding_system_require_warning
4676 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4677 /* Confirm that VAL can surely encode the current region. */
4678 val = call5 (Vselect_safe_coding_system_function,
4679 start, end, list2 (Qt, val),
4680 Qnil, filename);
4682 else
4684 /* If the variable `buffer-file-coding-system' is set locally,
4685 it means that the file was read with some kind of code
4686 conversion or the variable is explicitly set by users. We
4687 had better write it out with the same coding system even if
4688 `enable-multibyte-characters' is nil.
4690 If it is not set locally, we anyway have to convert EOL
4691 format if the default value of `buffer-file-coding-system'
4692 tells that it is not Unix-like (LF only) format. */
4693 bool using_default_coding = 0;
4694 bool force_raw_text = 0;
4696 val = BVAR (current_buffer, buffer_file_coding_system);
4697 if (NILP (val)
4698 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4700 val = Qnil;
4701 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4702 force_raw_text = 1;
4705 if (NILP (val))
4707 /* Check file-coding-system-alist. */
4708 Lisp_Object coding_systems
4709 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4710 filename, append, visit, lockname);
4711 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4712 val = XCDR (coding_systems);
4715 if (NILP (val))
4717 /* If we still have not decided a coding system, use the
4718 current buffer's value of buffer-file-coding-system. */
4719 val = BVAR (current_buffer, buffer_file_coding_system);
4720 using_default_coding = 1;
4723 if (! NILP (val) && ! force_raw_text)
4725 Lisp_Object spec, attrs;
4727 CHECK_CODING_SYSTEM (val);
4728 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4729 attrs = AREF (spec, 0);
4730 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4731 force_raw_text = 1;
4734 if (!force_raw_text
4735 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4737 /* Confirm that VAL can surely encode the current region. */
4738 val = call5 (Vselect_safe_coding_system_function,
4739 start, end, val, Qnil, filename);
4740 /* As the function specified by select-safe-coding-system-function
4741 is out of our control, make sure we are not fed by bogus
4742 values. */
4743 if (!NILP (val))
4744 CHECK_CODING_SYSTEM (val);
4747 /* If the decided coding-system doesn't specify end-of-line
4748 format, we use that of `buffer-file-coding-system'. */
4749 if (! using_default_coding)
4751 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4753 if (! NILP (dflt))
4754 val = coding_inherit_eol_type (val, dflt);
4757 /* If we decide not to encode text, use `raw-text' or one of its
4758 subsidiaries. */
4759 if (force_raw_text)
4760 val = raw_text_coding_system (val);
4763 val = coding_inherit_eol_type (val, eol_parent);
4764 setup_coding_system (val, coding);
4766 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4767 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4768 return val;
4771 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4772 "r\nFWrite region to file: \ni\ni\ni\np",
4773 doc: /* Write current region into specified file.
4774 When called from a program, requires three arguments:
4775 START, END and FILENAME. START and END are normally buffer positions
4776 specifying the part of the buffer to write.
4777 If START is nil, that means to use the entire buffer contents; END is
4778 ignored.
4779 If START is a string, then output that string to the file
4780 instead of any buffer contents; END is ignored.
4782 Optional fourth argument APPEND if non-nil means
4783 append to existing file contents (if any). If it is a number,
4784 seek to that offset in the file before writing.
4785 Optional fifth argument VISIT, if t or a string, means
4786 set the last-save-file-modtime of buffer to this file's modtime
4787 and mark buffer not modified.
4788 If VISIT is a string, it is a second file name;
4789 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4790 VISIT is also the file name to lock and unlock for clash detection.
4791 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4792 do not display the \"Wrote file\" message.
4793 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4794 use for locking and unlocking, overriding FILENAME and VISIT.
4795 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4796 for an existing file with the same name. If MUSTBENEW is `excl',
4797 that means to get an error if the file already exists; never overwrite.
4798 If MUSTBENEW is neither nil nor `excl', that means ask for
4799 confirmation before overwriting, but do go ahead and overwrite the file
4800 if the user confirms.
4802 This does code conversion according to the value of
4803 `coding-system-for-write', `buffer-file-coding-system', or
4804 `file-coding-system-alist', and sets the variable
4805 `last-coding-system-used' to the coding system actually used.
4807 This calls `write-region-annotate-functions' at the start, and
4808 `write-region-post-annotation-function' at the end. */)
4809 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4810 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4812 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4813 -1);
4816 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4817 descriptor for FILENAME, so do not open or close FILENAME. */
4819 Lisp_Object
4820 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4821 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4822 Lisp_Object mustbenew, int desc)
4824 int open_flags;
4825 int mode;
4826 off_t offset UNINIT;
4827 bool open_and_close_file = desc < 0;
4828 bool ok;
4829 int save_errno = 0;
4830 const char *fn;
4831 struct stat st;
4832 struct timespec modtime;
4833 ptrdiff_t count = SPECPDL_INDEX ();
4834 ptrdiff_t count1 UNINIT;
4835 Lisp_Object handler;
4836 Lisp_Object visit_file;
4837 Lisp_Object annotations;
4838 Lisp_Object encoded_filename;
4839 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4840 bool quietly = !NILP (visit);
4841 bool file_locked = 0;
4842 struct buffer *given_buffer;
4843 struct coding_system coding;
4845 if (current_buffer->base_buffer && visiting)
4846 error ("Cannot do file visiting in an indirect buffer");
4848 if (!NILP (start) && !STRINGP (start))
4849 validate_region (&start, &end);
4851 visit_file = Qnil;
4853 filename = Fexpand_file_name (filename, Qnil);
4855 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4856 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4858 if (STRINGP (visit))
4859 visit_file = Fexpand_file_name (visit, Qnil);
4860 else
4861 visit_file = filename;
4863 if (NILP (lockname))
4864 lockname = visit_file;
4866 annotations = Qnil;
4868 /* If the file name has special constructs in it,
4869 call the corresponding file handler. */
4870 handler = Ffind_file_name_handler (filename, Qwrite_region);
4871 /* If FILENAME has no handler, see if VISIT has one. */
4872 if (NILP (handler) && STRINGP (visit))
4873 handler = Ffind_file_name_handler (visit, Qwrite_region);
4875 if (!NILP (handler))
4877 Lisp_Object val;
4878 val = call6 (handler, Qwrite_region, start, end,
4879 filename, append, visit);
4881 if (visiting)
4883 SAVE_MODIFF = MODIFF;
4884 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4885 bset_filename (current_buffer, visit_file);
4888 return val;
4891 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4893 /* Special kludge to simplify auto-saving. */
4894 if (NILP (start))
4896 /* Do it later, so write-region-annotate-function can work differently
4897 if we save "the buffer" vs "a region".
4898 This is useful in tar-mode. --Stef
4899 XSETFASTINT (start, BEG);
4900 XSETFASTINT (end, Z); */
4901 Fwiden ();
4904 record_unwind_protect (build_annotations_unwind,
4905 Vwrite_region_annotation_buffers);
4906 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4908 given_buffer = current_buffer;
4910 if (!STRINGP (start))
4912 annotations = build_annotations (start, end);
4914 if (current_buffer != given_buffer)
4916 XSETFASTINT (start, BEGV);
4917 XSETFASTINT (end, ZV);
4921 if (NILP (start))
4923 XSETFASTINT (start, BEGV);
4924 XSETFASTINT (end, ZV);
4927 /* Decide the coding-system to encode the data with.
4928 We used to make this choice before calling build_annotations, but that
4929 leads to problems when a write-annotate-function takes care of
4930 unsavable chars (as was the case with X-Symbol). */
4931 Vlast_coding_system_used
4932 = choose_write_coding_system (start, end, filename,
4933 append, visit, lockname, &coding);
4935 if (open_and_close_file && !auto_saving)
4937 lock_file (lockname);
4938 file_locked = 1;
4941 encoded_filename = ENCODE_FILE (filename);
4942 fn = SSDATA (encoded_filename);
4943 open_flags = O_WRONLY | O_CREAT;
4944 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4945 if (NUMBERP (append))
4946 offset = file_offset (append);
4947 else if (!NILP (append))
4948 open_flags |= O_APPEND;
4949 #ifdef DOS_NT
4950 mode = S_IREAD | S_IWRITE;
4951 #else
4952 mode = auto_saving ? auto_save_mode_bits : 0666;
4953 #endif
4955 if (open_and_close_file)
4957 desc = emacs_open (fn, open_flags, mode);
4958 if (desc < 0)
4960 int open_errno = errno;
4961 if (file_locked)
4962 unlock_file (lockname);
4963 report_file_errno ("Opening output file", filename, open_errno);
4966 count1 = SPECPDL_INDEX ();
4967 record_unwind_protect_int (close_file_unwind, desc);
4970 if (NUMBERP (append))
4972 off_t ret = lseek (desc, offset, SEEK_SET);
4973 if (ret < 0)
4975 int lseek_errno = errno;
4976 if (file_locked)
4977 unlock_file (lockname);
4978 report_file_errno ("Lseek error", filename, lseek_errno);
4982 if (STRINGP (start))
4983 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4984 else if (XINT (start) != XINT (end))
4985 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4986 &annotations, &coding);
4987 else
4989 /* If file was empty, still need to write the annotations. */
4990 coding.mode |= CODING_MODE_LAST_BLOCK;
4991 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4993 save_errno = errno;
4995 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4996 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4998 /* We have to flush out a data. */
4999 coding.mode |= CODING_MODE_LAST_BLOCK;
5000 ok = e_write (desc, Qnil, 1, 1, &coding);
5001 save_errno = errno;
5004 /* fsync is not crucial for temporary files. Nor for auto-save
5005 files, since they might lose some work anyway. */
5006 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
5008 /* Transfer data and metadata to disk, retrying if interrupted.
5009 fsync can report a write failure here, e.g., due to disk full
5010 under NFS. But ignore EINVAL, which means fsync is not
5011 supported on this file. */
5012 while (fsync (desc) != 0)
5013 if (errno != EINTR)
5015 if (errno != EINVAL)
5016 ok = 0, save_errno = errno;
5017 break;
5021 modtime = invalid_timespec ();
5022 if (visiting)
5024 if (fstat (desc, &st) == 0)
5025 modtime = get_stat_mtime (&st);
5026 else
5027 ok = 0, save_errno = errno;
5030 if (open_and_close_file)
5032 /* NFS can report a write failure now. */
5033 if (emacs_close (desc) < 0)
5034 ok = 0, save_errno = errno;
5036 /* Discard the unwind protect for close_file_unwind. */
5037 specpdl_ptr = specpdl + count1;
5040 /* Some file systems have a bug where st_mtime is not updated
5041 properly after a write. For example, CIFS might not see the
5042 st_mtime change until after the file is opened again.
5044 Attempt to detect this file system bug, and update MODTIME to the
5045 newer st_mtime if the bug appears to be present. This introduces
5046 a race condition, so to avoid most instances of the race condition
5047 on non-buggy file systems, skip this check if the most recently
5048 encountered non-buggy file system was the current file system.
5050 A race condition can occur if some other process modifies the
5051 file between the fstat above and the fstat below, but the race is
5052 unlikely and a similar race between the last write and the fstat
5053 above cannot possibly be closed anyway. */
5055 if (timespec_valid_p (modtime)
5056 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
5058 int desc1 = emacs_open (fn, O_WRONLY, 0);
5059 if (desc1 >= 0)
5061 struct stat st1;
5062 if (fstat (desc1, &st1) == 0
5063 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
5065 /* Use the heuristic if it appears to be valid. With neither
5066 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
5067 file, the time stamp won't change. Also, some non-POSIX
5068 systems don't update an empty file's time stamp when
5069 truncating it. Finally, file systems with 100 ns or worse
5070 resolution sometimes seem to have bugs: on a system with ns
5071 resolution, checking ns % 100 incorrectly avoids the heuristic
5072 1% of the time, but the problem should be temporary as we will
5073 try again on the next time stamp. */
5074 bool use_heuristic
5075 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
5076 && st.st_size != 0
5077 && modtime.tv_nsec % 100 != 0);
5079 struct timespec modtime1 = get_stat_mtime (&st1);
5080 if (use_heuristic
5081 && timespec_cmp (modtime, modtime1) == 0
5082 && st.st_size == st1.st_size)
5084 timestamp_file_system = st.st_dev;
5085 valid_timestamp_file_system = 1;
5087 else
5089 st.st_size = st1.st_size;
5090 modtime = modtime1;
5093 emacs_close (desc1);
5097 /* Call write-region-post-annotation-function. */
5098 while (CONSP (Vwrite_region_annotation_buffers))
5100 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5101 if (!NILP (Fbuffer_live_p (buf)))
5103 Fset_buffer (buf);
5104 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5105 call0 (Vwrite_region_post_annotation_function);
5107 Vwrite_region_annotation_buffers
5108 = XCDR (Vwrite_region_annotation_buffers);
5111 unbind_to (count, Qnil);
5113 if (file_locked)
5114 unlock_file (lockname);
5116 /* Do this before reporting IO error
5117 to avoid a "file has changed on disk" warning on
5118 next attempt to save. */
5119 if (timespec_valid_p (modtime))
5121 current_buffer->modtime = modtime;
5122 current_buffer->modtime_size = st.st_size;
5125 if (! ok)
5126 report_file_errno ("Write error", filename, save_errno);
5128 bool auto_saving_into_visited_file =
5129 auto_saving
5130 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5131 BVAR (current_buffer, auto_save_file_name)));
5132 if (visiting)
5134 SAVE_MODIFF = MODIFF;
5135 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5136 bset_filename (current_buffer, visit_file);
5137 update_mode_lines = 14;
5138 if (auto_saving_into_visited_file)
5139 unlock_file (lockname);
5141 else if (quietly)
5143 if (auto_saving_into_visited_file)
5145 SAVE_MODIFF = MODIFF;
5146 unlock_file (lockname);
5149 return Qnil;
5152 if (!auto_saving && !noninteractive)
5154 AUTO_STRING (format, NUMBERP (append)
5155 ? "Updated `%s' (%d characters)"
5156 : ! NILP (append)
5157 ? "Added to `%s' (%d characters)"
5158 : "Wrote `%s' (%d characters)");
5159 EMACS_INT nchars = (STRINGP (start) ? SCHARS (start)
5160 : XINT (end) - XINT (start));
5161 CALLN (Fmessage, format, visit_file, make_number (nchars));
5163 return Qnil;
5166 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5167 doc: /* Return t if (car A) is numerically less than (car B). */)
5168 (Lisp_Object a, Lisp_Object b)
5170 return arithcompare (Fcar (a), Fcar (b), ARITH_LESS);
5173 /* Build the complete list of annotations appropriate for writing out
5174 the text between START and END, by calling all the functions in
5175 write-region-annotate-functions and merging the lists they return.
5176 If one of these functions switches to a different buffer, we assume
5177 that buffer contains altered text. Therefore, the caller must
5178 make sure to restore the current buffer in all cases,
5179 as save-excursion would do. */
5181 static Lisp_Object
5182 build_annotations (Lisp_Object start, Lisp_Object end)
5184 Lisp_Object annotations;
5185 Lisp_Object p, res;
5186 Lisp_Object original_buffer;
5187 int i;
5188 bool used_global = false;
5190 XSETBUFFER (original_buffer, current_buffer);
5192 annotations = Qnil;
5193 p = Vwrite_region_annotate_functions;
5194 while (CONSP (p))
5196 struct buffer *given_buffer = current_buffer;
5197 if (EQ (Qt, XCAR (p)) && !used_global)
5198 { /* Use the global value of the hook. */
5199 used_global = true;
5200 p = CALLN (Fappend,
5201 Fdefault_value (Qwrite_region_annotate_functions),
5202 XCDR (p));
5203 continue;
5205 Vwrite_region_annotations_so_far = annotations;
5206 res = call2 (XCAR (p), start, end);
5207 /* If the function makes a different buffer current,
5208 assume that means this buffer contains altered text to be output.
5209 Reset START and END from the buffer bounds
5210 and discard all previous annotations because they should have
5211 been dealt with by this function. */
5212 if (current_buffer != given_buffer)
5214 Vwrite_region_annotation_buffers
5215 = Fcons (Fcurrent_buffer (),
5216 Vwrite_region_annotation_buffers);
5217 XSETFASTINT (start, BEGV);
5218 XSETFASTINT (end, ZV);
5219 annotations = Qnil;
5221 Flength (res); /* Check basic validity of return value */
5222 annotations = merge (annotations, res, Qcar_less_than_car);
5223 p = XCDR (p);
5226 /* Now do the same for annotation functions implied by the file-format */
5227 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5228 p = BVAR (current_buffer, auto_save_file_format);
5229 else
5230 p = BVAR (current_buffer, file_format);
5231 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5233 struct buffer *given_buffer = current_buffer;
5235 Vwrite_region_annotations_so_far = annotations;
5237 /* Value is either a list of annotations or nil if the function
5238 has written annotations to a temporary buffer, which is now
5239 current. */
5240 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5241 original_buffer, make_number (i));
5242 if (current_buffer != given_buffer)
5244 XSETFASTINT (start, BEGV);
5245 XSETFASTINT (end, ZV);
5246 annotations = Qnil;
5249 if (CONSP (res))
5250 annotations = merge (annotations, res, Qcar_less_than_car);
5253 return annotations;
5257 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5258 If STRING is nil, POS is the character position in the current buffer.
5259 Intersperse with them the annotations from *ANNOT
5260 which fall within the range of POS to POS + NCHARS,
5261 each at its appropriate position.
5263 We modify *ANNOT by discarding elements as we use them up.
5265 Return true if successful. */
5267 static bool
5268 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5269 ptrdiff_t nchars, Lisp_Object *annot,
5270 struct coding_system *coding)
5272 Lisp_Object tem;
5273 ptrdiff_t nextpos;
5274 ptrdiff_t lastpos = pos + nchars;
5276 while (NILP (*annot) || CONSP (*annot))
5278 tem = Fcar_safe (Fcar (*annot));
5279 nextpos = pos - 1;
5280 if (INTEGERP (tem))
5281 nextpos = XFASTINT (tem);
5283 /* If there are no more annotations in this range,
5284 output the rest of the range all at once. */
5285 if (! (nextpos >= pos && nextpos <= lastpos))
5286 return e_write (desc, string, pos, lastpos, coding);
5288 /* Output buffer text up to the next annotation's position. */
5289 if (nextpos > pos)
5291 if (!e_write (desc, string, pos, nextpos, coding))
5292 return 0;
5293 pos = nextpos;
5295 /* Output the annotation. */
5296 tem = Fcdr (Fcar (*annot));
5297 if (STRINGP (tem))
5299 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5300 return 0;
5302 *annot = Fcdr (*annot);
5304 return 1;
5307 /* Maximum number of characters that the next
5308 function encodes per one loop iteration. */
5310 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5312 /* Write text in the range START and END into descriptor DESC,
5313 encoding them with coding system CODING. If STRING is nil, START
5314 and END are character positions of the current buffer, else they
5315 are indexes to the string STRING. Return true if successful. */
5317 static bool
5318 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5319 struct coding_system *coding)
5321 if (STRINGP (string))
5323 start = 0;
5324 end = SCHARS (string);
5327 /* We used to have a code for handling selective display here. But,
5328 now it is handled within encode_coding. */
5330 while (start < end)
5332 if (STRINGP (string))
5334 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5335 if (CODING_REQUIRE_ENCODING (coding))
5337 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5339 /* Avoid creating huge Lisp string in encode_coding_object. */
5340 if (nchars == E_WRITE_MAX)
5341 coding->raw_destination = 1;
5343 encode_coding_object
5344 (coding, string, start, string_char_to_byte (string, start),
5345 start + nchars, string_char_to_byte (string, start + nchars),
5346 Qt);
5348 else
5350 coding->dst_object = string;
5351 coding->consumed_char = SCHARS (string);
5352 coding->produced = SBYTES (string);
5355 else
5357 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5358 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5360 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5361 if (CODING_REQUIRE_ENCODING (coding))
5363 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5365 /* Likewise. */
5366 if (nchars == E_WRITE_MAX)
5367 coding->raw_destination = 1;
5369 encode_coding_object
5370 (coding, Fcurrent_buffer (), start, start_byte,
5371 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5373 else
5375 coding->dst_object = Qnil;
5376 coding->dst_pos_byte = start_byte;
5377 if (start >= GPT || end <= GPT)
5379 coding->consumed_char = end - start;
5380 coding->produced = end_byte - start_byte;
5382 else
5384 coding->consumed_char = GPT - start;
5385 coding->produced = GPT_BYTE - start_byte;
5390 if (coding->produced > 0)
5392 char *buf = (coding->raw_destination ? (char *) coding->destination
5393 : (STRINGP (coding->dst_object)
5394 ? SSDATA (coding->dst_object)
5395 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5396 coding->produced -= emacs_write_quit (desc, buf, coding->produced);
5398 if (coding->raw_destination)
5400 /* We're responsible for freeing this, see
5401 encode_coding_object to check why. */
5402 xfree (coding->destination);
5403 coding->raw_destination = 0;
5405 if (coding->produced)
5406 return 0;
5408 start += coding->consumed_char;
5411 return 1;
5414 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5415 Sverify_visited_file_modtime, 0, 1, 0,
5416 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5417 This means that the file has not been changed since it was visited or saved.
5418 If BUF is omitted or nil, it defaults to the current buffer.
5419 See Info node `(elisp)Modification Time' for more details. */)
5420 (Lisp_Object buf)
5422 struct buffer *b = decode_buffer (buf);
5423 struct stat st;
5424 Lisp_Object handler;
5425 Lisp_Object filename;
5426 struct timespec mtime;
5428 if (!STRINGP (BVAR (b, filename))) return Qt;
5429 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5431 /* If the file name has special constructs in it,
5432 call the corresponding file handler. */
5433 handler = Ffind_file_name_handler (BVAR (b, filename),
5434 Qverify_visited_file_modtime);
5435 if (!NILP (handler))
5436 return call2 (handler, Qverify_visited_file_modtime, buf);
5438 filename = ENCODE_FILE (BVAR (b, filename));
5440 mtime = (stat (SSDATA (filename), &st) == 0
5441 ? get_stat_mtime (&st)
5442 : time_error_value (errno));
5443 if (timespec_cmp (mtime, b->modtime) == 0
5444 && (b->modtime_size < 0
5445 || st.st_size == b->modtime_size))
5446 return Qt;
5447 return Qnil;
5450 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5451 Svisited_file_modtime, 0, 0, 0,
5452 doc: /* Return the current buffer's recorded visited file modification time.
5453 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5454 `file-attributes' returns. If the current buffer has no recorded file
5455 modification time, this function returns 0. If the visited file
5456 doesn't exist, return -1.
5457 See Info node `(elisp)Modification Time' for more details. */)
5458 (void)
5460 int ns = current_buffer->modtime.tv_nsec;
5461 if (ns < 0)
5462 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5463 return make_lisp_time (current_buffer->modtime);
5466 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5467 Sset_visited_file_modtime, 0, 1, 0,
5468 doc: /* Update buffer's recorded modification time from the visited file's time.
5469 Useful if the buffer was not read from the file normally
5470 or if the file itself has been changed for some known benign reason.
5471 An argument specifies the modification time value to use
5472 \(instead of that of the visited file), in the form of a list
5473 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5474 `visited-file-modtime'. */)
5475 (Lisp_Object time_flag)
5477 if (!NILP (time_flag))
5479 struct timespec mtime;
5480 if (INTEGERP (time_flag))
5482 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5483 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5485 else
5486 mtime = lisp_time_argument (time_flag);
5488 current_buffer->modtime = mtime;
5489 current_buffer->modtime_size = -1;
5491 else
5493 register Lisp_Object filename;
5494 struct stat st;
5495 Lisp_Object handler;
5497 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5499 /* If the file name has special constructs in it,
5500 call the corresponding file handler. */
5501 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5502 if (!NILP (handler))
5503 /* The handler can find the file name the same way we did. */
5504 return call2 (handler, Qset_visited_file_modtime, Qnil);
5506 filename = ENCODE_FILE (filename);
5508 if (stat (SSDATA (filename), &st) >= 0)
5510 current_buffer->modtime = get_stat_mtime (&st);
5511 current_buffer->modtime_size = st.st_size;
5515 return Qnil;
5518 static Lisp_Object
5519 auto_save_error (Lisp_Object error_val)
5521 auto_save_error_occurred = 1;
5523 ring_bell (XFRAME (selected_frame));
5525 AUTO_STRING (format, "Auto-saving %s: %s");
5526 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5527 Ferror_message_string (error_val));
5528 call3 (intern ("display-warning"),
5529 intern ("auto-save"), msg, intern ("error"));
5531 return Qnil;
5534 static Lisp_Object
5535 auto_save_1 (void)
5537 struct stat st;
5538 Lisp_Object modes;
5540 auto_save_mode_bits = 0666;
5542 /* Get visited file's mode to become the auto save file's mode. */
5543 if (! NILP (BVAR (current_buffer, filename)))
5545 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5546 /* But make sure we can overwrite it later! */
5547 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5548 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5549 INTEGERP (modes))
5550 /* Remote files don't cooperate with stat. */
5551 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5554 return
5555 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5556 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5557 Qnil, Qnil);
5560 struct auto_save_unwind
5562 FILE *stream;
5563 bool auto_raise;
5566 static void
5567 do_auto_save_unwind (void *arg)
5569 struct auto_save_unwind *p = arg;
5570 FILE *stream = p->stream;
5571 minibuffer_auto_raise = p->auto_raise;
5572 auto_saving = 0;
5573 if (stream != NULL)
5575 block_input ();
5576 fclose (stream);
5577 unblock_input ();
5581 static Lisp_Object
5582 do_auto_save_make_dir (Lisp_Object dir)
5584 Lisp_Object result;
5586 auto_saving_dir_umask = 077;
5587 result = call2 (Qmake_directory, dir, Qt);
5588 auto_saving_dir_umask = 0;
5589 return result;
5592 static Lisp_Object
5593 do_auto_save_eh (Lisp_Object ignore)
5595 auto_saving_dir_umask = 0;
5596 return Qnil;
5599 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5600 doc: /* Auto-save all buffers that need it.
5601 This is all buffers that have auto-saving enabled
5602 and are changed since last auto-saved.
5603 Auto-saving writes the buffer into a file
5604 so that your editing is not lost if the system crashes.
5605 This file is not the file you visited; that changes only when you save.
5606 Normally we run the normal hook `auto-save-hook' before saving.
5608 A non-nil NO-MESSAGE argument means do not print any message if successful.
5609 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5610 (Lisp_Object no_message, Lisp_Object current_only)
5612 struct buffer *old = current_buffer, *b;
5613 Lisp_Object tail, buf, hook;
5614 bool auto_saved = 0;
5615 int do_handled_files;
5616 Lisp_Object oquit;
5617 FILE *stream = NULL;
5618 ptrdiff_t count = SPECPDL_INDEX ();
5619 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5620 bool old_message_p = 0;
5621 struct auto_save_unwind auto_save_unwind;
5623 if (max_specpdl_size < specpdl_size + 40)
5624 max_specpdl_size = specpdl_size + 40;
5626 if (minibuf_level)
5627 no_message = Qt;
5629 if (NILP (no_message))
5631 old_message_p = push_message ();
5632 record_unwind_protect_void (pop_message_unwind);
5635 /* Ordinarily don't quit within this function,
5636 but don't make it impossible to quit (in case we get hung in I/O). */
5637 oquit = Vquit_flag;
5638 Vquit_flag = Qnil;
5640 hook = intern ("auto-save-hook");
5641 safe_run_hooks (hook);
5643 if (STRINGP (Vauto_save_list_file_name))
5645 Lisp_Object listfile;
5647 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5649 /* Don't try to create the directory when shutting down Emacs,
5650 because creating the directory might signal an error, and
5651 that would leave Emacs in a strange state. */
5652 if (!NILP (Vrun_hooks))
5654 Lisp_Object dir;
5655 dir = Ffile_name_directory (listfile);
5656 if (NILP (Ffile_directory_p (dir)))
5657 internal_condition_case_1 (do_auto_save_make_dir,
5658 dir, Qt,
5659 do_auto_save_eh);
5662 stream = emacs_fopen (SSDATA (listfile), "w");
5665 auto_save_unwind.stream = stream;
5666 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5667 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5668 minibuffer_auto_raise = 0;
5669 auto_saving = 1;
5670 auto_save_error_occurred = 0;
5672 /* On first pass, save all files that don't have handlers.
5673 On second pass, save all files that do have handlers.
5675 If Emacs is crashing, the handlers may tweak what is causing
5676 Emacs to crash in the first place, and it would be a shame if
5677 Emacs failed to autosave perfectly ordinary files because it
5678 couldn't handle some ange-ftp'd file. */
5680 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5681 FOR_EACH_LIVE_BUFFER (tail, buf)
5683 b = XBUFFER (buf);
5685 /* Record all the buffers that have auto save mode
5686 in the special file that lists them. For each of these buffers,
5687 Record visited name (if any) and auto save name. */
5688 if (STRINGP (BVAR (b, auto_save_file_name))
5689 && stream != NULL && do_handled_files == 0)
5691 block_input ();
5692 if (!NILP (BVAR (b, filename)))
5694 fwrite (SDATA (BVAR (b, filename)), 1,
5695 SBYTES (BVAR (b, filename)), stream);
5697 putc ('\n', stream);
5698 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5699 SBYTES (BVAR (b, auto_save_file_name)), stream);
5700 putc ('\n', stream);
5701 unblock_input ();
5704 if (!NILP (current_only)
5705 && b != current_buffer)
5706 continue;
5708 /* Don't auto-save indirect buffers.
5709 The base buffer takes care of it. */
5710 if (b->base_buffer)
5711 continue;
5713 /* Check for auto save enabled
5714 and file changed since last auto save
5715 and file changed since last real save. */
5716 if (STRINGP (BVAR (b, auto_save_file_name))
5717 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5718 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5719 /* -1 means we've turned off autosaving for a while--see below. */
5720 && XINT (BVAR (b, save_length)) >= 0
5721 && (do_handled_files
5722 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5723 Qwrite_region))))
5725 struct timespec before_time = current_timespec ();
5726 struct timespec after_time;
5728 /* If we had a failure, don't try again for 20 minutes. */
5729 if (b->auto_save_failure_time > 0
5730 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5731 continue;
5733 set_buffer_internal (b);
5734 if (NILP (Vauto_save_include_big_deletions)
5735 && (XFASTINT (BVAR (b, save_length)) * 10
5736 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5737 /* A short file is likely to change a large fraction;
5738 spare the user annoying messages. */
5739 && XFASTINT (BVAR (b, save_length)) > 5000
5740 /* These messages are frequent and annoying for `*mail*'. */
5741 && !EQ (BVAR (b, filename), Qnil)
5742 && NILP (no_message))
5744 /* It has shrunk too much; turn off auto-saving here. */
5745 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5746 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5747 BVAR (b, name), 1);
5748 minibuffer_auto_raise = 0;
5749 /* Turn off auto-saving until there's a real save,
5750 and prevent any more warnings. */
5751 XSETINT (BVAR (b, save_length), -1);
5752 Fsleep_for (make_number (1), Qnil);
5753 continue;
5755 if (!auto_saved && NILP (no_message))
5756 message1 ("Auto-saving...");
5757 internal_condition_case (auto_save_1, Qt, auto_save_error);
5758 auto_saved = 1;
5759 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5760 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5761 set_buffer_internal (old);
5763 after_time = current_timespec ();
5765 /* If auto-save took more than 60 seconds,
5766 assume it was an NFS failure that got a timeout. */
5767 if (after_time.tv_sec - before_time.tv_sec > 60)
5768 b->auto_save_failure_time = after_time.tv_sec;
5772 /* Prevent another auto save till enough input events come in. */
5773 record_auto_save ();
5775 if (auto_saved && NILP (no_message))
5777 if (old_message_p)
5779 /* If we are going to restore an old message,
5780 give time to read ours. */
5781 sit_for (make_number (1), 0, 0);
5782 restore_message ();
5784 else if (!auto_save_error_occurred)
5785 /* Don't overwrite the error message if an error occurred.
5786 If we displayed a message and then restored a state
5787 with no message, leave a "done" message on the screen. */
5788 message1 ("Auto-saving...done");
5791 Vquit_flag = oquit;
5793 /* This restores the message-stack status. */
5794 unbind_to (count, Qnil);
5795 return Qnil;
5798 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5799 Sset_buffer_auto_saved, 0, 0, 0,
5800 doc: /* Mark current buffer as auto-saved with its current text.
5801 No auto-save file will be written until the buffer changes again. */)
5802 (void)
5804 /* FIXME: This should not be called in indirect buffers, since
5805 they're not autosaved. */
5806 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5807 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5808 current_buffer->auto_save_failure_time = 0;
5809 return Qnil;
5812 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5813 Sclear_buffer_auto_save_failure, 0, 0, 0,
5814 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5815 (void)
5817 current_buffer->auto_save_failure_time = 0;
5818 return Qnil;
5821 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5822 0, 0, 0,
5823 doc: /* Return t if current buffer has been auto-saved recently.
5824 More precisely, if it has been auto-saved since last read from or saved
5825 in the visited file. If the buffer has no visited file,
5826 then any auto-save counts as "recent". */)
5827 (void)
5829 /* FIXME: maybe we should return nil for indirect buffers since
5830 they're never autosaved. */
5831 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5834 /* Reading and completing file names. */
5836 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5837 Snext_read_file_uses_dialog_p, 0, 0, 0,
5838 doc: /* Return t if a call to `read-file-name' will use a dialog.
5839 The return value is only relevant for a call to `read-file-name' that happens
5840 before any other event (mouse or keypress) is handled. */)
5841 (void)
5843 #if (defined USE_GTK || defined USE_MOTIF \
5844 || defined HAVE_NS || defined HAVE_NTGUI)
5845 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5846 && use_dialog_box
5847 && use_file_dialog
5848 && window_system_available (SELECTED_FRAME ()))
5849 return Qt;
5850 #endif
5851 return Qnil;
5855 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5856 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5857 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5858 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5859 it to text mode.
5861 As a side effect, this function flushes any pending STREAM's data.
5863 Value is the previous value of STREAM's I/O mode, nil for text mode,
5864 non-nil for binary mode.
5866 On MS-Windows and MS-DOS, binary mode is needed to read or write
5867 arbitrary binary data, and for disabling translation between CR-LF
5868 pairs and a single newline character. Examples include generation
5869 of text files with Unix-style end-of-line format using `princ' in
5870 batch mode, with standard output redirected to a file.
5872 On Posix systems, this function always returns non-nil, and has no
5873 effect except for flushing STREAM's data. */)
5874 (Lisp_Object stream, Lisp_Object mode)
5876 FILE *fp = NULL;
5877 int binmode;
5879 CHECK_SYMBOL (stream);
5880 if (EQ (stream, Qstdin))
5881 fp = stdin;
5882 else if (EQ (stream, Qstdout))
5883 fp = stdout;
5884 else if (EQ (stream, Qstderr))
5885 fp = stderr;
5886 else
5887 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5889 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5890 if (fp != stdin)
5891 fflush (fp);
5893 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5896 void
5897 init_fileio (void)
5899 realmask = umask (0);
5900 umask (realmask);
5902 valid_timestamp_file_system = 0;
5904 /* fsync can be a significant performance hit. Often it doesn't
5905 suffice to make the file-save operation survive a crash. For
5906 batch scripts, which are typically part of larger shell commands
5907 that don't fsync other files, its effect on performance can be
5908 significant so its utility is particularly questionable.
5909 Hence, for now by default fsync is used only when interactive.
5911 For more on why fsync often fails to work on today's hardware, see:
5912 Zheng M et al. Understanding the robustness of SSDs under power fault.
5913 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5914 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5916 For more on why fsync does not suffice even if it works properly, see:
5917 Roche X. Necessary step(s) to synchronize filename operations on disk.
5918 Austin Group Defect 672, 2013-03-19
5919 http://austingroupbugs.net/view.php?id=672 */
5920 write_region_inhibit_fsync = noninteractive;
5923 void
5924 syms_of_fileio (void)
5926 /* Property name of a file name handler,
5927 which gives a list of operations it handles. */
5928 DEFSYM (Qoperations, "operations");
5930 DEFSYM (Qexpand_file_name, "expand-file-name");
5931 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5932 DEFSYM (Qdirectory_file_name, "directory-file-name");
5933 DEFSYM (Qfile_name_directory, "file-name-directory");
5934 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5935 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5936 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5937 DEFSYM (Qcopy_file, "copy-file");
5938 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5939 DEFSYM (Qmake_directory, "make-directory");
5940 DEFSYM (Qdelete_file, "delete-file");
5941 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5942 DEFSYM (Qrename_file, "rename-file");
5943 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5944 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5945 DEFSYM (Qfile_exists_p, "file-exists-p");
5946 DEFSYM (Qfile_executable_p, "file-executable-p");
5947 DEFSYM (Qfile_readable_p, "file-readable-p");
5948 DEFSYM (Qfile_writable_p, "file-writable-p");
5949 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5950 DEFSYM (Qaccess_file, "access-file");
5951 DEFSYM (Qfile_directory_p, "file-directory-p");
5952 DEFSYM (Qfile_regular_p, "file-regular-p");
5953 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5954 DEFSYM (Qfile_modes, "file-modes");
5955 DEFSYM (Qset_file_modes, "set-file-modes");
5956 DEFSYM (Qset_file_times, "set-file-times");
5957 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5958 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5959 DEFSYM (Qfile_acl, "file-acl");
5960 DEFSYM (Qset_file_acl, "set-file-acl");
5961 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5962 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5963 DEFSYM (Qwrite_region, "write-region");
5964 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5965 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5967 /* The symbol bound to coding-system-for-read when
5968 insert-file-contents is called for recovering a file. This is not
5969 an actual coding system name, but just an indicator to tell
5970 insert-file-contents to use `emacs-mule' with a special flag for
5971 auto saving and recovering a file. */
5972 DEFSYM (Qauto_save_coding, "auto-save-coding");
5974 DEFSYM (Qfile_name_history, "file-name-history");
5975 Fset (Qfile_name_history, Qnil);
5977 DEFSYM (Qfile_error, "file-error");
5978 DEFSYM (Qfile_already_exists, "file-already-exists");
5979 DEFSYM (Qfile_date_error, "file-date-error");
5980 DEFSYM (Qfile_missing, "file-missing");
5981 DEFSYM (Qfile_notify_error, "file-notify-error");
5982 DEFSYM (Qexcl, "excl");
5984 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5985 doc: /* Coding system for encoding file names.
5986 If it is nil, `default-file-name-coding-system' (which see) is used.
5988 On MS-Windows, the value of this variable is largely ignored if
5989 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5990 behaves as if file names were encoded in `utf-8'. */);
5991 Vfile_name_coding_system = Qnil;
5993 DEFVAR_LISP ("default-file-name-coding-system",
5994 Vdefault_file_name_coding_system,
5995 doc: /* Default coding system for encoding file names.
5996 This variable is used only when `file-name-coding-system' is nil.
5998 This variable is set/changed by the command `set-language-environment'.
5999 User should not set this variable manually,
6000 instead use `file-name-coding-system' to get a constant encoding
6001 of file names regardless of the current language environment.
6003 On MS-Windows, the value of this variable is largely ignored if
6004 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
6005 behaves as if file names were encoded in `utf-8'. */);
6006 Vdefault_file_name_coding_system = Qnil;
6008 /* Lisp functions for translating file formats. */
6009 DEFSYM (Qformat_decode, "format-decode");
6010 DEFSYM (Qformat_annotate_function, "format-annotate-function");
6012 /* Lisp function for setting buffer-file-coding-system and the
6013 multibyteness of the current buffer after inserting a file. */
6014 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
6016 DEFSYM (Qcar_less_than_car, "car-less-than-car");
6018 Fput (Qfile_error, Qerror_conditions,
6019 Fpurecopy (list2 (Qfile_error, Qerror)));
6020 Fput (Qfile_error, Qerror_message,
6021 build_pure_c_string ("File error"));
6023 Fput (Qfile_already_exists, Qerror_conditions,
6024 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
6025 Fput (Qfile_already_exists, Qerror_message,
6026 build_pure_c_string ("File already exists"));
6028 Fput (Qfile_date_error, Qerror_conditions,
6029 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
6030 Fput (Qfile_date_error, Qerror_message,
6031 build_pure_c_string ("Cannot set file date"));
6033 Fput (Qfile_missing, Qerror_conditions,
6034 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
6035 Fput (Qfile_missing, Qerror_message,
6036 build_pure_c_string ("File is missing"));
6038 Fput (Qfile_notify_error, Qerror_conditions,
6039 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
6040 Fput (Qfile_notify_error, Qerror_message,
6041 build_pure_c_string ("File notification error"));
6043 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
6044 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
6045 If a file name matches REGEXP, all I/O on that file is done by calling
6046 HANDLER. If a file name matches more than one handler, the handler
6047 whose match starts last in the file name gets precedence. The
6048 function `find-file-name-handler' checks this list for a handler for
6049 its argument.
6051 HANDLER should be a function. The first argument given to it is the
6052 name of the I/O primitive to be handled; the remaining arguments are
6053 the arguments that were passed to that primitive. For example, if you
6054 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
6055 HANDLER is called like this:
6057 (funcall HANDLER \\='file-exists-p FILENAME)
6059 Note that HANDLER must be able to handle all I/O primitives; if it has
6060 nothing special to do for a primitive, it should reinvoke the
6061 primitive to handle the operation \"the usual way\".
6062 See Info node `(elisp)Magic File Names' for more details. */);
6063 Vfile_name_handler_alist = Qnil;
6065 DEFVAR_LISP ("set-auto-coding-function",
6066 Vset_auto_coding_function,
6067 doc: /* If non-nil, a function to call to decide a coding system of file.
6068 Two arguments are passed to this function: the file name
6069 and the length of a file contents following the point.
6070 This function should return a coding system to decode the file contents.
6071 It should check the file name against `auto-coding-alist'.
6072 If no coding system is decided, it should check a coding system
6073 specified in the heading lines with the format:
6074 -*- ... coding: CODING-SYSTEM; ... -*-
6075 or local variable spec of the tailing lines with `coding:' tag. */);
6076 Vset_auto_coding_function = Qnil;
6078 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
6079 doc: /* A list of functions to be called at the end of `insert-file-contents'.
6080 Each is passed one argument, the number of characters inserted,
6081 with point at the start of the inserted text. Each function
6082 should leave point the same, and return the new character count.
6083 If `insert-file-contents' is intercepted by a handler from
6084 `file-name-handler-alist', that handler is responsible for calling the
6085 functions in `after-insert-file-functions' if appropriate. */);
6086 Vafter_insert_file_functions = Qnil;
6088 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
6089 doc: /* A list of functions to be called at the start of `write-region'.
6090 Each is passed two arguments, START and END as for `write-region'.
6091 These are usually two numbers but not always; see the documentation
6092 for `write-region'. The function should return a list of pairs
6093 of the form (POSITION . STRING), consisting of strings to be effectively
6094 inserted at the specified positions of the file being written (1 means to
6095 insert before the first byte written). The POSITIONs must be sorted into
6096 increasing order.
6098 If there are several annotation functions, the lists returned by these
6099 functions are merged destructively. As each annotation function runs,
6100 the variable `write-region-annotations-so-far' contains a list of all
6101 annotations returned by previous annotation functions.
6103 An annotation function can return with a different buffer current.
6104 Doing so removes the annotations returned by previous functions, and
6105 resets START and END to `point-min' and `point-max' of the new buffer.
6107 After `write-region' completes, Emacs calls the function stored in
6108 `write-region-post-annotation-function', once for each buffer that was
6109 current when building the annotations (i.e., at least once), with that
6110 buffer current. */);
6111 Vwrite_region_annotate_functions = Qnil;
6112 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6114 DEFVAR_LISP ("write-region-post-annotation-function",
6115 Vwrite_region_post_annotation_function,
6116 doc: /* Function to call after `write-region' completes.
6117 The function is called with no arguments. If one or more of the
6118 annotation functions in `write-region-annotate-functions' changed the
6119 current buffer, the function stored in this variable is called for
6120 each of those additional buffers as well, in addition to the original
6121 buffer. The relevant buffer is current during each function call. */);
6122 Vwrite_region_post_annotation_function = Qnil;
6123 staticpro (&Vwrite_region_annotation_buffers);
6125 DEFVAR_LISP ("write-region-annotations-so-far",
6126 Vwrite_region_annotations_so_far,
6127 doc: /* When an annotation function is called, this holds the previous annotations.
6128 These are the annotations made by other annotation functions
6129 that were already called. See also `write-region-annotate-functions'. */);
6130 Vwrite_region_annotations_so_far = Qnil;
6132 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6133 doc: /* A list of file name handlers that temporarily should not be used.
6134 This applies only to the operation `inhibit-file-name-operation'. */);
6135 Vinhibit_file_name_handlers = Qnil;
6137 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6138 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6139 Vinhibit_file_name_operation = Qnil;
6141 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6142 doc: /* File name in which we write a list of all auto save file names.
6143 This variable is initialized automatically from `auto-save-list-file-prefix'
6144 shortly after Emacs reads your init file, if you have not yet given it
6145 a non-nil value. */);
6146 Vauto_save_list_file_name = Qnil;
6148 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6149 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6150 Normally auto-save files are written under other names. */);
6151 Vauto_save_visited_file_name = Qnil;
6153 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6154 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6155 If nil, deleting a substantial portion of the text disables auto-save
6156 in the buffer; this is the default behavior, because the auto-save
6157 file is usually more useful if it contains the deleted text. */);
6158 Vauto_save_include_big_deletions = Qnil;
6160 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6161 doc: /* Non-nil means don't call fsync in `write-region'.
6162 This variable affects calls to `write-region' as well as save commands.
6163 Setting this to nil may avoid data loss if the system loses power or
6164 the operating system crashes. By default, it is non-nil in batch mode. */);
6165 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6167 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6168 doc: /* Specifies whether to use the system's trash can.
6169 When non-nil, certain file deletion commands use the function
6170 `move-file-to-trash' instead of deleting files outright.
6171 This includes interactive calls to `delete-file' and
6172 `delete-directory' and the Dired deletion commands. */);
6173 delete_by_moving_to_trash = 0;
6174 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6176 /* Lisp function for moving files to trash. */
6177 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6179 /* Lisp function for recursively copying directories. */
6180 DEFSYM (Qcopy_directory, "copy-directory");
6182 /* Lisp function for recursively deleting directories. */
6183 DEFSYM (Qdelete_directory, "delete-directory");
6185 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6186 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6188 DEFSYM (Qstdin, "stdin");
6189 DEFSYM (Qstdout, "stdout");
6190 DEFSYM (Qstderr, "stderr");
6192 defsubr (&Sfind_file_name_handler);
6193 defsubr (&Sfile_name_directory);
6194 defsubr (&Sfile_name_nondirectory);
6195 defsubr (&Sunhandled_file_name_directory);
6196 defsubr (&Sfile_name_as_directory);
6197 defsubr (&Sdirectory_file_name);
6198 defsubr (&Smake_temp_name);
6199 defsubr (&Sexpand_file_name);
6200 defsubr (&Ssubstitute_in_file_name);
6201 defsubr (&Scopy_file);
6202 defsubr (&Smake_directory_internal);
6203 defsubr (&Sdelete_directory_internal);
6204 defsubr (&Sdelete_file);
6205 defsubr (&Sfile_name_case_insensitive_p);
6206 defsubr (&Srename_file);
6207 defsubr (&Sadd_name_to_file);
6208 defsubr (&Smake_symbolic_link);
6209 defsubr (&Sfile_name_absolute_p);
6210 defsubr (&Sfile_exists_p);
6211 defsubr (&Sfile_executable_p);
6212 defsubr (&Sfile_readable_p);
6213 defsubr (&Sfile_writable_p);
6214 defsubr (&Saccess_file);
6215 defsubr (&Sfile_symlink_p);
6216 defsubr (&Sfile_directory_p);
6217 defsubr (&Sfile_accessible_directory_p);
6218 defsubr (&Sfile_regular_p);
6219 defsubr (&Sfile_modes);
6220 defsubr (&Sset_file_modes);
6221 defsubr (&Sset_file_times);
6222 defsubr (&Sfile_selinux_context);
6223 defsubr (&Sfile_acl);
6224 defsubr (&Sset_file_acl);
6225 defsubr (&Sset_file_selinux_context);
6226 defsubr (&Sset_default_file_modes);
6227 defsubr (&Sdefault_file_modes);
6228 defsubr (&Sfile_newer_than_file_p);
6229 defsubr (&Sinsert_file_contents);
6230 defsubr (&Swrite_region);
6231 defsubr (&Scar_less_than_car);
6232 defsubr (&Sverify_visited_file_modtime);
6233 defsubr (&Svisited_file_modtime);
6234 defsubr (&Sset_visited_file_modtime);
6235 defsubr (&Sdo_auto_save);
6236 defsubr (&Sset_buffer_auto_saved);
6237 defsubr (&Sclear_buffer_auto_save_failure);
6238 defsubr (&Srecent_auto_save_p);
6240 defsubr (&Snext_read_file_uses_dialog_p);
6242 defsubr (&Sset_binary_mode);
6244 #ifdef HAVE_SYNC
6245 defsubr (&Sunix_sync);
6246 #endif