Add lisp watchpoints
[emacs.git] / src / fileio.c
blob7aa58177d49518751251e89bbbe66590e65ef9f4
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2016 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 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 #ifdef WINDOWSNT
888 /* Detect Windows file names in UNC format. */
889 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
890 #endif
891 #else /* not DOS_NT */
892 /* Detect Unix absolute file names (/... alone is not absolute on
893 DOS or Windows). */
894 && ! (IS_DIRECTORY_SEP (o[0]))
895 #endif /* not DOS_NT */
898 default_directory = Fexpand_file_name (default_directory, Qnil);
901 multibyte = STRING_MULTIBYTE (name);
902 if (multibyte != STRING_MULTIBYTE (default_directory))
904 if (multibyte)
906 unsigned char *p = SDATA (name);
908 while (*p && ASCII_CHAR_P (*p))
909 p++;
910 if (*p == '\0')
912 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
913 unibyte. Do not convert DEFAULT_DIRECTORY to
914 multibyte; instead, convert NAME to a unibyte string,
915 so that the result of this function is also a unibyte
916 string. This is needed during bootstrapping and
917 dumping, when Emacs cannot decode file names, because
918 the locale environment is not set up. */
919 name = make_unibyte_string (SSDATA (name), SBYTES (name));
920 multibyte = 0;
922 else
923 default_directory = string_to_multibyte (default_directory);
925 else
927 name = string_to_multibyte (name);
928 multibyte = 1;
932 #ifdef WINDOWSNT
933 if (!NILP (Vw32_downcase_file_names))
934 default_directory = Fdowncase (default_directory);
935 #endif
937 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
938 SAFE_ALLOCA_STRING (nm, name);
939 nmlim = nm + SBYTES (name);
941 #ifdef DOS_NT
942 /* Note if special escape prefix is present, but remove for now. */
943 if (nm[0] == '/' && nm[1] == ':')
945 is_escaped = 1;
946 nm += 2;
949 /* Find and remove drive specifier if present; this makes nm absolute
950 even if the rest of the name appears to be relative. Only look for
951 drive specifier at the beginning. */
952 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
954 drive = (unsigned char) nm[0];
955 nm += 2;
958 #ifdef WINDOWSNT
959 /* If we see "c://somedir", we want to strip the first slash after the
960 colon when stripping the drive letter. Otherwise, this expands to
961 "//somedir". */
962 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
963 nm++;
965 /* Discard any previous drive specifier if nm is now in UNC format. */
966 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
967 && !IS_DIRECTORY_SEP (nm[2]))
968 drive = 0;
969 #endif /* WINDOWSNT */
970 #endif /* DOS_NT */
972 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
973 none are found, we can probably return right away. We will avoid
974 allocating a new string if name is already fully expanded. */
975 if (
976 IS_DIRECTORY_SEP (nm[0])
977 #ifdef MSDOS
978 && drive && !is_escaped
979 #endif
980 #ifdef WINDOWSNT
981 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
982 #endif
985 /* If it turns out that the filename we want to return is just a
986 suffix of FILENAME, we don't need to go through and edit
987 things; we just need to construct a new string using data
988 starting at the middle of FILENAME. If we set LOSE, that
989 means we've discovered that we can't do that cool trick. */
990 bool lose = 0;
991 char *p = nm;
993 while (*p)
995 /* Since we know the name is absolute, we can assume that each
996 element starts with a "/". */
998 /* "." and ".." are hairy. */
999 if (IS_DIRECTORY_SEP (p[0])
1000 && p[1] == '.'
1001 && (IS_DIRECTORY_SEP (p[2])
1002 || p[2] == 0
1003 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1004 || p[3] == 0))))
1005 lose = 1;
1006 /* Replace multiple slashes with a single one, except
1007 leave leading "//" alone. */
1008 else if (IS_DIRECTORY_SEP (p[0])
1009 && IS_DIRECTORY_SEP (p[1])
1010 && (p != nm || IS_DIRECTORY_SEP (p[2])))
1011 lose = 1;
1012 p++;
1014 if (!lose)
1016 #ifdef DOS_NT
1017 /* Make sure directories are all separated with /, but
1018 avoid allocation of a new string when not required. */
1019 dostounix_filename (nm);
1020 #ifdef WINDOWSNT
1021 if (IS_DIRECTORY_SEP (nm[1]))
1023 if (strcmp (nm, SSDATA (name)) != 0)
1024 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1026 else
1027 #endif
1028 /* Drive must be set, so this is okay. */
1029 if (strcmp (nm - 2, SSDATA (name)) != 0)
1031 name = make_specified_string (nm, -1, p - nm, multibyte);
1032 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1033 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1034 name = concat2 (drive_prefix, name);
1036 #ifdef WINDOWSNT
1037 if (!NILP (Vw32_downcase_file_names))
1038 name = Fdowncase (name);
1039 #endif
1040 #else /* not DOS_NT */
1041 if (strcmp (nm, SSDATA (name)) != 0)
1042 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1043 #endif /* not DOS_NT */
1044 SAFE_FREE ();
1045 return name;
1049 /* At this point, nm might or might not be an absolute file name. We
1050 need to expand ~ or ~user if present, otherwise prefix nm with
1051 default_directory if nm is not absolute, and finally collapse /./
1052 and /foo/../ sequences.
1054 We set newdir to be the appropriate prefix if one is needed:
1055 - the relevant user directory if nm starts with ~ or ~user
1056 - the specified drive's working dir (DOS/NT only) if nm does not
1057 start with /
1058 - the value of default_directory.
1060 Note that these prefixes are not guaranteed to be absolute (except
1061 for the working dir of a drive). Therefore, to ensure we always
1062 return an absolute name, if the final prefix is not absolute we
1063 append it to the current working directory. */
1065 newdir = newdirlim = 0;
1067 if (nm[0] == '~') /* prefix ~ */
1069 if (IS_DIRECTORY_SEP (nm[1])
1070 || nm[1] == 0) /* ~ by itself */
1072 Lisp_Object tem;
1074 if (!(newdir = egetenv ("HOME")))
1075 newdir = newdirlim = "";
1076 nm++;
1077 /* `egetenv' may return a unibyte string, which will bite us since
1078 we expect the directory to be multibyte. */
1079 #ifdef WINDOWSNT
1080 if (newdir[0])
1082 char newdir_utf8[MAX_UTF8_PATH];
1084 filename_from_ansi (newdir, newdir_utf8);
1085 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1087 else
1088 #endif
1089 tem = build_string (newdir);
1090 newdirlim = newdir + SBYTES (tem);
1091 if (multibyte && !STRING_MULTIBYTE (tem))
1093 hdir = DECODE_FILE (tem);
1094 newdir = SSDATA (hdir);
1095 newdirlim = newdir + SBYTES (hdir);
1097 #ifdef DOS_NT
1098 collapse_newdir = false;
1099 #endif
1101 else /* ~user/filename */
1103 char *o, *p;
1104 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1105 continue;
1106 o = SAFE_ALLOCA (p - nm + 1);
1107 memcpy (o, nm, p - nm);
1108 o[p - nm] = 0;
1110 block_input ();
1111 pw = getpwnam (o + 1);
1112 unblock_input ();
1113 if (pw)
1115 Lisp_Object tem;
1117 newdir = pw->pw_dir;
1118 /* `getpwnam' may return a unibyte string, which will
1119 bite us since we expect the directory to be
1120 multibyte. */
1121 tem = make_unibyte_string (newdir, strlen (newdir));
1122 newdirlim = newdir + SBYTES (tem);
1123 if (multibyte && !STRING_MULTIBYTE (tem))
1125 hdir = DECODE_FILE (tem);
1126 newdir = SSDATA (hdir);
1127 newdirlim = newdir + SBYTES (hdir);
1129 nm = p;
1130 #ifdef DOS_NT
1131 collapse_newdir = false;
1132 #endif
1135 /* If we don't find a user of that name, leave the name
1136 unchanged; don't move nm forward to p. */
1140 #ifdef DOS_NT
1141 /* On DOS and Windows, nm is absolute if a drive name was specified;
1142 use the drive's current directory as the prefix if needed. */
1143 if (!newdir && drive)
1145 /* Get default directory if needed to make nm absolute. */
1146 char *adir = NULL;
1147 if (!IS_DIRECTORY_SEP (nm[0]))
1149 adir = alloca (MAXPATHLEN + 1);
1150 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1151 adir = NULL;
1152 else if (multibyte)
1154 Lisp_Object tem = build_string (adir);
1156 tem = DECODE_FILE (tem);
1157 newdirlim = adir + SBYTES (tem);
1158 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1160 else
1161 newdirlim = adir + strlen (adir);
1163 if (!adir)
1165 /* Either nm starts with /, or drive isn't mounted. */
1166 adir = alloca (4);
1167 adir[0] = DRIVE_LETTER (drive);
1168 adir[1] = ':';
1169 adir[2] = '/';
1170 adir[3] = 0;
1171 newdirlim = adir + 3;
1173 newdir = adir;
1175 #endif /* DOS_NT */
1177 /* Finally, if no prefix has been specified and nm is not absolute,
1178 then it must be expanded relative to default_directory. */
1180 if (1
1181 #ifndef DOS_NT
1182 /* /... alone is not absolute on DOS and Windows. */
1183 && !IS_DIRECTORY_SEP (nm[0])
1184 #endif
1185 #ifdef WINDOWSNT
1186 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1187 && !IS_DIRECTORY_SEP (nm[2]))
1188 #endif
1189 && !newdir)
1191 newdir = SSDATA (default_directory);
1192 newdirlim = newdir + SBYTES (default_directory);
1193 #ifdef DOS_NT
1194 /* Note if special escape prefix is present, but remove for now. */
1195 if (newdir[0] == '/' && newdir[1] == ':')
1197 is_escaped = 1;
1198 newdir += 2;
1200 #endif
1203 #ifdef DOS_NT
1204 if (newdir)
1206 /* First ensure newdir is an absolute name. */
1207 if (
1208 /* Detect MSDOS file names with drive specifiers. */
1209 ! (IS_DRIVE (newdir[0])
1210 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1211 #ifdef WINDOWSNT
1212 /* Detect Windows file names in UNC format. */
1213 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1214 && !IS_DIRECTORY_SEP (newdir[2]))
1215 #endif
1218 /* Effectively, let newdir be (expand-file-name newdir cwd).
1219 Because of the admonition against calling expand-file-name
1220 when we have pointers into lisp strings, we accomplish this
1221 indirectly by prepending newdir to nm if necessary, and using
1222 cwd (or the wd of newdir's drive) as the new newdir. */
1223 char *adir;
1224 #ifdef WINDOWSNT
1225 const int adir_size = MAX_UTF8_PATH;
1226 #else
1227 const int adir_size = MAXPATHLEN + 1;
1228 #endif
1230 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1232 drive = (unsigned char) newdir[0];
1233 newdir += 2;
1235 if (!IS_DIRECTORY_SEP (nm[0]))
1237 ptrdiff_t nmlen = nmlim - nm;
1238 ptrdiff_t newdirlen = newdirlim - newdir;
1239 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1240 + nmlen + 1);
1241 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1242 multibyte);
1243 memcpy (tmp + dlen, nm, nmlen + 1);
1244 nm = tmp;
1245 nmlim = nm + dlen + nmlen;
1247 adir = alloca (adir_size);
1248 if (drive)
1250 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1251 strcpy (adir, "/");
1253 else
1254 getcwd (adir, adir_size);
1255 if (multibyte)
1257 Lisp_Object tem = build_string (adir);
1259 tem = DECODE_FILE (tem);
1260 newdirlim = adir + SBYTES (tem);
1261 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1263 else
1264 newdirlim = adir + strlen (adir);
1265 newdir = adir;
1268 /* Strip off drive name from prefix, if present. */
1269 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1271 drive = newdir[0];
1272 newdir += 2;
1275 /* Keep only a prefix from newdir if nm starts with slash
1276 (//server/share for UNC, nothing otherwise). */
1277 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1279 #ifdef WINDOWSNT
1280 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1281 && !IS_DIRECTORY_SEP (newdir[2]))
1283 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1284 char *p = adir + 2;
1285 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1286 p++;
1287 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1288 *p = 0;
1289 newdir = adir;
1290 newdirlim = newdir + strlen (adir);
1292 else
1293 #endif
1294 newdir = newdirlim = "";
1297 #endif /* DOS_NT */
1299 /* Ignore any slash at the end of newdir, unless newdir is
1300 just "/" or "//". */
1301 length = newdirlim - newdir;
1302 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1303 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1304 length--;
1306 /* Now concatenate the directory and name to new space in the stack frame. */
1307 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1308 eassert (tlen > file_name_as_directory_slop + 1);
1309 #ifdef DOS_NT
1310 /* Reserve space for drive specifier and escape prefix, since either
1311 or both may need to be inserted. (The Microsoft x86 compiler
1312 produces incorrect code if the following two lines are combined.) */
1313 target = alloca (tlen + 4);
1314 target += 4;
1315 #else /* not DOS_NT */
1316 target = SAFE_ALLOCA (tlen);
1317 #endif /* not DOS_NT */
1318 *target = 0;
1319 nbytes = 0;
1321 if (newdir)
1323 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1325 #ifdef DOS_NT
1326 /* If newdir is effectively "C:/", then the drive letter will have
1327 been stripped and newdir will be "/". Concatenating with an
1328 absolute directory in nm produces "//", which will then be
1329 incorrectly treated as a network share. Ignore newdir in
1330 this case (keeping the drive letter). */
1331 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1332 && newdir[1] == '\0'))
1333 #endif
1335 memcpy (target, newdir, length);
1336 target[length] = 0;
1337 nbytes = length;
1340 else
1341 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1344 memcpy (target + nbytes, nm, nmlim - nm + 1);
1346 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1347 appear. */
1349 char *p = target;
1350 char *o = target;
1352 while (*p)
1354 if (!IS_DIRECTORY_SEP (*p))
1356 *o++ = *p++;
1358 else if (p[1] == '.'
1359 && (IS_DIRECTORY_SEP (p[2])
1360 || p[2] == 0))
1362 /* If "/." is the entire filename, keep the "/". Otherwise,
1363 just delete the whole "/.". */
1364 if (o == target && p[2] == '\0')
1365 *o++ = *p;
1366 p += 2;
1368 else if (p[1] == '.' && p[2] == '.'
1369 /* `/../' is the "superroot" on certain file systems.
1370 Turned off on DOS_NT systems because they have no
1371 "superroot" and because this causes us to produce
1372 file names like "d:/../foo" which fail file-related
1373 functions of the underlying OS. (To reproduce, try a
1374 long series of "../../" in default_directory, longer
1375 than the number of levels from the root.) */
1376 #ifndef DOS_NT
1377 && o != target
1378 #endif
1379 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1381 #ifdef WINDOWSNT
1382 char *prev_o = o;
1383 #endif
1384 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1385 continue;
1386 #ifdef WINDOWSNT
1387 /* Don't go below server level in UNC filenames. */
1388 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1389 && IS_DIRECTORY_SEP (*target))
1390 o = prev_o;
1391 else
1392 #endif
1393 /* Keep initial / only if this is the whole name. */
1394 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1395 ++o;
1396 p += 3;
1398 else if (IS_DIRECTORY_SEP (p[1])
1399 && (p != target || IS_DIRECTORY_SEP (p[2])))
1400 /* Collapse multiple "/", except leave leading "//" alone. */
1401 p++;
1402 else
1404 *o++ = *p++;
1408 #ifdef DOS_NT
1409 /* At last, set drive name. */
1410 #ifdef WINDOWSNT
1411 /* Except for network file name. */
1412 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1413 #endif /* WINDOWSNT */
1415 if (!drive) emacs_abort ();
1416 target -= 2;
1417 target[0] = DRIVE_LETTER (drive);
1418 target[1] = ':';
1420 /* Reinsert the escape prefix if required. */
1421 if (is_escaped)
1423 target -= 2;
1424 target[0] = '/';
1425 target[1] = ':';
1427 result = make_specified_string (target, -1, o - target, multibyte);
1428 dostounix_filename (SSDATA (result));
1429 #ifdef WINDOWSNT
1430 if (!NILP (Vw32_downcase_file_names))
1431 result = Fdowncase (result);
1432 #endif
1433 #else /* !DOS_NT */
1434 result = make_specified_string (target, -1, o - target, multibyte);
1435 #endif /* !DOS_NT */
1438 /* Again look to see if the file name has special constructs in it
1439 and perhaps call the corresponding file handler. This is needed
1440 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1441 the ".." component gives us "/user@host:/bar/../baz" which needs
1442 to be expanded again. */
1443 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1444 if (!NILP (handler))
1446 handled_name = call3 (handler, Qexpand_file_name,
1447 result, default_directory);
1448 if (! STRINGP (handled_name))
1449 error ("Invalid handler in `file-name-handler-alist'");
1450 result = handled_name;
1453 SAFE_FREE ();
1454 return result;
1457 #if 0
1458 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1459 This is the old version of expand-file-name, before it was thoroughly
1460 rewritten for Emacs 10.31. We leave this version here commented-out,
1461 because the code is very complex and likely to have subtle bugs. If
1462 bugs _are_ found, it might be of interest to look at the old code and
1463 see what did it do in the relevant situation.
1465 Don't remove this code: it's true that it will be accessible
1466 from the repository, but a few years from deletion, people will
1467 forget it is there. */
1469 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1470 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1471 "Convert FILENAME to absolute, and canonicalize it.\n\
1472 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1473 \(does not start with slash); if DEFAULT is nil or missing,\n\
1474 the current buffer's value of default-directory is used.\n\
1475 Filenames containing `.' or `..' as components are simplified;\n\
1476 initial `~/' expands to your home directory.\n\
1477 See also the function `substitute-in-file-name'.")
1478 (name, defalt)
1479 Lisp_Object name, defalt;
1481 unsigned char *nm;
1483 register unsigned char *newdir, *p, *o;
1484 ptrdiff_t tlen;
1485 unsigned char *target;
1486 struct passwd *pw;
1488 CHECK_STRING (name);
1489 nm = SDATA (name);
1491 /* If nm is absolute, flush ...// and detect /./ and /../.
1492 If no /./ or /../ we can return right away. */
1493 if (nm[0] == '/')
1495 bool lose = 0;
1496 p = nm;
1497 while (*p)
1499 if (p[0] == '/' && p[1] == '/')
1500 nm = p + 1;
1501 if (p[0] == '/' && p[1] == '~')
1502 nm = p + 1, lose = 1;
1503 if (p[0] == '/' && p[1] == '.'
1504 && (p[2] == '/' || p[2] == 0
1505 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1506 lose = 1;
1507 p++;
1509 if (!lose)
1511 if (nm == SDATA (name))
1512 return name;
1513 return build_string (nm);
1517 /* Now determine directory to start with and put it in NEWDIR. */
1519 newdir = 0;
1521 if (nm[0] == '~') /* prefix ~ */
1522 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1524 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1525 newdir = (unsigned char *) "";
1526 nm++;
1528 else /* ~user/filename */
1530 /* Get past ~ to user. */
1531 unsigned char *user = nm + 1;
1532 /* Find end of name. */
1533 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1534 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1535 /* Copy the user name into temp storage. */
1536 o = alloca (len + 1);
1537 memcpy (o, user, len);
1538 o[len] = 0;
1540 /* Look up the user name. */
1541 block_input ();
1542 pw = (struct passwd *) getpwnam (o + 1);
1543 unblock_input ();
1544 if (!pw)
1545 error ("\"%s\" isn't a registered user", o + 1);
1547 newdir = (unsigned char *) pw->pw_dir;
1549 /* Discard the user name from NM. */
1550 nm += len;
1553 if (nm[0] != '/' && !newdir)
1555 if (NILP (defalt))
1556 defalt = current_buffer->directory;
1557 CHECK_STRING (defalt);
1558 newdir = SDATA (defalt);
1561 /* Now concatenate the directory and name to new space in the stack frame. */
1563 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1564 target = alloca (tlen);
1565 *target = 0;
1567 if (newdir)
1569 if (nm[0] == 0 || nm[0] == '/')
1570 strcpy (target, newdir);
1571 else
1572 file_name_as_directory (target, newdir);
1575 strcat (target, nm);
1577 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1579 p = target;
1580 o = target;
1582 while (*p)
1584 if (*p != '/')
1586 *o++ = *p++;
1588 else if (!strncmp (p, "//", 2)
1591 o = target;
1592 p++;
1594 else if (p[0] == '/' && p[1] == '.'
1595 && (p[2] == '/' || p[2] == 0))
1596 p += 2;
1597 else if (!strncmp (p, "/..", 3)
1598 /* `/../' is the "superroot" on certain file systems. */
1599 && o != target
1600 && (p[3] == '/' || p[3] == 0))
1602 while (o != target && *--o != '/')
1604 if (o == target && *o == '/')
1605 ++o;
1606 p += 3;
1608 else
1610 *o++ = *p++;
1614 return make_string (target, o - target);
1616 #endif
1618 /* If /~ or // appears, discard everything through first slash. */
1619 static bool
1620 file_name_absolute_p (const char *filename)
1622 return
1623 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1624 #ifdef DOS_NT
1625 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1626 && IS_DIRECTORY_SEP (filename[2]))
1627 #endif
1631 static char *
1632 search_embedded_absfilename (char *nm, char *endp)
1634 char *p, *s;
1636 for (p = nm + 1; p < endp; p++)
1638 if (IS_DIRECTORY_SEP (p[-1])
1639 && file_name_absolute_p (p)
1640 #if defined (WINDOWSNT) || defined (CYGWIN)
1641 /* // at start of file name is meaningful in Apollo,
1642 WindowsNT and Cygwin systems. */
1643 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1644 #endif /* not (WINDOWSNT || CYGWIN) */
1647 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1648 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1650 USE_SAFE_ALLOCA;
1651 char *o = SAFE_ALLOCA (s - p + 1);
1652 struct passwd *pw;
1653 memcpy (o, p, s - p);
1654 o [s - p] = 0;
1656 /* If we have ~user and `user' exists, discard
1657 everything up to ~. But if `user' does not exist, leave
1658 ~user alone, it might be a literal file name. */
1659 block_input ();
1660 pw = getpwnam (o + 1);
1661 unblock_input ();
1662 SAFE_FREE ();
1663 if (pw)
1664 return p;
1666 else
1667 return p;
1670 return NULL;
1673 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1674 Ssubstitute_in_file_name, 1, 1, 0,
1675 doc: /* Substitute environment variables referred to in FILENAME.
1676 `$FOO' where FOO is an environment variable name means to substitute
1677 the value of that variable. The variable name should be terminated
1678 with a character not a letter, digit or underscore; otherwise, enclose
1679 the entire variable name in braces.
1681 If `/~' appears, all of FILENAME through that `/' is discarded.
1682 If `//' appears, everything up to and including the first of
1683 those `/' is discarded. */)
1684 (Lisp_Object filename)
1686 char *nm, *p, *x, *endp;
1687 bool substituted = false;
1688 bool multibyte;
1689 char *xnm;
1690 Lisp_Object handler;
1692 CHECK_STRING (filename);
1694 multibyte = STRING_MULTIBYTE (filename);
1696 /* If the file name has special constructs in it,
1697 call the corresponding file handler. */
1698 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1699 if (!NILP (handler))
1701 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1702 filename);
1703 if (STRINGP (handled_name))
1704 return handled_name;
1705 error ("Invalid handler in `file-name-handler-alist'");
1708 /* Always work on a copy of the string, in case GC happens during
1709 decode of environment variables, causing the original Lisp_String
1710 data to be relocated. */
1711 USE_SAFE_ALLOCA;
1712 SAFE_ALLOCA_STRING (nm, filename);
1714 #ifdef DOS_NT
1715 dostounix_filename (nm);
1716 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1717 #endif
1718 endp = nm + SBYTES (filename);
1720 /* If /~ or // appears, discard everything through first slash. */
1721 p = search_embedded_absfilename (nm, endp);
1722 if (p)
1723 /* Start over with the new string, so we check the file-name-handler
1724 again. Important with filenames like "/home/foo//:/hello///there"
1725 which would substitute to "/:/hello///there" rather than "/there". */
1727 Lisp_Object result
1728 = (Fsubstitute_in_file_name
1729 (make_specified_string (p, -1, endp - p, multibyte)));
1730 SAFE_FREE ();
1731 return result;
1734 /* See if any variables are substituted into the string. */
1736 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1738 Lisp_Object name
1739 = (!substituted ? filename
1740 : make_specified_string (nm, -1, endp - nm, multibyte));
1741 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1742 CHECK_STRING (tmp);
1743 if (!EQ (tmp, name))
1744 substituted = true;
1745 filename = tmp;
1748 if (!substituted)
1750 #ifdef WINDOWSNT
1751 if (!NILP (Vw32_downcase_file_names))
1752 filename = Fdowncase (filename);
1753 #endif
1754 SAFE_FREE ();
1755 return filename;
1758 xnm = SSDATA (filename);
1759 x = xnm + SBYTES (filename);
1761 /* If /~ or // appears, discard everything through first slash. */
1762 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1763 /* This time we do not start over because we've already expanded envvars
1764 and replaced $$ with $. Maybe we should start over as well, but we'd
1765 need to quote some $ to $$ first. */
1766 xnm = p;
1768 #ifdef WINDOWSNT
1769 if (!NILP (Vw32_downcase_file_names))
1771 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1773 filename = Fdowncase (xname);
1775 else
1776 #endif
1777 if (xnm != SSDATA (filename))
1778 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1779 SAFE_FREE ();
1780 return filename;
1783 /* A slightly faster and more convenient way to get
1784 (directory-file-name (expand-file-name FOO)). */
1786 Lisp_Object
1787 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1789 register Lisp_Object absname;
1791 absname = Fexpand_file_name (filename, defdir);
1793 /* Remove final slash, if any (unless this is the root dir).
1794 stat behaves differently depending! */
1795 if (SCHARS (absname) > 1
1796 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1797 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1798 /* We cannot take shortcuts; they might be wrong for magic file names. */
1799 absname = Fdirectory_file_name (absname);
1800 return absname;
1803 /* Signal an error if the file ABSNAME already exists.
1804 If KNOWN_TO_EXIST, the file is known to exist.
1805 QUERYSTRING is a name for the action that is being considered
1806 to alter the file.
1807 If INTERACTIVE, ask the user whether to proceed,
1808 and bypass the error if the user says to go ahead.
1809 If QUICK, ask for y or n, not yes or no. */
1811 static void
1812 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1813 const char *querystring, bool interactive,
1814 bool quick)
1816 Lisp_Object tem, encoded_filename;
1817 struct stat statbuf;
1819 encoded_filename = ENCODE_FILE (absname);
1821 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1823 if (S_ISDIR (statbuf.st_mode))
1824 xsignal2 (Qfile_error,
1825 build_string ("File is a directory"), absname);
1826 known_to_exist = true;
1829 if (known_to_exist)
1831 if (! interactive)
1832 xsignal2 (Qfile_already_exists,
1833 build_string ("File already exists"), absname);
1834 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1835 tem = CALLN (Fformat, format, absname, build_string (querystring));
1836 if (quick)
1837 tem = call1 (intern ("y-or-n-p"), tem);
1838 else
1839 tem = do_yes_or_no_p (tem);
1840 if (NILP (tem))
1841 xsignal2 (Qfile_already_exists,
1842 build_string ("File already exists"), absname);
1846 #ifndef WINDOWSNT
1847 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1848 static bool
1849 clone_file (int dest, int source)
1851 #ifdef FICLONE
1852 return ioctl (dest, FICLONE, source) == 0;
1853 #endif
1854 return false;
1856 #endif
1858 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1859 "fCopy file: \nGCopy %s to file: \np\nP",
1860 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1861 If NEWNAME names a directory, copy FILE there.
1863 This function always sets the file modes of the output file to match
1864 the input file.
1866 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1867 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1868 signal a `file-already-exists' error without overwriting. If
1869 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1870 about overwriting; this is what happens in interactive use with M-x.
1871 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1872 existing file.
1874 Fourth arg KEEP-TIME non-nil means give the output file the same
1875 last-modified time as the old one. (This works on only some systems.)
1877 A prefix arg makes KEEP-TIME non-nil.
1879 If PRESERVE-UID-GID is non-nil, we try to transfer the
1880 uid and gid of FILE to NEWNAME.
1882 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1883 this includes the file modes, along with ACL entries and SELinux
1884 context if present. Otherwise, if NEWNAME is created its file
1885 permission bits are those of FILE, masked by the default file
1886 permissions. */)
1887 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1888 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1889 Lisp_Object preserve_permissions)
1891 Lisp_Object handler;
1892 ptrdiff_t count = SPECPDL_INDEX ();
1893 Lisp_Object encoded_file, encoded_newname;
1894 #if HAVE_LIBSELINUX
1895 security_context_t con;
1896 int conlength = 0;
1897 #endif
1898 #ifdef WINDOWSNT
1899 int result;
1900 #else
1901 bool already_exists = false;
1902 mode_t new_mask;
1903 int ifd, ofd;
1904 struct stat st;
1905 #endif
1907 encoded_file = encoded_newname = Qnil;
1908 CHECK_STRING (file);
1909 CHECK_STRING (newname);
1911 if (!NILP (Ffile_directory_p (newname)))
1912 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1913 else
1914 newname = Fexpand_file_name (newname, Qnil);
1916 file = Fexpand_file_name (file, Qnil);
1918 /* If the input file name has special constructs in it,
1919 call the corresponding file handler. */
1920 handler = Ffind_file_name_handler (file, Qcopy_file);
1921 /* Likewise for output file name. */
1922 if (NILP (handler))
1923 handler = Ffind_file_name_handler (newname, Qcopy_file);
1924 if (!NILP (handler))
1925 return call7 (handler, Qcopy_file, file, newname,
1926 ok_if_already_exists, keep_time, preserve_uid_gid,
1927 preserve_permissions);
1929 encoded_file = ENCODE_FILE (file);
1930 encoded_newname = ENCODE_FILE (newname);
1932 #ifdef WINDOWSNT
1933 if (NILP (ok_if_already_exists)
1934 || INTEGERP (ok_if_already_exists))
1935 barf_or_query_if_file_exists (newname, false, "copy to it",
1936 INTEGERP (ok_if_already_exists), false);
1938 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1939 !NILP (keep_time), !NILP (preserve_uid_gid),
1940 !NILP (preserve_permissions));
1941 switch (result)
1943 case -1:
1944 report_file_error ("Copying file", list2 (file, newname));
1945 case -2:
1946 report_file_error ("Copying permissions from", file);
1947 case -3:
1948 xsignal2 (Qfile_date_error,
1949 build_string ("Resetting file times"), newname);
1950 case -4:
1951 report_file_error ("Copying permissions to", newname);
1953 #else /* not WINDOWSNT */
1954 immediate_quit = 1;
1955 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1956 immediate_quit = 0;
1958 if (ifd < 0)
1959 report_file_error ("Opening input file", file);
1961 record_unwind_protect_int (close_file_unwind, ifd);
1963 if (fstat (ifd, &st) != 0)
1964 report_file_error ("Input file status", file);
1966 if (!NILP (preserve_permissions))
1968 #if HAVE_LIBSELINUX
1969 if (is_selinux_enabled ())
1971 conlength = fgetfilecon (ifd, &con);
1972 if (conlength == -1)
1973 report_file_error ("Doing fgetfilecon", file);
1975 #endif
1978 /* We can copy only regular files. */
1979 if (!S_ISREG (st.st_mode))
1980 report_file_errno ("Non-regular file", file,
1981 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1983 #ifndef MSDOS
1984 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1985 #else
1986 new_mask = S_IREAD | S_IWRITE;
1987 #endif
1989 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1990 new_mask);
1991 if (ofd < 0 && errno == EEXIST)
1993 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1994 barf_or_query_if_file_exists (newname, true, "copy to it",
1995 INTEGERP (ok_if_already_exists), false);
1996 already_exists = true;
1997 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1999 if (ofd < 0)
2000 report_file_error ("Opening output file", newname);
2002 record_unwind_protect_int (close_file_unwind, ofd);
2004 off_t oldsize = 0, newsize;
2006 if (already_exists)
2008 struct stat out_st;
2009 if (fstat (ofd, &out_st) != 0)
2010 report_file_error ("Output file status", newname);
2011 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2012 report_file_errno ("Input and output files are the same",
2013 list2 (file, newname), 0);
2014 if (S_ISREG (out_st.st_mode))
2015 oldsize = out_st.st_size;
2018 immediate_quit = 1;
2019 QUIT;
2021 if (clone_file (ofd, ifd))
2022 newsize = st.st_size;
2023 else
2025 char buf[MAX_ALLOCA];
2026 ptrdiff_t n;
2027 for (newsize = 0; 0 < (n = emacs_read (ifd, buf, sizeof buf));
2028 newsize += n)
2029 if (emacs_write_sig (ofd, buf, n) != n)
2030 report_file_error ("Write error", newname);
2031 if (n < 0)
2032 report_file_error ("Read error", file);
2035 /* Truncate any existing output file after writing the data. This
2036 is more likely to work than truncation before writing, if the
2037 file system is out of space or the user is over disk quota. */
2038 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2039 report_file_error ("Truncating output file", newname);
2041 immediate_quit = 0;
2043 #ifndef MSDOS
2044 /* Preserve the original file permissions, and if requested, also its
2045 owner and group. */
2047 mode_t preserved_permissions = st.st_mode & 07777;
2048 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2049 if (!NILP (preserve_uid_gid))
2051 /* Attempt to change owner and group. If that doesn't work
2052 attempt to change just the group, as that is sometimes allowed.
2053 Adjust the mode mask to eliminate setuid or setgid bits
2054 or group permissions bits that are inappropriate if the
2055 owner or group are wrong. */
2056 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2058 if (fchown (ofd, -1, st.st_gid) == 0)
2059 preserved_permissions &= ~04000;
2060 else
2062 preserved_permissions &= ~06000;
2064 /* Copy the other bits to the group bits, since the
2065 group is wrong. */
2066 preserved_permissions &= ~070;
2067 preserved_permissions |= (preserved_permissions & 7) << 3;
2068 default_permissions &= ~070;
2069 default_permissions |= (default_permissions & 7) << 3;
2074 switch (!NILP (preserve_permissions)
2075 ? qcopy_acl (SSDATA (encoded_file), ifd,
2076 SSDATA (encoded_newname), ofd,
2077 preserved_permissions)
2078 : (already_exists
2079 || (new_mask & ~realmask) == default_permissions)
2081 : fchmod (ofd, default_permissions))
2083 case -2: report_file_error ("Copying permissions from", file);
2084 case -1: report_file_error ("Copying permissions to", newname);
2087 #endif /* not MSDOS */
2089 #if HAVE_LIBSELINUX
2090 if (conlength > 0)
2092 /* Set the modified context back to the file. */
2093 bool fail = fsetfilecon (ofd, con) != 0;
2094 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2095 if (fail && errno != ENOTSUP)
2096 report_file_error ("Doing fsetfilecon", newname);
2098 freecon (con);
2100 #endif
2102 if (!NILP (keep_time))
2104 struct timespec atime = get_stat_atime (&st);
2105 struct timespec mtime = get_stat_mtime (&st);
2106 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2107 xsignal2 (Qfile_date_error,
2108 build_string ("Cannot set file date"), newname);
2111 if (emacs_close (ofd) < 0)
2112 report_file_error ("Write error", newname);
2114 emacs_close (ifd);
2116 #ifdef MSDOS
2117 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2118 and if it can't, it tells so. Otherwise, under MSDOS we usually
2119 get only the READ bit, which will make the copied file read-only,
2120 so it's better not to chmod at all. */
2121 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2122 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2123 #endif /* MSDOS */
2124 #endif /* not WINDOWSNT */
2126 /* Discard the unwind protects. */
2127 specpdl_ptr = specpdl + count;
2129 return Qnil;
2132 DEFUN ("make-directory-internal", Fmake_directory_internal,
2133 Smake_directory_internal, 1, 1, 0,
2134 doc: /* Create a new directory named DIRECTORY. */)
2135 (Lisp_Object directory)
2137 const char *dir;
2138 Lisp_Object handler;
2139 Lisp_Object encoded_dir;
2141 CHECK_STRING (directory);
2142 directory = Fexpand_file_name (directory, Qnil);
2144 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2145 if (!NILP (handler))
2146 return call2 (handler, Qmake_directory_internal, directory);
2148 encoded_dir = ENCODE_FILE (directory);
2150 dir = SSDATA (encoded_dir);
2152 #ifdef WINDOWSNT
2153 if (mkdir (dir) != 0)
2154 #else
2155 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2156 #endif
2157 report_file_error ("Creating directory", directory);
2159 return Qnil;
2162 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2163 Sdelete_directory_internal, 1, 1, 0,
2164 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2165 (Lisp_Object directory)
2167 const char *dir;
2168 Lisp_Object encoded_dir;
2170 CHECK_STRING (directory);
2171 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2172 encoded_dir = ENCODE_FILE (directory);
2173 dir = SSDATA (encoded_dir);
2175 if (rmdir (dir) != 0)
2176 report_file_error ("Removing directory", directory);
2178 return Qnil;
2181 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2182 "(list (read-file-name \
2183 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2184 \"Move file to trash: \" \"Delete file: \") \
2185 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2186 (null current-prefix-arg))",
2187 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2188 If file has multiple names, it continues to exist with the other names.
2189 TRASH non-nil means to trash the file instead of deleting, provided
2190 `delete-by-moving-to-trash' is non-nil.
2192 When called interactively, TRASH is t if no prefix argument is given.
2193 With a prefix argument, TRASH is nil. */)
2194 (Lisp_Object filename, Lisp_Object trash)
2196 Lisp_Object handler;
2197 Lisp_Object encoded_file;
2199 if (!NILP (Ffile_directory_p (filename))
2200 && NILP (Ffile_symlink_p (filename)))
2201 xsignal2 (Qfile_error,
2202 build_string ("Removing old name: is a directory"),
2203 filename);
2204 filename = Fexpand_file_name (filename, Qnil);
2206 handler = Ffind_file_name_handler (filename, Qdelete_file);
2207 if (!NILP (handler))
2208 return call3 (handler, Qdelete_file, filename, trash);
2210 if (delete_by_moving_to_trash && !NILP (trash))
2211 return call1 (Qmove_file_to_trash, filename);
2213 encoded_file = ENCODE_FILE (filename);
2215 if (unlink (SSDATA (encoded_file)) < 0)
2216 report_file_error ("Removing old name", filename);
2217 return Qnil;
2220 static Lisp_Object
2221 internal_delete_file_1 (Lisp_Object ignore)
2223 return Qt;
2226 /* Delete file FILENAME, returning true if successful.
2227 This ignores `delete-by-moving-to-trash'. */
2229 bool
2230 internal_delete_file (Lisp_Object filename)
2232 Lisp_Object tem;
2234 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2235 Qt, internal_delete_file_1);
2236 return NILP (tem);
2239 /* Filesystems are case-sensitive on all supported systems except
2240 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2241 case-insensitive on the first two, but they may or may not be
2242 case-insensitive on Cygwin and OS X. The following function
2243 attempts to provide a runtime test on those two systems. If the
2244 test is not conclusive, we assume case-insensitivity on Cygwin and
2245 case-sensitivity on Mac OS X.
2247 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2248 NFS-mounted Windows volumes, might be case-insensitive. Can we
2249 detect this? */
2251 static bool
2252 file_name_case_insensitive_p (const char *filename)
2254 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2255 those flags are available. As of this writing (2016-11-14),
2256 Cygwin is the only platform known to support the former (starting
2257 with Cygwin-2.6.1), and Mac OS X is the only platform known to
2258 support the latter.
2260 There have been reports that pathconf with _PC_CASE_SENSITIVE
2261 does not work reliably on Mac OS X. If you have a problem,
2262 please recompile Emacs with -D DARWIN_OS_CASE_SENSITIVE_FIXME=1 or
2263 -D DARWIN_OS_CASE_SENSITIVE_FIXME=2, and file a bug report saying
2264 whether this fixed your problem. */
2266 #ifdef _PC_CASE_INSENSITIVE
2267 int res = pathconf (filename, _PC_CASE_INSENSITIVE);
2268 if (res >= 0)
2269 return res > 0;
2270 #elif defined _PC_CASE_SENSITIVE && !defined DARWIN_OS_CASE_SENSITIVE_FIXME
2271 int res = pathconf (filename, _PC_CASE_SENSITIVE);
2272 if (res >= 0)
2273 return res == 0;
2274 #endif
2276 #ifdef DARWIN_OS
2277 # ifndef DARWIN_OS_CASE_SENSITIVE_FIXME
2278 int DARWIN_OS_CASE_SENSITIVE_FIXME = 0;
2279 # endif
2281 if (DARWIN_OS_CASE_SENSITIVE_FIXME == 1)
2283 /* This is based on developer.apple.com's getattrlist man page. */
2284 struct attrlist alist = {.volattr = ATTR_VOL_CAPABILITIES};
2285 vol_capabilities_attr_t vcaps;
2286 if (getattrlist (filename, &alist, &vcaps, sizeof vcaps, 0) == 0)
2288 if (vcaps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE)
2289 return ! (vcaps.capabilities[VOL_CAPABILITIES_FORMAT]
2290 & VOL_CAP_FMT_CASE_SENSITIVE);
2293 else if (DARWIN_OS_CASE_SENSITIVE_FIXME == 2)
2295 /* The following is based on
2296 http://lists.apple.com/archives/darwin-dev/2007/Apr/msg00010.html. */
2297 struct attrlist alist;
2298 unsigned char buffer[sizeof (vol_capabilities_attr_t) + sizeof (size_t)];
2300 memset (&alist, 0, sizeof (alist));
2301 alist.volattr = ATTR_VOL_CAPABILITIES;
2302 if (getattrlist (filename, &alist, buffer, sizeof (buffer), 0)
2303 || !(alist.volattr & ATTR_VOL_CAPABILITIES))
2304 return 0;
2305 vol_capabilities_attr_t *vcaps = buffer;
2306 return !(vcaps->capabilities[0] & VOL_CAP_FMT_CASE_SENSITIVE);
2308 #endif /* DARWIN_OS */
2310 #if defined CYGWIN || defined DOS_NT
2311 return true;
2312 #else
2313 return false;
2314 #endif
2317 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p,
2318 Sfile_name_case_insensitive_p, 1, 1, 0,
2319 doc: /* Return t if file FILENAME is on a case-insensitive filesystem.
2320 The arg must be a string. */)
2321 (Lisp_Object filename)
2323 Lisp_Object handler;
2325 CHECK_STRING (filename);
2326 filename = Fexpand_file_name (filename, Qnil);
2328 /* If the file name has special constructs in it,
2329 call the corresponding file handler. */
2330 handler = Ffind_file_name_handler (filename, Qfile_name_case_insensitive_p);
2331 if (!NILP (handler))
2332 return call2 (handler, Qfile_name_case_insensitive_p, filename);
2334 filename = ENCODE_FILE (filename);
2335 return file_name_case_insensitive_p (SSDATA (filename)) ? Qt : Qnil;
2338 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2339 "fRename file: \nGRename %s to file: \np",
2340 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2341 If file has names other than FILE, it continues to have those names.
2342 Signals a `file-already-exists' error if a file NEWNAME already exists
2343 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2344 A number as third arg means request confirmation if NEWNAME already exists.
2345 This is what happens in interactive use with M-x. */)
2346 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2348 Lisp_Object handler;
2349 Lisp_Object encoded_file, encoded_newname, symlink_target;
2351 symlink_target = encoded_file = encoded_newname = Qnil;
2352 CHECK_STRING (file);
2353 CHECK_STRING (newname);
2354 file = Fexpand_file_name (file, Qnil);
2356 if ((!NILP (Ffile_directory_p (newname)))
2357 /* If the filesystem is case-insensitive and the file names are
2358 identical but for the case, don't attempt to move directory
2359 to itself. */
2360 && (NILP (Ffile_name_case_insensitive_p (file))
2361 || NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname)))))
2363 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2364 ? file : Fdirectory_file_name (file));
2365 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2367 else
2368 newname = Fexpand_file_name (newname, Qnil);
2370 /* If the file name has special constructs in it,
2371 call the corresponding file handler. */
2372 handler = Ffind_file_name_handler (file, Qrename_file);
2373 if (NILP (handler))
2374 handler = Ffind_file_name_handler (newname, Qrename_file);
2375 if (!NILP (handler))
2376 return call4 (handler, Qrename_file,
2377 file, newname, ok_if_already_exists);
2379 encoded_file = ENCODE_FILE (file);
2380 encoded_newname = ENCODE_FILE (newname);
2382 /* If the filesystem is case-insensitive and the file names are
2383 identical but for the case, don't ask for confirmation: they
2384 simply want to change the letter-case of the file name. */
2385 if ((!(file_name_case_insensitive_p (SSDATA (encoded_file)))
2386 || NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2387 && ((NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))))
2388 barf_or_query_if_file_exists (newname, false, "rename to it",
2389 INTEGERP (ok_if_already_exists), false);
2390 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2392 int rename_errno = errno;
2393 if (rename_errno == EXDEV)
2395 ptrdiff_t count;
2396 symlink_target = Ffile_symlink_p (file);
2397 if (! NILP (symlink_target))
2398 Fmake_symbolic_link (symlink_target, newname,
2399 NILP (ok_if_already_exists) ? Qnil : Qt);
2400 else if (!NILP (Ffile_directory_p (file)))
2401 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2402 else
2403 /* We have already prompted if it was an integer, so don't
2404 have copy-file prompt again. */
2405 Fcopy_file (file, newname,
2406 NILP (ok_if_already_exists) ? Qnil : Qt,
2407 Qt, Qt, Qt);
2409 count = SPECPDL_INDEX ();
2410 specbind (Qdelete_by_moving_to_trash, Qnil);
2412 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2413 call2 (Qdelete_directory, file, Qt);
2414 else
2415 Fdelete_file (file, Qnil);
2416 unbind_to (count, Qnil);
2418 else
2419 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2422 return Qnil;
2425 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2426 "fAdd name to file: \nGName to add to %s: \np",
2427 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2428 Signals a `file-already-exists' error if a file NEWNAME already exists
2429 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2430 A number as third arg means request confirmation if NEWNAME already exists.
2431 This is what happens in interactive use with M-x. */)
2432 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2434 Lisp_Object handler;
2435 Lisp_Object encoded_file, encoded_newname;
2437 encoded_file = encoded_newname = Qnil;
2438 CHECK_STRING (file);
2439 CHECK_STRING (newname);
2440 file = Fexpand_file_name (file, Qnil);
2442 if (!NILP (Ffile_directory_p (newname)))
2443 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2444 else
2445 newname = Fexpand_file_name (newname, Qnil);
2447 /* If the file name has special constructs in it,
2448 call the corresponding file handler. */
2449 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2450 if (!NILP (handler))
2451 return call4 (handler, Qadd_name_to_file, file,
2452 newname, ok_if_already_exists);
2454 /* If the new name has special constructs in it,
2455 call the corresponding file handler. */
2456 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2457 if (!NILP (handler))
2458 return call4 (handler, Qadd_name_to_file, file,
2459 newname, ok_if_already_exists);
2461 encoded_file = ENCODE_FILE (file);
2462 encoded_newname = ENCODE_FILE (newname);
2464 if (NILP (ok_if_already_exists)
2465 || INTEGERP (ok_if_already_exists))
2466 barf_or_query_if_file_exists (newname, false, "make it a new name",
2467 INTEGERP (ok_if_already_exists), false);
2469 unlink (SSDATA (newname));
2470 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2472 int link_errno = errno;
2473 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2476 return Qnil;
2479 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2480 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2481 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2482 Both args must be strings.
2483 Signals a `file-already-exists' error if a file LINKNAME already exists
2484 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2485 A number as third arg means request confirmation if LINKNAME already exists.
2486 This happens for interactive use with M-x. */)
2487 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2489 Lisp_Object handler;
2490 Lisp_Object encoded_target, encoded_linkname;
2492 encoded_target = encoded_linkname = Qnil;
2493 CHECK_STRING (target);
2494 CHECK_STRING (linkname);
2495 /* If the link target has a ~, we must expand it to get
2496 a truly valid file name. Otherwise, do not expand;
2497 we want to permit links to relative file names. */
2498 if (SREF (target, 0) == '~')
2499 target = Fexpand_file_name (target, Qnil);
2501 if (!NILP (Ffile_directory_p (linkname)))
2502 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2503 else
2504 linkname = Fexpand_file_name (linkname, Qnil);
2506 /* If the file name has special constructs in it,
2507 call the corresponding file handler. */
2508 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2509 if (!NILP (handler))
2510 return call4 (handler, Qmake_symbolic_link, target,
2511 linkname, ok_if_already_exists);
2513 /* If the new link name has special constructs in it,
2514 call the corresponding file handler. */
2515 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2516 if (!NILP (handler))
2517 return call4 (handler, Qmake_symbolic_link, target,
2518 linkname, ok_if_already_exists);
2520 encoded_target = ENCODE_FILE (target);
2521 encoded_linkname = ENCODE_FILE (linkname);
2523 if (NILP (ok_if_already_exists)
2524 || INTEGERP (ok_if_already_exists))
2525 barf_or_query_if_file_exists (linkname, false, "make it a link",
2526 INTEGERP (ok_if_already_exists), false);
2527 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2529 /* If we didn't complain already, silently delete existing file. */
2530 int symlink_errno;
2531 if (errno == EEXIST)
2533 unlink (SSDATA (encoded_linkname));
2534 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2535 >= 0)
2536 return Qnil;
2538 if (errno == ENOSYS)
2539 xsignal1 (Qfile_error,
2540 build_string ("Symbolic links are not supported"));
2542 symlink_errno = errno;
2543 report_file_errno ("Making symbolic link", list2 (target, linkname),
2544 symlink_errno);
2547 return Qnil;
2551 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2552 1, 1, 0,
2553 doc: /* Return t if file FILENAME specifies an absolute file name.
2554 On Unix, this is a name starting with a `/' or a `~'. */)
2555 (Lisp_Object filename)
2557 CHECK_STRING (filename);
2558 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2561 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2562 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2563 See also `file-readable-p' and `file-attributes'.
2564 This returns nil for a symlink to a nonexistent file.
2565 Use `file-symlink-p' to test for such links. */)
2566 (Lisp_Object filename)
2568 Lisp_Object absname;
2569 Lisp_Object handler;
2571 CHECK_STRING (filename);
2572 absname = Fexpand_file_name (filename, Qnil);
2574 /* If the file name has special constructs in it,
2575 call the corresponding file handler. */
2576 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2577 if (!NILP (handler))
2579 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2580 errno = 0;
2581 return result;
2584 absname = ENCODE_FILE (absname);
2586 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2589 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2590 doc: /* Return t if FILENAME can be executed by you.
2591 For a directory, this means you can access files in that directory.
2592 \(It is generally better to use `file-accessible-directory-p' for that
2593 purpose, though.) */)
2594 (Lisp_Object filename)
2596 Lisp_Object absname;
2597 Lisp_Object handler;
2599 CHECK_STRING (filename);
2600 absname = Fexpand_file_name (filename, Qnil);
2602 /* If the file name has special constructs in it,
2603 call the corresponding file handler. */
2604 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2605 if (!NILP (handler))
2606 return call2 (handler, Qfile_executable_p, absname);
2608 absname = ENCODE_FILE (absname);
2610 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2613 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2614 doc: /* Return t if file FILENAME exists and you can read it.
2615 See also `file-exists-p' and `file-attributes'. */)
2616 (Lisp_Object filename)
2618 Lisp_Object absname;
2619 Lisp_Object handler;
2621 CHECK_STRING (filename);
2622 absname = Fexpand_file_name (filename, Qnil);
2624 /* If the file name has special constructs in it,
2625 call the corresponding file handler. */
2626 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2627 if (!NILP (handler))
2628 return call2 (handler, Qfile_readable_p, absname);
2630 absname = ENCODE_FILE (absname);
2631 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2632 ? Qt : Qnil);
2635 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2636 doc: /* Return t if file FILENAME can be written or created by you. */)
2637 (Lisp_Object filename)
2639 Lisp_Object absname, dir, encoded;
2640 Lisp_Object handler;
2642 CHECK_STRING (filename);
2643 absname = Fexpand_file_name (filename, Qnil);
2645 /* If the file name has special constructs in it,
2646 call the corresponding file handler. */
2647 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2648 if (!NILP (handler))
2649 return call2 (handler, Qfile_writable_p, absname);
2651 encoded = ENCODE_FILE (absname);
2652 if (check_writable (SSDATA (encoded), W_OK))
2653 return Qt;
2654 if (errno != ENOENT)
2655 return Qnil;
2657 dir = Ffile_name_directory (absname);
2658 eassert (!NILP (dir));
2659 #ifdef MSDOS
2660 dir = Fdirectory_file_name (dir);
2661 #endif /* MSDOS */
2663 dir = ENCODE_FILE (dir);
2664 #ifdef WINDOWSNT
2665 /* The read-only attribute of the parent directory doesn't affect
2666 whether a file or directory can be created within it. Some day we
2667 should check ACLs though, which do affect this. */
2668 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2669 #else
2670 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2671 #endif
2674 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2675 doc: /* Access file FILENAME, and get an error if that does not work.
2676 The second argument STRING is used in the error message.
2677 If there is no error, returns nil. */)
2678 (Lisp_Object filename, Lisp_Object string)
2680 Lisp_Object handler, encoded_filename, absname;
2682 CHECK_STRING (filename);
2683 absname = Fexpand_file_name (filename, Qnil);
2685 CHECK_STRING (string);
2687 /* If the file name has special constructs in it,
2688 call the corresponding file handler. */
2689 handler = Ffind_file_name_handler (absname, Qaccess_file);
2690 if (!NILP (handler))
2691 return call3 (handler, Qaccess_file, absname, string);
2693 encoded_filename = ENCODE_FILE (absname);
2695 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2696 report_file_error (SSDATA (string), filename);
2698 return Qnil;
2701 /* Relative to directory FD, return the symbolic link value of FILENAME.
2702 On failure, return nil. */
2703 Lisp_Object
2704 emacs_readlinkat (int fd, char const *filename)
2706 static struct allocator const emacs_norealloc_allocator =
2707 { xmalloc, NULL, xfree, memory_full };
2708 Lisp_Object val;
2709 char readlink_buf[1024];
2710 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2711 &emacs_norealloc_allocator, readlinkat);
2712 if (!buf)
2713 return Qnil;
2715 val = build_unibyte_string (buf);
2716 if (buf[0] == '/' && strchr (buf, ':'))
2718 AUTO_STRING (slash_colon, "/:");
2719 val = concat2 (slash_colon, val);
2721 if (buf != readlink_buf)
2722 xfree (buf);
2723 val = DECODE_FILE (val);
2724 return val;
2727 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2728 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2729 The value is the link target, as a string.
2730 Otherwise it returns nil.
2732 This function does not check whether the link target exists. */)
2733 (Lisp_Object filename)
2735 Lisp_Object handler;
2737 CHECK_STRING (filename);
2738 filename = Fexpand_file_name (filename, Qnil);
2740 /* If the file name has special constructs in it,
2741 call the corresponding file handler. */
2742 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2743 if (!NILP (handler))
2744 return call2 (handler, Qfile_symlink_p, filename);
2746 filename = ENCODE_FILE (filename);
2748 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2751 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2752 doc: /* Return t if FILENAME names an existing directory.
2753 Symbolic links to directories count as directories.
2754 See `file-symlink-p' to distinguish symlinks. */)
2755 (Lisp_Object filename)
2757 Lisp_Object absname;
2758 Lisp_Object handler;
2760 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2762 /* If the file name has special constructs in it,
2763 call the corresponding file handler. */
2764 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2765 if (!NILP (handler))
2766 return call2 (handler, Qfile_directory_p, absname);
2768 absname = ENCODE_FILE (absname);
2770 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2773 /* Return true if FILE is a directory or a symlink to a directory. */
2774 bool
2775 file_directory_p (char const *file)
2777 #ifdef WINDOWSNT
2778 /* This is cheaper than 'stat'. */
2779 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2780 #else
2781 struct stat st;
2782 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2783 #endif
2786 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2787 Sfile_accessible_directory_p, 1, 1, 0,
2788 doc: /* Return t if FILENAME names a directory you can open.
2789 For the value to be t, FILENAME must specify the name of a directory
2790 as a file, and the directory must allow you to open files in it. In
2791 order to use a directory as a buffer's current directory, this
2792 predicate must return true. A directory name spec may be given
2793 instead; then the value is t if the directory so specified exists and
2794 really is a readable and searchable directory. */)
2795 (Lisp_Object filename)
2797 Lisp_Object absname;
2798 Lisp_Object handler;
2800 CHECK_STRING (filename);
2801 absname = Fexpand_file_name (filename, Qnil);
2803 /* If the file name has special constructs in it,
2804 call the corresponding file handler. */
2805 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2806 if (!NILP (handler))
2808 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2809 errno = 0;
2810 return r;
2813 absname = ENCODE_FILE (absname);
2814 return file_accessible_directory_p (absname) ? Qt : Qnil;
2817 /* If FILE is a searchable directory or a symlink to a
2818 searchable directory, return true. Otherwise return
2819 false and set errno to an error number. */
2820 bool
2821 file_accessible_directory_p (Lisp_Object file)
2823 #ifdef DOS_NT
2824 # ifdef WINDOWSNT
2825 /* We need a special-purpose test because (a) NTFS security data is
2826 not reflected in Posix-style mode bits, and (b) the trick with
2827 accessing "DIR/.", used below on Posix hosts, doesn't work on
2828 Windows, because "DIR/." is normalized to just "DIR" before
2829 hitting the disk. */
2830 return (SBYTES (file) == 0
2831 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2832 # else /* MSDOS */
2833 return file_directory_p (SSDATA (file));
2834 # endif /* MSDOS */
2835 #else /* !DOS_NT */
2836 /* On POSIXish platforms, use just one system call; this avoids a
2837 race and is typically faster. */
2838 const char *data = SSDATA (file);
2839 ptrdiff_t len = SBYTES (file);
2840 char const *dir;
2841 bool ok;
2842 int saved_errno;
2843 USE_SAFE_ALLOCA;
2845 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2846 There are three exceptions: "", "/", and "//". Leave "" alone,
2847 as it's invalid. Append only "." to the other two exceptions as
2848 "/" and "//" are distinct on some platforms, whereas "/", "///",
2849 "////", etc. are all equivalent. */
2850 if (! len)
2851 dir = data;
2852 else
2854 /* Just check for trailing '/' when deciding whether to append '/'.
2855 That's simpler than testing the two special cases "/" and "//",
2856 and it's a safe optimization here. */
2857 char *buf = SAFE_ALLOCA (len + 3);
2858 memcpy (buf, data, len);
2859 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2860 dir = buf;
2863 ok = check_existing (dir);
2864 saved_errno = errno;
2865 SAFE_FREE ();
2866 errno = saved_errno;
2867 return ok;
2868 #endif /* !DOS_NT */
2871 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2872 doc: /* Return t if FILENAME names a regular file.
2873 This is the sort of file that holds an ordinary stream of data bytes.
2874 Symbolic links to regular files count as regular files.
2875 See `file-symlink-p' to distinguish symlinks. */)
2876 (Lisp_Object filename)
2878 register Lisp_Object absname;
2879 struct stat st;
2880 Lisp_Object handler;
2882 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2884 /* If the file name has special constructs in it,
2885 call the corresponding file handler. */
2886 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2887 if (!NILP (handler))
2888 return call2 (handler, Qfile_regular_p, absname);
2890 absname = ENCODE_FILE (absname);
2892 #ifdef WINDOWSNT
2894 int result;
2895 Lisp_Object tem = Vw32_get_true_file_attributes;
2897 /* Tell stat to use expensive method to get accurate info. */
2898 Vw32_get_true_file_attributes = Qt;
2899 result = stat (SSDATA (absname), &st);
2900 Vw32_get_true_file_attributes = tem;
2902 if (result < 0)
2903 return Qnil;
2904 return S_ISREG (st.st_mode) ? Qt : Qnil;
2906 #else
2907 if (stat (SSDATA (absname), &st) < 0)
2908 return Qnil;
2909 return S_ISREG (st.st_mode) ? Qt : Qnil;
2910 #endif
2913 DEFUN ("file-selinux-context", Ffile_selinux_context,
2914 Sfile_selinux_context, 1, 1, 0,
2915 doc: /* Return SELinux context of file named FILENAME.
2916 The return value is a list (USER ROLE TYPE RANGE), where the list
2917 elements are strings naming the user, role, type, and range of the
2918 file's SELinux security context.
2920 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2921 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2922 (Lisp_Object filename)
2924 Lisp_Object absname;
2925 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2927 Lisp_Object handler;
2928 #if HAVE_LIBSELINUX
2929 security_context_t con;
2930 int conlength;
2931 context_t context;
2932 #endif
2934 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2936 /* If the file name has special constructs in it,
2937 call the corresponding file handler. */
2938 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2939 if (!NILP (handler))
2940 return call2 (handler, Qfile_selinux_context, absname);
2942 absname = ENCODE_FILE (absname);
2944 #if HAVE_LIBSELINUX
2945 if (is_selinux_enabled ())
2947 conlength = lgetfilecon (SSDATA (absname), &con);
2948 if (conlength > 0)
2950 context = context_new (con);
2951 if (context_user_get (context))
2952 user = build_string (context_user_get (context));
2953 if (context_role_get (context))
2954 role = build_string (context_role_get (context));
2955 if (context_type_get (context))
2956 type = build_string (context_type_get (context));
2957 if (context_range_get (context))
2958 range = build_string (context_range_get (context));
2959 context_free (context);
2960 freecon (con);
2963 #endif
2965 return list4 (user, role, type, range);
2968 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2969 Sset_file_selinux_context, 2, 2, 0,
2970 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2971 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2972 elements are strings naming the components of a SELinux context.
2974 Value is t if setting of SELinux context was successful, nil otherwise.
2976 This function does nothing and returns nil if SELinux is disabled,
2977 or if Emacs was not compiled with SELinux support. */)
2978 (Lisp_Object filename, Lisp_Object context)
2980 Lisp_Object absname;
2981 Lisp_Object handler;
2982 #if HAVE_LIBSELINUX
2983 Lisp_Object encoded_absname;
2984 Lisp_Object user = CAR_SAFE (context);
2985 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2986 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2987 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2988 security_context_t con;
2989 bool fail;
2990 int conlength;
2991 context_t parsed_con;
2992 #endif
2994 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2996 /* If the file name has special constructs in it,
2997 call the corresponding file handler. */
2998 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2999 if (!NILP (handler))
3000 return call3 (handler, Qset_file_selinux_context, absname, context);
3002 #if HAVE_LIBSELINUX
3003 if (is_selinux_enabled ())
3005 /* Get current file context. */
3006 encoded_absname = ENCODE_FILE (absname);
3007 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
3008 if (conlength > 0)
3010 parsed_con = context_new (con);
3011 /* Change the parts defined in the parameter.*/
3012 if (STRINGP (user))
3014 if (context_user_set (parsed_con, SSDATA (user)))
3015 error ("Doing context_user_set");
3017 if (STRINGP (role))
3019 if (context_role_set (parsed_con, SSDATA (role)))
3020 error ("Doing context_role_set");
3022 if (STRINGP (type))
3024 if (context_type_set (parsed_con, SSDATA (type)))
3025 error ("Doing context_type_set");
3027 if (STRINGP (range))
3029 if (context_range_set (parsed_con, SSDATA (range)))
3030 error ("Doing context_range_set");
3033 /* Set the modified context back to the file. */
3034 fail = (lsetfilecon (SSDATA (encoded_absname),
3035 context_str (parsed_con))
3036 != 0);
3037 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
3038 if (fail && errno != ENOTSUP)
3039 report_file_error ("Doing lsetfilecon", absname);
3041 context_free (parsed_con);
3042 freecon (con);
3043 return fail ? Qnil : Qt;
3045 else
3046 report_file_error ("Doing lgetfilecon", absname);
3048 #endif
3050 return Qnil;
3053 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
3054 doc: /* Return ACL entries of file named FILENAME.
3055 The entries are returned in a format suitable for use in `set-file-acl'
3056 but is otherwise undocumented and subject to change.
3057 Return nil if file does not exist or is not accessible, or if Emacs
3058 was unable to determine the ACL entries. */)
3059 (Lisp_Object filename)
3061 #if USE_ACL
3062 Lisp_Object absname;
3063 Lisp_Object handler;
3064 # ifdef HAVE_ACL_SET_FILE
3065 acl_t acl;
3066 Lisp_Object acl_string;
3067 char *str;
3068 # ifndef HAVE_ACL_TYPE_EXTENDED
3069 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
3070 # endif
3071 # endif
3073 absname = expand_and_dir_to_file (filename,
3074 BVAR (current_buffer, directory));
3076 /* If the file name has special constructs in it,
3077 call the corresponding file handler. */
3078 handler = Ffind_file_name_handler (absname, Qfile_acl);
3079 if (!NILP (handler))
3080 return call2 (handler, Qfile_acl, absname);
3082 # ifdef HAVE_ACL_SET_FILE
3083 absname = ENCODE_FILE (absname);
3085 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
3086 if (acl == NULL)
3087 return Qnil;
3089 str = acl_to_text (acl, NULL);
3090 if (str == NULL)
3092 acl_free (acl);
3093 return Qnil;
3096 acl_string = build_string (str);
3097 acl_free (str);
3098 acl_free (acl);
3100 return acl_string;
3101 # endif
3102 #endif
3104 return Qnil;
3107 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3108 2, 2, 0,
3109 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3110 ACL-STRING should contain the textual representation of the ACL
3111 entries in a format suitable for the platform.
3113 Value is t if setting of ACL was successful, nil otherwise.
3115 Setting ACL for local files requires Emacs to be built with ACL
3116 support. */)
3117 (Lisp_Object filename, Lisp_Object acl_string)
3119 #if USE_ACL
3120 Lisp_Object absname;
3121 Lisp_Object handler;
3122 # ifdef HAVE_ACL_SET_FILE
3123 Lisp_Object encoded_absname;
3124 acl_t acl;
3125 bool fail;
3126 # endif
3128 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3130 /* If the file name has special constructs in it,
3131 call the corresponding file handler. */
3132 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3133 if (!NILP (handler))
3134 return call3 (handler, Qset_file_acl, absname, acl_string);
3136 # ifdef HAVE_ACL_SET_FILE
3137 if (STRINGP (acl_string))
3139 acl = acl_from_text (SSDATA (acl_string));
3140 if (acl == NULL)
3142 report_file_error ("Converting ACL", absname);
3143 return Qnil;
3146 encoded_absname = ENCODE_FILE (absname);
3148 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3149 acl)
3150 != 0);
3151 if (fail && acl_errno_valid (errno))
3152 report_file_error ("Setting ACL", absname);
3154 acl_free (acl);
3155 return fail ? Qnil : Qt;
3157 # endif
3158 #endif
3160 return Qnil;
3163 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3164 doc: /* Return mode bits of file named FILENAME, as an integer.
3165 Return nil, if file does not exist or is not accessible. */)
3166 (Lisp_Object filename)
3168 Lisp_Object absname;
3169 struct stat st;
3170 Lisp_Object handler;
3172 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3174 /* If the file name has special constructs in it,
3175 call the corresponding file handler. */
3176 handler = Ffind_file_name_handler (absname, Qfile_modes);
3177 if (!NILP (handler))
3178 return call2 (handler, Qfile_modes, absname);
3180 absname = ENCODE_FILE (absname);
3182 if (stat (SSDATA (absname), &st) < 0)
3183 return Qnil;
3185 return make_number (st.st_mode & 07777);
3188 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3189 "(let ((file (read-file-name \"File: \"))) \
3190 (list file (read-file-modes nil file)))",
3191 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3192 Only the 12 low bits of MODE are used.
3194 Interactively, mode bits are read by `read-file-modes', which accepts
3195 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3196 (Lisp_Object filename, Lisp_Object mode)
3198 Lisp_Object absname, encoded_absname;
3199 Lisp_Object handler;
3201 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3202 CHECK_NUMBER (mode);
3204 /* If the file name has special constructs in it,
3205 call the corresponding file handler. */
3206 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3207 if (!NILP (handler))
3208 return call3 (handler, Qset_file_modes, absname, mode);
3210 encoded_absname = ENCODE_FILE (absname);
3212 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3213 report_file_error ("Doing chmod", absname);
3215 return Qnil;
3218 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3219 doc: /* Set the file permission bits for newly created files.
3220 The argument MODE should be an integer; only the low 9 bits are used.
3221 This setting is inherited by subprocesses. */)
3222 (Lisp_Object mode)
3224 mode_t oldrealmask, oldumask, newumask;
3225 CHECK_NUMBER (mode);
3226 oldrealmask = realmask;
3227 newumask = ~ XINT (mode) & 0777;
3229 block_input ();
3230 realmask = newumask;
3231 oldumask = umask (newumask);
3232 unblock_input ();
3234 eassert (oldumask == oldrealmask);
3235 return Qnil;
3238 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3239 doc: /* Return the default file protection for created files.
3240 The value is an integer. */)
3241 (void)
3243 Lisp_Object value;
3244 XSETINT (value, (~ realmask) & 0777);
3245 return value;
3249 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3250 doc: /* Set times of file FILENAME to TIMESTAMP.
3251 Set both access and modification times.
3252 Return t on success, else nil.
3253 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3254 `current-time'. */)
3255 (Lisp_Object filename, Lisp_Object timestamp)
3257 Lisp_Object absname, encoded_absname;
3258 Lisp_Object handler;
3259 struct timespec t = lisp_time_argument (timestamp);
3261 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3263 /* If the file name has special constructs in it,
3264 call the corresponding file handler. */
3265 handler = Ffind_file_name_handler (absname, Qset_file_times);
3266 if (!NILP (handler))
3267 return call3 (handler, Qset_file_times, absname, timestamp);
3269 encoded_absname = ENCODE_FILE (absname);
3272 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3274 #ifdef MSDOS
3275 /* Setting times on a directory always fails. */
3276 if (file_directory_p (SSDATA (encoded_absname)))
3277 return Qnil;
3278 #endif
3279 report_file_error ("Setting file times", absname);
3283 return Qt;
3286 #ifdef HAVE_SYNC
3287 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3288 doc: /* Tell Unix to finish all pending disk updates. */)
3289 (void)
3291 sync ();
3292 return Qnil;
3295 #endif /* HAVE_SYNC */
3297 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3298 doc: /* Return t if file FILE1 is newer than file FILE2.
3299 If FILE1 does not exist, the answer is nil;
3300 otherwise, if FILE2 does not exist, the answer is t. */)
3301 (Lisp_Object file1, Lisp_Object file2)
3303 Lisp_Object absname1, absname2;
3304 struct stat st1, st2;
3305 Lisp_Object handler;
3307 CHECK_STRING (file1);
3308 CHECK_STRING (file2);
3310 absname1 = Qnil;
3311 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3312 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3314 /* If the file name has special constructs in it,
3315 call the corresponding file handler. */
3316 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3317 if (NILP (handler))
3318 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3319 if (!NILP (handler))
3320 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3322 absname1 = ENCODE_FILE (absname1);
3323 absname2 = ENCODE_FILE (absname2);
3325 if (stat (SSDATA (absname1), &st1) < 0)
3326 return Qnil;
3328 if (stat (SSDATA (absname2), &st2) < 0)
3329 return Qt;
3331 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3332 ? Qt : Qnil);
3335 #ifndef READ_BUF_SIZE
3336 #define READ_BUF_SIZE (64 << 10)
3337 #endif
3338 /* Some buffer offsets are stored in 'int' variables. */
3339 verify (READ_BUF_SIZE <= INT_MAX);
3341 /* This function is called after Lisp functions to decide a coding
3342 system are called, or when they cause an error. Before they are
3343 called, the current buffer is set unibyte and it contains only a
3344 newly inserted text (thus the buffer was empty before the
3345 insertion).
3347 The functions may set markers, overlays, text properties, or even
3348 alter the buffer contents, change the current buffer.
3350 Here, we reset all those changes by:
3351 o set back the current buffer.
3352 o move all markers and overlays to BEG.
3353 o remove all text properties.
3354 o set back the buffer multibyteness. */
3356 static void
3357 decide_coding_unwind (Lisp_Object unwind_data)
3359 Lisp_Object multibyte, undo_list, buffer;
3361 multibyte = XCAR (unwind_data);
3362 unwind_data = XCDR (unwind_data);
3363 undo_list = XCAR (unwind_data);
3364 buffer = XCDR (unwind_data);
3366 set_buffer_internal (XBUFFER (buffer));
3367 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3368 adjust_overlays_for_delete (BEG, Z - BEG);
3369 set_buffer_intervals (current_buffer, NULL);
3370 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3372 /* Now we are safe to change the buffer's multibyteness directly. */
3373 bset_enable_multibyte_characters (current_buffer, multibyte);
3374 bset_undo_list (current_buffer, undo_list);
3377 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3378 object where slot 0 is the file descriptor, slot 1 specifies
3379 an offset to put the read bytes, and slot 2 is the maximum
3380 amount of bytes to read. Value is the number of bytes read. */
3382 static Lisp_Object
3383 read_non_regular (Lisp_Object state)
3385 int nbytes;
3387 immediate_quit = 1;
3388 QUIT;
3389 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3390 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3391 + XSAVE_INTEGER (state, 1)),
3392 XSAVE_INTEGER (state, 2));
3393 immediate_quit = 0;
3394 /* Fast recycle this object for the likely next call. */
3395 free_misc (state);
3396 return make_number (nbytes);
3400 /* Condition-case handler used when reading from non-regular files
3401 in insert-file-contents. */
3403 static Lisp_Object
3404 read_non_regular_quit (Lisp_Object ignore)
3406 return Qnil;
3409 /* Return the file offset that VAL represents, checking for type
3410 errors and overflow. */
3411 static off_t
3412 file_offset (Lisp_Object val)
3414 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3415 return XINT (val);
3417 if (FLOATP (val))
3419 double v = XFLOAT_DATA (val);
3420 if (0 <= v
3421 && (sizeof (off_t) < sizeof v
3422 ? v <= TYPE_MAXIMUM (off_t)
3423 : v < TYPE_MAXIMUM (off_t)))
3424 return v;
3427 wrong_type_argument (intern ("file-offset"), val);
3430 /* Return a special time value indicating the error number ERRNUM. */
3431 static struct timespec
3432 time_error_value (int errnum)
3434 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3435 ? NONEXISTENT_MODTIME_NSECS
3436 : UNKNOWN_MODTIME_NSECS);
3437 return make_timespec (0, ns);
3440 static Lisp_Object
3441 get_window_points_and_markers (void)
3443 Lisp_Object pt_marker = Fpoint_marker ();
3444 Lisp_Object windows
3445 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3446 Lisp_Object window_markers = windows;
3447 /* Window markers (and point) are handled specially: rather than move to
3448 just before or just after the modified text, we try to keep the
3449 markers at the same distance (bug#19161).
3450 In general, this is wrong, but for window-markers, this should be harmless
3451 and is convenient for the end user when most of the file is unmodified,
3452 except for a few minor details near the beginning and near the end. */
3453 for (; CONSP (windows); windows = XCDR (windows))
3454 if (WINDOWP (XCAR (windows)))
3456 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3457 XSETCAR (windows,
3458 Fcons (window_marker, Fmarker_position (window_marker)));
3460 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3463 static void
3464 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3465 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3467 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3468 if (CONSP (XCAR (window_markers)))
3470 Lisp_Object car = XCAR (window_markers);
3471 Lisp_Object marker = XCAR (car);
3472 Lisp_Object oldpos = XCDR (car);
3473 if (MARKERP (marker) && INTEGERP (oldpos)
3474 && XINT (oldpos) > same_at_start
3475 && XINT (oldpos) < same_at_end)
3477 ptrdiff_t oldsize = same_at_end - same_at_start;
3478 ptrdiff_t newsize = inserted;
3479 double growth = newsize / (double)oldsize;
3480 ptrdiff_t newpos
3481 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3482 Fset_marker (marker, make_number (newpos), Qnil);
3487 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3488 text as a linear C char array. */
3489 static void
3490 maybe_move_gap (struct buffer *b)
3492 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3494 struct buffer *cb = current_buffer;
3496 set_buffer_internal (b);
3497 move_gap_both (Z, Z_BYTE);
3498 set_buffer_internal (cb);
3502 /* FIXME: insert-file-contents should be split with the top-level moved to
3503 Elisp and only the core kept in C. */
3505 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3506 1, 5, 0,
3507 doc: /* Insert contents of file FILENAME after point.
3508 Returns list of absolute file name and number of characters inserted.
3509 If second argument VISIT is non-nil, the buffer's visited filename and
3510 last save file modtime are set, and it is marked unmodified. If
3511 visiting and the file does not exist, visiting is completed before the
3512 error is signaled.
3514 The optional third and fourth arguments BEG and END specify what portion
3515 of the file to insert. These arguments count bytes in the file, not
3516 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3518 If optional fifth argument REPLACE is non-nil, replace the current
3519 buffer contents (in the accessible portion) with the file contents.
3520 This is better than simply deleting and inserting the whole thing
3521 because (1) it preserves some marker positions and (2) it puts less data
3522 in the undo list. When REPLACE is non-nil, the second return value is
3523 the number of characters that replace previous buffer contents.
3525 This function does code conversion according to the value of
3526 `coding-system-for-read' or `file-coding-system-alist', and sets the
3527 variable `last-coding-system-used' to the coding system actually used.
3529 In addition, this function decodes the inserted text from known formats
3530 by calling `format-decode', which see. */)
3531 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3533 struct stat st;
3534 struct timespec mtime;
3535 int fd;
3536 ptrdiff_t inserted = 0;
3537 ptrdiff_t how_much;
3538 off_t beg_offset, end_offset;
3539 int unprocessed;
3540 ptrdiff_t count = SPECPDL_INDEX ();
3541 Lisp_Object handler, val, insval, orig_filename, old_undo;
3542 Lisp_Object p;
3543 ptrdiff_t total = 0;
3544 bool not_regular = 0;
3545 int save_errno = 0;
3546 char read_buf[READ_BUF_SIZE];
3547 struct coding_system coding;
3548 bool replace_handled = false;
3549 bool set_coding_system = false;
3550 Lisp_Object coding_system;
3551 bool read_quit = false;
3552 /* If the undo log only contains the insertion, there's no point
3553 keeping it. It's typically when we first fill a file-buffer. */
3554 bool empty_undo_list_p
3555 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3556 && BEG == Z);
3557 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3558 bool we_locked_file = false;
3559 ptrdiff_t fd_index;
3560 Lisp_Object window_markers = Qnil;
3561 /* same_at_start and same_at_end count bytes, because file access counts
3562 bytes and BEG and END count bytes. */
3563 ptrdiff_t same_at_start = BEGV_BYTE;
3564 ptrdiff_t same_at_end = ZV_BYTE;
3565 /* SAME_AT_END_CHARPOS counts characters, because
3566 restore_window_points needs the old character count. */
3567 ptrdiff_t same_at_end_charpos = ZV;
3569 if (current_buffer->base_buffer && ! NILP (visit))
3570 error ("Cannot do file visiting in an indirect buffer");
3572 if (!NILP (BVAR (current_buffer, read_only)))
3573 Fbarf_if_buffer_read_only (Qnil);
3575 val = Qnil;
3576 p = Qnil;
3577 orig_filename = Qnil;
3578 old_undo = Qnil;
3580 CHECK_STRING (filename);
3581 filename = Fexpand_file_name (filename, Qnil);
3583 /* The value Qnil means that the coding system is not yet
3584 decided. */
3585 coding_system = Qnil;
3587 /* If the file name has special constructs in it,
3588 call the corresponding file handler. */
3589 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3590 if (!NILP (handler))
3592 val = call6 (handler, Qinsert_file_contents, filename,
3593 visit, beg, end, replace);
3594 if (CONSP (val) && CONSP (XCDR (val))
3595 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3596 inserted = XINT (XCAR (XCDR (val)));
3597 goto handled;
3600 orig_filename = filename;
3601 filename = ENCODE_FILE (filename);
3603 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3604 if (fd < 0)
3606 save_errno = errno;
3607 if (NILP (visit))
3608 report_file_error ("Opening input file", orig_filename);
3609 mtime = time_error_value (save_errno);
3610 st.st_size = -1;
3611 if (!NILP (Vcoding_system_for_read))
3613 /* Don't let invalid values into buffer-file-coding-system. */
3614 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3615 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3617 goto notfound;
3620 fd_index = SPECPDL_INDEX ();
3621 record_unwind_protect_int (close_file_unwind, fd);
3623 /* Replacement should preserve point as it preserves markers. */
3624 if (!NILP (replace))
3626 window_markers = get_window_points_and_markers ();
3627 record_unwind_protect (restore_point_unwind,
3628 XCAR (XCAR (window_markers)));
3631 if (fstat (fd, &st) != 0)
3632 report_file_error ("Input file status", orig_filename);
3633 mtime = get_stat_mtime (&st);
3635 /* This code will need to be changed in order to work on named
3636 pipes, and it's probably just not worth it. So we should at
3637 least signal an error. */
3638 if (!S_ISREG (st.st_mode))
3640 not_regular = 1;
3642 if (! NILP (visit))
3643 goto notfound;
3645 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3646 xsignal2 (Qfile_error,
3647 build_string ("not a regular file"), orig_filename);
3650 if (!NILP (visit))
3652 if (!NILP (beg) || !NILP (end))
3653 error ("Attempt to visit less than an entire file");
3654 if (BEG < Z && NILP (replace))
3655 error ("Cannot do file visiting in a non-empty buffer");
3658 if (!NILP (beg))
3659 beg_offset = file_offset (beg);
3660 else
3661 beg_offset = 0;
3663 if (!NILP (end))
3664 end_offset = file_offset (end);
3665 else
3667 if (not_regular)
3668 end_offset = TYPE_MAXIMUM (off_t);
3669 else
3671 end_offset = st.st_size;
3673 /* A negative size can happen on a platform that allows file
3674 sizes greater than the maximum off_t value. */
3675 if (end_offset < 0)
3676 buffer_overflow ();
3678 /* The file size returned from stat may be zero, but data
3679 may be readable nonetheless, for example when this is a
3680 file in the /proc filesystem. */
3681 if (end_offset == 0)
3682 end_offset = READ_BUF_SIZE;
3686 /* Check now whether the buffer will become too large,
3687 in the likely case where the file's length is not changing.
3688 This saves a lot of needless work before a buffer overflow. */
3689 if (! not_regular)
3691 /* The likely offset where we will stop reading. We could read
3692 more (or less), if the file grows (or shrinks) as we read it. */
3693 off_t likely_end = min (end_offset, st.st_size);
3695 if (beg_offset < likely_end)
3697 ptrdiff_t buf_bytes
3698 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3699 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3700 off_t likely_growth = likely_end - beg_offset;
3701 if (buf_growth_max < likely_growth)
3702 buffer_overflow ();
3706 /* Prevent redisplay optimizations. */
3707 current_buffer->clip_changed = true;
3709 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3711 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3712 setup_coding_system (coding_system, &coding);
3713 /* Ensure we set Vlast_coding_system_used. */
3714 set_coding_system = true;
3716 else if (BEG < Z)
3718 /* Decide the coding system to use for reading the file now
3719 because we can't use an optimized method for handling
3720 `coding:' tag if the current buffer is not empty. */
3721 if (!NILP (Vcoding_system_for_read))
3722 coding_system = Vcoding_system_for_read;
3723 else
3725 /* Don't try looking inside a file for a coding system
3726 specification if it is not seekable. */
3727 if (! not_regular && ! NILP (Vset_auto_coding_function))
3729 /* Find a coding system specified in the heading two
3730 lines or in the tailing several lines of the file.
3731 We assume that the 1K-byte and 3K-byte for heading
3732 and tailing respectively are sufficient for this
3733 purpose. */
3734 int nread;
3736 if (st.st_size <= (1024 * 4))
3737 nread = emacs_read (fd, read_buf, 1024 * 4);
3738 else
3740 nread = emacs_read (fd, read_buf, 1024);
3741 if (nread == 1024)
3743 int ntail;
3744 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3745 report_file_error ("Setting file position",
3746 orig_filename);
3747 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3748 nread = ntail < 0 ? ntail : nread + ntail;
3752 if (nread < 0)
3753 report_file_error ("Read error", orig_filename);
3754 else if (nread > 0)
3756 AUTO_STRING (name, " *code-converting-work*");
3757 struct buffer *prev = current_buffer;
3758 Lisp_Object workbuf;
3759 struct buffer *buf;
3761 record_unwind_current_buffer ();
3763 workbuf = Fget_buffer_create (name);
3764 buf = XBUFFER (workbuf);
3766 delete_all_overlays (buf);
3767 bset_directory (buf, BVAR (current_buffer, directory));
3768 bset_read_only (buf, Qnil);
3769 bset_filename (buf, Qnil);
3770 bset_undo_list (buf, Qt);
3771 eassert (buf->overlays_before == NULL);
3772 eassert (buf->overlays_after == NULL);
3774 set_buffer_internal (buf);
3775 Ferase_buffer ();
3776 bset_enable_multibyte_characters (buf, Qnil);
3778 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3779 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3780 coding_system = call2 (Vset_auto_coding_function,
3781 filename, make_number (nread));
3782 set_buffer_internal (prev);
3784 /* Discard the unwind protect for recovering the
3785 current buffer. */
3786 specpdl_ptr--;
3788 /* Rewind the file for the actual read done later. */
3789 if (lseek (fd, 0, SEEK_SET) < 0)
3790 report_file_error ("Setting file position", orig_filename);
3794 if (NILP (coding_system))
3796 /* If we have not yet decided a coding system, check
3797 file-coding-system-alist. */
3798 coding_system = CALLN (Ffind_operation_coding_system,
3799 Qinsert_file_contents, orig_filename,
3800 visit, beg, end, replace);
3801 if (CONSP (coding_system))
3802 coding_system = XCAR (coding_system);
3806 if (NILP (coding_system))
3807 coding_system = Qundecided;
3808 else
3809 CHECK_CODING_SYSTEM (coding_system);
3811 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3812 /* We must suppress all character code conversion except for
3813 end-of-line conversion. */
3814 coding_system = raw_text_coding_system (coding_system);
3816 setup_coding_system (coding_system, &coding);
3817 /* Ensure we set Vlast_coding_system_used. */
3818 set_coding_system = true;
3821 /* If requested, replace the accessible part of the buffer
3822 with the file contents. Avoid replacing text at the
3823 beginning or end of the buffer that matches the file contents;
3824 that preserves markers pointing to the unchanged parts.
3826 Here we implement this feature in an optimized way
3827 for the case where code conversion is NOT needed.
3828 The following if-statement handles the case of conversion
3829 in a less optimal way.
3831 If the code conversion is "automatic" then we try using this
3832 method and hope for the best.
3833 But if we discover the need for conversion, we give up on this method
3834 and let the following if-statement handle the replace job. */
3835 if (!NILP (replace)
3836 && BEGV < ZV
3837 && (NILP (coding_system)
3838 || ! CODING_REQUIRE_DECODING (&coding)))
3840 ptrdiff_t overlap;
3841 /* There is still a possibility we will find the need to do code
3842 conversion. If that happens, set this variable to
3843 give up on handling REPLACE in the optimized way. */
3844 bool giveup_match_end = false;
3846 if (beg_offset != 0)
3848 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3849 report_file_error ("Setting file position", orig_filename);
3852 immediate_quit = 1;
3853 QUIT;
3854 /* Count how many chars at the start of the file
3855 match the text at the beginning of the buffer. */
3856 while (1)
3858 int nread, bufpos;
3860 nread = emacs_read (fd, read_buf, sizeof read_buf);
3861 if (nread < 0)
3862 report_file_error ("Read error", orig_filename);
3863 else if (nread == 0)
3864 break;
3866 if (CODING_REQUIRE_DETECTION (&coding))
3868 coding_system = detect_coding_system ((unsigned char *) read_buf,
3869 nread, nread, 1, 0,
3870 coding_system);
3871 setup_coding_system (coding_system, &coding);
3874 if (CODING_REQUIRE_DECODING (&coding))
3875 /* We found that the file should be decoded somehow.
3876 Let's give up here. */
3878 giveup_match_end = true;
3879 break;
3882 bufpos = 0;
3883 while (bufpos < nread && same_at_start < ZV_BYTE
3884 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3885 same_at_start++, bufpos++;
3886 /* If we found a discrepancy, stop the scan.
3887 Otherwise loop around and scan the next bufferful. */
3888 if (bufpos != nread)
3889 break;
3891 immediate_quit = false;
3892 /* If the file matches the buffer completely,
3893 there's no need to replace anything. */
3894 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3896 emacs_close (fd);
3897 clear_unwind_protect (fd_index);
3899 /* Truncate the buffer to the size of the file. */
3900 del_range_1 (same_at_start, same_at_end, 0, 0);
3901 goto handled;
3903 immediate_quit = true;
3904 QUIT;
3905 /* Count how many chars at the end of the file
3906 match the text at the end of the buffer. But, if we have
3907 already found that decoding is necessary, don't waste time. */
3908 while (!giveup_match_end)
3910 int total_read, nread, bufpos, trial;
3911 off_t curpos;
3913 /* At what file position are we now scanning? */
3914 curpos = end_offset - (ZV_BYTE - same_at_end);
3915 /* If the entire file matches the buffer tail, stop the scan. */
3916 if (curpos == 0)
3917 break;
3918 /* How much can we scan in the next step? */
3919 trial = min (curpos, sizeof read_buf);
3920 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3921 report_file_error ("Setting file position", orig_filename);
3923 total_read = nread = 0;
3924 while (total_read < trial)
3926 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3927 if (nread < 0)
3928 report_file_error ("Read error", orig_filename);
3929 else if (nread == 0)
3930 break;
3931 total_read += nread;
3934 /* Scan this bufferful from the end, comparing with
3935 the Emacs buffer. */
3936 bufpos = total_read;
3938 /* Compare with same_at_start to avoid counting some buffer text
3939 as matching both at the file's beginning and at the end. */
3940 while (bufpos > 0 && same_at_end > same_at_start
3941 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3942 same_at_end--, bufpos--;
3944 /* If we found a discrepancy, stop the scan.
3945 Otherwise loop around and scan the preceding bufferful. */
3946 if (bufpos != 0)
3948 /* If this discrepancy is because of code conversion,
3949 we cannot use this method; giveup and try the other. */
3950 if (same_at_end > same_at_start
3951 && FETCH_BYTE (same_at_end - 1) >= 0200
3952 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3953 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3954 giveup_match_end = true;
3955 break;
3958 if (nread == 0)
3959 break;
3961 immediate_quit = 0;
3963 if (! giveup_match_end)
3965 ptrdiff_t temp;
3966 ptrdiff_t this_count = SPECPDL_INDEX ();
3968 /* We win! We can handle REPLACE the optimized way. */
3970 /* Extend the start of non-matching text area to multibyte
3971 character boundary. */
3972 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3973 while (same_at_start > BEGV_BYTE
3974 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3975 same_at_start--;
3977 /* Extend the end of non-matching text area to multibyte
3978 character boundary. */
3979 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3980 while (same_at_end < ZV_BYTE
3981 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3982 same_at_end++;
3984 /* Don't try to reuse the same piece of text twice. */
3985 overlap = (same_at_start - BEGV_BYTE
3986 - (same_at_end
3987 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3988 if (overlap > 0)
3989 same_at_end += overlap;
3990 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3992 /* Arrange to read only the nonmatching middle part of the file. */
3993 beg_offset += same_at_start - BEGV_BYTE;
3994 end_offset -= ZV_BYTE - same_at_end;
3996 /* This binding is to avoid ask-user-about-supersession-threat
3997 being called in insert_from_buffer or del_range_bytes (via
3998 prepare_to_modify_buffer).
3999 AFAICT we could avoid ask-user-about-supersession-threat by setting
4000 current_buffer->modtime earlier, but we could still end up calling
4001 ask-user-about-supersession-threat if the file is modified while
4002 we read it, so we bind buffer-file-name instead. */
4003 specbind (intern ("buffer-file-name"), Qnil);
4004 del_range_byte (same_at_start, same_at_end);
4005 /* Insert from the file at the proper position. */
4006 temp = BYTE_TO_CHAR (same_at_start);
4007 SET_PT_BOTH (temp, same_at_start);
4008 unbind_to (this_count, Qnil);
4010 /* If display currently starts at beginning of line,
4011 keep it that way. */
4012 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4013 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4015 replace_handled = true;
4019 /* If requested, replace the accessible part of the buffer
4020 with the file contents. Avoid replacing text at the
4021 beginning or end of the buffer that matches the file contents;
4022 that preserves markers pointing to the unchanged parts.
4024 Here we implement this feature for the case where code conversion
4025 is needed, in a simple way that needs a lot of memory.
4026 The preceding if-statement handles the case of no conversion
4027 in a more optimized way. */
4028 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
4030 ptrdiff_t same_at_start_charpos;
4031 ptrdiff_t inserted_chars;
4032 ptrdiff_t overlap;
4033 ptrdiff_t bufpos;
4034 unsigned char *decoded;
4035 ptrdiff_t temp;
4036 ptrdiff_t this = 0;
4037 ptrdiff_t this_count = SPECPDL_INDEX ();
4038 bool multibyte
4039 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4040 Lisp_Object conversion_buffer;
4042 conversion_buffer = code_conversion_save (1, multibyte);
4044 /* First read the whole file, performing code conversion into
4045 CONVERSION_BUFFER. */
4047 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4048 report_file_error ("Setting file position", orig_filename);
4050 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
4051 unprocessed = 0; /* Bytes not processed in previous loop. */
4053 while (1)
4055 /* Read at most READ_BUF_SIZE bytes at a time, to allow
4056 quitting while reading a huge file. */
4058 /* Allow quitting out of the actual I/O. */
4059 immediate_quit = 1;
4060 QUIT;
4061 this = emacs_read (fd, read_buf + unprocessed,
4062 READ_BUF_SIZE - unprocessed);
4063 immediate_quit = 0;
4065 if (this <= 0)
4066 break;
4068 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
4069 BUF_Z (XBUFFER (conversion_buffer)));
4070 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4071 unprocessed + this, conversion_buffer);
4072 unprocessed = coding.carryover_bytes;
4073 if (coding.carryover_bytes > 0)
4074 memcpy (read_buf, coding.carryover, unprocessed);
4077 if (this < 0)
4078 report_file_error ("Read error", orig_filename);
4079 emacs_close (fd);
4080 clear_unwind_protect (fd_index);
4082 if (unprocessed > 0)
4084 coding.mode |= CODING_MODE_LAST_BLOCK;
4085 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4086 unprocessed, conversion_buffer);
4087 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4090 coding_system = CODING_ID_NAME (coding.id);
4091 set_coding_system = true;
4092 maybe_move_gap (XBUFFER (conversion_buffer));
4093 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
4094 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4095 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4097 /* Compare the beginning of the converted string with the buffer
4098 text. */
4100 bufpos = 0;
4101 while (bufpos < inserted && same_at_start < same_at_end
4102 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4103 same_at_start++, bufpos++;
4105 /* If the file matches the head of buffer completely,
4106 there's no need to replace anything. */
4108 if (bufpos == inserted)
4110 /* Truncate the buffer to the size of the file. */
4111 if (same_at_start != same_at_end)
4113 /* See previous specbind for the reason behind this. */
4114 specbind (intern ("buffer-file-name"), Qnil);
4115 del_range_byte (same_at_start, same_at_end);
4117 inserted = 0;
4119 unbind_to (this_count, Qnil);
4120 goto handled;
4123 /* Extend the start of non-matching text area to the previous
4124 multibyte character boundary. */
4125 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4126 while (same_at_start > BEGV_BYTE
4127 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4128 same_at_start--;
4130 /* Scan this bufferful from the end, comparing with
4131 the Emacs buffer. */
4132 bufpos = inserted;
4134 /* Compare with same_at_start to avoid counting some buffer text
4135 as matching both at the file's beginning and at the end. */
4136 while (bufpos > 0 && same_at_end > same_at_start
4137 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4138 same_at_end--, bufpos--;
4140 /* Extend the end of non-matching text area to the next
4141 multibyte character boundary. */
4142 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4143 while (same_at_end < ZV_BYTE
4144 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4145 same_at_end++;
4147 /* Don't try to reuse the same piece of text twice. */
4148 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4149 if (overlap > 0)
4150 same_at_end += overlap;
4151 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4153 /* If display currently starts at beginning of line,
4154 keep it that way. */
4155 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4156 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4158 /* Replace the chars that we need to replace,
4159 and update INSERTED to equal the number of bytes
4160 we are taking from the decoded string. */
4161 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4163 /* See previous specbind for the reason behind this. */
4164 specbind (intern ("buffer-file-name"), Qnil);
4165 if (same_at_end != same_at_start)
4167 del_range_byte (same_at_start, same_at_end);
4168 temp = GPT;
4169 eassert (same_at_start == GPT_BYTE);
4170 same_at_start = GPT_BYTE;
4172 else
4174 temp = same_at_end_charpos;
4176 /* Insert from the file at the proper position. */
4177 SET_PT_BOTH (temp, same_at_start);
4178 same_at_start_charpos
4179 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4180 same_at_start - BEGV_BYTE
4181 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4182 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4183 inserted_chars
4184 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4185 same_at_start + inserted - BEGV_BYTE
4186 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4187 - same_at_start_charpos);
4188 insert_from_buffer (XBUFFER (conversion_buffer),
4189 same_at_start_charpos, inserted_chars, 0);
4190 /* Set `inserted' to the number of inserted characters. */
4191 inserted = PT - temp;
4192 /* Set point before the inserted characters. */
4193 SET_PT_BOTH (temp, same_at_start);
4195 unbind_to (this_count, Qnil);
4197 goto handled;
4200 if (! not_regular)
4201 total = end_offset - beg_offset;
4202 else
4203 /* For a special file, all we can do is guess. */
4204 total = READ_BUF_SIZE;
4206 if (NILP (visit) && total > 0)
4208 if (!NILP (BVAR (current_buffer, file_truename))
4209 /* Make binding buffer-file-name to nil effective. */
4210 && !NILP (BVAR (current_buffer, filename))
4211 && SAVE_MODIFF >= MODIFF)
4212 we_locked_file = true;
4213 prepare_to_modify_buffer (PT, PT, NULL);
4216 move_gap_both (PT, PT_BYTE);
4217 if (GAP_SIZE < total)
4218 make_gap (total - GAP_SIZE);
4220 if (beg_offset != 0 || !NILP (replace))
4222 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4223 report_file_error ("Setting file position", orig_filename);
4226 /* In the following loop, HOW_MUCH contains the total bytes read so
4227 far for a regular file, and not changed for a special file. But,
4228 before exiting the loop, it is set to a negative value if I/O
4229 error occurs. */
4230 how_much = 0;
4232 /* Total bytes inserted. */
4233 inserted = 0;
4235 /* Here, we don't do code conversion in the loop. It is done by
4236 decode_coding_gap after all data are read into the buffer. */
4238 ptrdiff_t gap_size = GAP_SIZE;
4240 while (how_much < total)
4242 /* `try' is reserved in some compilers (Microsoft C). */
4243 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4244 ptrdiff_t this;
4246 if (not_regular)
4248 Lisp_Object nbytes;
4250 /* Maybe make more room. */
4251 if (gap_size < trytry)
4253 make_gap (trytry - gap_size);
4254 gap_size = GAP_SIZE - inserted;
4257 /* Read from the file, capturing `quit'. When an
4258 error occurs, end the loop, and arrange for a quit
4259 to be signaled after decoding the text we read. */
4260 nbytes = internal_condition_case_1
4261 (read_non_regular,
4262 make_save_int_int_int (fd, inserted, trytry),
4263 Qerror, read_non_regular_quit);
4265 if (NILP (nbytes))
4267 read_quit = true;
4268 break;
4271 this = XINT (nbytes);
4273 else
4275 /* Allow quitting out of the actual I/O. We don't make text
4276 part of the buffer until all the reading is done, so a C-g
4277 here doesn't do any harm. */
4278 immediate_quit = 1;
4279 QUIT;
4280 this = emacs_read (fd,
4281 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4282 + inserted),
4283 trytry);
4284 immediate_quit = 0;
4287 if (this <= 0)
4289 how_much = this;
4290 break;
4293 gap_size -= this;
4295 /* For a regular file, where TOTAL is the real size,
4296 count HOW_MUCH to compare with it.
4297 For a special file, where TOTAL is just a buffer size,
4298 so don't bother counting in HOW_MUCH.
4299 (INSERTED is where we count the number of characters inserted.) */
4300 if (! not_regular)
4301 how_much += this;
4302 inserted += this;
4306 /* Now we have either read all the file data into the gap,
4307 or stop reading on I/O error or quit. If nothing was
4308 read, undo marking the buffer modified. */
4310 if (inserted == 0)
4312 if (we_locked_file)
4313 unlock_file (BVAR (current_buffer, file_truename));
4314 Vdeactivate_mark = old_Vdeactivate_mark;
4316 else
4317 Fset (Qdeactivate_mark, Qt);
4319 emacs_close (fd);
4320 clear_unwind_protect (fd_index);
4322 if (how_much < 0)
4323 report_file_error ("Read error", orig_filename);
4325 /* Make the text read part of the buffer. */
4326 GAP_SIZE -= inserted;
4327 GPT += inserted;
4328 GPT_BYTE += inserted;
4329 ZV += inserted;
4330 ZV_BYTE += inserted;
4331 Z += inserted;
4332 Z_BYTE += inserted;
4334 if (GAP_SIZE > 0)
4335 /* Put an anchor to ensure multi-byte form ends at gap. */
4336 *GPT_ADDR = 0;
4338 notfound:
4340 if (NILP (coding_system))
4342 /* The coding system is not yet decided. Decide it by an
4343 optimized method for handling `coding:' tag.
4345 Note that we can get here only if the buffer was empty
4346 before the insertion. */
4348 if (!NILP (Vcoding_system_for_read))
4349 coding_system = Vcoding_system_for_read;
4350 else
4352 /* Since we are sure that the current buffer was empty
4353 before the insertion, we can toggle
4354 enable-multibyte-characters directly here without taking
4355 care of marker adjustment. By this way, we can run Lisp
4356 program safely before decoding the inserted text. */
4357 Lisp_Object unwind_data;
4358 ptrdiff_t count1 = SPECPDL_INDEX ();
4360 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4361 Fcons (BVAR (current_buffer, undo_list),
4362 Fcurrent_buffer ()));
4363 bset_enable_multibyte_characters (current_buffer, Qnil);
4364 bset_undo_list (current_buffer, Qt);
4365 record_unwind_protect (decide_coding_unwind, unwind_data);
4367 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4369 coding_system = call2 (Vset_auto_coding_function,
4370 filename, make_number (inserted));
4373 if (NILP (coding_system))
4375 /* If the coding system is not yet decided, check
4376 file-coding-system-alist. */
4377 coding_system = CALLN (Ffind_operation_coding_system,
4378 Qinsert_file_contents, orig_filename,
4379 visit, beg, end, Qnil);
4380 if (CONSP (coding_system))
4381 coding_system = XCAR (coding_system);
4383 unbind_to (count1, Qnil);
4384 inserted = Z_BYTE - BEG_BYTE;
4387 if (NILP (coding_system))
4388 coding_system = Qundecided;
4389 else
4390 CHECK_CODING_SYSTEM (coding_system);
4392 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4393 /* We must suppress all character code conversion except for
4394 end-of-line conversion. */
4395 coding_system = raw_text_coding_system (coding_system);
4396 setup_coding_system (coding_system, &coding);
4397 /* Ensure we set Vlast_coding_system_used. */
4398 set_coding_system = true;
4401 if (!NILP (visit))
4403 /* When we visit a file by raw-text, we change the buffer to
4404 unibyte. */
4405 if (CODING_FOR_UNIBYTE (&coding)
4406 /* Can't do this if part of the buffer might be preserved. */
4407 && NILP (replace))
4409 /* Visiting a file with these coding system makes the buffer
4410 unibyte. */
4411 if (inserted > 0)
4412 bset_enable_multibyte_characters (current_buffer, Qnil);
4413 else
4414 Fset_buffer_multibyte (Qnil);
4418 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4419 if (CODING_MAY_REQUIRE_DECODING (&coding)
4420 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4422 move_gap_both (PT, PT_BYTE);
4423 GAP_SIZE += inserted;
4424 ZV_BYTE -= inserted;
4425 Z_BYTE -= inserted;
4426 ZV -= inserted;
4427 Z -= inserted;
4428 decode_coding_gap (&coding, inserted, inserted);
4429 inserted = coding.produced_char;
4430 coding_system = CODING_ID_NAME (coding.id);
4432 else if (inserted > 0)
4434 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4435 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4436 inserted);
4439 /* Call after-change hooks for the inserted text, aside from the case
4440 of normal visiting (not with REPLACE), which is done in a new buffer
4441 "before" the buffer is changed. */
4442 if (inserted > 0 && total > 0
4443 && (NILP (visit) || !NILP (replace)))
4445 signal_after_change (PT, 0, inserted);
4446 update_compositions (PT, PT, CHECK_BORDER);
4449 /* Now INSERTED is measured in characters. */
4451 handled:
4453 if (inserted > 0)
4454 restore_window_points (window_markers, inserted,
4455 BYTE_TO_CHAR (same_at_start),
4456 same_at_end_charpos);
4458 if (!NILP (visit))
4460 if (empty_undo_list_p)
4461 bset_undo_list (current_buffer, Qnil);
4463 if (NILP (handler))
4465 current_buffer->modtime = mtime;
4466 current_buffer->modtime_size = st.st_size;
4467 bset_filename (current_buffer, orig_filename);
4470 SAVE_MODIFF = MODIFF;
4471 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4472 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4473 if (NILP (handler))
4475 if (!NILP (BVAR (current_buffer, file_truename)))
4476 unlock_file (BVAR (current_buffer, file_truename));
4477 unlock_file (filename);
4479 if (not_regular)
4480 xsignal2 (Qfile_error,
4481 build_string ("not a regular file"), orig_filename);
4484 if (set_coding_system)
4485 Vlast_coding_system_used = coding_system;
4487 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4489 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4490 visit);
4491 if (! NILP (insval))
4493 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4494 wrong_type_argument (intern ("inserted-chars"), insval);
4495 inserted = XFASTINT (insval);
4499 /* Decode file format. */
4500 if (inserted > 0)
4502 /* Don't run point motion or modification hooks when decoding. */
4503 ptrdiff_t count1 = SPECPDL_INDEX ();
4504 ptrdiff_t old_inserted = inserted;
4505 specbind (Qinhibit_point_motion_hooks, Qt);
4506 specbind (Qinhibit_modification_hooks, Qt);
4508 /* Save old undo list and don't record undo for decoding. */
4509 old_undo = BVAR (current_buffer, undo_list);
4510 bset_undo_list (current_buffer, Qt);
4512 if (NILP (replace))
4514 insval = call3 (Qformat_decode,
4515 Qnil, make_number (inserted), visit);
4516 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4517 wrong_type_argument (intern ("inserted-chars"), insval);
4518 inserted = XFASTINT (insval);
4520 else
4522 /* If REPLACE is non-nil and we succeeded in not replacing the
4523 beginning or end of the buffer text with the file's contents,
4524 call format-decode with `point' positioned at the beginning
4525 of the buffer and `inserted' equaling the number of
4526 characters in the buffer. Otherwise, format-decode might
4527 fail to correctly analyze the beginning or end of the buffer.
4528 Hence we temporarily save `point' and `inserted' here and
4529 restore `point' iff format-decode did not insert or delete
4530 any text. Otherwise we leave `point' at point-min. */
4531 ptrdiff_t opoint = PT;
4532 ptrdiff_t opoint_byte = PT_BYTE;
4533 ptrdiff_t oinserted = ZV - BEGV;
4534 EMACS_INT ochars_modiff = CHARS_MODIFF;
4536 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4537 insval = call3 (Qformat_decode,
4538 Qnil, make_number (oinserted), visit);
4539 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4540 wrong_type_argument (intern ("inserted-chars"), insval);
4541 if (ochars_modiff == CHARS_MODIFF)
4542 /* format_decode didn't modify buffer's characters => move
4543 point back to position before inserted text and leave
4544 value of inserted alone. */
4545 SET_PT_BOTH (opoint, opoint_byte);
4546 else
4547 /* format_decode modified buffer's characters => consider
4548 entire buffer changed and leave point at point-min. */
4549 inserted = XFASTINT (insval);
4552 /* For consistency with format-decode call these now iff inserted > 0
4553 (martin 2007-06-28). */
4554 p = Vafter_insert_file_functions;
4555 while (CONSP (p))
4557 if (NILP (replace))
4559 insval = call1 (XCAR (p), make_number (inserted));
4560 if (!NILP (insval))
4562 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4563 wrong_type_argument (intern ("inserted-chars"), insval);
4564 inserted = XFASTINT (insval);
4567 else
4569 /* For the rationale of this see the comment on
4570 format-decode above. */
4571 ptrdiff_t opoint = PT;
4572 ptrdiff_t opoint_byte = PT_BYTE;
4573 ptrdiff_t oinserted = ZV - BEGV;
4574 EMACS_INT ochars_modiff = CHARS_MODIFF;
4576 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4577 insval = call1 (XCAR (p), make_number (oinserted));
4578 if (!NILP (insval))
4580 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4581 wrong_type_argument (intern ("inserted-chars"), insval);
4582 if (ochars_modiff == CHARS_MODIFF)
4583 /* after_insert_file_functions didn't modify
4584 buffer's characters => move point back to
4585 position before inserted text and leave value of
4586 inserted alone. */
4587 SET_PT_BOTH (opoint, opoint_byte);
4588 else
4589 /* after_insert_file_functions did modify buffer's
4590 characters => consider entire buffer changed and
4591 leave point at point-min. */
4592 inserted = XFASTINT (insval);
4596 QUIT;
4597 p = XCDR (p);
4600 if (!empty_undo_list_p)
4602 bset_undo_list (current_buffer, old_undo);
4603 if (CONSP (old_undo) && inserted != old_inserted)
4605 /* Adjust the last undo record for the size change during
4606 the format conversion. */
4607 Lisp_Object tem = XCAR (old_undo);
4608 if (CONSP (tem) && INTEGERP (XCAR (tem))
4609 && INTEGERP (XCDR (tem))
4610 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4611 XSETCDR (tem, make_number (PT + inserted));
4614 else
4615 /* If undo_list was Qt before, keep it that way.
4616 Otherwise start with an empty undo_list. */
4617 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4619 unbind_to (count1, Qnil);
4622 if (!NILP (visit)
4623 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4625 /* If visiting nonexistent file, return nil. */
4626 report_file_errno ("Opening input file", orig_filename, save_errno);
4629 /* We made a lot of deletions and insertions above, so invalidate
4630 the newline cache for the entire region of the inserted
4631 characters. */
4632 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4633 invalidate_region_cache (current_buffer->base_buffer,
4634 current_buffer->base_buffer->newline_cache,
4635 PT - BEG, Z - PT - inserted);
4636 else if (current_buffer->newline_cache)
4637 invalidate_region_cache (current_buffer,
4638 current_buffer->newline_cache,
4639 PT - BEG, Z - PT - inserted);
4641 if (read_quit)
4642 quit ();
4644 /* Retval needs to be dealt with in all cases consistently. */
4645 if (NILP (val))
4646 val = list2 (orig_filename, make_number (inserted));
4648 return unbind_to (count, val);
4651 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4653 static void
4654 build_annotations_unwind (Lisp_Object arg)
4656 Vwrite_region_annotation_buffers = arg;
4659 /* Decide the coding-system to encode the data with. */
4661 static Lisp_Object
4662 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4663 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4664 struct coding_system *coding)
4666 Lisp_Object val;
4667 Lisp_Object eol_parent = Qnil;
4669 if (auto_saving
4670 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4671 BVAR (current_buffer, auto_save_file_name))))
4673 val = Qutf_8_emacs;
4674 eol_parent = Qunix;
4676 else if (!NILP (Vcoding_system_for_write))
4678 val = Vcoding_system_for_write;
4679 if (coding_system_require_warning
4680 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4681 /* Confirm that VAL can surely encode the current region. */
4682 val = call5 (Vselect_safe_coding_system_function,
4683 start, end, list2 (Qt, val),
4684 Qnil, filename);
4686 else
4688 /* If the variable `buffer-file-coding-system' is set locally,
4689 it means that the file was read with some kind of code
4690 conversion or the variable is explicitly set by users. We
4691 had better write it out with the same coding system even if
4692 `enable-multibyte-characters' is nil.
4694 If it is not set locally, we anyway have to convert EOL
4695 format if the default value of `buffer-file-coding-system'
4696 tells that it is not Unix-like (LF only) format. */
4697 bool using_default_coding = 0;
4698 bool force_raw_text = 0;
4700 val = BVAR (current_buffer, buffer_file_coding_system);
4701 if (NILP (val)
4702 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4704 val = Qnil;
4705 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4706 force_raw_text = 1;
4709 if (NILP (val))
4711 /* Check file-coding-system-alist. */
4712 Lisp_Object coding_systems
4713 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4714 filename, append, visit, lockname);
4715 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4716 val = XCDR (coding_systems);
4719 if (NILP (val))
4721 /* If we still have not decided a coding system, use the
4722 current buffer's value of buffer-file-coding-system. */
4723 val = BVAR (current_buffer, buffer_file_coding_system);
4724 using_default_coding = 1;
4727 if (! NILP (val) && ! force_raw_text)
4729 Lisp_Object spec, attrs;
4731 CHECK_CODING_SYSTEM (val);
4732 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4733 attrs = AREF (spec, 0);
4734 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4735 force_raw_text = 1;
4738 if (!force_raw_text
4739 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4741 /* Confirm that VAL can surely encode the current region. */
4742 val = call5 (Vselect_safe_coding_system_function,
4743 start, end, val, Qnil, filename);
4744 /* As the function specified by select-safe-coding-system-function
4745 is out of our control, make sure we are not fed by bogus
4746 values. */
4747 if (!NILP (val))
4748 CHECK_CODING_SYSTEM (val);
4751 /* If the decided coding-system doesn't specify end-of-line
4752 format, we use that of `buffer-file-coding-system'. */
4753 if (! using_default_coding)
4755 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4757 if (! NILP (dflt))
4758 val = coding_inherit_eol_type (val, dflt);
4761 /* If we decide not to encode text, use `raw-text' or one of its
4762 subsidiaries. */
4763 if (force_raw_text)
4764 val = raw_text_coding_system (val);
4767 val = coding_inherit_eol_type (val, eol_parent);
4768 setup_coding_system (val, coding);
4770 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4771 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4772 return val;
4775 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4776 "r\nFWrite region to file: \ni\ni\ni\np",
4777 doc: /* Write current region into specified file.
4778 When called from a program, requires three arguments:
4779 START, END and FILENAME. START and END are normally buffer positions
4780 specifying the part of the buffer to write.
4781 If START is nil, that means to use the entire buffer contents; END is
4782 ignored.
4783 If START is a string, then output that string to the file
4784 instead of any buffer contents; END is ignored.
4786 Optional fourth argument APPEND if non-nil means
4787 append to existing file contents (if any). If it is a number,
4788 seek to that offset in the file before writing.
4789 Optional fifth argument VISIT, if t or a string, means
4790 set the last-save-file-modtime of buffer to this file's modtime
4791 and mark buffer not modified.
4792 If VISIT is a string, it is a second file name;
4793 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4794 VISIT is also the file name to lock and unlock for clash detection.
4795 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4796 do not display the \"Wrote file\" message.
4797 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4798 use for locking and unlocking, overriding FILENAME and VISIT.
4799 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4800 for an existing file with the same name. If MUSTBENEW is `excl',
4801 that means to get an error if the file already exists; never overwrite.
4802 If MUSTBENEW is neither nil nor `excl', that means ask for
4803 confirmation before overwriting, but do go ahead and overwrite the file
4804 if the user confirms.
4806 This does code conversion according to the value of
4807 `coding-system-for-write', `buffer-file-coding-system', or
4808 `file-coding-system-alist', and sets the variable
4809 `last-coding-system-used' to the coding system actually used.
4811 This calls `write-region-annotate-functions' at the start, and
4812 `write-region-post-annotation-function' at the end. */)
4813 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4814 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4816 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4817 -1);
4820 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4821 descriptor for FILENAME, so do not open or close FILENAME. */
4823 Lisp_Object
4824 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4825 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4826 Lisp_Object mustbenew, int desc)
4828 int open_flags;
4829 int mode;
4830 off_t offset UNINIT;
4831 bool open_and_close_file = desc < 0;
4832 bool ok;
4833 int save_errno = 0;
4834 const char *fn;
4835 struct stat st;
4836 struct timespec modtime;
4837 ptrdiff_t count = SPECPDL_INDEX ();
4838 ptrdiff_t count1 UNINIT;
4839 Lisp_Object handler;
4840 Lisp_Object visit_file;
4841 Lisp_Object annotations;
4842 Lisp_Object encoded_filename;
4843 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4844 bool quietly = !NILP (visit);
4845 bool file_locked = 0;
4846 struct buffer *given_buffer;
4847 struct coding_system coding;
4849 if (current_buffer->base_buffer && visiting)
4850 error ("Cannot do file visiting in an indirect buffer");
4852 if (!NILP (start) && !STRINGP (start))
4853 validate_region (&start, &end);
4855 visit_file = Qnil;
4857 filename = Fexpand_file_name (filename, Qnil);
4859 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4860 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4862 if (STRINGP (visit))
4863 visit_file = Fexpand_file_name (visit, Qnil);
4864 else
4865 visit_file = filename;
4867 if (NILP (lockname))
4868 lockname = visit_file;
4870 annotations = Qnil;
4872 /* If the file name has special constructs in it,
4873 call the corresponding file handler. */
4874 handler = Ffind_file_name_handler (filename, Qwrite_region);
4875 /* If FILENAME has no handler, see if VISIT has one. */
4876 if (NILP (handler) && STRINGP (visit))
4877 handler = Ffind_file_name_handler (visit, Qwrite_region);
4879 if (!NILP (handler))
4881 Lisp_Object val;
4882 val = call6 (handler, Qwrite_region, start, end,
4883 filename, append, visit);
4885 if (visiting)
4887 SAVE_MODIFF = MODIFF;
4888 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4889 bset_filename (current_buffer, visit_file);
4892 return val;
4895 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4897 /* Special kludge to simplify auto-saving. */
4898 if (NILP (start))
4900 /* Do it later, so write-region-annotate-function can work differently
4901 if we save "the buffer" vs "a region".
4902 This is useful in tar-mode. --Stef
4903 XSETFASTINT (start, BEG);
4904 XSETFASTINT (end, Z); */
4905 Fwiden ();
4908 record_unwind_protect (build_annotations_unwind,
4909 Vwrite_region_annotation_buffers);
4910 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4912 given_buffer = current_buffer;
4914 if (!STRINGP (start))
4916 annotations = build_annotations (start, end);
4918 if (current_buffer != given_buffer)
4920 XSETFASTINT (start, BEGV);
4921 XSETFASTINT (end, ZV);
4925 if (NILP (start))
4927 XSETFASTINT (start, BEGV);
4928 XSETFASTINT (end, ZV);
4931 /* Decide the coding-system to encode the data with.
4932 We used to make this choice before calling build_annotations, but that
4933 leads to problems when a write-annotate-function takes care of
4934 unsavable chars (as was the case with X-Symbol). */
4935 Vlast_coding_system_used
4936 = choose_write_coding_system (start, end, filename,
4937 append, visit, lockname, &coding);
4939 if (open_and_close_file && !auto_saving)
4941 lock_file (lockname);
4942 file_locked = 1;
4945 encoded_filename = ENCODE_FILE (filename);
4946 fn = SSDATA (encoded_filename);
4947 open_flags = O_WRONLY | O_CREAT;
4948 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4949 if (NUMBERP (append))
4950 offset = file_offset (append);
4951 else if (!NILP (append))
4952 open_flags |= O_APPEND;
4953 #ifdef DOS_NT
4954 mode = S_IREAD | S_IWRITE;
4955 #else
4956 mode = auto_saving ? auto_save_mode_bits : 0666;
4957 #endif
4959 if (open_and_close_file)
4961 desc = emacs_open (fn, open_flags, mode);
4962 if (desc < 0)
4964 int open_errno = errno;
4965 if (file_locked)
4966 unlock_file (lockname);
4967 report_file_errno ("Opening output file", filename, open_errno);
4970 count1 = SPECPDL_INDEX ();
4971 record_unwind_protect_int (close_file_unwind, desc);
4974 if (NUMBERP (append))
4976 off_t ret = lseek (desc, offset, SEEK_SET);
4977 if (ret < 0)
4979 int lseek_errno = errno;
4980 if (file_locked)
4981 unlock_file (lockname);
4982 report_file_errno ("Lseek error", filename, lseek_errno);
4986 immediate_quit = 1;
4988 if (STRINGP (start))
4989 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4990 else if (XINT (start) != XINT (end))
4991 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4992 &annotations, &coding);
4993 else
4995 /* If file was empty, still need to write the annotations. */
4996 coding.mode |= CODING_MODE_LAST_BLOCK;
4997 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4999 save_errno = errno;
5001 if (ok && CODING_REQUIRE_FLUSHING (&coding)
5002 && !(coding.mode & CODING_MODE_LAST_BLOCK))
5004 /* We have to flush out a data. */
5005 coding.mode |= CODING_MODE_LAST_BLOCK;
5006 ok = e_write (desc, Qnil, 1, 1, &coding);
5007 save_errno = errno;
5010 immediate_quit = 0;
5012 /* fsync is not crucial for temporary files. Nor for auto-save
5013 files, since they might lose some work anyway. */
5014 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
5016 /* Transfer data and metadata to disk, retrying if interrupted.
5017 fsync can report a write failure here, e.g., due to disk full
5018 under NFS. But ignore EINVAL, which means fsync is not
5019 supported on this file. */
5020 while (fsync (desc) != 0)
5021 if (errno != EINTR)
5023 if (errno != EINVAL)
5024 ok = 0, save_errno = errno;
5025 break;
5029 modtime = invalid_timespec ();
5030 if (visiting)
5032 if (fstat (desc, &st) == 0)
5033 modtime = get_stat_mtime (&st);
5034 else
5035 ok = 0, save_errno = errno;
5038 if (open_and_close_file)
5040 /* NFS can report a write failure now. */
5041 if (emacs_close (desc) < 0)
5042 ok = 0, save_errno = errno;
5044 /* Discard the unwind protect for close_file_unwind. */
5045 specpdl_ptr = specpdl + count1;
5048 /* Some file systems have a bug where st_mtime is not updated
5049 properly after a write. For example, CIFS might not see the
5050 st_mtime change until after the file is opened again.
5052 Attempt to detect this file system bug, and update MODTIME to the
5053 newer st_mtime if the bug appears to be present. This introduces
5054 a race condition, so to avoid most instances of the race condition
5055 on non-buggy file systems, skip this check if the most recently
5056 encountered non-buggy file system was the current file system.
5058 A race condition can occur if some other process modifies the
5059 file between the fstat above and the fstat below, but the race is
5060 unlikely and a similar race between the last write and the fstat
5061 above cannot possibly be closed anyway. */
5063 if (timespec_valid_p (modtime)
5064 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
5066 int desc1 = emacs_open (fn, O_WRONLY, 0);
5067 if (desc1 >= 0)
5069 struct stat st1;
5070 if (fstat (desc1, &st1) == 0
5071 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
5073 /* Use the heuristic if it appears to be valid. With neither
5074 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
5075 file, the time stamp won't change. Also, some non-POSIX
5076 systems don't update an empty file's time stamp when
5077 truncating it. Finally, file systems with 100 ns or worse
5078 resolution sometimes seem to have bugs: on a system with ns
5079 resolution, checking ns % 100 incorrectly avoids the heuristic
5080 1% of the time, but the problem should be temporary as we will
5081 try again on the next time stamp. */
5082 bool use_heuristic
5083 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
5084 && st.st_size != 0
5085 && modtime.tv_nsec % 100 != 0);
5087 struct timespec modtime1 = get_stat_mtime (&st1);
5088 if (use_heuristic
5089 && timespec_cmp (modtime, modtime1) == 0
5090 && st.st_size == st1.st_size)
5092 timestamp_file_system = st.st_dev;
5093 valid_timestamp_file_system = 1;
5095 else
5097 st.st_size = st1.st_size;
5098 modtime = modtime1;
5101 emacs_close (desc1);
5105 /* Call write-region-post-annotation-function. */
5106 while (CONSP (Vwrite_region_annotation_buffers))
5108 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5109 if (!NILP (Fbuffer_live_p (buf)))
5111 Fset_buffer (buf);
5112 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5113 call0 (Vwrite_region_post_annotation_function);
5115 Vwrite_region_annotation_buffers
5116 = XCDR (Vwrite_region_annotation_buffers);
5119 unbind_to (count, Qnil);
5121 if (file_locked)
5122 unlock_file (lockname);
5124 /* Do this before reporting IO error
5125 to avoid a "file has changed on disk" warning on
5126 next attempt to save. */
5127 if (timespec_valid_p (modtime))
5129 current_buffer->modtime = modtime;
5130 current_buffer->modtime_size = st.st_size;
5133 if (! ok)
5134 report_file_errno ("Write error", filename, save_errno);
5136 if (visiting)
5138 SAVE_MODIFF = MODIFF;
5139 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5140 bset_filename (current_buffer, visit_file);
5141 update_mode_lines = 14;
5143 else if (quietly)
5145 if (auto_saving
5146 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5147 BVAR (current_buffer, auto_save_file_name))))
5148 SAVE_MODIFF = MODIFF;
5150 return Qnil;
5153 if (!auto_saving && !noninteractive)
5154 message_with_string ((NUMBERP (append)
5155 ? "Updated %s"
5156 : ! NILP (append)
5157 ? "Added to %s"
5158 : "Wrote %s"),
5159 visit_file, 1);
5161 return Qnil;
5164 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5165 doc: /* Return t if (car A) is numerically less than (car B). */)
5166 (Lisp_Object a, Lisp_Object b)
5168 return CALLN (Flss, Fcar (a), Fcar (b));
5171 /* Build the complete list of annotations appropriate for writing out
5172 the text between START and END, by calling all the functions in
5173 write-region-annotate-functions and merging the lists they return.
5174 If one of these functions switches to a different buffer, we assume
5175 that buffer contains altered text. Therefore, the caller must
5176 make sure to restore the current buffer in all cases,
5177 as save-excursion would do. */
5179 static Lisp_Object
5180 build_annotations (Lisp_Object start, Lisp_Object end)
5182 Lisp_Object annotations;
5183 Lisp_Object p, res;
5184 Lisp_Object original_buffer;
5185 int i;
5186 bool used_global = false;
5188 XSETBUFFER (original_buffer, current_buffer);
5190 annotations = Qnil;
5191 p = Vwrite_region_annotate_functions;
5192 while (CONSP (p))
5194 struct buffer *given_buffer = current_buffer;
5195 if (EQ (Qt, XCAR (p)) && !used_global)
5196 { /* Use the global value of the hook. */
5197 used_global = true;
5198 p = CALLN (Fappend,
5199 Fdefault_value (Qwrite_region_annotate_functions),
5200 XCDR (p));
5201 continue;
5203 Vwrite_region_annotations_so_far = annotations;
5204 res = call2 (XCAR (p), start, end);
5205 /* If the function makes a different buffer current,
5206 assume that means this buffer contains altered text to be output.
5207 Reset START and END from the buffer bounds
5208 and discard all previous annotations because they should have
5209 been dealt with by this function. */
5210 if (current_buffer != given_buffer)
5212 Vwrite_region_annotation_buffers
5213 = Fcons (Fcurrent_buffer (),
5214 Vwrite_region_annotation_buffers);
5215 XSETFASTINT (start, BEGV);
5216 XSETFASTINT (end, ZV);
5217 annotations = Qnil;
5219 Flength (res); /* Check basic validity of return value */
5220 annotations = merge (annotations, res, Qcar_less_than_car);
5221 p = XCDR (p);
5224 /* Now do the same for annotation functions implied by the file-format */
5225 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5226 p = BVAR (current_buffer, auto_save_file_format);
5227 else
5228 p = BVAR (current_buffer, file_format);
5229 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5231 struct buffer *given_buffer = current_buffer;
5233 Vwrite_region_annotations_so_far = annotations;
5235 /* Value is either a list of annotations or nil if the function
5236 has written annotations to a temporary buffer, which is now
5237 current. */
5238 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5239 original_buffer, make_number (i));
5240 if (current_buffer != given_buffer)
5242 XSETFASTINT (start, BEGV);
5243 XSETFASTINT (end, ZV);
5244 annotations = Qnil;
5247 if (CONSP (res))
5248 annotations = merge (annotations, res, Qcar_less_than_car);
5251 return annotations;
5255 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5256 If STRING is nil, POS is the character position in the current buffer.
5257 Intersperse with them the annotations from *ANNOT
5258 which fall within the range of POS to POS + NCHARS,
5259 each at its appropriate position.
5261 We modify *ANNOT by discarding elements as we use them up.
5263 Return true if successful. */
5265 static bool
5266 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5267 ptrdiff_t nchars, Lisp_Object *annot,
5268 struct coding_system *coding)
5270 Lisp_Object tem;
5271 ptrdiff_t nextpos;
5272 ptrdiff_t lastpos = pos + nchars;
5274 while (NILP (*annot) || CONSP (*annot))
5276 tem = Fcar_safe (Fcar (*annot));
5277 nextpos = pos - 1;
5278 if (INTEGERP (tem))
5279 nextpos = XFASTINT (tem);
5281 /* If there are no more annotations in this range,
5282 output the rest of the range all at once. */
5283 if (! (nextpos >= pos && nextpos <= lastpos))
5284 return e_write (desc, string, pos, lastpos, coding);
5286 /* Output buffer text up to the next annotation's position. */
5287 if (nextpos > pos)
5289 if (!e_write (desc, string, pos, nextpos, coding))
5290 return 0;
5291 pos = nextpos;
5293 /* Output the annotation. */
5294 tem = Fcdr (Fcar (*annot));
5295 if (STRINGP (tem))
5297 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5298 return 0;
5300 *annot = Fcdr (*annot);
5302 return 1;
5305 /* Maximum number of characters that the next
5306 function encodes per one loop iteration. */
5308 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5310 /* Write text in the range START and END into descriptor DESC,
5311 encoding them with coding system CODING. If STRING is nil, START
5312 and END are character positions of the current buffer, else they
5313 are indexes to the string STRING. Return true if successful. */
5315 static bool
5316 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5317 struct coding_system *coding)
5319 if (STRINGP (string))
5321 start = 0;
5322 end = SCHARS (string);
5325 /* We used to have a code for handling selective display here. But,
5326 now it is handled within encode_coding. */
5328 while (start < end)
5330 if (STRINGP (string))
5332 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5333 if (CODING_REQUIRE_ENCODING (coding))
5335 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5337 /* Avoid creating huge Lisp string in encode_coding_object. */
5338 if (nchars == E_WRITE_MAX)
5339 coding->raw_destination = 1;
5341 encode_coding_object
5342 (coding, string, start, string_char_to_byte (string, start),
5343 start + nchars, string_char_to_byte (string, start + nchars),
5344 Qt);
5346 else
5348 coding->dst_object = string;
5349 coding->consumed_char = SCHARS (string);
5350 coding->produced = SBYTES (string);
5353 else
5355 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5356 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5358 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5359 if (CODING_REQUIRE_ENCODING (coding))
5361 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5363 /* Likewise. */
5364 if (nchars == E_WRITE_MAX)
5365 coding->raw_destination = 1;
5367 encode_coding_object
5368 (coding, Fcurrent_buffer (), start, start_byte,
5369 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5371 else
5373 coding->dst_object = Qnil;
5374 coding->dst_pos_byte = start_byte;
5375 if (start >= GPT || end <= GPT)
5377 coding->consumed_char = end - start;
5378 coding->produced = end_byte - start_byte;
5380 else
5382 coding->consumed_char = GPT - start;
5383 coding->produced = GPT_BYTE - start_byte;
5388 if (coding->produced > 0)
5390 char *buf = (coding->raw_destination ? (char *) coding->destination
5391 : (STRINGP (coding->dst_object)
5392 ? SSDATA (coding->dst_object)
5393 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5394 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5396 if (coding->raw_destination)
5398 /* We're responsible for freeing this, see
5399 encode_coding_object to check why. */
5400 xfree (coding->destination);
5401 coding->raw_destination = 0;
5403 if (coding->produced)
5404 return 0;
5406 start += coding->consumed_char;
5409 return 1;
5412 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5413 Sverify_visited_file_modtime, 0, 1, 0,
5414 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5415 This means that the file has not been changed since it was visited or saved.
5416 If BUF is omitted or nil, it defaults to the current buffer.
5417 See Info node `(elisp)Modification Time' for more details. */)
5418 (Lisp_Object buf)
5420 struct buffer *b = decode_buffer (buf);
5421 struct stat st;
5422 Lisp_Object handler;
5423 Lisp_Object filename;
5424 struct timespec mtime;
5426 if (!STRINGP (BVAR (b, filename))) return Qt;
5427 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5429 /* If the file name has special constructs in it,
5430 call the corresponding file handler. */
5431 handler = Ffind_file_name_handler (BVAR (b, filename),
5432 Qverify_visited_file_modtime);
5433 if (!NILP (handler))
5434 return call2 (handler, Qverify_visited_file_modtime, buf);
5436 filename = ENCODE_FILE (BVAR (b, filename));
5438 mtime = (stat (SSDATA (filename), &st) == 0
5439 ? get_stat_mtime (&st)
5440 : time_error_value (errno));
5441 if (timespec_cmp (mtime, b->modtime) == 0
5442 && (b->modtime_size < 0
5443 || st.st_size == b->modtime_size))
5444 return Qt;
5445 return Qnil;
5448 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5449 Svisited_file_modtime, 0, 0, 0,
5450 doc: /* Return the current buffer's recorded visited file modification time.
5451 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5452 `file-attributes' returns. If the current buffer has no recorded file
5453 modification time, this function returns 0. If the visited file
5454 doesn't exist, return -1.
5455 See Info node `(elisp)Modification Time' for more details. */)
5456 (void)
5458 int ns = current_buffer->modtime.tv_nsec;
5459 if (ns < 0)
5460 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5461 return make_lisp_time (current_buffer->modtime);
5464 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5465 Sset_visited_file_modtime, 0, 1, 0,
5466 doc: /* Update buffer's recorded modification time from the visited file's time.
5467 Useful if the buffer was not read from the file normally
5468 or if the file itself has been changed for some known benign reason.
5469 An argument specifies the modification time value to use
5470 \(instead of that of the visited file), in the form of a list
5471 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5472 `visited-file-modtime'. */)
5473 (Lisp_Object time_flag)
5475 if (!NILP (time_flag))
5477 struct timespec mtime;
5478 if (INTEGERP (time_flag))
5480 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5481 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5483 else
5484 mtime = lisp_time_argument (time_flag);
5486 current_buffer->modtime = mtime;
5487 current_buffer->modtime_size = -1;
5489 else
5491 register Lisp_Object filename;
5492 struct stat st;
5493 Lisp_Object handler;
5495 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5497 /* If the file name has special constructs in it,
5498 call the corresponding file handler. */
5499 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5500 if (!NILP (handler))
5501 /* The handler can find the file name the same way we did. */
5502 return call2 (handler, Qset_visited_file_modtime, Qnil);
5504 filename = ENCODE_FILE (filename);
5506 if (stat (SSDATA (filename), &st) >= 0)
5508 current_buffer->modtime = get_stat_mtime (&st);
5509 current_buffer->modtime_size = st.st_size;
5513 return Qnil;
5516 static Lisp_Object
5517 auto_save_error (Lisp_Object error_val)
5519 auto_save_error_occurred = 1;
5521 ring_bell (XFRAME (selected_frame));
5523 AUTO_STRING (format, "Auto-saving %s: %s");
5524 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5525 Ferror_message_string (error_val));
5526 call3 (intern ("display-warning"),
5527 intern ("auto-save"), msg, intern ("error"));
5529 return Qnil;
5532 static Lisp_Object
5533 auto_save_1 (void)
5535 struct stat st;
5536 Lisp_Object modes;
5538 auto_save_mode_bits = 0666;
5540 /* Get visited file's mode to become the auto save file's mode. */
5541 if (! NILP (BVAR (current_buffer, filename)))
5543 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5544 /* But make sure we can overwrite it later! */
5545 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5546 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5547 INTEGERP (modes))
5548 /* Remote files don't cooperate with stat. */
5549 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5552 return
5553 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5554 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5555 Qnil, Qnil);
5558 struct auto_save_unwind
5560 FILE *stream;
5561 bool auto_raise;
5564 static void
5565 do_auto_save_unwind (void *arg)
5567 struct auto_save_unwind *p = arg;
5568 FILE *stream = p->stream;
5569 minibuffer_auto_raise = p->auto_raise;
5570 auto_saving = 0;
5571 if (stream != NULL)
5573 block_input ();
5574 fclose (stream);
5575 unblock_input ();
5579 static Lisp_Object
5580 do_auto_save_make_dir (Lisp_Object dir)
5582 Lisp_Object result;
5584 auto_saving_dir_umask = 077;
5585 result = call2 (Qmake_directory, dir, Qt);
5586 auto_saving_dir_umask = 0;
5587 return result;
5590 static Lisp_Object
5591 do_auto_save_eh (Lisp_Object ignore)
5593 auto_saving_dir_umask = 0;
5594 return Qnil;
5597 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5598 doc: /* Auto-save all buffers that need it.
5599 This is all buffers that have auto-saving enabled
5600 and are changed since last auto-saved.
5601 Auto-saving writes the buffer into a file
5602 so that your editing is not lost if the system crashes.
5603 This file is not the file you visited; that changes only when you save.
5604 Normally we run the normal hook `auto-save-hook' before saving.
5606 A non-nil NO-MESSAGE argument means do not print any message if successful.
5607 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5608 (Lisp_Object no_message, Lisp_Object current_only)
5610 struct buffer *old = current_buffer, *b;
5611 Lisp_Object tail, buf, hook;
5612 bool auto_saved = 0;
5613 int do_handled_files;
5614 Lisp_Object oquit;
5615 FILE *stream = NULL;
5616 ptrdiff_t count = SPECPDL_INDEX ();
5617 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5618 bool old_message_p = 0;
5619 struct auto_save_unwind auto_save_unwind;
5621 if (max_specpdl_size < specpdl_size + 40)
5622 max_specpdl_size = specpdl_size + 40;
5624 if (minibuf_level)
5625 no_message = Qt;
5627 if (NILP (no_message))
5629 old_message_p = push_message ();
5630 record_unwind_protect_void (pop_message_unwind);
5633 /* Ordinarily don't quit within this function,
5634 but don't make it impossible to quit (in case we get hung in I/O). */
5635 oquit = Vquit_flag;
5636 Vquit_flag = Qnil;
5638 hook = intern ("auto-save-hook");
5639 safe_run_hooks (hook);
5641 if (STRINGP (Vauto_save_list_file_name))
5643 Lisp_Object listfile;
5645 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5647 /* Don't try to create the directory when shutting down Emacs,
5648 because creating the directory might signal an error, and
5649 that would leave Emacs in a strange state. */
5650 if (!NILP (Vrun_hooks))
5652 Lisp_Object dir;
5653 dir = Ffile_name_directory (listfile);
5654 if (NILP (Ffile_directory_p (dir)))
5655 internal_condition_case_1 (do_auto_save_make_dir,
5656 dir, Qt,
5657 do_auto_save_eh);
5660 stream = emacs_fopen (SSDATA (listfile), "w");
5663 auto_save_unwind.stream = stream;
5664 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5665 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5666 minibuffer_auto_raise = 0;
5667 auto_saving = 1;
5668 auto_save_error_occurred = 0;
5670 /* On first pass, save all files that don't have handlers.
5671 On second pass, save all files that do have handlers.
5673 If Emacs is crashing, the handlers may tweak what is causing
5674 Emacs to crash in the first place, and it would be a shame if
5675 Emacs failed to autosave perfectly ordinary files because it
5676 couldn't handle some ange-ftp'd file. */
5678 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5679 FOR_EACH_LIVE_BUFFER (tail, buf)
5681 b = XBUFFER (buf);
5683 /* Record all the buffers that have auto save mode
5684 in the special file that lists them. For each of these buffers,
5685 Record visited name (if any) and auto save name. */
5686 if (STRINGP (BVAR (b, auto_save_file_name))
5687 && stream != NULL && do_handled_files == 0)
5689 block_input ();
5690 if (!NILP (BVAR (b, filename)))
5692 fwrite (SDATA (BVAR (b, filename)), 1,
5693 SBYTES (BVAR (b, filename)), stream);
5695 putc ('\n', stream);
5696 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5697 SBYTES (BVAR (b, auto_save_file_name)), stream);
5698 putc ('\n', stream);
5699 unblock_input ();
5702 if (!NILP (current_only)
5703 && b != current_buffer)
5704 continue;
5706 /* Don't auto-save indirect buffers.
5707 The base buffer takes care of it. */
5708 if (b->base_buffer)
5709 continue;
5711 /* Check for auto save enabled
5712 and file changed since last auto save
5713 and file changed since last real save. */
5714 if (STRINGP (BVAR (b, auto_save_file_name))
5715 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5716 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5717 /* -1 means we've turned off autosaving for a while--see below. */
5718 && XINT (BVAR (b, save_length)) >= 0
5719 && (do_handled_files
5720 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5721 Qwrite_region))))
5723 struct timespec before_time = current_timespec ();
5724 struct timespec after_time;
5726 /* If we had a failure, don't try again for 20 minutes. */
5727 if (b->auto_save_failure_time > 0
5728 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5729 continue;
5731 set_buffer_internal (b);
5732 if (NILP (Vauto_save_include_big_deletions)
5733 && (XFASTINT (BVAR (b, save_length)) * 10
5734 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5735 /* A short file is likely to change a large fraction;
5736 spare the user annoying messages. */
5737 && XFASTINT (BVAR (b, save_length)) > 5000
5738 /* These messages are frequent and annoying for `*mail*'. */
5739 && !EQ (BVAR (b, filename), Qnil)
5740 && NILP (no_message))
5742 /* It has shrunk too much; turn off auto-saving here. */
5743 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5744 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5745 BVAR (b, name), 1);
5746 minibuffer_auto_raise = 0;
5747 /* Turn off auto-saving until there's a real save,
5748 and prevent any more warnings. */
5749 XSETINT (BVAR (b, save_length), -1);
5750 Fsleep_for (make_number (1), Qnil);
5751 continue;
5753 if (!auto_saved && NILP (no_message))
5754 message1 ("Auto-saving...");
5755 internal_condition_case (auto_save_1, Qt, auto_save_error);
5756 auto_saved = 1;
5757 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5758 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5759 set_buffer_internal (old);
5761 after_time = current_timespec ();
5763 /* If auto-save took more than 60 seconds,
5764 assume it was an NFS failure that got a timeout. */
5765 if (after_time.tv_sec - before_time.tv_sec > 60)
5766 b->auto_save_failure_time = after_time.tv_sec;
5770 /* Prevent another auto save till enough input events come in. */
5771 record_auto_save ();
5773 if (auto_saved && NILP (no_message))
5775 if (old_message_p)
5777 /* If we are going to restore an old message,
5778 give time to read ours. */
5779 sit_for (make_number (1), 0, 0);
5780 restore_message ();
5782 else if (!auto_save_error_occurred)
5783 /* Don't overwrite the error message if an error occurred.
5784 If we displayed a message and then restored a state
5785 with no message, leave a "done" message on the screen. */
5786 message1 ("Auto-saving...done");
5789 Vquit_flag = oquit;
5791 /* This restores the message-stack status. */
5792 unbind_to (count, Qnil);
5793 return Qnil;
5796 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5797 Sset_buffer_auto_saved, 0, 0, 0,
5798 doc: /* Mark current buffer as auto-saved with its current text.
5799 No auto-save file will be written until the buffer changes again. */)
5800 (void)
5802 /* FIXME: This should not be called in indirect buffers, since
5803 they're not autosaved. */
5804 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5805 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5806 current_buffer->auto_save_failure_time = 0;
5807 return Qnil;
5810 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5811 Sclear_buffer_auto_save_failure, 0, 0, 0,
5812 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5813 (void)
5815 current_buffer->auto_save_failure_time = 0;
5816 return Qnil;
5819 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5820 0, 0, 0,
5821 doc: /* Return t if current buffer has been auto-saved recently.
5822 More precisely, if it has been auto-saved since last read from or saved
5823 in the visited file. If the buffer has no visited file,
5824 then any auto-save counts as "recent". */)
5825 (void)
5827 /* FIXME: maybe we should return nil for indirect buffers since
5828 they're never autosaved. */
5829 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5832 /* Reading and completing file names. */
5834 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5835 Snext_read_file_uses_dialog_p, 0, 0, 0,
5836 doc: /* Return t if a call to `read-file-name' will use a dialog.
5837 The return value is only relevant for a call to `read-file-name' that happens
5838 before any other event (mouse or keypress) is handled. */)
5839 (void)
5841 #if (defined USE_GTK || defined USE_MOTIF \
5842 || defined HAVE_NS || defined HAVE_NTGUI)
5843 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5844 && use_dialog_box
5845 && use_file_dialog
5846 && window_system_available (SELECTED_FRAME ()))
5847 return Qt;
5848 #endif
5849 return Qnil;
5853 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5854 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5855 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5856 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5857 it to text mode.
5859 As a side effect, this function flushes any pending STREAM's data.
5861 Value is the previous value of STREAM's I/O mode, nil for text mode,
5862 non-nil for binary mode.
5864 On MS-Windows and MS-DOS, binary mode is needed to read or write
5865 arbitrary binary data, and for disabling translation between CR-LF
5866 pairs and a single newline character. Examples include generation
5867 of text files with Unix-style end-of-line format using `princ' in
5868 batch mode, with standard output redirected to a file.
5870 On Posix systems, this function always returns non-nil, and has no
5871 effect except for flushing STREAM's data. */)
5872 (Lisp_Object stream, Lisp_Object mode)
5874 FILE *fp = NULL;
5875 int binmode;
5877 CHECK_SYMBOL (stream);
5878 if (EQ (stream, Qstdin))
5879 fp = stdin;
5880 else if (EQ (stream, Qstdout))
5881 fp = stdout;
5882 else if (EQ (stream, Qstderr))
5883 fp = stderr;
5884 else
5885 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5887 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5888 if (fp != stdin)
5889 fflush (fp);
5891 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5894 void
5895 init_fileio (void)
5897 realmask = umask (0);
5898 umask (realmask);
5900 valid_timestamp_file_system = 0;
5902 /* fsync can be a significant performance hit. Often it doesn't
5903 suffice to make the file-save operation survive a crash. For
5904 batch scripts, which are typically part of larger shell commands
5905 that don't fsync other files, its effect on performance can be
5906 significant so its utility is particularly questionable.
5907 Hence, for now by default fsync is used only when interactive.
5909 For more on why fsync often fails to work on today's hardware, see:
5910 Zheng M et al. Understanding the robustness of SSDs under power fault.
5911 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5912 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5914 For more on why fsync does not suffice even if it works properly, see:
5915 Roche X. Necessary step(s) to synchronize filename operations on disk.
5916 Austin Group Defect 672, 2013-03-19
5917 http://austingroupbugs.net/view.php?id=672 */
5918 write_region_inhibit_fsync = noninteractive;
5921 void
5922 syms_of_fileio (void)
5924 /* Property name of a file name handler,
5925 which gives a list of operations it handles. */
5926 DEFSYM (Qoperations, "operations");
5928 DEFSYM (Qexpand_file_name, "expand-file-name");
5929 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5930 DEFSYM (Qdirectory_file_name, "directory-file-name");
5931 DEFSYM (Qfile_name_directory, "file-name-directory");
5932 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5933 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5934 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5935 DEFSYM (Qcopy_file, "copy-file");
5936 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5937 DEFSYM (Qmake_directory, "make-directory");
5938 DEFSYM (Qdelete_file, "delete-file");
5939 DEFSYM (Qfile_name_case_insensitive_p, "file-name-case-insensitive-p");
5940 DEFSYM (Qrename_file, "rename-file");
5941 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5942 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5943 DEFSYM (Qfile_exists_p, "file-exists-p");
5944 DEFSYM (Qfile_executable_p, "file-executable-p");
5945 DEFSYM (Qfile_readable_p, "file-readable-p");
5946 DEFSYM (Qfile_writable_p, "file-writable-p");
5947 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5948 DEFSYM (Qaccess_file, "access-file");
5949 DEFSYM (Qfile_directory_p, "file-directory-p");
5950 DEFSYM (Qfile_regular_p, "file-regular-p");
5951 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5952 DEFSYM (Qfile_modes, "file-modes");
5953 DEFSYM (Qset_file_modes, "set-file-modes");
5954 DEFSYM (Qset_file_times, "set-file-times");
5955 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5956 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5957 DEFSYM (Qfile_acl, "file-acl");
5958 DEFSYM (Qset_file_acl, "set-file-acl");
5959 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5960 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5961 DEFSYM (Qwrite_region, "write-region");
5962 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5963 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5965 /* The symbol bound to coding-system-for-read when
5966 insert-file-contents is called for recovering a file. This is not
5967 an actual coding system name, but just an indicator to tell
5968 insert-file-contents to use `emacs-mule' with a special flag for
5969 auto saving and recovering a file. */
5970 DEFSYM (Qauto_save_coding, "auto-save-coding");
5972 DEFSYM (Qfile_name_history, "file-name-history");
5973 Fset (Qfile_name_history, Qnil);
5975 DEFSYM (Qfile_error, "file-error");
5976 DEFSYM (Qfile_already_exists, "file-already-exists");
5977 DEFSYM (Qfile_date_error, "file-date-error");
5978 DEFSYM (Qfile_missing, "file-missing");
5979 DEFSYM (Qfile_notify_error, "file-notify-error");
5980 DEFSYM (Qexcl, "excl");
5982 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5983 doc: /* Coding system for encoding file names.
5984 If it is nil, `default-file-name-coding-system' (which see) is used.
5986 On MS-Windows, the value of this variable is largely ignored if
5987 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5988 behaves as if file names were encoded in `utf-8'. */);
5989 Vfile_name_coding_system = Qnil;
5991 DEFVAR_LISP ("default-file-name-coding-system",
5992 Vdefault_file_name_coding_system,
5993 doc: /* Default coding system for encoding file names.
5994 This variable is used only when `file-name-coding-system' is nil.
5996 This variable is set/changed by the command `set-language-environment'.
5997 User should not set this variable manually,
5998 instead use `file-name-coding-system' to get a constant encoding
5999 of file names regardless of the current language environment.
6001 On MS-Windows, the value of this variable is largely ignored if
6002 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
6003 behaves as if file names were encoded in `utf-8'. */);
6004 Vdefault_file_name_coding_system = Qnil;
6006 /* Lisp functions for translating file formats. */
6007 DEFSYM (Qformat_decode, "format-decode");
6008 DEFSYM (Qformat_annotate_function, "format-annotate-function");
6010 /* Lisp function for setting buffer-file-coding-system and the
6011 multibyteness of the current buffer after inserting a file. */
6012 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
6014 DEFSYM (Qcar_less_than_car, "car-less-than-car");
6016 Fput (Qfile_error, Qerror_conditions,
6017 Fpurecopy (list2 (Qfile_error, Qerror)));
6018 Fput (Qfile_error, Qerror_message,
6019 build_pure_c_string ("File error"));
6021 Fput (Qfile_already_exists, Qerror_conditions,
6022 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
6023 Fput (Qfile_already_exists, Qerror_message,
6024 build_pure_c_string ("File already exists"));
6026 Fput (Qfile_date_error, Qerror_conditions,
6027 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
6028 Fput (Qfile_date_error, Qerror_message,
6029 build_pure_c_string ("Cannot set file date"));
6031 Fput (Qfile_missing, Qerror_conditions,
6032 Fpurecopy (list3 (Qfile_missing, Qfile_error, Qerror)));
6033 Fput (Qfile_missing, Qerror_message,
6034 build_pure_c_string ("File is missing"));
6036 Fput (Qfile_notify_error, Qerror_conditions,
6037 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
6038 Fput (Qfile_notify_error, Qerror_message,
6039 build_pure_c_string ("File notification error"));
6041 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
6042 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
6043 If a file name matches REGEXP, all I/O on that file is done by calling
6044 HANDLER. If a file name matches more than one handler, the handler
6045 whose match starts last in the file name gets precedence. The
6046 function `find-file-name-handler' checks this list for a handler for
6047 its argument.
6049 HANDLER should be a function. The first argument given to it is the
6050 name of the I/O primitive to be handled; the remaining arguments are
6051 the arguments that were passed to that primitive. For example, if you
6052 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
6053 HANDLER is called like this:
6055 (funcall HANDLER \\='file-exists-p FILENAME)
6057 Note that HANDLER must be able to handle all I/O primitives; if it has
6058 nothing special to do for a primitive, it should reinvoke the
6059 primitive to handle the operation \"the usual way\".
6060 See Info node `(elisp)Magic File Names' for more details. */);
6061 Vfile_name_handler_alist = Qnil;
6063 DEFVAR_LISP ("set-auto-coding-function",
6064 Vset_auto_coding_function,
6065 doc: /* If non-nil, a function to call to decide a coding system of file.
6066 Two arguments are passed to this function: the file name
6067 and the length of a file contents following the point.
6068 This function should return a coding system to decode the file contents.
6069 It should check the file name against `auto-coding-alist'.
6070 If no coding system is decided, it should check a coding system
6071 specified in the heading lines with the format:
6072 -*- ... coding: CODING-SYSTEM; ... -*-
6073 or local variable spec of the tailing lines with `coding:' tag. */);
6074 Vset_auto_coding_function = Qnil;
6076 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
6077 doc: /* A list of functions to be called at the end of `insert-file-contents'.
6078 Each is passed one argument, the number of characters inserted,
6079 with point at the start of the inserted text. Each function
6080 should leave point the same, and return the new character count.
6081 If `insert-file-contents' is intercepted by a handler from
6082 `file-name-handler-alist', that handler is responsible for calling the
6083 functions in `after-insert-file-functions' if appropriate. */);
6084 Vafter_insert_file_functions = Qnil;
6086 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
6087 doc: /* A list of functions to be called at the start of `write-region'.
6088 Each is passed two arguments, START and END as for `write-region'.
6089 These are usually two numbers but not always; see the documentation
6090 for `write-region'. The function should return a list of pairs
6091 of the form (POSITION . STRING), consisting of strings to be effectively
6092 inserted at the specified positions of the file being written (1 means to
6093 insert before the first byte written). The POSITIONs must be sorted into
6094 increasing order.
6096 If there are several annotation functions, the lists returned by these
6097 functions are merged destructively. As each annotation function runs,
6098 the variable `write-region-annotations-so-far' contains a list of all
6099 annotations returned by previous annotation functions.
6101 An annotation function can return with a different buffer current.
6102 Doing so removes the annotations returned by previous functions, and
6103 resets START and END to `point-min' and `point-max' of the new buffer.
6105 After `write-region' completes, Emacs calls the function stored in
6106 `write-region-post-annotation-function', once for each buffer that was
6107 current when building the annotations (i.e., at least once), with that
6108 buffer current. */);
6109 Vwrite_region_annotate_functions = Qnil;
6110 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6112 DEFVAR_LISP ("write-region-post-annotation-function",
6113 Vwrite_region_post_annotation_function,
6114 doc: /* Function to call after `write-region' completes.
6115 The function is called with no arguments. If one or more of the
6116 annotation functions in `write-region-annotate-functions' changed the
6117 current buffer, the function stored in this variable is called for
6118 each of those additional buffers as well, in addition to the original
6119 buffer. The relevant buffer is current during each function call. */);
6120 Vwrite_region_post_annotation_function = Qnil;
6121 staticpro (&Vwrite_region_annotation_buffers);
6123 DEFVAR_LISP ("write-region-annotations-so-far",
6124 Vwrite_region_annotations_so_far,
6125 doc: /* When an annotation function is called, this holds the previous annotations.
6126 These are the annotations made by other annotation functions
6127 that were already called. See also `write-region-annotate-functions'. */);
6128 Vwrite_region_annotations_so_far = Qnil;
6130 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6131 doc: /* A list of file name handlers that temporarily should not be used.
6132 This applies only to the operation `inhibit-file-name-operation'. */);
6133 Vinhibit_file_name_handlers = Qnil;
6135 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6136 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6137 Vinhibit_file_name_operation = Qnil;
6139 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6140 doc: /* File name in which we write a list of all auto save file names.
6141 This variable is initialized automatically from `auto-save-list-file-prefix'
6142 shortly after Emacs reads your init file, if you have not yet given it
6143 a non-nil value. */);
6144 Vauto_save_list_file_name = Qnil;
6146 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6147 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6148 Normally auto-save files are written under other names. */);
6149 Vauto_save_visited_file_name = Qnil;
6151 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6152 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6153 If nil, deleting a substantial portion of the text disables auto-save
6154 in the buffer; this is the default behavior, because the auto-save
6155 file is usually more useful if it contains the deleted text. */);
6156 Vauto_save_include_big_deletions = Qnil;
6158 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6159 doc: /* Non-nil means don't call fsync in `write-region'.
6160 This variable affects calls to `write-region' as well as save commands.
6161 Setting this to nil may avoid data loss if the system loses power or
6162 the operating system crashes. By default, it is non-nil in batch mode. */);
6163 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6165 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6166 doc: /* Specifies whether to use the system's trash can.
6167 When non-nil, certain file deletion commands use the function
6168 `move-file-to-trash' instead of deleting files outright.
6169 This includes interactive calls to `delete-file' and
6170 `delete-directory' and the Dired deletion commands. */);
6171 delete_by_moving_to_trash = 0;
6172 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6174 /* Lisp function for moving files to trash. */
6175 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6177 /* Lisp function for recursively copying directories. */
6178 DEFSYM (Qcopy_directory, "copy-directory");
6180 /* Lisp function for recursively deleting directories. */
6181 DEFSYM (Qdelete_directory, "delete-directory");
6183 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6184 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6186 DEFSYM (Qstdin, "stdin");
6187 DEFSYM (Qstdout, "stdout");
6188 DEFSYM (Qstderr, "stderr");
6190 defsubr (&Sfind_file_name_handler);
6191 defsubr (&Sfile_name_directory);
6192 defsubr (&Sfile_name_nondirectory);
6193 defsubr (&Sunhandled_file_name_directory);
6194 defsubr (&Sfile_name_as_directory);
6195 defsubr (&Sdirectory_file_name);
6196 defsubr (&Smake_temp_name);
6197 defsubr (&Sexpand_file_name);
6198 defsubr (&Ssubstitute_in_file_name);
6199 defsubr (&Scopy_file);
6200 defsubr (&Smake_directory_internal);
6201 defsubr (&Sdelete_directory_internal);
6202 defsubr (&Sdelete_file);
6203 defsubr (&Sfile_name_case_insensitive_p);
6204 defsubr (&Srename_file);
6205 defsubr (&Sadd_name_to_file);
6206 defsubr (&Smake_symbolic_link);
6207 defsubr (&Sfile_name_absolute_p);
6208 defsubr (&Sfile_exists_p);
6209 defsubr (&Sfile_executable_p);
6210 defsubr (&Sfile_readable_p);
6211 defsubr (&Sfile_writable_p);
6212 defsubr (&Saccess_file);
6213 defsubr (&Sfile_symlink_p);
6214 defsubr (&Sfile_directory_p);
6215 defsubr (&Sfile_accessible_directory_p);
6216 defsubr (&Sfile_regular_p);
6217 defsubr (&Sfile_modes);
6218 defsubr (&Sset_file_modes);
6219 defsubr (&Sset_file_times);
6220 defsubr (&Sfile_selinux_context);
6221 defsubr (&Sfile_acl);
6222 defsubr (&Sset_file_acl);
6223 defsubr (&Sset_file_selinux_context);
6224 defsubr (&Sset_default_file_modes);
6225 defsubr (&Sdefault_file_modes);
6226 defsubr (&Sfile_newer_than_file_p);
6227 defsubr (&Sinsert_file_contents);
6228 defsubr (&Swrite_region);
6229 defsubr (&Scar_less_than_car);
6230 defsubr (&Sverify_visited_file_modtime);
6231 defsubr (&Svisited_file_modtime);
6232 defsubr (&Sset_visited_file_modtime);
6233 defsubr (&Sdo_auto_save);
6234 defsubr (&Sset_buffer_auto_saved);
6235 defsubr (&Sclear_buffer_auto_save_failure);
6236 defsubr (&Srecent_auto_save_p);
6238 defsubr (&Snext_read_file_uses_dialog_p);
6240 defsubr (&Sset_binary_mode);
6242 #ifdef HAVE_SYNC
6243 defsubr (&Sunix_sync);
6244 #endif