Pacify --enable-gcc-warnings for lib-src/pop.c
[emacs.git] / src / fileio.c
blobbf6bf622abfa1c3d5b8f17476a081fa13e331bad
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 HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #include <errno.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
37 #endif
39 #if USE_ACL && defined HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "composite.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "coding.h"
50 #include "window.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
53 #include "frame.h"
55 #ifdef WINDOWSNT
56 #define NOMINMAX 1
57 #include <windows.h>
58 #include <sys/file.h>
59 #include "w32.h"
60 #endif /* not WINDOWSNT */
62 #ifdef MSDOS
63 #include "msdos.h"
64 #include <sys/param.h>
65 #endif
67 #ifdef DOS_NT
68 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
69 redirector allows the six letters between 'Z' and 'a' as well. */
70 #ifdef MSDOS
71 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
72 #endif
73 #ifdef WINDOWSNT
74 #define IS_DRIVE(x) c_isalpha (x)
75 #endif
76 /* Need to lower-case the drive letter, or else expanded
77 filenames will sometimes compare unequal, because
78 `expand-file-name' doesn't always down-case the drive letter. */
79 #define DRIVE_LETTER(x) c_tolower (x)
80 #endif
82 #include "systime.h"
83 #include <acl.h>
84 #include <allocator.h>
85 #include <careadlinkat.h>
86 #include <stat-time.h>
88 #include <binary-io.h>
90 #ifdef HPUX
91 #include <netio.h>
92 #endif
94 #include "commands.h"
96 /* True during writing of auto-save files. */
97 static bool auto_saving;
99 /* Emacs's real umask. */
100 static mode_t realmask;
102 /* Nonzero umask during creation of auto-save directories. */
103 static mode_t auto_saving_dir_umask;
105 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
106 a new file with the same mode as the original. */
107 static mode_t auto_save_mode_bits;
109 /* Set by auto_save_1 if an error occurred during the last auto-save. */
110 static bool auto_save_error_occurred;
112 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
113 number of a file system where time stamps were observed to to work. */
114 static bool valid_timestamp_file_system;
115 static dev_t timestamp_file_system;
117 /* Each time an annotation function changes the buffer, the new buffer
118 is added here. */
119 static Lisp_Object Vwrite_region_annotation_buffers;
121 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
122 Lisp_Object *, struct coding_system *);
123 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
124 struct coding_system *);
127 /* Return true if FILENAME exists. */
129 static bool
130 check_existing (const char *filename)
132 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
135 /* Return true if file FILENAME exists and can be executed. */
137 static bool
138 check_executable (char *filename)
140 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
143 /* Return true if file FILENAME exists and can be accessed
144 according to AMODE, which should include W_OK.
145 On failure, return false and set errno. */
147 static bool
148 check_writable (const char *filename, int amode)
150 #ifdef MSDOS
151 /* FIXME: an faccessat implementation should be added to the
152 DOS/Windows ports and this #ifdef branch should be removed. */
153 struct stat st;
154 if (stat (filename, &st) < 0)
155 return 0;
156 errno = EPERM;
157 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
158 #else /* not MSDOS */
159 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
160 #ifdef CYGWIN
161 /* faccessat may have returned failure because Cygwin couldn't
162 determine the file's UID or GID; if so, we return success. */
163 if (!res)
165 int faccessat_errno = errno;
166 struct stat st;
167 if (stat (filename, &st) < 0)
168 return 0;
169 res = (st.st_uid == -1 || st.st_gid == -1);
170 errno = faccessat_errno;
172 #endif /* CYGWIN */
173 return res;
174 #endif /* not MSDOS */
177 /* Signal a file-access failure. STRING describes the failure,
178 NAME the file involved, and ERRORNO the errno value.
180 If NAME is neither null nor a pair, package it up as a singleton
181 list before reporting it; this saves report_file_errno's caller the
182 trouble of preserving errno before calling list1. */
184 void
185 report_file_errno (char const *string, Lisp_Object name, int errorno)
187 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
188 char *str = emacs_strerror (errorno);
189 AUTO_STRING (unibyte_str, str);
190 Lisp_Object errstring
191 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
192 Lisp_Object errdata = Fcons (errstring, data);
194 if (errorno == EEXIST)
195 xsignal (Qfile_already_exists, errdata);
196 else
197 xsignal (Qfile_error, Fcons (build_string (string), errdata));
200 /* Signal a file-access failure that set errno. STRING describes the
201 failure, NAME the file involved. When invoking this function, take
202 care to not use arguments such as build_string ("foo") that involve
203 side effects that may set errno. */
205 void
206 report_file_error (char const *string, Lisp_Object name)
208 report_file_errno (string, name, errno);
211 /* Like report_file_error, but reports a file-notify-error instead. */
213 void
214 report_file_notify_error (const char *string, Lisp_Object name)
216 char *str = emacs_strerror (errno);
217 AUTO_STRING (unibyte_str, str);
218 Lisp_Object errstring
219 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
220 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
221 Lisp_Object errdata = Fcons (errstring, data);
223 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
226 void
227 close_file_unwind (int fd)
229 emacs_close (fd);
232 void
233 fclose_unwind (void *arg)
235 FILE *stream = arg;
236 fclose (stream);
239 /* Restore point, having saved it as a marker. */
241 void
242 restore_point_unwind (Lisp_Object location)
244 Fgoto_char (location);
245 unchain_marker (XMARKER (location));
249 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
250 Sfind_file_name_handler, 2, 2, 0,
251 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
252 Otherwise, return nil.
253 A file name is handled if one of the regular expressions in
254 `file-name-handler-alist' matches it.
256 If OPERATION equals `inhibit-file-name-operation', then we ignore
257 any handlers that are members of `inhibit-file-name-handlers',
258 but we still do run any other handlers. This lets handlers
259 use the standard functions without calling themselves recursively. */)
260 (Lisp_Object filename, Lisp_Object operation)
262 /* This function must not munge the match data. */
263 Lisp_Object chain, inhibited_handlers, result;
264 ptrdiff_t pos = -1;
266 result = Qnil;
267 CHECK_STRING (filename);
269 if (EQ (operation, Vinhibit_file_name_operation))
270 inhibited_handlers = Vinhibit_file_name_handlers;
271 else
272 inhibited_handlers = Qnil;
274 for (chain = Vfile_name_handler_alist; CONSP (chain);
275 chain = XCDR (chain))
277 Lisp_Object elt;
278 elt = XCAR (chain);
279 if (CONSP (elt))
281 Lisp_Object string = XCAR (elt);
282 ptrdiff_t match_pos;
283 Lisp_Object handler = XCDR (elt);
284 Lisp_Object operations = Qnil;
286 if (SYMBOLP (handler))
287 operations = Fget (handler, Qoperations);
289 if (STRINGP (string)
290 && (match_pos = fast_string_match (string, filename)) > pos
291 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
293 Lisp_Object tem;
295 handler = XCDR (elt);
296 tem = Fmemq (handler, inhibited_handlers);
297 if (NILP (tem))
299 result = handler;
300 pos = match_pos;
305 QUIT;
307 return result;
310 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
311 1, 1, 0,
312 doc: /* Return the directory component in file name FILENAME.
313 Return nil if FILENAME does not include a directory.
314 Otherwise return a directory name.
315 Given a Unix syntax file name, returns a string ending in slash. */)
316 (Lisp_Object filename)
318 Lisp_Object handler;
320 CHECK_STRING (filename);
322 /* If the file name has special constructs in it,
323 call the corresponding file handler. */
324 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
325 if (!NILP (handler))
327 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
328 filename);
329 return STRINGP (handled_name) ? handled_name : Qnil;
332 char *beg = SSDATA (filename);
333 char const *p = beg + SBYTES (filename);
335 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
336 #ifdef DOS_NT
337 /* only recognize drive specifier at the beginning */
338 && !(p[-1] == ':'
339 /* handle the "/:d:foo" and "/:foo" cases correctly */
340 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
341 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
342 #endif
343 ) p--;
345 if (p == beg)
346 return Qnil;
347 #ifdef DOS_NT
348 /* Expansion of "c:" to drive and default directory. */
349 Lisp_Object tem_fn;
350 USE_SAFE_ALLOCA;
351 SAFE_ALLOCA_STRING (beg, filename);
352 p = beg + (p - SSDATA (filename));
354 if (p[-1] == ':')
356 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
357 char *res = alloca (MAXPATHLEN + 1);
358 char *r = res;
360 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
362 memcpy (res, beg, 2);
363 beg += 2;
364 r += 2;
367 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
369 size_t l = strlen (res);
371 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
372 strcat (res, "/");
373 beg = res;
374 p = beg + strlen (beg);
375 dostounix_filename (beg);
376 tem_fn = make_specified_string (beg, -1, p - beg,
377 STRING_MULTIBYTE (filename));
379 else
380 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
381 STRING_MULTIBYTE (filename));
383 else if (STRING_MULTIBYTE (filename))
385 tem_fn = make_specified_string (beg, -1, p - beg, 1);
386 dostounix_filename (SSDATA (tem_fn));
387 #ifdef WINDOWSNT
388 if (!NILP (Vw32_downcase_file_names))
389 tem_fn = Fdowncase (tem_fn);
390 #endif
392 else
394 dostounix_filename (beg);
395 tem_fn = make_specified_string (beg, -1, p - beg, 0);
397 SAFE_FREE ();
398 return tem_fn;
399 #else /* DOS_NT */
400 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
401 #endif /* DOS_NT */
404 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
405 Sfile_name_nondirectory, 1, 1, 0,
406 doc: /* Return file name FILENAME sans its directory.
407 For example, in a Unix-syntax file name,
408 this is everything after the last slash,
409 or the entire name if it contains no slash. */)
410 (Lisp_Object filename)
412 register const char *beg, *p, *end;
413 Lisp_Object handler;
415 CHECK_STRING (filename);
417 /* If the file name has special constructs in it,
418 call the corresponding file handler. */
419 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
420 if (!NILP (handler))
422 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
423 filename);
424 if (STRINGP (handled_name))
425 return handled_name;
426 error ("Invalid handler in `file-name-handler-alist'");
429 beg = SSDATA (filename);
430 end = p = beg + SBYTES (filename);
432 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
433 #ifdef DOS_NT
434 /* only recognize drive specifier at beginning */
435 && !(p[-1] == ':'
436 /* handle the "/:d:foo" case correctly */
437 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
438 #endif
440 p--;
442 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
445 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
446 Sunhandled_file_name_directory, 1, 1, 0,
447 doc: /* Return a directly usable directory name somehow associated with FILENAME.
448 A `directly usable' directory name is one that may be used without the
449 intervention of any file handler.
450 If FILENAME is a directly usable file itself, return
451 \(file-name-as-directory FILENAME).
452 If FILENAME refers to a file which is not accessible from a local process,
453 then this should return nil.
454 The `call-process' and `start-process' functions use this function to
455 get a current directory to run processes in. */)
456 (Lisp_Object filename)
458 Lisp_Object handler;
460 /* If the file name has special constructs in it,
461 call the corresponding file handler. */
462 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
463 if (!NILP (handler))
465 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
466 filename);
467 return STRINGP (handled_name) ? handled_name : Qnil;
470 return Ffile_name_as_directory (filename);
473 /* Maximum number of bytes that DST will be longer than SRC
474 in file_name_as_directory. This occurs when SRCLEN == 0. */
475 enum { file_name_as_directory_slop = 2 };
477 /* Convert from file name SRC of length SRCLEN to directory name in
478 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
479 string. On UNIX, just make sure there is a terminating /. Return
480 the length of DST in bytes. */
482 static ptrdiff_t
483 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
484 bool multibyte)
486 if (srclen == 0)
488 dst[0] = '.';
489 dst[1] = '/';
490 dst[2] = '\0';
491 return 2;
494 memcpy (dst, src, srclen);
495 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
496 dst[srclen++] = DIRECTORY_SEP;
497 dst[srclen] = 0;
498 #ifdef DOS_NT
499 dostounix_filename (dst);
500 #endif
501 return srclen;
504 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
505 Sfile_name_as_directory, 1, 1, 0,
506 doc: /* Return a string representing the file name FILE interpreted as a directory.
507 This operation exists because a directory is also a file, but its name as
508 a directory is different from its name as a file.
509 The result can be used as the value of `default-directory'
510 or passed as second argument to `expand-file-name'.
511 For a Unix-syntax file name, just appends a slash unless a trailing slash
512 is already present. */)
513 (Lisp_Object file)
515 char *buf;
516 ptrdiff_t length;
517 Lisp_Object handler, val;
518 USE_SAFE_ALLOCA;
520 CHECK_STRING (file);
522 /* If the file name has special constructs in it,
523 call the corresponding file handler. */
524 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
525 if (!NILP (handler))
527 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
528 file);
529 if (STRINGP (handled_name))
530 return handled_name;
531 error ("Invalid handler in `file-name-handler-alist'");
534 #ifdef WINDOWSNT
535 if (!NILP (Vw32_downcase_file_names))
536 file = Fdowncase (file);
537 #endif
538 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
539 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
540 STRING_MULTIBYTE (file));
541 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
542 SAFE_FREE ();
543 return val;
546 /* Convert from directory name SRC of length SRCLEN to file name in
547 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
548 string. On UNIX, just make sure there isn't a terminating /.
549 Return the length of DST in bytes. */
551 static ptrdiff_t
552 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
554 /* Process as Unix format: just remove any final slash.
555 But leave "/" and "//" unchanged. */
556 while (srclen > 1
557 #ifdef DOS_NT
558 && !IS_ANY_SEP (src[srclen - 2])
559 #endif
560 && IS_DIRECTORY_SEP (src[srclen - 1])
561 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
562 srclen--;
564 memcpy (dst, src, srclen);
565 dst[srclen] = 0;
566 #ifdef DOS_NT
567 dostounix_filename (dst);
568 #endif
569 return srclen;
572 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
573 1, 1, 0,
574 doc: /* Returns the file name of the directory named DIRECTORY.
575 This is the name of the file that holds the data for the directory DIRECTORY.
576 This operation exists because a directory is also a file, but its name as
577 a directory is different from its name as a file.
578 In Unix-syntax, this function just removes the final slash. */)
579 (Lisp_Object directory)
581 char *buf;
582 ptrdiff_t length;
583 Lisp_Object handler, val;
584 USE_SAFE_ALLOCA;
586 CHECK_STRING (directory);
588 /* If the file name has special constructs in it,
589 call the corresponding file handler. */
590 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
591 if (!NILP (handler))
593 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
594 directory);
595 if (STRINGP (handled_name))
596 return handled_name;
597 error ("Invalid handler in `file-name-handler-alist'");
600 #ifdef WINDOWSNT
601 if (!NILP (Vw32_downcase_file_names))
602 directory = Fdowncase (directory);
603 #endif
604 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
605 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
606 STRING_MULTIBYTE (directory));
607 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
608 SAFE_FREE ();
609 return val;
612 static const char make_temp_name_tbl[64] =
614 'A','B','C','D','E','F','G','H',
615 'I','J','K','L','M','N','O','P',
616 'Q','R','S','T','U','V','W','X',
617 'Y','Z','a','b','c','d','e','f',
618 'g','h','i','j','k','l','m','n',
619 'o','p','q','r','s','t','u','v',
620 'w','x','y','z','0','1','2','3',
621 '4','5','6','7','8','9','-','_'
624 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
626 /* Value is a temporary file name starting with PREFIX, a string.
628 The Emacs process number forms part of the result, so there is
629 no danger of generating a name being used by another process.
630 In addition, this function makes an attempt to choose a name
631 which has no existing file. To make this work, PREFIX should be
632 an absolute file name.
634 BASE64_P means add the pid as 3 characters in base64
635 encoding. In this case, 6 characters will be added to PREFIX to
636 form the file name. Otherwise, if Emacs is running on a system
637 with long file names, add the pid as a decimal number.
639 This function signals an error if no unique file name could be
640 generated. */
642 Lisp_Object
643 make_temp_name (Lisp_Object prefix, bool base64_p)
645 Lisp_Object val, encoded_prefix;
646 ptrdiff_t len;
647 printmax_t pid;
648 char *p, *data;
649 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
650 int pidlen;
652 CHECK_STRING (prefix);
654 /* VAL is created by adding 6 characters to PREFIX. The first
655 three are the PID of this process, in base 64, and the second
656 three are incremented if the file already exists. This ensures
657 262144 unique file names per PID per PREFIX. */
659 pid = getpid ();
661 if (base64_p)
663 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
664 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
665 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
666 pidlen = 3;
668 else
670 #ifdef HAVE_LONG_FILE_NAMES
671 pidlen = sprintf (pidbuf, "%"pMd, pid);
672 #else
673 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
674 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
675 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
676 pidlen = 3;
677 #endif
680 encoded_prefix = ENCODE_FILE (prefix);
681 len = SBYTES (encoded_prefix);
682 val = make_uninit_string (len + 3 + pidlen);
683 data = SSDATA (val);
684 memcpy (data, SSDATA (encoded_prefix), len);
685 p = data + len;
687 memcpy (p, pidbuf, pidlen);
688 p += pidlen;
690 /* Here we try to minimize useless stat'ing when this function is
691 invoked many times successively with the same PREFIX. We achieve
692 this by initializing count to a random value, and incrementing it
693 afterwards.
695 We don't want make-temp-name to be called while dumping,
696 because then make_temp_name_count_initialized_p would get set
697 and then make_temp_name_count would not be set when Emacs starts. */
699 if (!make_temp_name_count_initialized_p)
701 make_temp_name_count = time (NULL);
702 make_temp_name_count_initialized_p = 1;
705 while (1)
707 unsigned num = make_temp_name_count;
709 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
710 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
711 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
713 /* Poor man's congruential RN generator. Replace with
714 ++make_temp_name_count for debugging. */
715 make_temp_name_count += 25229;
716 make_temp_name_count %= 225307;
718 if (!check_existing (data))
720 /* We want to return only if errno is ENOENT. */
721 if (errno == ENOENT)
722 return DECODE_FILE (val);
723 else
724 /* The error here is dubious, but there is little else we
725 can do. The alternatives are to return nil, which is
726 as bad as (and in many cases worse than) throwing the
727 error, or to ignore the error, which will likely result
728 in looping through 225307 stat's, which is not only
729 dog-slow, but also useless since eventually nil would
730 have to be returned anyway. */
731 report_file_error ("Cannot create temporary name for prefix",
732 prefix);
733 /* not reached */
739 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
740 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
741 The Emacs process number forms part of the result, so there is no
742 danger of generating a name being used by another Emacs process
743 \(so long as only a single host can access the containing directory...).
745 This function tries to choose a name that has no existing file.
746 For this to work, PREFIX should be an absolute file name.
748 There is a race condition between calling `make-temp-name' and creating the
749 file, which opens all kinds of security holes. For that reason, you should
750 normally use `make-temp-file' instead. */)
751 (Lisp_Object prefix)
753 return make_temp_name (prefix, 0);
756 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
757 doc: /* Convert filename NAME to absolute, and canonicalize it.
758 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
759 \(does not start with slash or tilde); both the directory name and
760 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
761 missing, the current buffer's value of `default-directory' is used.
762 NAME should be a string that is a valid file name for the underlying
763 filesystem.
764 File name components that are `.' are removed, and
765 so are file name components followed by `..', along with the `..' itself;
766 note that these simplifications are done without checking the resulting
767 file names in the file system.
768 Multiple consecutive slashes are collapsed into a single slash,
769 except at the beginning of the file name when they are significant (e.g.,
770 UNC file names on MS-Windows.)
771 An initial `~/' expands to your home directory.
772 An initial `~USER/' expands to USER's home directory.
773 See also the function `substitute-in-file-name'.
775 For technical reasons, this function can return correct but
776 non-intuitive results for the root directory; for instance,
777 \(expand-file-name ".." "/") returns "/..". For this reason, use
778 \(directory-file-name (file-name-directory dirname)) to traverse a
779 filesystem tree, not (expand-file-name ".." dirname). */)
780 (Lisp_Object name, Lisp_Object default_directory)
782 /* These point to SDATA and need to be careful with string-relocation
783 during GC (via DECODE_FILE). */
784 char *nm;
785 char *nmlim;
786 const char *newdir;
787 const char *newdirlim;
788 /* This should only point to alloca'd data. */
789 char *target;
791 ptrdiff_t tlen;
792 struct passwd *pw;
793 #ifdef DOS_NT
794 int drive = 0;
795 bool collapse_newdir = true;
796 bool is_escaped = 0;
797 #endif /* DOS_NT */
798 ptrdiff_t length, nbytes;
799 Lisp_Object handler, result, handled_name;
800 bool multibyte;
801 Lisp_Object hdir;
802 USE_SAFE_ALLOCA;
804 CHECK_STRING (name);
806 /* If the file name has special constructs in it,
807 call the corresponding file handler. */
808 handler = Ffind_file_name_handler (name, Qexpand_file_name);
809 if (!NILP (handler))
811 handled_name = call3 (handler, Qexpand_file_name,
812 name, default_directory);
813 if (STRINGP (handled_name))
814 return handled_name;
815 error ("Invalid handler in `file-name-handler-alist'");
819 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
820 if (NILP (default_directory))
821 default_directory = BVAR (current_buffer, directory);
822 if (! STRINGP (default_directory))
824 #ifdef DOS_NT
825 /* "/" is not considered a root directory on DOS_NT, so using "/"
826 here causes an infinite recursion in, e.g., the following:
828 (let (default-directory)
829 (expand-file-name "a"))
831 To avoid this, we set default_directory to the root of the
832 current drive. */
833 default_directory = build_string (emacs_root_dir ());
834 #else
835 default_directory = build_string ("/");
836 #endif
839 if (!NILP (default_directory))
841 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
842 if (!NILP (handler))
844 handled_name = call3 (handler, Qexpand_file_name,
845 name, default_directory);
846 if (STRINGP (handled_name))
847 return handled_name;
848 error ("Invalid handler in `file-name-handler-alist'");
853 char *o = SSDATA (default_directory);
855 /* Make sure DEFAULT_DIRECTORY is properly expanded.
856 It would be better to do this down below where we actually use
857 default_directory. Unfortunately, calling Fexpand_file_name recursively
858 could invoke GC, and the strings might be relocated. This would
859 be annoying because we have pointers into strings lying around
860 that would need adjusting, and people would add new pointers to
861 the code and forget to adjust them, resulting in intermittent bugs.
862 Putting this call here avoids all that crud.
864 The EQ test avoids infinite recursion. */
865 if (! NILP (default_directory) && !EQ (default_directory, name)
866 /* Save time in some common cases - as long as default_directory
867 is not relative, it can be canonicalized with name below (if it
868 is needed at all) without requiring it to be expanded now. */
869 #ifdef DOS_NT
870 /* Detect MSDOS file names with drive specifiers. */
871 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
872 && IS_DIRECTORY_SEP (o[2]))
873 #ifdef WINDOWSNT
874 /* Detect Windows file names in UNC format. */
875 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
876 #endif
877 #else /* not DOS_NT */
878 /* Detect Unix absolute file names (/... alone is not absolute on
879 DOS or Windows). */
880 && ! (IS_DIRECTORY_SEP (o[0]))
881 #endif /* not DOS_NT */
884 default_directory = Fexpand_file_name (default_directory, Qnil);
887 multibyte = STRING_MULTIBYTE (name);
888 if (multibyte != STRING_MULTIBYTE (default_directory))
890 if (multibyte)
892 unsigned char *p = SDATA (name);
894 while (*p && ASCII_CHAR_P (*p))
895 p++;
896 if (*p == '\0')
898 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
899 unibyte. Do not convert DEFAULT_DIRECTORY to
900 multibyte; instead, convert NAME to a unibyte string,
901 so that the result of this function is also a unibyte
902 string. This is needed during bootstrapping and
903 dumping, when Emacs cannot decode file names, because
904 the locale environment is not set up. */
905 name = make_unibyte_string (SSDATA (name), SBYTES (name));
906 multibyte = 0;
908 else
909 default_directory = string_to_multibyte (default_directory);
911 else
913 name = string_to_multibyte (name);
914 multibyte = 1;
918 #ifdef WINDOWSNT
919 if (!NILP (Vw32_downcase_file_names))
920 default_directory = Fdowncase (default_directory);
921 #endif
923 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
924 SAFE_ALLOCA_STRING (nm, name);
925 nmlim = nm + SBYTES (name);
927 #ifdef DOS_NT
928 /* Note if special escape prefix is present, but remove for now. */
929 if (nm[0] == '/' && nm[1] == ':')
931 is_escaped = 1;
932 nm += 2;
935 /* Find and remove drive specifier if present; this makes nm absolute
936 even if the rest of the name appears to be relative. Only look for
937 drive specifier at the beginning. */
938 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
940 drive = (unsigned char) nm[0];
941 nm += 2;
944 #ifdef WINDOWSNT
945 /* If we see "c://somedir", we want to strip the first slash after the
946 colon when stripping the drive letter. Otherwise, this expands to
947 "//somedir". */
948 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
949 nm++;
951 /* Discard any previous drive specifier if nm is now in UNC format. */
952 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
953 && !IS_DIRECTORY_SEP (nm[2]))
954 drive = 0;
955 #endif /* WINDOWSNT */
956 #endif /* DOS_NT */
958 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
959 none are found, we can probably return right away. We will avoid
960 allocating a new string if name is already fully expanded. */
961 if (
962 IS_DIRECTORY_SEP (nm[0])
963 #ifdef MSDOS
964 && drive && !is_escaped
965 #endif
966 #ifdef WINDOWSNT
967 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
968 #endif
971 /* If it turns out that the filename we want to return is just a
972 suffix of FILENAME, we don't need to go through and edit
973 things; we just need to construct a new string using data
974 starting at the middle of FILENAME. If we set LOSE, that
975 means we've discovered that we can't do that cool trick. */
976 bool lose = 0;
977 char *p = nm;
979 while (*p)
981 /* Since we know the name is absolute, we can assume that each
982 element starts with a "/". */
984 /* "." and ".." are hairy. */
985 if (IS_DIRECTORY_SEP (p[0])
986 && p[1] == '.'
987 && (IS_DIRECTORY_SEP (p[2])
988 || p[2] == 0
989 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
990 || p[3] == 0))))
991 lose = 1;
992 /* Replace multiple slashes with a single one, except
993 leave leading "//" alone. */
994 else if (IS_DIRECTORY_SEP (p[0])
995 && IS_DIRECTORY_SEP (p[1])
996 && (p != nm || IS_DIRECTORY_SEP (p[2])))
997 lose = 1;
998 p++;
1000 if (!lose)
1002 #ifdef DOS_NT
1003 /* Make sure directories are all separated with /, but
1004 avoid allocation of a new string when not required. */
1005 dostounix_filename (nm);
1006 #ifdef WINDOWSNT
1007 if (IS_DIRECTORY_SEP (nm[1]))
1009 if (strcmp (nm, SSDATA (name)) != 0)
1010 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1012 else
1013 #endif
1014 /* Drive must be set, so this is okay. */
1015 if (strcmp (nm - 2, SSDATA (name)) != 0)
1017 name = make_specified_string (nm, -1, p - nm, multibyte);
1018 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1019 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1020 name = concat2 (drive_prefix, name);
1022 #ifdef WINDOWSNT
1023 if (!NILP (Vw32_downcase_file_names))
1024 name = Fdowncase (name);
1025 #endif
1026 #else /* not DOS_NT */
1027 if (strcmp (nm, SSDATA (name)) != 0)
1028 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1029 #endif /* not DOS_NT */
1030 SAFE_FREE ();
1031 return name;
1035 /* At this point, nm might or might not be an absolute file name. We
1036 need to expand ~ or ~user if present, otherwise prefix nm with
1037 default_directory if nm is not absolute, and finally collapse /./
1038 and /foo/../ sequences.
1040 We set newdir to be the appropriate prefix if one is needed:
1041 - the relevant user directory if nm starts with ~ or ~user
1042 - the specified drive's working dir (DOS/NT only) if nm does not
1043 start with /
1044 - the value of default_directory.
1046 Note that these prefixes are not guaranteed to be absolute (except
1047 for the working dir of a drive). Therefore, to ensure we always
1048 return an absolute name, if the final prefix is not absolute we
1049 append it to the current working directory. */
1051 newdir = newdirlim = 0;
1053 if (nm[0] == '~') /* prefix ~ */
1055 if (IS_DIRECTORY_SEP (nm[1])
1056 || nm[1] == 0) /* ~ by itself */
1058 Lisp_Object tem;
1060 if (!(newdir = egetenv ("HOME")))
1061 newdir = newdirlim = "";
1062 nm++;
1063 /* `egetenv' may return a unibyte string, which will bite us since
1064 we expect the directory to be multibyte. */
1065 #ifdef WINDOWSNT
1066 if (newdir[0])
1068 char newdir_utf8[MAX_UTF8_PATH];
1070 filename_from_ansi (newdir, newdir_utf8);
1071 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1073 else
1074 #endif
1075 tem = build_string (newdir);
1076 newdirlim = newdir + SBYTES (tem);
1077 if (multibyte && !STRING_MULTIBYTE (tem))
1079 hdir = DECODE_FILE (tem);
1080 newdir = SSDATA (hdir);
1081 newdirlim = newdir + SBYTES (hdir);
1083 #ifdef DOS_NT
1084 collapse_newdir = false;
1085 #endif
1087 else /* ~user/filename */
1089 char *o, *p;
1090 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1091 continue;
1092 o = SAFE_ALLOCA (p - nm + 1);
1093 memcpy (o, nm, p - nm);
1094 o[p - nm] = 0;
1096 block_input ();
1097 pw = getpwnam (o + 1);
1098 unblock_input ();
1099 if (pw)
1101 Lisp_Object tem;
1103 newdir = pw->pw_dir;
1104 /* `getpwnam' may return a unibyte string, which will
1105 bite us since we expect the directory to be
1106 multibyte. */
1107 tem = make_unibyte_string (newdir, strlen (newdir));
1108 newdirlim = newdir + SBYTES (tem);
1109 if (multibyte && !STRING_MULTIBYTE (tem))
1111 hdir = DECODE_FILE (tem);
1112 newdir = SSDATA (hdir);
1113 newdirlim = newdir + SBYTES (hdir);
1115 nm = p;
1116 #ifdef DOS_NT
1117 collapse_newdir = false;
1118 #endif
1121 /* If we don't find a user of that name, leave the name
1122 unchanged; don't move nm forward to p. */
1126 #ifdef DOS_NT
1127 /* On DOS and Windows, nm is absolute if a drive name was specified;
1128 use the drive's current directory as the prefix if needed. */
1129 if (!newdir && drive)
1131 /* Get default directory if needed to make nm absolute. */
1132 char *adir = NULL;
1133 if (!IS_DIRECTORY_SEP (nm[0]))
1135 adir = alloca (MAXPATHLEN + 1);
1136 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1137 adir = NULL;
1138 else if (multibyte)
1140 Lisp_Object tem = build_string (adir);
1142 tem = DECODE_FILE (tem);
1143 newdirlim = adir + SBYTES (tem);
1144 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1146 else
1147 newdirlim = adir + strlen (adir);
1149 if (!adir)
1151 /* Either nm starts with /, or drive isn't mounted. */
1152 adir = alloca (4);
1153 adir[0] = DRIVE_LETTER (drive);
1154 adir[1] = ':';
1155 adir[2] = '/';
1156 adir[3] = 0;
1157 newdirlim = adir + 3;
1159 newdir = adir;
1161 #endif /* DOS_NT */
1163 /* Finally, if no prefix has been specified and nm is not absolute,
1164 then it must be expanded relative to default_directory. */
1166 if (1
1167 #ifndef DOS_NT
1168 /* /... alone is not absolute on DOS and Windows. */
1169 && !IS_DIRECTORY_SEP (nm[0])
1170 #endif
1171 #ifdef WINDOWSNT
1172 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1173 && !IS_DIRECTORY_SEP (nm[2]))
1174 #endif
1175 && !newdir)
1177 newdir = SSDATA (default_directory);
1178 newdirlim = newdir + SBYTES (default_directory);
1179 #ifdef DOS_NT
1180 /* Note if special escape prefix is present, but remove for now. */
1181 if (newdir[0] == '/' && newdir[1] == ':')
1183 is_escaped = 1;
1184 newdir += 2;
1186 #endif
1189 #ifdef DOS_NT
1190 if (newdir)
1192 /* First ensure newdir is an absolute name. */
1193 if (
1194 /* Detect MSDOS file names with drive specifiers. */
1195 ! (IS_DRIVE (newdir[0])
1196 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1197 #ifdef WINDOWSNT
1198 /* Detect Windows file names in UNC format. */
1199 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1200 && !IS_DIRECTORY_SEP (newdir[2]))
1201 #endif
1204 /* Effectively, let newdir be (expand-file-name newdir cwd).
1205 Because of the admonition against calling expand-file-name
1206 when we have pointers into lisp strings, we accomplish this
1207 indirectly by prepending newdir to nm if necessary, and using
1208 cwd (or the wd of newdir's drive) as the new newdir. */
1209 char *adir;
1210 #ifdef WINDOWSNT
1211 const int adir_size = MAX_UTF8_PATH;
1212 #else
1213 const int adir_size = MAXPATHLEN + 1;
1214 #endif
1216 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1218 drive = (unsigned char) newdir[0];
1219 newdir += 2;
1221 if (!IS_DIRECTORY_SEP (nm[0]))
1223 ptrdiff_t nmlen = nmlim - nm;
1224 ptrdiff_t newdirlen = newdirlim - newdir;
1225 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1226 + nmlen + 1);
1227 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1228 multibyte);
1229 memcpy (tmp + dlen, nm, nmlen + 1);
1230 nm = tmp;
1231 nmlim = nm + dlen + nmlen;
1233 adir = alloca (adir_size);
1234 if (drive)
1236 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1237 strcpy (adir, "/");
1239 else
1240 getcwd (adir, adir_size);
1241 if (multibyte)
1243 Lisp_Object tem = build_string (adir);
1245 tem = DECODE_FILE (tem);
1246 newdirlim = adir + SBYTES (tem);
1247 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1249 else
1250 newdirlim = adir + strlen (adir);
1251 newdir = adir;
1254 /* Strip off drive name from prefix, if present. */
1255 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1257 drive = newdir[0];
1258 newdir += 2;
1261 /* Keep only a prefix from newdir if nm starts with slash
1262 (//server/share for UNC, nothing otherwise). */
1263 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1265 #ifdef WINDOWSNT
1266 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1267 && !IS_DIRECTORY_SEP (newdir[2]))
1269 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1270 char *p = adir + 2;
1271 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1272 p++;
1273 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1274 *p = 0;
1275 newdir = adir;
1276 newdirlim = newdir + strlen (adir);
1278 else
1279 #endif
1280 newdir = newdirlim = "";
1283 #endif /* DOS_NT */
1285 /* Ignore any slash at the end of newdir, unless newdir is
1286 just "/" or "//". */
1287 length = newdirlim - newdir;
1288 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1289 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1290 length--;
1292 /* Now concatenate the directory and name to new space in the stack frame. */
1293 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1294 eassert (tlen > file_name_as_directory_slop + 1);
1295 #ifdef DOS_NT
1296 /* Reserve space for drive specifier and escape prefix, since either
1297 or both may need to be inserted. (The Microsoft x86 compiler
1298 produces incorrect code if the following two lines are combined.) */
1299 target = alloca (tlen + 4);
1300 target += 4;
1301 #else /* not DOS_NT */
1302 target = SAFE_ALLOCA (tlen);
1303 #endif /* not DOS_NT */
1304 *target = 0;
1305 nbytes = 0;
1307 if (newdir)
1309 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1311 #ifdef DOS_NT
1312 /* If newdir is effectively "C:/", then the drive letter will have
1313 been stripped and newdir will be "/". Concatenating with an
1314 absolute directory in nm produces "//", which will then be
1315 incorrectly treated as a network share. Ignore newdir in
1316 this case (keeping the drive letter). */
1317 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1318 && newdir[1] == '\0'))
1319 #endif
1321 memcpy (target, newdir, length);
1322 target[length] = 0;
1323 nbytes = length;
1326 else
1327 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1330 memcpy (target + nbytes, nm, nmlim - nm + 1);
1332 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1333 appear. */
1335 char *p = target;
1336 char *o = target;
1338 while (*p)
1340 if (!IS_DIRECTORY_SEP (*p))
1342 *o++ = *p++;
1344 else if (p[1] == '.'
1345 && (IS_DIRECTORY_SEP (p[2])
1346 || p[2] == 0))
1348 /* If "/." is the entire filename, keep the "/". Otherwise,
1349 just delete the whole "/.". */
1350 if (o == target && p[2] == '\0')
1351 *o++ = *p;
1352 p += 2;
1354 else if (p[1] == '.' && p[2] == '.'
1355 /* `/../' is the "superroot" on certain file systems.
1356 Turned off on DOS_NT systems because they have no
1357 "superroot" and because this causes us to produce
1358 file names like "d:/../foo" which fail file-related
1359 functions of the underlying OS. (To reproduce, try a
1360 long series of "../../" in default_directory, longer
1361 than the number of levels from the root.) */
1362 #ifndef DOS_NT
1363 && o != target
1364 #endif
1365 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1367 #ifdef WINDOWSNT
1368 char *prev_o = o;
1369 #endif
1370 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1371 continue;
1372 #ifdef WINDOWSNT
1373 /* Don't go below server level in UNC filenames. */
1374 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1375 && IS_DIRECTORY_SEP (*target))
1376 o = prev_o;
1377 else
1378 #endif
1379 /* Keep initial / only if this is the whole name. */
1380 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1381 ++o;
1382 p += 3;
1384 else if (IS_DIRECTORY_SEP (p[1])
1385 && (p != target || IS_DIRECTORY_SEP (p[2])))
1386 /* Collapse multiple "/", except leave leading "//" alone. */
1387 p++;
1388 else
1390 *o++ = *p++;
1394 #ifdef DOS_NT
1395 /* At last, set drive name. */
1396 #ifdef WINDOWSNT
1397 /* Except for network file name. */
1398 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1399 #endif /* WINDOWSNT */
1401 if (!drive) emacs_abort ();
1402 target -= 2;
1403 target[0] = DRIVE_LETTER (drive);
1404 target[1] = ':';
1406 /* Reinsert the escape prefix if required. */
1407 if (is_escaped)
1409 target -= 2;
1410 target[0] = '/';
1411 target[1] = ':';
1413 result = make_specified_string (target, -1, o - target, multibyte);
1414 dostounix_filename (SSDATA (result));
1415 #ifdef WINDOWSNT
1416 if (!NILP (Vw32_downcase_file_names))
1417 result = Fdowncase (result);
1418 #endif
1419 #else /* !DOS_NT */
1420 result = make_specified_string (target, -1, o - target, multibyte);
1421 #endif /* !DOS_NT */
1424 /* Again look to see if the file name has special constructs in it
1425 and perhaps call the corresponding file handler. This is needed
1426 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1427 the ".." component gives us "/user@host:/bar/../baz" which needs
1428 to be expanded again. */
1429 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1430 if (!NILP (handler))
1432 handled_name = call3 (handler, Qexpand_file_name,
1433 result, default_directory);
1434 if (! STRINGP (handled_name))
1435 error ("Invalid handler in `file-name-handler-alist'");
1436 result = handled_name;
1439 SAFE_FREE ();
1440 return result;
1443 #if 0
1444 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1445 This is the old version of expand-file-name, before it was thoroughly
1446 rewritten for Emacs 10.31. We leave this version here commented-out,
1447 because the code is very complex and likely to have subtle bugs. If
1448 bugs _are_ found, it might be of interest to look at the old code and
1449 see what did it do in the relevant situation.
1451 Don't remove this code: it's true that it will be accessible
1452 from the repository, but a few years from deletion, people will
1453 forget it is there. */
1455 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1456 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1457 "Convert FILENAME to absolute, and canonicalize it.\n\
1458 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1459 \(does not start with slash); if DEFAULT is nil or missing,\n\
1460 the current buffer's value of default-directory is used.\n\
1461 Filenames containing `.' or `..' as components are simplified;\n\
1462 initial `~/' expands to your home directory.\n\
1463 See also the function `substitute-in-file-name'.")
1464 (name, defalt)
1465 Lisp_Object name, defalt;
1467 unsigned char *nm;
1469 register unsigned char *newdir, *p, *o;
1470 ptrdiff_t tlen;
1471 unsigned char *target;
1472 struct passwd *pw;
1474 CHECK_STRING (name);
1475 nm = SDATA (name);
1477 /* If nm is absolute, flush ...// and detect /./ and /../.
1478 If no /./ or /../ we can return right away. */
1479 if (nm[0] == '/')
1481 bool lose = 0;
1482 p = nm;
1483 while (*p)
1485 if (p[0] == '/' && p[1] == '/')
1486 nm = p + 1;
1487 if (p[0] == '/' && p[1] == '~')
1488 nm = p + 1, lose = 1;
1489 if (p[0] == '/' && p[1] == '.'
1490 && (p[2] == '/' || p[2] == 0
1491 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1492 lose = 1;
1493 p++;
1495 if (!lose)
1497 if (nm == SDATA (name))
1498 return name;
1499 return build_string (nm);
1503 /* Now determine directory to start with and put it in NEWDIR. */
1505 newdir = 0;
1507 if (nm[0] == '~') /* prefix ~ */
1508 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1510 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1511 newdir = (unsigned char *) "";
1512 nm++;
1514 else /* ~user/filename */
1516 /* Get past ~ to user. */
1517 unsigned char *user = nm + 1;
1518 /* Find end of name. */
1519 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1520 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1521 /* Copy the user name into temp storage. */
1522 o = alloca (len + 1);
1523 memcpy (o, user, len);
1524 o[len] = 0;
1526 /* Look up the user name. */
1527 block_input ();
1528 pw = (struct passwd *) getpwnam (o + 1);
1529 unblock_input ();
1530 if (!pw)
1531 error ("\"%s\" isn't a registered user", o + 1);
1533 newdir = (unsigned char *) pw->pw_dir;
1535 /* Discard the user name from NM. */
1536 nm += len;
1539 if (nm[0] != '/' && !newdir)
1541 if (NILP (defalt))
1542 defalt = current_buffer->directory;
1543 CHECK_STRING (defalt);
1544 newdir = SDATA (defalt);
1547 /* Now concatenate the directory and name to new space in the stack frame. */
1549 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1550 target = alloca (tlen);
1551 *target = 0;
1553 if (newdir)
1555 if (nm[0] == 0 || nm[0] == '/')
1556 strcpy (target, newdir);
1557 else
1558 file_name_as_directory (target, newdir);
1561 strcat (target, nm);
1563 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1565 p = target;
1566 o = target;
1568 while (*p)
1570 if (*p != '/')
1572 *o++ = *p++;
1574 else if (!strncmp (p, "//", 2)
1577 o = target;
1578 p++;
1580 else if (p[0] == '/' && p[1] == '.'
1581 && (p[2] == '/' || p[2] == 0))
1582 p += 2;
1583 else if (!strncmp (p, "/..", 3)
1584 /* `/../' is the "superroot" on certain file systems. */
1585 && o != target
1586 && (p[3] == '/' || p[3] == 0))
1588 while (o != target && *--o != '/')
1590 if (o == target && *o == '/')
1591 ++o;
1592 p += 3;
1594 else
1596 *o++ = *p++;
1600 return make_string (target, o - target);
1602 #endif
1604 /* If /~ or // appears, discard everything through first slash. */
1605 static bool
1606 file_name_absolute_p (const char *filename)
1608 return
1609 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1610 #ifdef DOS_NT
1611 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1612 && IS_DIRECTORY_SEP (filename[2]))
1613 #endif
1617 static char *
1618 search_embedded_absfilename (char *nm, char *endp)
1620 char *p, *s;
1622 for (p = nm + 1; p < endp; p++)
1624 if (IS_DIRECTORY_SEP (p[-1])
1625 && file_name_absolute_p (p)
1626 #if defined (WINDOWSNT) || defined (CYGWIN)
1627 /* // at start of file name is meaningful in Apollo,
1628 WindowsNT and Cygwin systems. */
1629 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1630 #endif /* not (WINDOWSNT || CYGWIN) */
1633 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1634 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1636 USE_SAFE_ALLOCA;
1637 char *o = SAFE_ALLOCA (s - p + 1);
1638 struct passwd *pw;
1639 memcpy (o, p, s - p);
1640 o [s - p] = 0;
1642 /* If we have ~user and `user' exists, discard
1643 everything up to ~. But if `user' does not exist, leave
1644 ~user alone, it might be a literal file name. */
1645 block_input ();
1646 pw = getpwnam (o + 1);
1647 unblock_input ();
1648 SAFE_FREE ();
1649 if (pw)
1650 return p;
1652 else
1653 return p;
1656 return NULL;
1659 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1660 Ssubstitute_in_file_name, 1, 1, 0,
1661 doc: /* Substitute environment variables referred to in FILENAME.
1662 `$FOO' where FOO is an environment variable name means to substitute
1663 the value of that variable. The variable name should be terminated
1664 with a character not a letter, digit or underscore; otherwise, enclose
1665 the entire variable name in braces.
1667 If `/~' appears, all of FILENAME through that `/' is discarded.
1668 If `//' appears, everything up to and including the first of
1669 those `/' is discarded. */)
1670 (Lisp_Object filename)
1672 char *nm, *p, *x, *endp;
1673 bool substituted = false;
1674 bool multibyte;
1675 char *xnm;
1676 Lisp_Object handler;
1678 CHECK_STRING (filename);
1680 multibyte = STRING_MULTIBYTE (filename);
1682 /* If the file name has special constructs in it,
1683 call the corresponding file handler. */
1684 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1685 if (!NILP (handler))
1687 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1688 filename);
1689 if (STRINGP (handled_name))
1690 return handled_name;
1691 error ("Invalid handler in `file-name-handler-alist'");
1694 /* Always work on a copy of the string, in case GC happens during
1695 decode of environment variables, causing the original Lisp_String
1696 data to be relocated. */
1697 USE_SAFE_ALLOCA;
1698 SAFE_ALLOCA_STRING (nm, filename);
1700 #ifdef DOS_NT
1701 dostounix_filename (nm);
1702 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1703 #endif
1704 endp = nm + SBYTES (filename);
1706 /* If /~ or // appears, discard everything through first slash. */
1707 p = search_embedded_absfilename (nm, endp);
1708 if (p)
1709 /* Start over with the new string, so we check the file-name-handler
1710 again. Important with filenames like "/home/foo//:/hello///there"
1711 which would substitute to "/:/hello///there" rather than "/there". */
1713 Lisp_Object result
1714 = (Fsubstitute_in_file_name
1715 (make_specified_string (p, -1, endp - p, multibyte)));
1716 SAFE_FREE ();
1717 return result;
1720 /* See if any variables are substituted into the string. */
1722 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1724 Lisp_Object name
1725 = (!substituted ? filename
1726 : make_specified_string (nm, -1, endp - nm, multibyte));
1727 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1728 CHECK_STRING (tmp);
1729 if (!EQ (tmp, name))
1730 substituted = true;
1731 filename = tmp;
1734 if (!substituted)
1736 #ifdef WINDOWSNT
1737 if (!NILP (Vw32_downcase_file_names))
1738 filename = Fdowncase (filename);
1739 #endif
1740 SAFE_FREE ();
1741 return filename;
1744 xnm = SSDATA (filename);
1745 x = xnm + SBYTES (filename);
1747 /* If /~ or // appears, discard everything through first slash. */
1748 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1749 /* This time we do not start over because we've already expanded envvars
1750 and replaced $$ with $. Maybe we should start over as well, but we'd
1751 need to quote some $ to $$ first. */
1752 xnm = p;
1754 #ifdef WINDOWSNT
1755 if (!NILP (Vw32_downcase_file_names))
1757 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1759 filename = Fdowncase (xname);
1761 else
1762 #endif
1763 if (xnm != SSDATA (filename))
1764 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1765 SAFE_FREE ();
1766 return filename;
1769 /* A slightly faster and more convenient way to get
1770 (directory-file-name (expand-file-name FOO)). */
1772 Lisp_Object
1773 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1775 register Lisp_Object absname;
1777 absname = Fexpand_file_name (filename, defdir);
1779 /* Remove final slash, if any (unless this is the root dir).
1780 stat behaves differently depending! */
1781 if (SCHARS (absname) > 1
1782 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1783 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1784 /* We cannot take shortcuts; they might be wrong for magic file names. */
1785 absname = Fdirectory_file_name (absname);
1786 return absname;
1789 /* Signal an error if the file ABSNAME already exists.
1790 If KNOWN_TO_EXIST, the file is known to exist.
1791 QUERYSTRING is a name for the action that is being considered
1792 to alter the file.
1793 If INTERACTIVE, ask the user whether to proceed,
1794 and bypass the error if the user says to go ahead.
1795 If QUICK, ask for y or n, not yes or no. */
1797 static void
1798 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1799 const char *querystring, bool interactive,
1800 bool quick)
1802 Lisp_Object tem, encoded_filename;
1803 struct stat statbuf;
1805 encoded_filename = ENCODE_FILE (absname);
1807 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1809 if (S_ISDIR (statbuf.st_mode))
1810 xsignal2 (Qfile_error,
1811 build_string ("File is a directory"), absname);
1812 known_to_exist = true;
1815 if (known_to_exist)
1817 if (! interactive)
1818 xsignal2 (Qfile_already_exists,
1819 build_string ("File already exists"), absname);
1820 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1821 tem = CALLN (Fformat, format, absname, build_string (querystring));
1822 if (quick)
1823 tem = call1 (intern ("y-or-n-p"), tem);
1824 else
1825 tem = do_yes_or_no_p (tem);
1826 if (NILP (tem))
1827 xsignal2 (Qfile_already_exists,
1828 build_string ("File already exists"), absname);
1832 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1833 "fCopy file: \nGCopy %s to file: \np\nP",
1834 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1835 If NEWNAME names a directory, copy FILE there.
1837 This function always sets the file modes of the output file to match
1838 the input file.
1840 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1841 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1842 signal a `file-already-exists' error without overwriting. If
1843 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1844 about overwriting; this is what happens in interactive use with M-x.
1845 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1846 existing file.
1848 Fourth arg KEEP-TIME non-nil means give the output file the same
1849 last-modified time as the old one. (This works on only some systems.)
1851 A prefix arg makes KEEP-TIME non-nil.
1853 If PRESERVE-UID-GID is non-nil, we try to transfer the
1854 uid and gid of FILE to NEWNAME.
1856 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1857 this includes the file modes, along with ACL entries and SELinux
1858 context if present. Otherwise, if NEWNAME is created its file
1859 permission bits are those of FILE, masked by the default file
1860 permissions. */)
1861 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1862 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1863 Lisp_Object preserve_permissions)
1865 Lisp_Object handler;
1866 ptrdiff_t count = SPECPDL_INDEX ();
1867 Lisp_Object encoded_file, encoded_newname;
1868 #if HAVE_LIBSELINUX
1869 security_context_t con;
1870 int conlength = 0;
1871 #endif
1872 #ifdef WINDOWSNT
1873 int result;
1874 #else
1875 bool already_exists = false;
1876 mode_t new_mask;
1877 int ifd, ofd;
1878 struct stat st;
1879 #endif
1881 encoded_file = encoded_newname = Qnil;
1882 CHECK_STRING (file);
1883 CHECK_STRING (newname);
1885 if (!NILP (Ffile_directory_p (newname)))
1886 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1887 else
1888 newname = Fexpand_file_name (newname, Qnil);
1890 file = Fexpand_file_name (file, Qnil);
1892 /* If the input file name has special constructs in it,
1893 call the corresponding file handler. */
1894 handler = Ffind_file_name_handler (file, Qcopy_file);
1895 /* Likewise for output file name. */
1896 if (NILP (handler))
1897 handler = Ffind_file_name_handler (newname, Qcopy_file);
1898 if (!NILP (handler))
1899 return call7 (handler, Qcopy_file, file, newname,
1900 ok_if_already_exists, keep_time, preserve_uid_gid,
1901 preserve_permissions);
1903 encoded_file = ENCODE_FILE (file);
1904 encoded_newname = ENCODE_FILE (newname);
1906 #ifdef WINDOWSNT
1907 if (NILP (ok_if_already_exists)
1908 || INTEGERP (ok_if_already_exists))
1909 barf_or_query_if_file_exists (newname, false, "copy to it",
1910 INTEGERP (ok_if_already_exists), false);
1912 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1913 !NILP (keep_time), !NILP (preserve_uid_gid),
1914 !NILP (preserve_permissions));
1915 switch (result)
1917 case -1:
1918 report_file_error ("Copying file", list2 (file, newname));
1919 case -2:
1920 report_file_error ("Copying permissions from", file);
1921 case -3:
1922 xsignal2 (Qfile_date_error,
1923 build_string ("Resetting file times"), newname);
1924 case -4:
1925 report_file_error ("Copying permissions to", newname);
1927 #else /* not WINDOWSNT */
1928 immediate_quit = 1;
1929 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1930 immediate_quit = 0;
1932 if (ifd < 0)
1933 report_file_error ("Opening input file", file);
1935 record_unwind_protect_int (close_file_unwind, ifd);
1937 if (fstat (ifd, &st) != 0)
1938 report_file_error ("Input file status", file);
1940 if (!NILP (preserve_permissions))
1942 #if HAVE_LIBSELINUX
1943 if (is_selinux_enabled ())
1945 conlength = fgetfilecon (ifd, &con);
1946 if (conlength == -1)
1947 report_file_error ("Doing fgetfilecon", file);
1949 #endif
1952 /* We can copy only regular files. */
1953 if (!S_ISREG (st.st_mode))
1954 report_file_errno ("Non-regular file", file,
1955 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1957 #ifndef MSDOS
1958 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1959 #else
1960 new_mask = S_IREAD | S_IWRITE;
1961 #endif
1963 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1964 new_mask);
1965 if (ofd < 0 && errno == EEXIST)
1967 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1968 barf_or_query_if_file_exists (newname, true, "copy to it",
1969 INTEGERP (ok_if_already_exists), false);
1970 already_exists = true;
1971 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1973 if (ofd < 0)
1974 report_file_error ("Opening output file", newname);
1976 record_unwind_protect_int (close_file_unwind, ofd);
1978 off_t oldsize = 0, newsize = 0;
1980 if (already_exists)
1982 struct stat out_st;
1983 if (fstat (ofd, &out_st) != 0)
1984 report_file_error ("Output file status", newname);
1985 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1986 report_file_errno ("Input and output files are the same",
1987 list2 (file, newname), 0);
1988 if (S_ISREG (out_st.st_mode))
1989 oldsize = out_st.st_size;
1992 immediate_quit = 1;
1993 QUIT;
1994 while (true)
1996 char buf[MAX_ALLOCA];
1997 ptrdiff_t n = emacs_read (ifd, buf, sizeof buf);
1998 if (n < 0)
1999 report_file_error ("Read error", file);
2000 if (n == 0)
2001 break;
2002 if (emacs_write_sig (ofd, buf, n) != n)
2003 report_file_error ("Write error", newname);
2004 newsize += n;
2007 /* Truncate any existing output file after writing the data. This
2008 is more likely to work than truncation before writing, if the
2009 file system is out of space or the user is over disk quota. */
2010 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2011 report_file_error ("Truncating output file", newname);
2013 immediate_quit = 0;
2015 #ifndef MSDOS
2016 /* Preserve the original file permissions, and if requested, also its
2017 owner and group. */
2019 mode_t preserved_permissions = st.st_mode & 07777;
2020 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2021 if (!NILP (preserve_uid_gid))
2023 /* Attempt to change owner and group. If that doesn't work
2024 attempt to change just the group, as that is sometimes allowed.
2025 Adjust the mode mask to eliminate setuid or setgid bits
2026 or group permissions bits that are inappropriate if the
2027 owner or group are wrong. */
2028 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2030 if (fchown (ofd, -1, st.st_gid) == 0)
2031 preserved_permissions &= ~04000;
2032 else
2034 preserved_permissions &= ~06000;
2036 /* Copy the other bits to the group bits, since the
2037 group is wrong. */
2038 preserved_permissions &= ~070;
2039 preserved_permissions |= (preserved_permissions & 7) << 3;
2040 default_permissions &= ~070;
2041 default_permissions |= (default_permissions & 7) << 3;
2046 switch (!NILP (preserve_permissions)
2047 ? qcopy_acl (SSDATA (encoded_file), ifd,
2048 SSDATA (encoded_newname), ofd,
2049 preserved_permissions)
2050 : (already_exists
2051 || (new_mask & ~realmask) == default_permissions)
2053 : fchmod (ofd, default_permissions))
2055 case -2: report_file_error ("Copying permissions from", file);
2056 case -1: report_file_error ("Copying permissions to", newname);
2059 #endif /* not MSDOS */
2061 #if HAVE_LIBSELINUX
2062 if (conlength > 0)
2064 /* Set the modified context back to the file. */
2065 bool fail = fsetfilecon (ofd, con) != 0;
2066 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2067 if (fail && errno != ENOTSUP)
2068 report_file_error ("Doing fsetfilecon", newname);
2070 freecon (con);
2072 #endif
2074 if (!NILP (keep_time))
2076 struct timespec atime = get_stat_atime (&st);
2077 struct timespec mtime = get_stat_mtime (&st);
2078 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2079 xsignal2 (Qfile_date_error,
2080 build_string ("Cannot set file date"), newname);
2083 if (emacs_close (ofd) < 0)
2084 report_file_error ("Write error", newname);
2086 emacs_close (ifd);
2088 #ifdef MSDOS
2089 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2090 and if it can't, it tells so. Otherwise, under MSDOS we usually
2091 get only the READ bit, which will make the copied file read-only,
2092 so it's better not to chmod at all. */
2093 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2094 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2095 #endif /* MSDOS */
2096 #endif /* not WINDOWSNT */
2098 /* Discard the unwind protects. */
2099 specpdl_ptr = specpdl + count;
2101 return Qnil;
2104 DEFUN ("make-directory-internal", Fmake_directory_internal,
2105 Smake_directory_internal, 1, 1, 0,
2106 doc: /* Create a new directory named DIRECTORY. */)
2107 (Lisp_Object directory)
2109 const char *dir;
2110 Lisp_Object handler;
2111 Lisp_Object encoded_dir;
2113 CHECK_STRING (directory);
2114 directory = Fexpand_file_name (directory, Qnil);
2116 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2117 if (!NILP (handler))
2118 return call2 (handler, Qmake_directory_internal, directory);
2120 encoded_dir = ENCODE_FILE (directory);
2122 dir = SSDATA (encoded_dir);
2124 #ifdef WINDOWSNT
2125 if (mkdir (dir) != 0)
2126 #else
2127 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2128 #endif
2129 report_file_error ("Creating directory", directory);
2131 return Qnil;
2134 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2135 Sdelete_directory_internal, 1, 1, 0,
2136 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2137 (Lisp_Object directory)
2139 const char *dir;
2140 Lisp_Object encoded_dir;
2142 CHECK_STRING (directory);
2143 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2144 encoded_dir = ENCODE_FILE (directory);
2145 dir = SSDATA (encoded_dir);
2147 if (rmdir (dir) != 0)
2148 report_file_error ("Removing directory", directory);
2150 return Qnil;
2153 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2154 "(list (read-file-name \
2155 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2156 \"Move file to trash: \" \"Delete file: \") \
2157 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2158 (null current-prefix-arg))",
2159 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2160 If file has multiple names, it continues to exist with the other names.
2161 TRASH non-nil means to trash the file instead of deleting, provided
2162 `delete-by-moving-to-trash' is non-nil.
2164 When called interactively, TRASH is t if no prefix argument is given.
2165 With a prefix argument, TRASH is nil. */)
2166 (Lisp_Object filename, Lisp_Object trash)
2168 Lisp_Object handler;
2169 Lisp_Object encoded_file;
2171 if (!NILP (Ffile_directory_p (filename))
2172 && NILP (Ffile_symlink_p (filename)))
2173 xsignal2 (Qfile_error,
2174 build_string ("Removing old name: is a directory"),
2175 filename);
2176 filename = Fexpand_file_name (filename, Qnil);
2178 handler = Ffind_file_name_handler (filename, Qdelete_file);
2179 if (!NILP (handler))
2180 return call3 (handler, Qdelete_file, filename, trash);
2182 if (delete_by_moving_to_trash && !NILP (trash))
2183 return call1 (Qmove_file_to_trash, filename);
2185 encoded_file = ENCODE_FILE (filename);
2187 if (unlink (SSDATA (encoded_file)) < 0)
2188 report_file_error ("Removing old name", filename);
2189 return Qnil;
2192 static Lisp_Object
2193 internal_delete_file_1 (Lisp_Object ignore)
2195 return Qt;
2198 /* Delete file FILENAME, returning true if successful.
2199 This ignores `delete-by-moving-to-trash'. */
2201 bool
2202 internal_delete_file (Lisp_Object filename)
2204 Lisp_Object tem;
2206 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2207 Qt, internal_delete_file_1);
2208 return NILP (tem);
2211 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2212 "fRename file: \nGRename %s to file: \np",
2213 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2214 If file has names other than FILE, it continues to have those names.
2215 Signals a `file-already-exists' error if a file NEWNAME already exists
2216 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2217 A number as third arg means request confirmation if NEWNAME already exists.
2218 This is what happens in interactive use with M-x. */)
2219 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2221 Lisp_Object handler;
2222 Lisp_Object encoded_file, encoded_newname, symlink_target;
2224 symlink_target = encoded_file = encoded_newname = Qnil;
2225 CHECK_STRING (file);
2226 CHECK_STRING (newname);
2227 file = Fexpand_file_name (file, Qnil);
2229 if ((!NILP (Ffile_directory_p (newname)))
2230 #ifdef DOS_NT
2231 /* If the file names are identical but for the case,
2232 don't attempt to move directory to itself. */
2233 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2234 #endif
2237 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2238 ? file : Fdirectory_file_name (file));
2239 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2241 else
2242 newname = Fexpand_file_name (newname, Qnil);
2244 /* If the file name has special constructs in it,
2245 call the corresponding file handler. */
2246 handler = Ffind_file_name_handler (file, Qrename_file);
2247 if (NILP (handler))
2248 handler = Ffind_file_name_handler (newname, Qrename_file);
2249 if (!NILP (handler))
2250 return call4 (handler, Qrename_file,
2251 file, newname, ok_if_already_exists);
2253 encoded_file = ENCODE_FILE (file);
2254 encoded_newname = ENCODE_FILE (newname);
2256 #ifdef DOS_NT
2257 /* If the file names are identical but for the case, don't ask for
2258 confirmation: they simply want to change the letter-case of the
2259 file name. */
2260 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2261 #endif
2262 if (NILP (ok_if_already_exists)
2263 || INTEGERP (ok_if_already_exists))
2264 barf_or_query_if_file_exists (newname, false, "rename to it",
2265 INTEGERP (ok_if_already_exists), false);
2266 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2268 int rename_errno = errno;
2269 if (rename_errno == EXDEV)
2271 ptrdiff_t count;
2272 symlink_target = Ffile_symlink_p (file);
2273 if (! NILP (symlink_target))
2274 Fmake_symbolic_link (symlink_target, newname,
2275 NILP (ok_if_already_exists) ? Qnil : Qt);
2276 else if (!NILP (Ffile_directory_p (file)))
2277 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2278 else
2279 /* We have already prompted if it was an integer, so don't
2280 have copy-file prompt again. */
2281 Fcopy_file (file, newname,
2282 NILP (ok_if_already_exists) ? Qnil : Qt,
2283 Qt, Qt, Qt);
2285 count = SPECPDL_INDEX ();
2286 specbind (Qdelete_by_moving_to_trash, Qnil);
2288 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2289 call2 (Qdelete_directory, file, Qt);
2290 else
2291 Fdelete_file (file, Qnil);
2292 unbind_to (count, Qnil);
2294 else
2295 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2298 return Qnil;
2301 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2302 "fAdd name to file: \nGName to add to %s: \np",
2303 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2304 Signals a `file-already-exists' error if a file NEWNAME already exists
2305 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2306 A number as third arg means request confirmation if NEWNAME already exists.
2307 This is what happens in interactive use with M-x. */)
2308 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2310 Lisp_Object handler;
2311 Lisp_Object encoded_file, encoded_newname;
2313 encoded_file = encoded_newname = Qnil;
2314 CHECK_STRING (file);
2315 CHECK_STRING (newname);
2316 file = Fexpand_file_name (file, Qnil);
2318 if (!NILP (Ffile_directory_p (newname)))
2319 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2320 else
2321 newname = Fexpand_file_name (newname, Qnil);
2323 /* If the file name has special constructs in it,
2324 call the corresponding file handler. */
2325 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2326 if (!NILP (handler))
2327 return call4 (handler, Qadd_name_to_file, file,
2328 newname, ok_if_already_exists);
2330 /* If the new name has special constructs in it,
2331 call the corresponding file handler. */
2332 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2333 if (!NILP (handler))
2334 return call4 (handler, Qadd_name_to_file, file,
2335 newname, ok_if_already_exists);
2337 encoded_file = ENCODE_FILE (file);
2338 encoded_newname = ENCODE_FILE (newname);
2340 if (NILP (ok_if_already_exists)
2341 || INTEGERP (ok_if_already_exists))
2342 barf_or_query_if_file_exists (newname, false, "make it a new name",
2343 INTEGERP (ok_if_already_exists), false);
2345 unlink (SSDATA (newname));
2346 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2348 int link_errno = errno;
2349 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2352 return Qnil;
2355 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2356 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2357 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2358 Both args must be strings.
2359 Signals a `file-already-exists' error if a file LINKNAME already exists
2360 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2361 A number as third arg means request confirmation if LINKNAME already exists.
2362 This happens for interactive use with M-x. */)
2363 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2365 Lisp_Object handler;
2366 Lisp_Object encoded_target, encoded_linkname;
2368 encoded_target = encoded_linkname = Qnil;
2369 CHECK_STRING (target);
2370 CHECK_STRING (linkname);
2371 /* If the link target has a ~, we must expand it to get
2372 a truly valid file name. Otherwise, do not expand;
2373 we want to permit links to relative file names. */
2374 if (SREF (target, 0) == '~')
2375 target = Fexpand_file_name (target, Qnil);
2377 if (!NILP (Ffile_directory_p (linkname)))
2378 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2379 else
2380 linkname = Fexpand_file_name (linkname, Qnil);
2382 /* If the file name has special constructs in it,
2383 call the corresponding file handler. */
2384 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2385 if (!NILP (handler))
2386 return call4 (handler, Qmake_symbolic_link, target,
2387 linkname, ok_if_already_exists);
2389 /* If the new link name has special constructs in it,
2390 call the corresponding file handler. */
2391 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2392 if (!NILP (handler))
2393 return call4 (handler, Qmake_symbolic_link, target,
2394 linkname, ok_if_already_exists);
2396 encoded_target = ENCODE_FILE (target);
2397 encoded_linkname = ENCODE_FILE (linkname);
2399 if (NILP (ok_if_already_exists)
2400 || INTEGERP (ok_if_already_exists))
2401 barf_or_query_if_file_exists (linkname, false, "make it a link",
2402 INTEGERP (ok_if_already_exists), false);
2403 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2405 /* If we didn't complain already, silently delete existing file. */
2406 int symlink_errno;
2407 if (errno == EEXIST)
2409 unlink (SSDATA (encoded_linkname));
2410 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2411 >= 0)
2412 return Qnil;
2414 if (errno == ENOSYS)
2415 xsignal1 (Qfile_error,
2416 build_string ("Symbolic links are not supported"));
2418 symlink_errno = errno;
2419 report_file_errno ("Making symbolic link", list2 (target, linkname),
2420 symlink_errno);
2423 return Qnil;
2427 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2428 1, 1, 0,
2429 doc: /* Return t if file FILENAME specifies an absolute file name.
2430 On Unix, this is a name starting with a `/' or a `~'. */)
2431 (Lisp_Object filename)
2433 CHECK_STRING (filename);
2434 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2437 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2438 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2439 See also `file-readable-p' and `file-attributes'.
2440 This returns nil for a symlink to a nonexistent file.
2441 Use `file-symlink-p' to test for such links. */)
2442 (Lisp_Object filename)
2444 Lisp_Object absname;
2445 Lisp_Object handler;
2447 CHECK_STRING (filename);
2448 absname = Fexpand_file_name (filename, Qnil);
2450 /* If the file name has special constructs in it,
2451 call the corresponding file handler. */
2452 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2453 if (!NILP (handler))
2455 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2456 errno = 0;
2457 return result;
2460 absname = ENCODE_FILE (absname);
2462 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2465 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2466 doc: /* Return t if FILENAME can be executed by you.
2467 For a directory, this means you can access files in that directory.
2468 \(It is generally better to use `file-accessible-directory-p' for that
2469 purpose, though.) */)
2470 (Lisp_Object filename)
2472 Lisp_Object absname;
2473 Lisp_Object handler;
2475 CHECK_STRING (filename);
2476 absname = Fexpand_file_name (filename, Qnil);
2478 /* If the file name has special constructs in it,
2479 call the corresponding file handler. */
2480 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2481 if (!NILP (handler))
2482 return call2 (handler, Qfile_executable_p, absname);
2484 absname = ENCODE_FILE (absname);
2486 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2489 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2490 doc: /* Return t if file FILENAME exists and you can read it.
2491 See also `file-exists-p' and `file-attributes'. */)
2492 (Lisp_Object filename)
2494 Lisp_Object absname;
2495 Lisp_Object handler;
2497 CHECK_STRING (filename);
2498 absname = Fexpand_file_name (filename, Qnil);
2500 /* If the file name has special constructs in it,
2501 call the corresponding file handler. */
2502 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2503 if (!NILP (handler))
2504 return call2 (handler, Qfile_readable_p, absname);
2506 absname = ENCODE_FILE (absname);
2507 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2508 ? Qt : Qnil);
2511 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2512 doc: /* Return t if file FILENAME can be written or created by you. */)
2513 (Lisp_Object filename)
2515 Lisp_Object absname, dir, encoded;
2516 Lisp_Object handler;
2518 CHECK_STRING (filename);
2519 absname = Fexpand_file_name (filename, Qnil);
2521 /* If the file name has special constructs in it,
2522 call the corresponding file handler. */
2523 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2524 if (!NILP (handler))
2525 return call2 (handler, Qfile_writable_p, absname);
2527 encoded = ENCODE_FILE (absname);
2528 if (check_writable (SSDATA (encoded), W_OK))
2529 return Qt;
2530 if (errno != ENOENT)
2531 return Qnil;
2533 dir = Ffile_name_directory (absname);
2534 eassert (!NILP (dir));
2535 #ifdef MSDOS
2536 dir = Fdirectory_file_name (dir);
2537 #endif /* MSDOS */
2539 dir = ENCODE_FILE (dir);
2540 #ifdef WINDOWSNT
2541 /* The read-only attribute of the parent directory doesn't affect
2542 whether a file or directory can be created within it. Some day we
2543 should check ACLs though, which do affect this. */
2544 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2545 #else
2546 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2547 #endif
2550 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2551 doc: /* Access file FILENAME, and get an error if that does not work.
2552 The second argument STRING is used in the error message.
2553 If there is no error, returns nil. */)
2554 (Lisp_Object filename, Lisp_Object string)
2556 Lisp_Object handler, encoded_filename, absname;
2558 CHECK_STRING (filename);
2559 absname = Fexpand_file_name (filename, Qnil);
2561 CHECK_STRING (string);
2563 /* If the file name has special constructs in it,
2564 call the corresponding file handler. */
2565 handler = Ffind_file_name_handler (absname, Qaccess_file);
2566 if (!NILP (handler))
2567 return call3 (handler, Qaccess_file, absname, string);
2569 encoded_filename = ENCODE_FILE (absname);
2571 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2572 report_file_error (SSDATA (string), filename);
2574 return Qnil;
2577 /* Relative to directory FD, return the symbolic link value of FILENAME.
2578 On failure, return nil. */
2579 Lisp_Object
2580 emacs_readlinkat (int fd, char const *filename)
2582 static struct allocator const emacs_norealloc_allocator =
2583 { xmalloc, NULL, xfree, memory_full };
2584 Lisp_Object val;
2585 char readlink_buf[1024];
2586 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2587 &emacs_norealloc_allocator, readlinkat);
2588 if (!buf)
2589 return Qnil;
2591 val = build_unibyte_string (buf);
2592 if (buf[0] == '/' && strchr (buf, ':'))
2594 AUTO_STRING (slash_colon, "/:");
2595 val = concat2 (slash_colon, val);
2597 if (buf != readlink_buf)
2598 xfree (buf);
2599 val = DECODE_FILE (val);
2600 return val;
2603 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2604 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2605 The value is the link target, as a string.
2606 Otherwise it returns nil.
2608 This function does not check whether the link target exists. */)
2609 (Lisp_Object filename)
2611 Lisp_Object handler;
2613 CHECK_STRING (filename);
2614 filename = Fexpand_file_name (filename, Qnil);
2616 /* If the file name has special constructs in it,
2617 call the corresponding file handler. */
2618 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2619 if (!NILP (handler))
2620 return call2 (handler, Qfile_symlink_p, filename);
2622 filename = ENCODE_FILE (filename);
2624 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2627 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2628 doc: /* Return t if FILENAME names an existing directory.
2629 Symbolic links to directories count as directories.
2630 See `file-symlink-p' to distinguish symlinks. */)
2631 (Lisp_Object filename)
2633 Lisp_Object absname;
2634 Lisp_Object handler;
2636 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2638 /* If the file name has special constructs in it,
2639 call the corresponding file handler. */
2640 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2641 if (!NILP (handler))
2642 return call2 (handler, Qfile_directory_p, absname);
2644 absname = ENCODE_FILE (absname);
2646 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2649 /* Return true if FILE is a directory or a symlink to a directory. */
2650 bool
2651 file_directory_p (char const *file)
2653 #ifdef WINDOWSNT
2654 /* This is cheaper than 'stat'. */
2655 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2656 #else
2657 struct stat st;
2658 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2659 #endif
2662 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2663 Sfile_accessible_directory_p, 1, 1, 0,
2664 doc: /* Return t if FILENAME names a directory you can open.
2665 For the value to be t, FILENAME must specify the name of a directory
2666 as a file, and the directory must allow you to open files in it. In
2667 order to use a directory as a buffer's current directory, this
2668 predicate must return true. A directory name spec may be given
2669 instead; then the value is t if the directory so specified exists and
2670 really is a readable and searchable directory. */)
2671 (Lisp_Object filename)
2673 Lisp_Object absname;
2674 Lisp_Object handler;
2676 CHECK_STRING (filename);
2677 absname = Fexpand_file_name (filename, Qnil);
2679 /* If the file name has special constructs in it,
2680 call the corresponding file handler. */
2681 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2682 if (!NILP (handler))
2684 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2685 errno = 0;
2686 return r;
2689 absname = ENCODE_FILE (absname);
2690 return file_accessible_directory_p (absname) ? Qt : Qnil;
2693 /* If FILE is a searchable directory or a symlink to a
2694 searchable directory, return true. Otherwise return
2695 false and set errno to an error number. */
2696 bool
2697 file_accessible_directory_p (Lisp_Object file)
2699 #ifdef DOS_NT
2700 # ifdef WINDOWSNT
2701 /* We need a special-purpose test because (a) NTFS security data is
2702 not reflected in Posix-style mode bits, and (b) the trick with
2703 accessing "DIR/.", used below on Posix hosts, doesn't work on
2704 Windows, because "DIR/." is normalized to just "DIR" before
2705 hitting the disk. */
2706 return (SBYTES (file) == 0
2707 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2708 # else /* MSDOS */
2709 return file_directory_p (SSDATA (file));
2710 # endif /* MSDOS */
2711 #else /* !DOS_NT */
2712 /* On POSIXish platforms, use just one system call; this avoids a
2713 race and is typically faster. */
2714 const char *data = SSDATA (file);
2715 ptrdiff_t len = SBYTES (file);
2716 char const *dir;
2717 bool ok;
2718 int saved_errno;
2719 USE_SAFE_ALLOCA;
2721 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2722 There are three exceptions: "", "/", and "//". Leave "" alone,
2723 as it's invalid. Append only "." to the other two exceptions as
2724 "/" and "//" are distinct on some platforms, whereas "/", "///",
2725 "////", etc. are all equivalent. */
2726 if (! len)
2727 dir = data;
2728 else
2730 /* Just check for trailing '/' when deciding whether to append '/'.
2731 That's simpler than testing the two special cases "/" and "//",
2732 and it's a safe optimization here. */
2733 char *buf = SAFE_ALLOCA (len + 3);
2734 memcpy (buf, data, len);
2735 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2736 dir = buf;
2739 ok = check_existing (dir);
2740 saved_errno = errno;
2741 SAFE_FREE ();
2742 errno = saved_errno;
2743 return ok;
2744 #endif /* !DOS_NT */
2747 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2748 doc: /* Return t if FILENAME names a regular file.
2749 This is the sort of file that holds an ordinary stream of data bytes.
2750 Symbolic links to regular files count as regular files.
2751 See `file-symlink-p' to distinguish symlinks. */)
2752 (Lisp_Object filename)
2754 register Lisp_Object absname;
2755 struct stat st;
2756 Lisp_Object handler;
2758 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2760 /* If the file name has special constructs in it,
2761 call the corresponding file handler. */
2762 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2763 if (!NILP (handler))
2764 return call2 (handler, Qfile_regular_p, absname);
2766 absname = ENCODE_FILE (absname);
2768 #ifdef WINDOWSNT
2770 int result;
2771 Lisp_Object tem = Vw32_get_true_file_attributes;
2773 /* Tell stat to use expensive method to get accurate info. */
2774 Vw32_get_true_file_attributes = Qt;
2775 result = stat (SSDATA (absname), &st);
2776 Vw32_get_true_file_attributes = tem;
2778 if (result < 0)
2779 return Qnil;
2780 return S_ISREG (st.st_mode) ? Qt : Qnil;
2782 #else
2783 if (stat (SSDATA (absname), &st) < 0)
2784 return Qnil;
2785 return S_ISREG (st.st_mode) ? Qt : Qnil;
2786 #endif
2789 DEFUN ("file-selinux-context", Ffile_selinux_context,
2790 Sfile_selinux_context, 1, 1, 0,
2791 doc: /* Return SELinux context of file named FILENAME.
2792 The return value is a list (USER ROLE TYPE RANGE), where the list
2793 elements are strings naming the user, role, type, and range of the
2794 file's SELinux security context.
2796 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2797 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2798 (Lisp_Object filename)
2800 Lisp_Object absname;
2801 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2803 Lisp_Object handler;
2804 #if HAVE_LIBSELINUX
2805 security_context_t con;
2806 int conlength;
2807 context_t context;
2808 #endif
2810 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2812 /* If the file name has special constructs in it,
2813 call the corresponding file handler. */
2814 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2815 if (!NILP (handler))
2816 return call2 (handler, Qfile_selinux_context, absname);
2818 absname = ENCODE_FILE (absname);
2820 #if HAVE_LIBSELINUX
2821 if (is_selinux_enabled ())
2823 conlength = lgetfilecon (SSDATA (absname), &con);
2824 if (conlength > 0)
2826 context = context_new (con);
2827 if (context_user_get (context))
2828 user = build_string (context_user_get (context));
2829 if (context_role_get (context))
2830 role = build_string (context_role_get (context));
2831 if (context_type_get (context))
2832 type = build_string (context_type_get (context));
2833 if (context_range_get (context))
2834 range = build_string (context_range_get (context));
2835 context_free (context);
2836 freecon (con);
2839 #endif
2841 return list4 (user, role, type, range);
2844 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2845 Sset_file_selinux_context, 2, 2, 0,
2846 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2847 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2848 elements are strings naming the components of a SELinux context.
2850 Value is t if setting of SELinux context was successful, nil otherwise.
2852 This function does nothing and returns nil if SELinux is disabled,
2853 or if Emacs was not compiled with SELinux support. */)
2854 (Lisp_Object filename, Lisp_Object context)
2856 Lisp_Object absname;
2857 Lisp_Object handler;
2858 #if HAVE_LIBSELINUX
2859 Lisp_Object encoded_absname;
2860 Lisp_Object user = CAR_SAFE (context);
2861 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2862 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2863 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2864 security_context_t con;
2865 bool fail;
2866 int conlength;
2867 context_t parsed_con;
2868 #endif
2870 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2872 /* If the file name has special constructs in it,
2873 call the corresponding file handler. */
2874 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2875 if (!NILP (handler))
2876 return call3 (handler, Qset_file_selinux_context, absname, context);
2878 #if HAVE_LIBSELINUX
2879 if (is_selinux_enabled ())
2881 /* Get current file context. */
2882 encoded_absname = ENCODE_FILE (absname);
2883 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2884 if (conlength > 0)
2886 parsed_con = context_new (con);
2887 /* Change the parts defined in the parameter.*/
2888 if (STRINGP (user))
2890 if (context_user_set (parsed_con, SSDATA (user)))
2891 error ("Doing context_user_set");
2893 if (STRINGP (role))
2895 if (context_role_set (parsed_con, SSDATA (role)))
2896 error ("Doing context_role_set");
2898 if (STRINGP (type))
2900 if (context_type_set (parsed_con, SSDATA (type)))
2901 error ("Doing context_type_set");
2903 if (STRINGP (range))
2905 if (context_range_set (parsed_con, SSDATA (range)))
2906 error ("Doing context_range_set");
2909 /* Set the modified context back to the file. */
2910 fail = (lsetfilecon (SSDATA (encoded_absname),
2911 context_str (parsed_con))
2912 != 0);
2913 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2914 if (fail && errno != ENOTSUP)
2915 report_file_error ("Doing lsetfilecon", absname);
2917 context_free (parsed_con);
2918 freecon (con);
2919 return fail ? Qnil : Qt;
2921 else
2922 report_file_error ("Doing lgetfilecon", absname);
2924 #endif
2926 return Qnil;
2929 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2930 doc: /* Return ACL entries of file named FILENAME.
2931 The entries are returned in a format suitable for use in `set-file-acl'
2932 but is otherwise undocumented and subject to change.
2933 Return nil if file does not exist or is not accessible, or if Emacs
2934 was unable to determine the ACL entries. */)
2935 (Lisp_Object filename)
2937 #if USE_ACL
2938 Lisp_Object absname;
2939 Lisp_Object handler;
2940 # ifdef HAVE_ACL_SET_FILE
2941 acl_t acl;
2942 Lisp_Object acl_string;
2943 char *str;
2944 # ifndef HAVE_ACL_TYPE_EXTENDED
2945 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2946 # endif
2947 # endif
2949 absname = expand_and_dir_to_file (filename,
2950 BVAR (current_buffer, directory));
2952 /* If the file name has special constructs in it,
2953 call the corresponding file handler. */
2954 handler = Ffind_file_name_handler (absname, Qfile_acl);
2955 if (!NILP (handler))
2956 return call2 (handler, Qfile_acl, absname);
2958 # ifdef HAVE_ACL_SET_FILE
2959 absname = ENCODE_FILE (absname);
2961 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2962 if (acl == NULL)
2963 return Qnil;
2965 str = acl_to_text (acl, NULL);
2966 if (str == NULL)
2968 acl_free (acl);
2969 return Qnil;
2972 acl_string = build_string (str);
2973 acl_free (str);
2974 acl_free (acl);
2976 return acl_string;
2977 # endif
2978 #endif
2980 return Qnil;
2983 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
2984 2, 2, 0,
2985 doc: /* Set ACL of file named FILENAME to ACL-STRING.
2986 ACL-STRING should contain the textual representation of the ACL
2987 entries in a format suitable for the platform.
2989 Value is t if setting of ACL was successful, nil otherwise.
2991 Setting ACL for local files requires Emacs to be built with ACL
2992 support. */)
2993 (Lisp_Object filename, Lisp_Object acl_string)
2995 #if USE_ACL
2996 Lisp_Object absname;
2997 Lisp_Object handler;
2998 # ifdef HAVE_ACL_SET_FILE
2999 Lisp_Object encoded_absname;
3000 acl_t acl;
3001 bool fail;
3002 # endif
3004 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3006 /* If the file name has special constructs in it,
3007 call the corresponding file handler. */
3008 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3009 if (!NILP (handler))
3010 return call3 (handler, Qset_file_acl, absname, acl_string);
3012 # ifdef HAVE_ACL_SET_FILE
3013 if (STRINGP (acl_string))
3015 acl = acl_from_text (SSDATA (acl_string));
3016 if (acl == NULL)
3018 report_file_error ("Converting ACL", absname);
3019 return Qnil;
3022 encoded_absname = ENCODE_FILE (absname);
3024 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3025 acl)
3026 != 0);
3027 if (fail && acl_errno_valid (errno))
3028 report_file_error ("Setting ACL", absname);
3030 acl_free (acl);
3031 return fail ? Qnil : Qt;
3033 # endif
3034 #endif
3036 return Qnil;
3039 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3040 doc: /* Return mode bits of file named FILENAME, as an integer.
3041 Return nil, if file does not exist or is not accessible. */)
3042 (Lisp_Object filename)
3044 Lisp_Object absname;
3045 struct stat st;
3046 Lisp_Object handler;
3048 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3050 /* If the file name has special constructs in it,
3051 call the corresponding file handler. */
3052 handler = Ffind_file_name_handler (absname, Qfile_modes);
3053 if (!NILP (handler))
3054 return call2 (handler, Qfile_modes, absname);
3056 absname = ENCODE_FILE (absname);
3058 if (stat (SSDATA (absname), &st) < 0)
3059 return Qnil;
3061 return make_number (st.st_mode & 07777);
3064 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3065 "(let ((file (read-file-name \"File: \"))) \
3066 (list file (read-file-modes nil file)))",
3067 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3068 Only the 12 low bits of MODE are used.
3070 Interactively, mode bits are read by `read-file-modes', which accepts
3071 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3072 (Lisp_Object filename, Lisp_Object mode)
3074 Lisp_Object absname, encoded_absname;
3075 Lisp_Object handler;
3077 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3078 CHECK_NUMBER (mode);
3080 /* If the file name has special constructs in it,
3081 call the corresponding file handler. */
3082 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3083 if (!NILP (handler))
3084 return call3 (handler, Qset_file_modes, absname, mode);
3086 encoded_absname = ENCODE_FILE (absname);
3088 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3089 report_file_error ("Doing chmod", absname);
3091 return Qnil;
3094 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3095 doc: /* Set the file permission bits for newly created files.
3096 The argument MODE should be an integer; only the low 9 bits are used.
3097 This setting is inherited by subprocesses. */)
3098 (Lisp_Object mode)
3100 mode_t oldrealmask, oldumask, newumask;
3101 CHECK_NUMBER (mode);
3102 oldrealmask = realmask;
3103 newumask = ~ XINT (mode) & 0777;
3105 block_input ();
3106 realmask = newumask;
3107 oldumask = umask (newumask);
3108 unblock_input ();
3110 eassert (oldumask == oldrealmask);
3111 return Qnil;
3114 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3115 doc: /* Return the default file protection for created files.
3116 The value is an integer. */)
3117 (void)
3119 Lisp_Object value;
3120 XSETINT (value, (~ realmask) & 0777);
3121 return value;
3125 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3126 doc: /* Set times of file FILENAME to TIMESTAMP.
3127 Set both access and modification times.
3128 Return t on success, else nil.
3129 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3130 `current-time'. */)
3131 (Lisp_Object filename, Lisp_Object timestamp)
3133 Lisp_Object absname, encoded_absname;
3134 Lisp_Object handler;
3135 struct timespec t = lisp_time_argument (timestamp);
3137 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3139 /* If the file name has special constructs in it,
3140 call the corresponding file handler. */
3141 handler = Ffind_file_name_handler (absname, Qset_file_times);
3142 if (!NILP (handler))
3143 return call3 (handler, Qset_file_times, absname, timestamp);
3145 encoded_absname = ENCODE_FILE (absname);
3148 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3150 #ifdef MSDOS
3151 /* Setting times on a directory always fails. */
3152 if (file_directory_p (SSDATA (encoded_absname)))
3153 return Qnil;
3154 #endif
3155 report_file_error ("Setting file times", absname);
3159 return Qt;
3162 #ifdef HAVE_SYNC
3163 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3164 doc: /* Tell Unix to finish all pending disk updates. */)
3165 (void)
3167 sync ();
3168 return Qnil;
3171 #endif /* HAVE_SYNC */
3173 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3174 doc: /* Return t if file FILE1 is newer than file FILE2.
3175 If FILE1 does not exist, the answer is nil;
3176 otherwise, if FILE2 does not exist, the answer is t. */)
3177 (Lisp_Object file1, Lisp_Object file2)
3179 Lisp_Object absname1, absname2;
3180 struct stat st1, st2;
3181 Lisp_Object handler;
3183 CHECK_STRING (file1);
3184 CHECK_STRING (file2);
3186 absname1 = Qnil;
3187 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3188 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3190 /* If the file name has special constructs in it,
3191 call the corresponding file handler. */
3192 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3193 if (NILP (handler))
3194 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3195 if (!NILP (handler))
3196 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3198 absname1 = ENCODE_FILE (absname1);
3199 absname2 = ENCODE_FILE (absname2);
3201 if (stat (SSDATA (absname1), &st1) < 0)
3202 return Qnil;
3204 if (stat (SSDATA (absname2), &st2) < 0)
3205 return Qt;
3207 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3208 ? Qt : Qnil);
3211 #ifndef READ_BUF_SIZE
3212 #define READ_BUF_SIZE (64 << 10)
3213 #endif
3214 /* Some buffer offsets are stored in 'int' variables. */
3215 verify (READ_BUF_SIZE <= INT_MAX);
3217 /* This function is called after Lisp functions to decide a coding
3218 system are called, or when they cause an error. Before they are
3219 called, the current buffer is set unibyte and it contains only a
3220 newly inserted text (thus the buffer was empty before the
3221 insertion).
3223 The functions may set markers, overlays, text properties, or even
3224 alter the buffer contents, change the current buffer.
3226 Here, we reset all those changes by:
3227 o set back the current buffer.
3228 o move all markers and overlays to BEG.
3229 o remove all text properties.
3230 o set back the buffer multibyteness. */
3232 static void
3233 decide_coding_unwind (Lisp_Object unwind_data)
3235 Lisp_Object multibyte, undo_list, buffer;
3237 multibyte = XCAR (unwind_data);
3238 unwind_data = XCDR (unwind_data);
3239 undo_list = XCAR (unwind_data);
3240 buffer = XCDR (unwind_data);
3242 set_buffer_internal (XBUFFER (buffer));
3243 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3244 adjust_overlays_for_delete (BEG, Z - BEG);
3245 set_buffer_intervals (current_buffer, NULL);
3246 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3248 /* Now we are safe to change the buffer's multibyteness directly. */
3249 bset_enable_multibyte_characters (current_buffer, multibyte);
3250 bset_undo_list (current_buffer, undo_list);
3253 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3254 object where slot 0 is the file descriptor, slot 1 specifies
3255 an offset to put the read bytes, and slot 2 is the maximum
3256 amount of bytes to read. Value is the number of bytes read. */
3258 static Lisp_Object
3259 read_non_regular (Lisp_Object state)
3261 int nbytes;
3263 immediate_quit = 1;
3264 QUIT;
3265 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3266 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3267 + XSAVE_INTEGER (state, 1)),
3268 XSAVE_INTEGER (state, 2));
3269 immediate_quit = 0;
3270 /* Fast recycle this object for the likely next call. */
3271 free_misc (state);
3272 return make_number (nbytes);
3276 /* Condition-case handler used when reading from non-regular files
3277 in insert-file-contents. */
3279 static Lisp_Object
3280 read_non_regular_quit (Lisp_Object ignore)
3282 return Qnil;
3285 /* Return the file offset that VAL represents, checking for type
3286 errors and overflow. */
3287 static off_t
3288 file_offset (Lisp_Object val)
3290 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3291 return XINT (val);
3293 if (FLOATP (val))
3295 double v = XFLOAT_DATA (val);
3296 if (0 <= v
3297 && (sizeof (off_t) < sizeof v
3298 ? v <= TYPE_MAXIMUM (off_t)
3299 : v < TYPE_MAXIMUM (off_t)))
3300 return v;
3303 wrong_type_argument (intern ("file-offset"), val);
3306 /* Return a special time value indicating the error number ERRNUM. */
3307 static struct timespec
3308 time_error_value (int errnum)
3310 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3311 ? NONEXISTENT_MODTIME_NSECS
3312 : UNKNOWN_MODTIME_NSECS);
3313 return make_timespec (0, ns);
3316 static Lisp_Object
3317 get_window_points_and_markers (void)
3319 Lisp_Object pt_marker = Fpoint_marker ();
3320 Lisp_Object windows
3321 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3322 Lisp_Object window_markers = windows;
3323 /* Window markers (and point) are handled specially: rather than move to
3324 just before or just after the modified text, we try to keep the
3325 markers at the same distance (bug#19161).
3326 In general, this is wrong, but for window-markers, this should be harmless
3327 and is convenient for the end user when most of the file is unmodified,
3328 except for a few minor details near the beginning and near the end. */
3329 for (; CONSP (windows); windows = XCDR (windows))
3330 if (WINDOWP (XCAR (windows)))
3332 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3333 XSETCAR (windows,
3334 Fcons (window_marker, Fmarker_position (window_marker)));
3336 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3339 static void
3340 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3341 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3343 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3344 if (CONSP (XCAR (window_markers)))
3346 Lisp_Object car = XCAR (window_markers);
3347 Lisp_Object marker = XCAR (car);
3348 Lisp_Object oldpos = XCDR (car);
3349 if (MARKERP (marker) && INTEGERP (oldpos)
3350 && XINT (oldpos) > same_at_start
3351 && XINT (oldpos) < same_at_end)
3353 ptrdiff_t oldsize = same_at_end - same_at_start;
3354 ptrdiff_t newsize = inserted;
3355 double growth = newsize / (double)oldsize;
3356 ptrdiff_t newpos
3357 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3358 Fset_marker (marker, make_number (newpos), Qnil);
3363 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3364 text as a linear C char array. */
3365 static void
3366 maybe_move_gap (struct buffer *b)
3368 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3370 struct buffer *cb = current_buffer;
3372 set_buffer_internal (b);
3373 move_gap_both (Z, Z_BYTE);
3374 set_buffer_internal (cb);
3378 /* FIXME: insert-file-contents should be split with the top-level moved to
3379 Elisp and only the core kept in C. */
3381 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3382 1, 5, 0,
3383 doc: /* Insert contents of file FILENAME after point.
3384 Returns list of absolute file name and number of characters inserted.
3385 If second argument VISIT is non-nil, the buffer's visited filename and
3386 last save file modtime are set, and it is marked unmodified. If
3387 visiting and the file does not exist, visiting is completed before the
3388 error is signaled.
3390 The optional third and fourth arguments BEG and END specify what portion
3391 of the file to insert. These arguments count bytes in the file, not
3392 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3394 If optional fifth argument REPLACE is non-nil, replace the current
3395 buffer contents (in the accessible portion) with the file contents.
3396 This is better than simply deleting and inserting the whole thing
3397 because (1) it preserves some marker positions and (2) it puts less data
3398 in the undo list. When REPLACE is non-nil, the second return value is
3399 the number of characters that replace previous buffer contents.
3401 This function does code conversion according to the value of
3402 `coding-system-for-read' or `file-coding-system-alist', and sets the
3403 variable `last-coding-system-used' to the coding system actually used.
3405 In addition, this function decodes the inserted text from known formats
3406 by calling `format-decode', which see. */)
3407 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3409 struct stat st;
3410 struct timespec mtime;
3411 int fd;
3412 ptrdiff_t inserted = 0;
3413 ptrdiff_t how_much;
3414 off_t beg_offset, end_offset;
3415 int unprocessed;
3416 ptrdiff_t count = SPECPDL_INDEX ();
3417 Lisp_Object handler, val, insval, orig_filename, old_undo;
3418 Lisp_Object p;
3419 ptrdiff_t total = 0;
3420 bool not_regular = 0;
3421 int save_errno = 0;
3422 char read_buf[READ_BUF_SIZE];
3423 struct coding_system coding;
3424 bool replace_handled = false;
3425 bool set_coding_system = false;
3426 Lisp_Object coding_system;
3427 bool read_quit = false;
3428 /* If the undo log only contains the insertion, there's no point
3429 keeping it. It's typically when we first fill a file-buffer. */
3430 bool empty_undo_list_p
3431 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3432 && BEG == Z);
3433 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3434 bool we_locked_file = false;
3435 ptrdiff_t fd_index;
3436 Lisp_Object window_markers = Qnil;
3437 /* same_at_start and same_at_end count bytes, because file access counts
3438 bytes and BEG and END count bytes. */
3439 ptrdiff_t same_at_start = BEGV_BYTE;
3440 ptrdiff_t same_at_end = ZV_BYTE;
3441 /* SAME_AT_END_CHARPOS counts characters, because
3442 restore_window_points needs the old character count. */
3443 ptrdiff_t same_at_end_charpos = ZV;
3445 if (current_buffer->base_buffer && ! NILP (visit))
3446 error ("Cannot do file visiting in an indirect buffer");
3448 if (!NILP (BVAR (current_buffer, read_only)))
3449 Fbarf_if_buffer_read_only (Qnil);
3451 val = Qnil;
3452 p = Qnil;
3453 orig_filename = Qnil;
3454 old_undo = Qnil;
3456 CHECK_STRING (filename);
3457 filename = Fexpand_file_name (filename, Qnil);
3459 /* The value Qnil means that the coding system is not yet
3460 decided. */
3461 coding_system = Qnil;
3463 /* If the file name has special constructs in it,
3464 call the corresponding file handler. */
3465 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3466 if (!NILP (handler))
3468 val = call6 (handler, Qinsert_file_contents, filename,
3469 visit, beg, end, replace);
3470 if (CONSP (val) && CONSP (XCDR (val))
3471 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3472 inserted = XINT (XCAR (XCDR (val)));
3473 goto handled;
3476 orig_filename = filename;
3477 filename = ENCODE_FILE (filename);
3479 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3480 if (fd < 0)
3482 save_errno = errno;
3483 if (NILP (visit))
3484 report_file_error ("Opening input file", orig_filename);
3485 mtime = time_error_value (save_errno);
3486 st.st_size = -1;
3487 if (!NILP (Vcoding_system_for_read))
3489 /* Don't let invalid values into buffer-file-coding-system. */
3490 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3491 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3493 goto notfound;
3496 fd_index = SPECPDL_INDEX ();
3497 record_unwind_protect_int (close_file_unwind, fd);
3499 /* Replacement should preserve point as it preserves markers. */
3500 if (!NILP (replace))
3502 window_markers = get_window_points_and_markers ();
3503 record_unwind_protect (restore_point_unwind,
3504 XCAR (XCAR (window_markers)));
3507 if (fstat (fd, &st) != 0)
3508 report_file_error ("Input file status", orig_filename);
3509 mtime = get_stat_mtime (&st);
3511 /* This code will need to be changed in order to work on named
3512 pipes, and it's probably just not worth it. So we should at
3513 least signal an error. */
3514 if (!S_ISREG (st.st_mode))
3516 not_regular = 1;
3518 if (! NILP (visit))
3519 goto notfound;
3521 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3522 xsignal2 (Qfile_error,
3523 build_string ("not a regular file"), orig_filename);
3526 if (!NILP (visit))
3528 if (!NILP (beg) || !NILP (end))
3529 error ("Attempt to visit less than an entire file");
3530 if (BEG < Z && NILP (replace))
3531 error ("Cannot do file visiting in a non-empty buffer");
3534 if (!NILP (beg))
3535 beg_offset = file_offset (beg);
3536 else
3537 beg_offset = 0;
3539 if (!NILP (end))
3540 end_offset = file_offset (end);
3541 else
3543 if (not_regular)
3544 end_offset = TYPE_MAXIMUM (off_t);
3545 else
3547 end_offset = st.st_size;
3549 /* A negative size can happen on a platform that allows file
3550 sizes greater than the maximum off_t value. */
3551 if (end_offset < 0)
3552 buffer_overflow ();
3554 /* The file size returned from stat may be zero, but data
3555 may be readable nonetheless, for example when this is a
3556 file in the /proc filesystem. */
3557 if (end_offset == 0)
3558 end_offset = READ_BUF_SIZE;
3562 /* Check now whether the buffer will become too large,
3563 in the likely case where the file's length is not changing.
3564 This saves a lot of needless work before a buffer overflow. */
3565 if (! not_regular)
3567 /* The likely offset where we will stop reading. We could read
3568 more (or less), if the file grows (or shrinks) as we read it. */
3569 off_t likely_end = min (end_offset, st.st_size);
3571 if (beg_offset < likely_end)
3573 ptrdiff_t buf_bytes
3574 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3575 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3576 off_t likely_growth = likely_end - beg_offset;
3577 if (buf_growth_max < likely_growth)
3578 buffer_overflow ();
3582 /* Prevent redisplay optimizations. */
3583 current_buffer->clip_changed = true;
3585 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3587 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3588 setup_coding_system (coding_system, &coding);
3589 /* Ensure we set Vlast_coding_system_used. */
3590 set_coding_system = true;
3592 else if (BEG < Z)
3594 /* Decide the coding system to use for reading the file now
3595 because we can't use an optimized method for handling
3596 `coding:' tag if the current buffer is not empty. */
3597 if (!NILP (Vcoding_system_for_read))
3598 coding_system = Vcoding_system_for_read;
3599 else
3601 /* Don't try looking inside a file for a coding system
3602 specification if it is not seekable. */
3603 if (! not_regular && ! NILP (Vset_auto_coding_function))
3605 /* Find a coding system specified in the heading two
3606 lines or in the tailing several lines of the file.
3607 We assume that the 1K-byte and 3K-byte for heading
3608 and tailing respectively are sufficient for this
3609 purpose. */
3610 int nread;
3612 if (st.st_size <= (1024 * 4))
3613 nread = emacs_read (fd, read_buf, 1024 * 4);
3614 else
3616 nread = emacs_read (fd, read_buf, 1024);
3617 if (nread == 1024)
3619 int ntail;
3620 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3621 report_file_error ("Setting file position",
3622 orig_filename);
3623 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3624 nread = ntail < 0 ? ntail : nread + ntail;
3628 if (nread < 0)
3629 report_file_error ("Read error", orig_filename);
3630 else if (nread > 0)
3632 AUTO_STRING (name, " *code-converting-work*");
3633 struct buffer *prev = current_buffer;
3634 Lisp_Object workbuf;
3635 struct buffer *buf;
3637 record_unwind_current_buffer ();
3639 workbuf = Fget_buffer_create (name);
3640 buf = XBUFFER (workbuf);
3642 delete_all_overlays (buf);
3643 bset_directory (buf, BVAR (current_buffer, directory));
3644 bset_read_only (buf, Qnil);
3645 bset_filename (buf, Qnil);
3646 bset_undo_list (buf, Qt);
3647 eassert (buf->overlays_before == NULL);
3648 eassert (buf->overlays_after == NULL);
3650 set_buffer_internal (buf);
3651 Ferase_buffer ();
3652 bset_enable_multibyte_characters (buf, Qnil);
3654 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3655 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3656 coding_system = call2 (Vset_auto_coding_function,
3657 filename, make_number (nread));
3658 set_buffer_internal (prev);
3660 /* Discard the unwind protect for recovering the
3661 current buffer. */
3662 specpdl_ptr--;
3664 /* Rewind the file for the actual read done later. */
3665 if (lseek (fd, 0, SEEK_SET) < 0)
3666 report_file_error ("Setting file position", orig_filename);
3670 if (NILP (coding_system))
3672 /* If we have not yet decided a coding system, check
3673 file-coding-system-alist. */
3674 coding_system = CALLN (Ffind_operation_coding_system,
3675 Qinsert_file_contents, orig_filename,
3676 visit, beg, end, replace);
3677 if (CONSP (coding_system))
3678 coding_system = XCAR (coding_system);
3682 if (NILP (coding_system))
3683 coding_system = Qundecided;
3684 else
3685 CHECK_CODING_SYSTEM (coding_system);
3687 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3688 /* We must suppress all character code conversion except for
3689 end-of-line conversion. */
3690 coding_system = raw_text_coding_system (coding_system);
3692 setup_coding_system (coding_system, &coding);
3693 /* Ensure we set Vlast_coding_system_used. */
3694 set_coding_system = true;
3697 /* If requested, replace the accessible part of the buffer
3698 with the file contents. Avoid replacing text at the
3699 beginning or end of the buffer that matches the file contents;
3700 that preserves markers pointing to the unchanged parts.
3702 Here we implement this feature in an optimized way
3703 for the case where code conversion is NOT needed.
3704 The following if-statement handles the case of conversion
3705 in a less optimal way.
3707 If the code conversion is "automatic" then we try using this
3708 method and hope for the best.
3709 But if we discover the need for conversion, we give up on this method
3710 and let the following if-statement handle the replace job. */
3711 if (!NILP (replace)
3712 && BEGV < ZV
3713 && (NILP (coding_system)
3714 || ! CODING_REQUIRE_DECODING (&coding)))
3716 ptrdiff_t overlap;
3717 /* There is still a possibility we will find the need to do code
3718 conversion. If that happens, set this variable to
3719 give up on handling REPLACE in the optimized way. */
3720 bool giveup_match_end = false;
3722 if (beg_offset != 0)
3724 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3725 report_file_error ("Setting file position", orig_filename);
3728 immediate_quit = 1;
3729 QUIT;
3730 /* Count how many chars at the start of the file
3731 match the text at the beginning of the buffer. */
3732 while (1)
3734 int nread, bufpos;
3736 nread = emacs_read (fd, read_buf, sizeof read_buf);
3737 if (nread < 0)
3738 report_file_error ("Read error", orig_filename);
3739 else if (nread == 0)
3740 break;
3742 if (CODING_REQUIRE_DETECTION (&coding))
3744 coding_system = detect_coding_system ((unsigned char *) read_buf,
3745 nread, nread, 1, 0,
3746 coding_system);
3747 setup_coding_system (coding_system, &coding);
3750 if (CODING_REQUIRE_DECODING (&coding))
3751 /* We found that the file should be decoded somehow.
3752 Let's give up here. */
3754 giveup_match_end = true;
3755 break;
3758 bufpos = 0;
3759 while (bufpos < nread && same_at_start < ZV_BYTE
3760 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3761 same_at_start++, bufpos++;
3762 /* If we found a discrepancy, stop the scan.
3763 Otherwise loop around and scan the next bufferful. */
3764 if (bufpos != nread)
3765 break;
3767 immediate_quit = false;
3768 /* If the file matches the buffer completely,
3769 there's no need to replace anything. */
3770 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3772 emacs_close (fd);
3773 clear_unwind_protect (fd_index);
3775 /* Truncate the buffer to the size of the file. */
3776 del_range_1 (same_at_start, same_at_end, 0, 0);
3777 goto handled;
3779 immediate_quit = true;
3780 QUIT;
3781 /* Count how many chars at the end of the file
3782 match the text at the end of the buffer. But, if we have
3783 already found that decoding is necessary, don't waste time. */
3784 while (!giveup_match_end)
3786 int total_read, nread, bufpos, trial;
3787 off_t curpos;
3789 /* At what file position are we now scanning? */
3790 curpos = end_offset - (ZV_BYTE - same_at_end);
3791 /* If the entire file matches the buffer tail, stop the scan. */
3792 if (curpos == 0)
3793 break;
3794 /* How much can we scan in the next step? */
3795 trial = min (curpos, sizeof read_buf);
3796 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3797 report_file_error ("Setting file position", orig_filename);
3799 total_read = nread = 0;
3800 while (total_read < trial)
3802 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3803 if (nread < 0)
3804 report_file_error ("Read error", orig_filename);
3805 else if (nread == 0)
3806 break;
3807 total_read += nread;
3810 /* Scan this bufferful from the end, comparing with
3811 the Emacs buffer. */
3812 bufpos = total_read;
3814 /* Compare with same_at_start to avoid counting some buffer text
3815 as matching both at the file's beginning and at the end. */
3816 while (bufpos > 0 && same_at_end > same_at_start
3817 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3818 same_at_end--, bufpos--;
3820 /* If we found a discrepancy, stop the scan.
3821 Otherwise loop around and scan the preceding bufferful. */
3822 if (bufpos != 0)
3824 /* If this discrepancy is because of code conversion,
3825 we cannot use this method; giveup and try the other. */
3826 if (same_at_end > same_at_start
3827 && FETCH_BYTE (same_at_end - 1) >= 0200
3828 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3829 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3830 giveup_match_end = true;
3831 break;
3834 if (nread == 0)
3835 break;
3837 immediate_quit = 0;
3839 if (! giveup_match_end)
3841 ptrdiff_t temp;
3843 /* We win! We can handle REPLACE the optimized way. */
3845 /* Extend the start of non-matching text area to multibyte
3846 character boundary. */
3847 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3848 while (same_at_start > BEGV_BYTE
3849 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3850 same_at_start--;
3852 /* Extend the end of non-matching text area to multibyte
3853 character boundary. */
3854 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3855 while (same_at_end < ZV_BYTE
3856 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3857 same_at_end++;
3859 /* Don't try to reuse the same piece of text twice. */
3860 overlap = (same_at_start - BEGV_BYTE
3861 - (same_at_end
3862 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3863 if (overlap > 0)
3864 same_at_end += overlap;
3865 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3867 /* Arrange to read only the nonmatching middle part of the file. */
3868 beg_offset += same_at_start - BEGV_BYTE;
3869 end_offset -= ZV_BYTE - same_at_end;
3871 invalidate_buffer_caches (current_buffer,
3872 BYTE_TO_CHAR (same_at_start),
3873 same_at_end_charpos);
3874 del_range_byte (same_at_start, same_at_end, 0);
3875 /* Insert from the file at the proper position. */
3876 temp = BYTE_TO_CHAR (same_at_start);
3877 SET_PT_BOTH (temp, same_at_start);
3879 /* If display currently starts at beginning of line,
3880 keep it that way. */
3881 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3882 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3884 replace_handled = true;
3888 /* If requested, replace the accessible part of the buffer
3889 with the file contents. Avoid replacing text at the
3890 beginning or end of the buffer that matches the file contents;
3891 that preserves markers pointing to the unchanged parts.
3893 Here we implement this feature for the case where code conversion
3894 is needed, in a simple way that needs a lot of memory.
3895 The preceding if-statement handles the case of no conversion
3896 in a more optimized way. */
3897 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3899 ptrdiff_t same_at_start_charpos;
3900 ptrdiff_t inserted_chars;
3901 ptrdiff_t overlap;
3902 ptrdiff_t bufpos;
3903 unsigned char *decoded;
3904 ptrdiff_t temp;
3905 ptrdiff_t this = 0;
3906 ptrdiff_t this_count = SPECPDL_INDEX ();
3907 bool multibyte
3908 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3909 Lisp_Object conversion_buffer;
3911 conversion_buffer = code_conversion_save (1, multibyte);
3913 /* First read the whole file, performing code conversion into
3914 CONVERSION_BUFFER. */
3916 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3917 report_file_error ("Setting file position", orig_filename);
3919 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3920 unprocessed = 0; /* Bytes not processed in previous loop. */
3922 while (1)
3924 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3925 quitting while reading a huge file. */
3927 /* Allow quitting out of the actual I/O. */
3928 immediate_quit = 1;
3929 QUIT;
3930 this = emacs_read (fd, read_buf + unprocessed,
3931 READ_BUF_SIZE - unprocessed);
3932 immediate_quit = 0;
3934 if (this <= 0)
3935 break;
3937 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3938 BUF_Z (XBUFFER (conversion_buffer)));
3939 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3940 unprocessed + this, conversion_buffer);
3941 unprocessed = coding.carryover_bytes;
3942 if (coding.carryover_bytes > 0)
3943 memcpy (read_buf, coding.carryover, unprocessed);
3946 if (this < 0)
3947 report_file_error ("Read error", orig_filename);
3948 emacs_close (fd);
3949 clear_unwind_protect (fd_index);
3951 if (unprocessed > 0)
3953 coding.mode |= CODING_MODE_LAST_BLOCK;
3954 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3955 unprocessed, conversion_buffer);
3956 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3959 coding_system = CODING_ID_NAME (coding.id);
3960 set_coding_system = true;
3961 maybe_move_gap (XBUFFER (conversion_buffer));
3962 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3963 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3964 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3966 /* Compare the beginning of the converted string with the buffer
3967 text. */
3969 bufpos = 0;
3970 while (bufpos < inserted && same_at_start < same_at_end
3971 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3972 same_at_start++, bufpos++;
3974 /* If the file matches the head of buffer completely,
3975 there's no need to replace anything. */
3977 if (bufpos == inserted)
3979 /* Truncate the buffer to the size of the file. */
3980 if (same_at_start != same_at_end)
3982 invalidate_buffer_caches (current_buffer,
3983 BYTE_TO_CHAR (same_at_start),
3984 BYTE_TO_CHAR (same_at_end));
3985 del_range_byte (same_at_start, same_at_end, 0);
3987 inserted = 0;
3989 unbind_to (this_count, Qnil);
3990 goto handled;
3993 /* Extend the start of non-matching text area to the previous
3994 multibyte character boundary. */
3995 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3996 while (same_at_start > BEGV_BYTE
3997 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3998 same_at_start--;
4000 /* Scan this bufferful from the end, comparing with
4001 the Emacs buffer. */
4002 bufpos = inserted;
4004 /* Compare with same_at_start to avoid counting some buffer text
4005 as matching both at the file's beginning and at the end. */
4006 while (bufpos > 0 && same_at_end > same_at_start
4007 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4008 same_at_end--, bufpos--;
4010 /* Extend the end of non-matching text area to the next
4011 multibyte character boundary. */
4012 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4013 while (same_at_end < ZV_BYTE
4014 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4015 same_at_end++;
4017 /* Don't try to reuse the same piece of text twice. */
4018 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4019 if (overlap > 0)
4020 same_at_end += overlap;
4021 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4023 /* If display currently starts at beginning of line,
4024 keep it that way. */
4025 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4026 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4028 /* Replace the chars that we need to replace,
4029 and update INSERTED to equal the number of bytes
4030 we are taking from the decoded string. */
4031 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4033 if (same_at_end != same_at_start)
4035 invalidate_buffer_caches (current_buffer,
4036 BYTE_TO_CHAR (same_at_start),
4037 same_at_end_charpos);
4038 del_range_byte (same_at_start, same_at_end, 0);
4039 temp = GPT;
4040 eassert (same_at_start == GPT_BYTE);
4041 same_at_start = GPT_BYTE;
4043 else
4045 temp = same_at_end_charpos;
4047 /* Insert from the file at the proper position. */
4048 SET_PT_BOTH (temp, same_at_start);
4049 same_at_start_charpos
4050 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4051 same_at_start - BEGV_BYTE
4052 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4053 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4054 inserted_chars
4055 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4056 same_at_start + inserted - BEGV_BYTE
4057 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4058 - same_at_start_charpos);
4059 /* This binding is to avoid ask-user-about-supersession-threat
4060 being called in insert_from_buffer (via in
4061 prepare_to_modify_buffer). */
4062 specbind (intern ("buffer-file-name"), Qnil);
4063 insert_from_buffer (XBUFFER (conversion_buffer),
4064 same_at_start_charpos, inserted_chars, 0);
4065 /* Set `inserted' to the number of inserted characters. */
4066 inserted = PT - temp;
4067 /* Set point before the inserted characters. */
4068 SET_PT_BOTH (temp, same_at_start);
4070 unbind_to (this_count, Qnil);
4072 goto handled;
4075 if (! not_regular)
4076 total = end_offset - beg_offset;
4077 else
4078 /* For a special file, all we can do is guess. */
4079 total = READ_BUF_SIZE;
4081 if (NILP (visit) && total > 0)
4083 if (!NILP (BVAR (current_buffer, file_truename))
4084 /* Make binding buffer-file-name to nil effective. */
4085 && !NILP (BVAR (current_buffer, filename))
4086 && SAVE_MODIFF >= MODIFF)
4087 we_locked_file = true;
4088 prepare_to_modify_buffer (PT, PT, NULL);
4091 move_gap_both (PT, PT_BYTE);
4092 if (GAP_SIZE < total)
4093 make_gap (total - GAP_SIZE);
4095 if (beg_offset != 0 || !NILP (replace))
4097 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4098 report_file_error ("Setting file position", orig_filename);
4101 /* In the following loop, HOW_MUCH contains the total bytes read so
4102 far for a regular file, and not changed for a special file. But,
4103 before exiting the loop, it is set to a negative value if I/O
4104 error occurs. */
4105 how_much = 0;
4107 /* Total bytes inserted. */
4108 inserted = 0;
4110 /* Here, we don't do code conversion in the loop. It is done by
4111 decode_coding_gap after all data are read into the buffer. */
4113 ptrdiff_t gap_size = GAP_SIZE;
4115 while (how_much < total)
4117 /* `try' is reserved in some compilers (Microsoft C). */
4118 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4119 ptrdiff_t this;
4121 if (not_regular)
4123 Lisp_Object nbytes;
4125 /* Maybe make more room. */
4126 if (gap_size < trytry)
4128 make_gap (trytry - gap_size);
4129 gap_size = GAP_SIZE - inserted;
4132 /* Read from the file, capturing `quit'. When an
4133 error occurs, end the loop, and arrange for a quit
4134 to be signaled after decoding the text we read. */
4135 nbytes = internal_condition_case_1
4136 (read_non_regular,
4137 make_save_int_int_int (fd, inserted, trytry),
4138 Qerror, read_non_regular_quit);
4140 if (NILP (nbytes))
4142 read_quit = true;
4143 break;
4146 this = XINT (nbytes);
4148 else
4150 /* Allow quitting out of the actual I/O. We don't make text
4151 part of the buffer until all the reading is done, so a C-g
4152 here doesn't do any harm. */
4153 immediate_quit = 1;
4154 QUIT;
4155 this = emacs_read (fd,
4156 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4157 + inserted),
4158 trytry);
4159 immediate_quit = 0;
4162 if (this <= 0)
4164 how_much = this;
4165 break;
4168 gap_size -= this;
4170 /* For a regular file, where TOTAL is the real size,
4171 count HOW_MUCH to compare with it.
4172 For a special file, where TOTAL is just a buffer size,
4173 so don't bother counting in HOW_MUCH.
4174 (INSERTED is where we count the number of characters inserted.) */
4175 if (! not_regular)
4176 how_much += this;
4177 inserted += this;
4181 /* Now we have either read all the file data into the gap,
4182 or stop reading on I/O error or quit. If nothing was
4183 read, undo marking the buffer modified. */
4185 if (inserted == 0)
4187 if (we_locked_file)
4188 unlock_file (BVAR (current_buffer, file_truename));
4189 Vdeactivate_mark = old_Vdeactivate_mark;
4191 else
4192 Fset (Qdeactivate_mark, Qt);
4194 emacs_close (fd);
4195 clear_unwind_protect (fd_index);
4197 if (how_much < 0)
4198 report_file_error ("Read error", orig_filename);
4200 /* Make the text read part of the buffer. */
4201 GAP_SIZE -= inserted;
4202 GPT += inserted;
4203 GPT_BYTE += inserted;
4204 ZV += inserted;
4205 ZV_BYTE += inserted;
4206 Z += inserted;
4207 Z_BYTE += inserted;
4209 if (GAP_SIZE > 0)
4210 /* Put an anchor to ensure multi-byte form ends at gap. */
4211 *GPT_ADDR = 0;
4213 notfound:
4215 if (NILP (coding_system))
4217 /* The coding system is not yet decided. Decide it by an
4218 optimized method for handling `coding:' tag.
4220 Note that we can get here only if the buffer was empty
4221 before the insertion. */
4223 if (!NILP (Vcoding_system_for_read))
4224 coding_system = Vcoding_system_for_read;
4225 else
4227 /* Since we are sure that the current buffer was empty
4228 before the insertion, we can toggle
4229 enable-multibyte-characters directly here without taking
4230 care of marker adjustment. By this way, we can run Lisp
4231 program safely before decoding the inserted text. */
4232 Lisp_Object unwind_data;
4233 ptrdiff_t count1 = SPECPDL_INDEX ();
4235 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4236 Fcons (BVAR (current_buffer, undo_list),
4237 Fcurrent_buffer ()));
4238 bset_enable_multibyte_characters (current_buffer, Qnil);
4239 bset_undo_list (current_buffer, Qt);
4240 record_unwind_protect (decide_coding_unwind, unwind_data);
4242 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4244 coding_system = call2 (Vset_auto_coding_function,
4245 filename, make_number (inserted));
4248 if (NILP (coding_system))
4250 /* If the coding system is not yet decided, check
4251 file-coding-system-alist. */
4252 coding_system = CALLN (Ffind_operation_coding_system,
4253 Qinsert_file_contents, orig_filename,
4254 visit, beg, end, Qnil);
4255 if (CONSP (coding_system))
4256 coding_system = XCAR (coding_system);
4258 unbind_to (count1, Qnil);
4259 inserted = Z_BYTE - BEG_BYTE;
4262 if (NILP (coding_system))
4263 coding_system = Qundecided;
4264 else
4265 CHECK_CODING_SYSTEM (coding_system);
4267 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4268 /* We must suppress all character code conversion except for
4269 end-of-line conversion. */
4270 coding_system = raw_text_coding_system (coding_system);
4271 setup_coding_system (coding_system, &coding);
4272 /* Ensure we set Vlast_coding_system_used. */
4273 set_coding_system = true;
4276 if (!NILP (visit))
4278 /* When we visit a file by raw-text, we change the buffer to
4279 unibyte. */
4280 if (CODING_FOR_UNIBYTE (&coding)
4281 /* Can't do this if part of the buffer might be preserved. */
4282 && NILP (replace))
4284 /* Visiting a file with these coding system makes the buffer
4285 unibyte. */
4286 if (inserted > 0)
4287 bset_enable_multibyte_characters (current_buffer, Qnil);
4288 else
4289 Fset_buffer_multibyte (Qnil);
4293 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4294 if (CODING_MAY_REQUIRE_DECODING (&coding)
4295 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4297 move_gap_both (PT, PT_BYTE);
4298 GAP_SIZE += inserted;
4299 ZV_BYTE -= inserted;
4300 Z_BYTE -= inserted;
4301 ZV -= inserted;
4302 Z -= inserted;
4303 decode_coding_gap (&coding, inserted, inserted);
4304 inserted = coding.produced_char;
4305 coding_system = CODING_ID_NAME (coding.id);
4307 else if (inserted > 0)
4309 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4310 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4311 inserted);
4314 /* Call after-change hooks for the inserted text, aside from the case
4315 of normal visiting (not with REPLACE), which is done in a new buffer
4316 "before" the buffer is changed. */
4317 if (inserted > 0 && total > 0
4318 && (NILP (visit) || !NILP (replace)))
4320 signal_after_change (PT, 0, inserted);
4321 update_compositions (PT, PT, CHECK_BORDER);
4324 /* Now INSERTED is measured in characters. */
4326 handled:
4328 if (inserted > 0)
4329 restore_window_points (window_markers, inserted,
4330 BYTE_TO_CHAR (same_at_start),
4331 same_at_end_charpos);
4333 if (!NILP (visit))
4335 if (empty_undo_list_p)
4336 bset_undo_list (current_buffer, Qnil);
4338 if (NILP (handler))
4340 current_buffer->modtime = mtime;
4341 current_buffer->modtime_size = st.st_size;
4342 bset_filename (current_buffer, orig_filename);
4345 SAVE_MODIFF = MODIFF;
4346 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4347 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4348 if (NILP (handler))
4350 if (!NILP (BVAR (current_buffer, file_truename)))
4351 unlock_file (BVAR (current_buffer, file_truename));
4352 unlock_file (filename);
4354 if (not_regular)
4355 xsignal2 (Qfile_error,
4356 build_string ("not a regular file"), orig_filename);
4359 if (set_coding_system)
4360 Vlast_coding_system_used = coding_system;
4362 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4364 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4365 visit);
4366 if (! NILP (insval))
4368 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4369 wrong_type_argument (intern ("inserted-chars"), insval);
4370 inserted = XFASTINT (insval);
4374 /* Decode file format. */
4375 if (inserted > 0)
4377 /* Don't run point motion or modification hooks when decoding. */
4378 ptrdiff_t count1 = SPECPDL_INDEX ();
4379 ptrdiff_t old_inserted = inserted;
4380 specbind (Qinhibit_point_motion_hooks, Qt);
4381 specbind (Qinhibit_modification_hooks, Qt);
4383 /* Save old undo list and don't record undo for decoding. */
4384 old_undo = BVAR (current_buffer, undo_list);
4385 bset_undo_list (current_buffer, Qt);
4387 if (NILP (replace))
4389 insval = call3 (Qformat_decode,
4390 Qnil, make_number (inserted), visit);
4391 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4392 wrong_type_argument (intern ("inserted-chars"), insval);
4393 inserted = XFASTINT (insval);
4395 else
4397 /* If REPLACE is non-nil and we succeeded in not replacing the
4398 beginning or end of the buffer text with the file's contents,
4399 call format-decode with `point' positioned at the beginning
4400 of the buffer and `inserted' equaling the number of
4401 characters in the buffer. Otherwise, format-decode might
4402 fail to correctly analyze the beginning or end of the buffer.
4403 Hence we temporarily save `point' and `inserted' here and
4404 restore `point' iff format-decode did not insert or delete
4405 any text. Otherwise we leave `point' at point-min. */
4406 ptrdiff_t opoint = PT;
4407 ptrdiff_t opoint_byte = PT_BYTE;
4408 ptrdiff_t oinserted = ZV - BEGV;
4409 EMACS_INT ochars_modiff = CHARS_MODIFF;
4411 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4412 insval = call3 (Qformat_decode,
4413 Qnil, make_number (oinserted), visit);
4414 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4415 wrong_type_argument (intern ("inserted-chars"), insval);
4416 if (ochars_modiff == CHARS_MODIFF)
4417 /* format_decode didn't modify buffer's characters => move
4418 point back to position before inserted text and leave
4419 value of inserted alone. */
4420 SET_PT_BOTH (opoint, opoint_byte);
4421 else
4422 /* format_decode modified buffer's characters => consider
4423 entire buffer changed and leave point at point-min. */
4424 inserted = XFASTINT (insval);
4427 /* For consistency with format-decode call these now iff inserted > 0
4428 (martin 2007-06-28). */
4429 p = Vafter_insert_file_functions;
4430 while (CONSP (p))
4432 if (NILP (replace))
4434 insval = call1 (XCAR (p), make_number (inserted));
4435 if (!NILP (insval))
4437 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4438 wrong_type_argument (intern ("inserted-chars"), insval);
4439 inserted = XFASTINT (insval);
4442 else
4444 /* For the rationale of this see the comment on
4445 format-decode above. */
4446 ptrdiff_t opoint = PT;
4447 ptrdiff_t opoint_byte = PT_BYTE;
4448 ptrdiff_t oinserted = ZV - BEGV;
4449 EMACS_INT ochars_modiff = CHARS_MODIFF;
4451 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4452 insval = call1 (XCAR (p), make_number (oinserted));
4453 if (!NILP (insval))
4455 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4456 wrong_type_argument (intern ("inserted-chars"), insval);
4457 if (ochars_modiff == CHARS_MODIFF)
4458 /* after_insert_file_functions didn't modify
4459 buffer's characters => move point back to
4460 position before inserted text and leave value of
4461 inserted alone. */
4462 SET_PT_BOTH (opoint, opoint_byte);
4463 else
4464 /* after_insert_file_functions did modify buffer's
4465 characters => consider entire buffer changed and
4466 leave point at point-min. */
4467 inserted = XFASTINT (insval);
4471 QUIT;
4472 p = XCDR (p);
4475 if (!empty_undo_list_p)
4477 bset_undo_list (current_buffer, old_undo);
4478 if (CONSP (old_undo) && inserted != old_inserted)
4480 /* Adjust the last undo record for the size change during
4481 the format conversion. */
4482 Lisp_Object tem = XCAR (old_undo);
4483 if (CONSP (tem) && INTEGERP (XCAR (tem))
4484 && INTEGERP (XCDR (tem))
4485 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4486 XSETCDR (tem, make_number (PT + inserted));
4489 else
4490 /* If undo_list was Qt before, keep it that way.
4491 Otherwise start with an empty undo_list. */
4492 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4494 unbind_to (count1, Qnil);
4497 if (!NILP (visit)
4498 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4500 /* If visiting nonexistent file, return nil. */
4501 report_file_errno ("Opening input file", orig_filename, save_errno);
4504 /* We made a lot of deletions and insertions above, so invalidate
4505 the newline cache for the entire region of the inserted
4506 characters. */
4507 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4508 invalidate_region_cache (current_buffer->base_buffer,
4509 current_buffer->base_buffer->newline_cache,
4510 PT - BEG, Z - PT - inserted);
4511 else if (current_buffer->newline_cache)
4512 invalidate_region_cache (current_buffer,
4513 current_buffer->newline_cache,
4514 PT - BEG, Z - PT - inserted);
4516 if (read_quit)
4517 quit ();
4519 /* Retval needs to be dealt with in all cases consistently. */
4520 if (NILP (val))
4521 val = list2 (orig_filename, make_number (inserted));
4523 return unbind_to (count, val);
4526 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4528 static void
4529 build_annotations_unwind (Lisp_Object arg)
4531 Vwrite_region_annotation_buffers = arg;
4534 /* Decide the coding-system to encode the data with. */
4536 static Lisp_Object
4537 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4538 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4539 struct coding_system *coding)
4541 Lisp_Object val;
4542 Lisp_Object eol_parent = Qnil;
4544 if (auto_saving
4545 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4546 BVAR (current_buffer, auto_save_file_name))))
4548 val = Qutf_8_emacs;
4549 eol_parent = Qunix;
4551 else if (!NILP (Vcoding_system_for_write))
4553 val = Vcoding_system_for_write;
4554 if (coding_system_require_warning
4555 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4556 /* Confirm that VAL can surely encode the current region. */
4557 val = call5 (Vselect_safe_coding_system_function,
4558 start, end, list2 (Qt, val),
4559 Qnil, filename);
4561 else
4563 /* If the variable `buffer-file-coding-system' is set locally,
4564 it means that the file was read with some kind of code
4565 conversion or the variable is explicitly set by users. We
4566 had better write it out with the same coding system even if
4567 `enable-multibyte-characters' is nil.
4569 If it is not set locally, we anyway have to convert EOL
4570 format if the default value of `buffer-file-coding-system'
4571 tells that it is not Unix-like (LF only) format. */
4572 bool using_default_coding = 0;
4573 bool force_raw_text = 0;
4575 val = BVAR (current_buffer, buffer_file_coding_system);
4576 if (NILP (val)
4577 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4579 val = Qnil;
4580 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4581 force_raw_text = 1;
4584 if (NILP (val))
4586 /* Check file-coding-system-alist. */
4587 Lisp_Object coding_systems
4588 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4589 filename, append, visit, lockname);
4590 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4591 val = XCDR (coding_systems);
4594 if (NILP (val))
4596 /* If we still have not decided a coding system, use the
4597 current buffer's value of buffer-file-coding-system. */
4598 val = BVAR (current_buffer, buffer_file_coding_system);
4599 using_default_coding = 1;
4602 if (! NILP (val) && ! force_raw_text)
4604 Lisp_Object spec, attrs;
4606 CHECK_CODING_SYSTEM (val);
4607 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4608 attrs = AREF (spec, 0);
4609 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4610 force_raw_text = 1;
4613 if (!force_raw_text
4614 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4616 /* Confirm that VAL can surely encode the current region. */
4617 val = call5 (Vselect_safe_coding_system_function,
4618 start, end, val, Qnil, filename);
4619 /* As the function specified by select-safe-coding-system-function
4620 is out of our control, make sure we are not fed by bogus
4621 values. */
4622 if (!NILP (val))
4623 CHECK_CODING_SYSTEM (val);
4626 /* If the decided coding-system doesn't specify end-of-line
4627 format, we use that of
4628 `default-buffer-file-coding-system'. */
4629 if (! using_default_coding)
4631 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4633 if (! NILP (dflt))
4634 val = coding_inherit_eol_type (val, dflt);
4637 /* If we decide not to encode text, use `raw-text' or one of its
4638 subsidiaries. */
4639 if (force_raw_text)
4640 val = raw_text_coding_system (val);
4643 val = coding_inherit_eol_type (val, eol_parent);
4644 setup_coding_system (val, coding);
4646 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4647 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4648 return val;
4651 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4652 "r\nFWrite region to file: \ni\ni\ni\np",
4653 doc: /* Write current region into specified file.
4654 When called from a program, requires three arguments:
4655 START, END and FILENAME. START and END are normally buffer positions
4656 specifying the part of the buffer to write.
4657 If START is nil, that means to use the entire buffer contents; END is
4658 ignored.
4659 If START is a string, then output that string to the file
4660 instead of any buffer contents; END is ignored.
4662 Optional fourth argument APPEND if non-nil means
4663 append to existing file contents (if any). If it is a number,
4664 seek to that offset in the file before writing.
4665 Optional fifth argument VISIT, if t or a string, means
4666 set the last-save-file-modtime of buffer to this file's modtime
4667 and mark buffer not modified.
4668 If VISIT is a string, it is a second file name;
4669 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4670 VISIT is also the file name to lock and unlock for clash detection.
4671 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4672 do not display the \"Wrote file\" message.
4673 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4674 use for locking and unlocking, overriding FILENAME and VISIT.
4675 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4676 for an existing file with the same name. If MUSTBENEW is `excl',
4677 that means to get an error if the file already exists; never overwrite.
4678 If MUSTBENEW is neither nil nor `excl', that means ask for
4679 confirmation before overwriting, but do go ahead and overwrite the file
4680 if the user confirms.
4682 This does code conversion according to the value of
4683 `coding-system-for-write', `buffer-file-coding-system', or
4684 `file-coding-system-alist', and sets the variable
4685 `last-coding-system-used' to the coding system actually used.
4687 This calls `write-region-annotate-functions' at the start, and
4688 `write-region-post-annotation-function' at the end. */)
4689 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4690 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4692 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4693 -1);
4696 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4697 descriptor for FILENAME, so do not open or close FILENAME. */
4699 Lisp_Object
4700 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4701 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4702 Lisp_Object mustbenew, int desc)
4704 int open_flags;
4705 int mode;
4706 off_t offset UNINIT;
4707 bool open_and_close_file = desc < 0;
4708 bool ok;
4709 int save_errno = 0;
4710 const char *fn;
4711 struct stat st;
4712 struct timespec modtime;
4713 ptrdiff_t count = SPECPDL_INDEX ();
4714 ptrdiff_t count1 UNINIT;
4715 Lisp_Object handler;
4716 Lisp_Object visit_file;
4717 Lisp_Object annotations;
4718 Lisp_Object encoded_filename;
4719 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4720 bool quietly = !NILP (visit);
4721 bool file_locked = 0;
4722 struct buffer *given_buffer;
4723 struct coding_system coding;
4725 if (current_buffer->base_buffer && visiting)
4726 error ("Cannot do file visiting in an indirect buffer");
4728 if (!NILP (start) && !STRINGP (start))
4729 validate_region (&start, &end);
4731 visit_file = Qnil;
4733 filename = Fexpand_file_name (filename, Qnil);
4735 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4736 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4738 if (STRINGP (visit))
4739 visit_file = Fexpand_file_name (visit, Qnil);
4740 else
4741 visit_file = filename;
4743 if (NILP (lockname))
4744 lockname = visit_file;
4746 annotations = Qnil;
4748 /* If the file name has special constructs in it,
4749 call the corresponding file handler. */
4750 handler = Ffind_file_name_handler (filename, Qwrite_region);
4751 /* If FILENAME has no handler, see if VISIT has one. */
4752 if (NILP (handler) && STRINGP (visit))
4753 handler = Ffind_file_name_handler (visit, Qwrite_region);
4755 if (!NILP (handler))
4757 Lisp_Object val;
4758 val = call6 (handler, Qwrite_region, start, end,
4759 filename, append, visit);
4761 if (visiting)
4763 SAVE_MODIFF = MODIFF;
4764 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4765 bset_filename (current_buffer, visit_file);
4768 return val;
4771 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4773 /* Special kludge to simplify auto-saving. */
4774 if (NILP (start))
4776 /* Do it later, so write-region-annotate-function can work differently
4777 if we save "the buffer" vs "a region".
4778 This is useful in tar-mode. --Stef
4779 XSETFASTINT (start, BEG);
4780 XSETFASTINT (end, Z); */
4781 Fwiden ();
4784 record_unwind_protect (build_annotations_unwind,
4785 Vwrite_region_annotation_buffers);
4786 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4788 given_buffer = current_buffer;
4790 if (!STRINGP (start))
4792 annotations = build_annotations (start, end);
4794 if (current_buffer != given_buffer)
4796 XSETFASTINT (start, BEGV);
4797 XSETFASTINT (end, ZV);
4801 if (NILP (start))
4803 XSETFASTINT (start, BEGV);
4804 XSETFASTINT (end, ZV);
4807 /* Decide the coding-system to encode the data with.
4808 We used to make this choice before calling build_annotations, but that
4809 leads to problems when a write-annotate-function takes care of
4810 unsavable chars (as was the case with X-Symbol). */
4811 Vlast_coding_system_used
4812 = choose_write_coding_system (start, end, filename,
4813 append, visit, lockname, &coding);
4815 if (open_and_close_file && !auto_saving)
4817 lock_file (lockname);
4818 file_locked = 1;
4821 encoded_filename = ENCODE_FILE (filename);
4822 fn = SSDATA (encoded_filename);
4823 open_flags = O_WRONLY | O_CREAT;
4824 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4825 if (NUMBERP (append))
4826 offset = file_offset (append);
4827 else if (!NILP (append))
4828 open_flags |= O_APPEND;
4829 #ifdef DOS_NT
4830 mode = S_IREAD | S_IWRITE;
4831 #else
4832 mode = auto_saving ? auto_save_mode_bits : 0666;
4833 #endif
4835 if (open_and_close_file)
4837 desc = emacs_open (fn, open_flags, mode);
4838 if (desc < 0)
4840 int open_errno = errno;
4841 if (file_locked)
4842 unlock_file (lockname);
4843 report_file_errno ("Opening output file", filename, open_errno);
4846 count1 = SPECPDL_INDEX ();
4847 record_unwind_protect_int (close_file_unwind, desc);
4850 if (NUMBERP (append))
4852 off_t ret = lseek (desc, offset, SEEK_SET);
4853 if (ret < 0)
4855 int lseek_errno = errno;
4856 if (file_locked)
4857 unlock_file (lockname);
4858 report_file_errno ("Lseek error", filename, lseek_errno);
4862 immediate_quit = 1;
4864 if (STRINGP (start))
4865 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4866 else if (XINT (start) != XINT (end))
4867 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4868 &annotations, &coding);
4869 else
4871 /* If file was empty, still need to write the annotations. */
4872 coding.mode |= CODING_MODE_LAST_BLOCK;
4873 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4875 save_errno = errno;
4877 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4878 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4880 /* We have to flush out a data. */
4881 coding.mode |= CODING_MODE_LAST_BLOCK;
4882 ok = e_write (desc, Qnil, 1, 1, &coding);
4883 save_errno = errno;
4886 immediate_quit = 0;
4888 /* fsync is not crucial for temporary files. Nor for auto-save
4889 files, since they might lose some work anyway. */
4890 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4892 /* Transfer data and metadata to disk, retrying if interrupted.
4893 fsync can report a write failure here, e.g., due to disk full
4894 under NFS. But ignore EINVAL, which means fsync is not
4895 supported on this file. */
4896 while (fsync (desc) != 0)
4897 if (errno != EINTR)
4899 if (errno != EINVAL)
4900 ok = 0, save_errno = errno;
4901 break;
4905 modtime = invalid_timespec ();
4906 if (visiting)
4908 if (fstat (desc, &st) == 0)
4909 modtime = get_stat_mtime (&st);
4910 else
4911 ok = 0, save_errno = errno;
4914 if (open_and_close_file)
4916 /* NFS can report a write failure now. */
4917 if (emacs_close (desc) < 0)
4918 ok = 0, save_errno = errno;
4920 /* Discard the unwind protect for close_file_unwind. */
4921 specpdl_ptr = specpdl + count1;
4924 /* Some file systems have a bug where st_mtime is not updated
4925 properly after a write. For example, CIFS might not see the
4926 st_mtime change until after the file is opened again.
4928 Attempt to detect this file system bug, and update MODTIME to the
4929 newer st_mtime if the bug appears to be present. This introduces
4930 a race condition, so to avoid most instances of the race condition
4931 on non-buggy file systems, skip this check if the most recently
4932 encountered non-buggy file system was the current file system.
4934 A race condition can occur if some other process modifies the
4935 file between the fstat above and the fstat below, but the race is
4936 unlikely and a similar race between the last write and the fstat
4937 above cannot possibly be closed anyway. */
4939 if (timespec_valid_p (modtime)
4940 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4942 int desc1 = emacs_open (fn, O_WRONLY, 0);
4943 if (desc1 >= 0)
4945 struct stat st1;
4946 if (fstat (desc1, &st1) == 0
4947 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4949 /* Use the heuristic if it appears to be valid. With neither
4950 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4951 file, the time stamp won't change. Also, some non-POSIX
4952 systems don't update an empty file's time stamp when
4953 truncating it. Finally, file systems with 100 ns or worse
4954 resolution sometimes seem to have bugs: on a system with ns
4955 resolution, checking ns % 100 incorrectly avoids the heuristic
4956 1% of the time, but the problem should be temporary as we will
4957 try again on the next time stamp. */
4958 bool use_heuristic
4959 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4960 && st.st_size != 0
4961 && modtime.tv_nsec % 100 != 0);
4963 struct timespec modtime1 = get_stat_mtime (&st1);
4964 if (use_heuristic
4965 && timespec_cmp (modtime, modtime1) == 0
4966 && st.st_size == st1.st_size)
4968 timestamp_file_system = st.st_dev;
4969 valid_timestamp_file_system = 1;
4971 else
4973 st.st_size = st1.st_size;
4974 modtime = modtime1;
4977 emacs_close (desc1);
4981 /* Call write-region-post-annotation-function. */
4982 while (CONSP (Vwrite_region_annotation_buffers))
4984 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4985 if (!NILP (Fbuffer_live_p (buf)))
4987 Fset_buffer (buf);
4988 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4989 call0 (Vwrite_region_post_annotation_function);
4991 Vwrite_region_annotation_buffers
4992 = XCDR (Vwrite_region_annotation_buffers);
4995 unbind_to (count, Qnil);
4997 if (file_locked)
4998 unlock_file (lockname);
5000 /* Do this before reporting IO error
5001 to avoid a "file has changed on disk" warning on
5002 next attempt to save. */
5003 if (timespec_valid_p (modtime))
5005 current_buffer->modtime = modtime;
5006 current_buffer->modtime_size = st.st_size;
5009 if (! ok)
5010 report_file_errno ("Write error", filename, save_errno);
5012 if (visiting)
5014 SAVE_MODIFF = MODIFF;
5015 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5016 bset_filename (current_buffer, visit_file);
5017 update_mode_lines = 14;
5019 else if (quietly)
5021 if (auto_saving
5022 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5023 BVAR (current_buffer, auto_save_file_name))))
5024 SAVE_MODIFF = MODIFF;
5026 return Qnil;
5029 if (!auto_saving && !noninteractive)
5030 message_with_string ((NUMBERP (append)
5031 ? "Updated %s"
5032 : ! NILP (append)
5033 ? "Added to %s"
5034 : "Wrote %s"),
5035 visit_file, 1);
5037 return Qnil;
5040 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5041 doc: /* Return t if (car A) is numerically less than (car B). */)
5042 (Lisp_Object a, Lisp_Object b)
5044 return CALLN (Flss, Fcar (a), Fcar (b));
5047 /* Build the complete list of annotations appropriate for writing out
5048 the text between START and END, by calling all the functions in
5049 write-region-annotate-functions and merging the lists they return.
5050 If one of these functions switches to a different buffer, we assume
5051 that buffer contains altered text. Therefore, the caller must
5052 make sure to restore the current buffer in all cases,
5053 as save-excursion would do. */
5055 static Lisp_Object
5056 build_annotations (Lisp_Object start, Lisp_Object end)
5058 Lisp_Object annotations;
5059 Lisp_Object p, res;
5060 Lisp_Object original_buffer;
5061 int i;
5062 bool used_global = false;
5064 XSETBUFFER (original_buffer, current_buffer);
5066 annotations = Qnil;
5067 p = Vwrite_region_annotate_functions;
5068 while (CONSP (p))
5070 struct buffer *given_buffer = current_buffer;
5071 if (EQ (Qt, XCAR (p)) && !used_global)
5072 { /* Use the global value of the hook. */
5073 used_global = true;
5074 p = CALLN (Fappend,
5075 Fdefault_value (Qwrite_region_annotate_functions),
5076 XCDR (p));
5077 continue;
5079 Vwrite_region_annotations_so_far = annotations;
5080 res = call2 (XCAR (p), start, end);
5081 /* If the function makes a different buffer current,
5082 assume that means this buffer contains altered text to be output.
5083 Reset START and END from the buffer bounds
5084 and discard all previous annotations because they should have
5085 been dealt with by this function. */
5086 if (current_buffer != given_buffer)
5088 Vwrite_region_annotation_buffers
5089 = Fcons (Fcurrent_buffer (),
5090 Vwrite_region_annotation_buffers);
5091 XSETFASTINT (start, BEGV);
5092 XSETFASTINT (end, ZV);
5093 annotations = Qnil;
5095 Flength (res); /* Check basic validity of return value */
5096 annotations = merge (annotations, res, Qcar_less_than_car);
5097 p = XCDR (p);
5100 /* Now do the same for annotation functions implied by the file-format */
5101 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5102 p = BVAR (current_buffer, auto_save_file_format);
5103 else
5104 p = BVAR (current_buffer, file_format);
5105 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5107 struct buffer *given_buffer = current_buffer;
5109 Vwrite_region_annotations_so_far = annotations;
5111 /* Value is either a list of annotations or nil if the function
5112 has written annotations to a temporary buffer, which is now
5113 current. */
5114 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5115 original_buffer, make_number (i));
5116 if (current_buffer != given_buffer)
5118 XSETFASTINT (start, BEGV);
5119 XSETFASTINT (end, ZV);
5120 annotations = Qnil;
5123 if (CONSP (res))
5124 annotations = merge (annotations, res, Qcar_less_than_car);
5127 return annotations;
5131 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5132 If STRING is nil, POS is the character position in the current buffer.
5133 Intersperse with them the annotations from *ANNOT
5134 which fall within the range of POS to POS + NCHARS,
5135 each at its appropriate position.
5137 We modify *ANNOT by discarding elements as we use them up.
5139 Return true if successful. */
5141 static bool
5142 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5143 ptrdiff_t nchars, Lisp_Object *annot,
5144 struct coding_system *coding)
5146 Lisp_Object tem;
5147 ptrdiff_t nextpos;
5148 ptrdiff_t lastpos = pos + nchars;
5150 while (NILP (*annot) || CONSP (*annot))
5152 tem = Fcar_safe (Fcar (*annot));
5153 nextpos = pos - 1;
5154 if (INTEGERP (tem))
5155 nextpos = XFASTINT (tem);
5157 /* If there are no more annotations in this range,
5158 output the rest of the range all at once. */
5159 if (! (nextpos >= pos && nextpos <= lastpos))
5160 return e_write (desc, string, pos, lastpos, coding);
5162 /* Output buffer text up to the next annotation's position. */
5163 if (nextpos > pos)
5165 if (!e_write (desc, string, pos, nextpos, coding))
5166 return 0;
5167 pos = nextpos;
5169 /* Output the annotation. */
5170 tem = Fcdr (Fcar (*annot));
5171 if (STRINGP (tem))
5173 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5174 return 0;
5176 *annot = Fcdr (*annot);
5178 return 1;
5181 /* Maximum number of characters that the next
5182 function encodes per one loop iteration. */
5184 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5186 /* Write text in the range START and END into descriptor DESC,
5187 encoding them with coding system CODING. If STRING is nil, START
5188 and END are character positions of the current buffer, else they
5189 are indexes to the string STRING. Return true if successful. */
5191 static bool
5192 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5193 struct coding_system *coding)
5195 if (STRINGP (string))
5197 start = 0;
5198 end = SCHARS (string);
5201 /* We used to have a code for handling selective display here. But,
5202 now it is handled within encode_coding. */
5204 while (start < end)
5206 if (STRINGP (string))
5208 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5209 if (CODING_REQUIRE_ENCODING (coding))
5211 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5213 /* Avoid creating huge Lisp string in encode_coding_object. */
5214 if (nchars == E_WRITE_MAX)
5215 coding->raw_destination = 1;
5217 encode_coding_object
5218 (coding, string, start, string_char_to_byte (string, start),
5219 start + nchars, string_char_to_byte (string, start + nchars),
5220 Qt);
5222 else
5224 coding->dst_object = string;
5225 coding->consumed_char = SCHARS (string);
5226 coding->produced = SBYTES (string);
5229 else
5231 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5232 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5234 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5235 if (CODING_REQUIRE_ENCODING (coding))
5237 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5239 /* Likewise. */
5240 if (nchars == E_WRITE_MAX)
5241 coding->raw_destination = 1;
5243 encode_coding_object
5244 (coding, Fcurrent_buffer (), start, start_byte,
5245 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5247 else
5249 coding->dst_object = Qnil;
5250 coding->dst_pos_byte = start_byte;
5251 if (start >= GPT || end <= GPT)
5253 coding->consumed_char = end - start;
5254 coding->produced = end_byte - start_byte;
5256 else
5258 coding->consumed_char = GPT - start;
5259 coding->produced = GPT_BYTE - start_byte;
5264 if (coding->produced > 0)
5266 char *buf = (coding->raw_destination ? (char *) coding->destination
5267 : (STRINGP (coding->dst_object)
5268 ? SSDATA (coding->dst_object)
5269 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5270 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5272 if (coding->raw_destination)
5274 /* We're responsible for freeing this, see
5275 encode_coding_object to check why. */
5276 xfree (coding->destination);
5277 coding->raw_destination = 0;
5279 if (coding->produced)
5280 return 0;
5282 start += coding->consumed_char;
5285 return 1;
5288 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5289 Sverify_visited_file_modtime, 0, 1, 0,
5290 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5291 This means that the file has not been changed since it was visited or saved.
5292 If BUF is omitted or nil, it defaults to the current buffer.
5293 See Info node `(elisp)Modification Time' for more details. */)
5294 (Lisp_Object buf)
5296 struct buffer *b = decode_buffer (buf);
5297 struct stat st;
5298 Lisp_Object handler;
5299 Lisp_Object filename;
5300 struct timespec mtime;
5302 if (!STRINGP (BVAR (b, filename))) return Qt;
5303 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5305 /* If the file name has special constructs in it,
5306 call the corresponding file handler. */
5307 handler = Ffind_file_name_handler (BVAR (b, filename),
5308 Qverify_visited_file_modtime);
5309 if (!NILP (handler))
5310 return call2 (handler, Qverify_visited_file_modtime, buf);
5312 filename = ENCODE_FILE (BVAR (b, filename));
5314 mtime = (stat (SSDATA (filename), &st) == 0
5315 ? get_stat_mtime (&st)
5316 : time_error_value (errno));
5317 if (timespec_cmp (mtime, b->modtime) == 0
5318 && (b->modtime_size < 0
5319 || st.st_size == b->modtime_size))
5320 return Qt;
5321 return Qnil;
5324 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5325 Svisited_file_modtime, 0, 0, 0,
5326 doc: /* Return the current buffer's recorded visited file modification time.
5327 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5328 `file-attributes' returns. If the current buffer has no recorded file
5329 modification time, this function returns 0. If the visited file
5330 doesn't exist, return -1.
5331 See Info node `(elisp)Modification Time' for more details. */)
5332 (void)
5334 int ns = current_buffer->modtime.tv_nsec;
5335 if (ns < 0)
5336 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5337 return make_lisp_time (current_buffer->modtime);
5340 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5341 Sset_visited_file_modtime, 0, 1, 0,
5342 doc: /* Update buffer's recorded modification time from the visited file's time.
5343 Useful if the buffer was not read from the file normally
5344 or if the file itself has been changed for some known benign reason.
5345 An argument specifies the modification time value to use
5346 \(instead of that of the visited file), in the form of a list
5347 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5348 `visited-file-modtime'. */)
5349 (Lisp_Object time_flag)
5351 if (!NILP (time_flag))
5353 struct timespec mtime;
5354 if (INTEGERP (time_flag))
5356 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5357 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5359 else
5360 mtime = lisp_time_argument (time_flag);
5362 current_buffer->modtime = mtime;
5363 current_buffer->modtime_size = -1;
5365 else
5367 register Lisp_Object filename;
5368 struct stat st;
5369 Lisp_Object handler;
5371 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5373 /* If the file name has special constructs in it,
5374 call the corresponding file handler. */
5375 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5376 if (!NILP (handler))
5377 /* The handler can find the file name the same way we did. */
5378 return call2 (handler, Qset_visited_file_modtime, Qnil);
5380 filename = ENCODE_FILE (filename);
5382 if (stat (SSDATA (filename), &st) >= 0)
5384 current_buffer->modtime = get_stat_mtime (&st);
5385 current_buffer->modtime_size = st.st_size;
5389 return Qnil;
5392 static Lisp_Object
5393 auto_save_error (Lisp_Object error_val)
5395 auto_save_error_occurred = 1;
5397 ring_bell (XFRAME (selected_frame));
5399 AUTO_STRING (format, "Auto-saving %s: %s");
5400 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5401 Ferror_message_string (error_val));
5402 call3 (intern ("display-warning"),
5403 intern ("auto-save"), msg, intern ("error"));
5405 return Qnil;
5408 static Lisp_Object
5409 auto_save_1 (void)
5411 struct stat st;
5412 Lisp_Object modes;
5414 auto_save_mode_bits = 0666;
5416 /* Get visited file's mode to become the auto save file's mode. */
5417 if (! NILP (BVAR (current_buffer, filename)))
5419 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5420 /* But make sure we can overwrite it later! */
5421 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5422 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5423 INTEGERP (modes))
5424 /* Remote files don't cooperate with stat. */
5425 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5428 return
5429 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5430 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5431 Qnil, Qnil);
5434 struct auto_save_unwind
5436 FILE *stream;
5437 bool auto_raise;
5440 static void
5441 do_auto_save_unwind (void *arg)
5443 struct auto_save_unwind *p = arg;
5444 FILE *stream = p->stream;
5445 minibuffer_auto_raise = p->auto_raise;
5446 auto_saving = 0;
5447 if (stream != NULL)
5449 block_input ();
5450 fclose (stream);
5451 unblock_input ();
5455 static Lisp_Object
5456 do_auto_save_make_dir (Lisp_Object dir)
5458 Lisp_Object result;
5460 auto_saving_dir_umask = 077;
5461 result = call2 (Qmake_directory, dir, Qt);
5462 auto_saving_dir_umask = 0;
5463 return result;
5466 static Lisp_Object
5467 do_auto_save_eh (Lisp_Object ignore)
5469 auto_saving_dir_umask = 0;
5470 return Qnil;
5473 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5474 doc: /* Auto-save all buffers that need it.
5475 This is all buffers that have auto-saving enabled
5476 and are changed since last auto-saved.
5477 Auto-saving writes the buffer into a file
5478 so that your editing is not lost if the system crashes.
5479 This file is not the file you visited; that changes only when you save.
5480 Normally we run the normal hook `auto-save-hook' before saving.
5482 A non-nil NO-MESSAGE argument means do not print any message if successful.
5483 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5484 (Lisp_Object no_message, Lisp_Object current_only)
5486 struct buffer *old = current_buffer, *b;
5487 Lisp_Object tail, buf, hook;
5488 bool auto_saved = 0;
5489 int do_handled_files;
5490 Lisp_Object oquit;
5491 FILE *stream = NULL;
5492 ptrdiff_t count = SPECPDL_INDEX ();
5493 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5494 bool old_message_p = 0;
5495 struct auto_save_unwind auto_save_unwind;
5497 if (max_specpdl_size < specpdl_size + 40)
5498 max_specpdl_size = specpdl_size + 40;
5500 if (minibuf_level)
5501 no_message = Qt;
5503 if (NILP (no_message))
5505 old_message_p = push_message ();
5506 record_unwind_protect_void (pop_message_unwind);
5509 /* Ordinarily don't quit within this function,
5510 but don't make it impossible to quit (in case we get hung in I/O). */
5511 oquit = Vquit_flag;
5512 Vquit_flag = Qnil;
5514 hook = intern ("auto-save-hook");
5515 safe_run_hooks (hook);
5517 if (STRINGP (Vauto_save_list_file_name))
5519 Lisp_Object listfile;
5521 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5523 /* Don't try to create the directory when shutting down Emacs,
5524 because creating the directory might signal an error, and
5525 that would leave Emacs in a strange state. */
5526 if (!NILP (Vrun_hooks))
5528 Lisp_Object dir;
5529 dir = Ffile_name_directory (listfile);
5530 if (NILP (Ffile_directory_p (dir)))
5531 internal_condition_case_1 (do_auto_save_make_dir,
5532 dir, Qt,
5533 do_auto_save_eh);
5536 stream = emacs_fopen (SSDATA (listfile), "w");
5539 auto_save_unwind.stream = stream;
5540 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5541 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5542 minibuffer_auto_raise = 0;
5543 auto_saving = 1;
5544 auto_save_error_occurred = 0;
5546 /* On first pass, save all files that don't have handlers.
5547 On second pass, save all files that do have handlers.
5549 If Emacs is crashing, the handlers may tweak what is causing
5550 Emacs to crash in the first place, and it would be a shame if
5551 Emacs failed to autosave perfectly ordinary files because it
5552 couldn't handle some ange-ftp'd file. */
5554 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5555 FOR_EACH_LIVE_BUFFER (tail, buf)
5557 b = XBUFFER (buf);
5559 /* Record all the buffers that have auto save mode
5560 in the special file that lists them. For each of these buffers,
5561 Record visited name (if any) and auto save name. */
5562 if (STRINGP (BVAR (b, auto_save_file_name))
5563 && stream != NULL && do_handled_files == 0)
5565 block_input ();
5566 if (!NILP (BVAR (b, filename)))
5568 fwrite (SDATA (BVAR (b, filename)), 1,
5569 SBYTES (BVAR (b, filename)), stream);
5571 putc ('\n', stream);
5572 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5573 SBYTES (BVAR (b, auto_save_file_name)), stream);
5574 putc ('\n', stream);
5575 unblock_input ();
5578 if (!NILP (current_only)
5579 && b != current_buffer)
5580 continue;
5582 /* Don't auto-save indirect buffers.
5583 The base buffer takes care of it. */
5584 if (b->base_buffer)
5585 continue;
5587 /* Check for auto save enabled
5588 and file changed since last auto save
5589 and file changed since last real save. */
5590 if (STRINGP (BVAR (b, auto_save_file_name))
5591 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5592 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5593 /* -1 means we've turned off autosaving for a while--see below. */
5594 && XINT (BVAR (b, save_length)) >= 0
5595 && (do_handled_files
5596 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5597 Qwrite_region))))
5599 struct timespec before_time = current_timespec ();
5600 struct timespec after_time;
5602 /* If we had a failure, don't try again for 20 minutes. */
5603 if (b->auto_save_failure_time > 0
5604 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5605 continue;
5607 set_buffer_internal (b);
5608 if (NILP (Vauto_save_include_big_deletions)
5609 && (XFASTINT (BVAR (b, save_length)) * 10
5610 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5611 /* A short file is likely to change a large fraction;
5612 spare the user annoying messages. */
5613 && XFASTINT (BVAR (b, save_length)) > 5000
5614 /* These messages are frequent and annoying for `*mail*'. */
5615 && !EQ (BVAR (b, filename), Qnil)
5616 && NILP (no_message))
5618 /* It has shrunk too much; turn off auto-saving here. */
5619 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5620 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5621 BVAR (b, name), 1);
5622 minibuffer_auto_raise = 0;
5623 /* Turn off auto-saving until there's a real save,
5624 and prevent any more warnings. */
5625 XSETINT (BVAR (b, save_length), -1);
5626 Fsleep_for (make_number (1), Qnil);
5627 continue;
5629 if (!auto_saved && NILP (no_message))
5630 message1 ("Auto-saving...");
5631 internal_condition_case (auto_save_1, Qt, auto_save_error);
5632 auto_saved = 1;
5633 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5634 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5635 set_buffer_internal (old);
5637 after_time = current_timespec ();
5639 /* If auto-save took more than 60 seconds,
5640 assume it was an NFS failure that got a timeout. */
5641 if (after_time.tv_sec - before_time.tv_sec > 60)
5642 b->auto_save_failure_time = after_time.tv_sec;
5646 /* Prevent another auto save till enough input events come in. */
5647 record_auto_save ();
5649 if (auto_saved && NILP (no_message))
5651 if (old_message_p)
5653 /* If we are going to restore an old message,
5654 give time to read ours. */
5655 sit_for (make_number (1), 0, 0);
5656 restore_message ();
5658 else if (!auto_save_error_occurred)
5659 /* Don't overwrite the error message if an error occurred.
5660 If we displayed a message and then restored a state
5661 with no message, leave a "done" message on the screen. */
5662 message1 ("Auto-saving...done");
5665 Vquit_flag = oquit;
5667 /* This restores the message-stack status. */
5668 unbind_to (count, Qnil);
5669 return Qnil;
5672 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5673 Sset_buffer_auto_saved, 0, 0, 0,
5674 doc: /* Mark current buffer as auto-saved with its current text.
5675 No auto-save file will be written until the buffer changes again. */)
5676 (void)
5678 /* FIXME: This should not be called in indirect buffers, since
5679 they're not autosaved. */
5680 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5681 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5682 current_buffer->auto_save_failure_time = 0;
5683 return Qnil;
5686 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5687 Sclear_buffer_auto_save_failure, 0, 0, 0,
5688 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5689 (void)
5691 current_buffer->auto_save_failure_time = 0;
5692 return Qnil;
5695 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5696 0, 0, 0,
5697 doc: /* Return t if current buffer has been auto-saved recently.
5698 More precisely, if it has been auto-saved since last read from or saved
5699 in the visited file. If the buffer has no visited file,
5700 then any auto-save counts as "recent". */)
5701 (void)
5703 /* FIXME: maybe we should return nil for indirect buffers since
5704 they're never autosaved. */
5705 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5708 /* Reading and completing file names. */
5710 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5711 Snext_read_file_uses_dialog_p, 0, 0, 0,
5712 doc: /* Return t if a call to `read-file-name' will use a dialog.
5713 The return value is only relevant for a call to `read-file-name' that happens
5714 before any other event (mouse or keypress) is handled. */)
5715 (void)
5717 #if (defined USE_GTK || defined USE_MOTIF \
5718 || defined HAVE_NS || defined HAVE_NTGUI)
5719 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5720 && use_dialog_box
5721 && use_file_dialog
5722 && window_system_available (SELECTED_FRAME ()))
5723 return Qt;
5724 #endif
5725 return Qnil;
5729 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5730 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5731 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5732 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5733 it to text mode.
5735 As a side effect, this function flushes any pending STREAM's data.
5737 Value is the previous value of STREAM's I/O mode, nil for text mode,
5738 non-nil for binary mode.
5740 On MS-Windows and MS-DOS, binary mode is needed to read or write
5741 arbitrary binary data, and for disabling translation between CR-LF
5742 pairs and a single newline character. Examples include generation
5743 of text files with Unix-style end-of-line format using `princ' in
5744 batch mode, with standard output redirected to a file.
5746 On Posix systems, this function always returns non-nil, and has no
5747 effect except for flushing STREAM's data. */)
5748 (Lisp_Object stream, Lisp_Object mode)
5750 FILE *fp = NULL;
5751 int binmode;
5753 CHECK_SYMBOL (stream);
5754 if (EQ (stream, Qstdin))
5755 fp = stdin;
5756 else if (EQ (stream, Qstdout))
5757 fp = stdout;
5758 else if (EQ (stream, Qstderr))
5759 fp = stderr;
5760 else
5761 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5763 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5764 if (fp != stdin)
5765 fflush (fp);
5767 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5770 void
5771 init_fileio (void)
5773 realmask = umask (0);
5774 umask (realmask);
5776 valid_timestamp_file_system = 0;
5778 /* fsync can be a significant performance hit. Often it doesn't
5779 suffice to make the file-save operation survive a crash. For
5780 batch scripts, which are typically part of larger shell commands
5781 that don't fsync other files, its effect on performance can be
5782 significant so its utility is particularly questionable.
5783 Hence, for now by default fsync is used only when interactive.
5785 For more on why fsync often fails to work on today's hardware, see:
5786 Zheng M et al. Understanding the robustness of SSDs under power fault.
5787 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5788 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5790 For more on why fsync does not suffice even if it works properly, see:
5791 Roche X. Necessary step(s) to synchronize filename operations on disk.
5792 Austin Group Defect 672, 2013-03-19
5793 http://austingroupbugs.net/view.php?id=672 */
5794 write_region_inhibit_fsync = noninteractive;
5797 void
5798 syms_of_fileio (void)
5800 /* Property name of a file name handler,
5801 which gives a list of operations it handles. */
5802 DEFSYM (Qoperations, "operations");
5804 DEFSYM (Qexpand_file_name, "expand-file-name");
5805 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5806 DEFSYM (Qdirectory_file_name, "directory-file-name");
5807 DEFSYM (Qfile_name_directory, "file-name-directory");
5808 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5809 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5810 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5811 DEFSYM (Qcopy_file, "copy-file");
5812 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5813 DEFSYM (Qmake_directory, "make-directory");
5814 DEFSYM (Qdelete_file, "delete-file");
5815 DEFSYM (Qrename_file, "rename-file");
5816 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5817 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5818 DEFSYM (Qfile_exists_p, "file-exists-p");
5819 DEFSYM (Qfile_executable_p, "file-executable-p");
5820 DEFSYM (Qfile_readable_p, "file-readable-p");
5821 DEFSYM (Qfile_writable_p, "file-writable-p");
5822 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5823 DEFSYM (Qaccess_file, "access-file");
5824 DEFSYM (Qfile_directory_p, "file-directory-p");
5825 DEFSYM (Qfile_regular_p, "file-regular-p");
5826 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5827 DEFSYM (Qfile_modes, "file-modes");
5828 DEFSYM (Qset_file_modes, "set-file-modes");
5829 DEFSYM (Qset_file_times, "set-file-times");
5830 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5831 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5832 DEFSYM (Qfile_acl, "file-acl");
5833 DEFSYM (Qset_file_acl, "set-file-acl");
5834 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5835 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5836 DEFSYM (Qwrite_region, "write-region");
5837 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5838 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5840 /* The symbol bound to coding-system-for-read when
5841 insert-file-contents is called for recovering a file. This is not
5842 an actual coding system name, but just an indicator to tell
5843 insert-file-contents to use `emacs-mule' with a special flag for
5844 auto saving and recovering a file. */
5845 DEFSYM (Qauto_save_coding, "auto-save-coding");
5847 DEFSYM (Qfile_name_history, "file-name-history");
5848 Fset (Qfile_name_history, Qnil);
5850 DEFSYM (Qfile_error, "file-error");
5851 DEFSYM (Qfile_already_exists, "file-already-exists");
5852 DEFSYM (Qfile_date_error, "file-date-error");
5853 DEFSYM (Qfile_notify_error, "file-notify-error");
5854 DEFSYM (Qexcl, "excl");
5856 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5857 doc: /* Coding system for encoding file names.
5858 If it is nil, `default-file-name-coding-system' (which see) is used.
5860 On MS-Windows, the value of this variable is largely ignored if
5861 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5862 behaves as if file names were encoded in `utf-8'. */);
5863 Vfile_name_coding_system = Qnil;
5865 DEFVAR_LISP ("default-file-name-coding-system",
5866 Vdefault_file_name_coding_system,
5867 doc: /* Default coding system for encoding file names.
5868 This variable is used only when `file-name-coding-system' is nil.
5870 This variable is set/changed by the command `set-language-environment'.
5871 User should not set this variable manually,
5872 instead use `file-name-coding-system' to get a constant encoding
5873 of file names regardless of the current language environment.
5875 On MS-Windows, the value of this variable is largely ignored if
5876 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5877 behaves as if file names were encoded in `utf-8'. */);
5878 Vdefault_file_name_coding_system = Qnil;
5880 /* Lisp functions for translating file formats. */
5881 DEFSYM (Qformat_decode, "format-decode");
5882 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5884 /* Lisp function for setting buffer-file-coding-system and the
5885 multibyteness of the current buffer after inserting a file. */
5886 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5888 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5890 Fput (Qfile_error, Qerror_conditions,
5891 Fpurecopy (list2 (Qfile_error, Qerror)));
5892 Fput (Qfile_error, Qerror_message,
5893 build_pure_c_string ("File error"));
5895 Fput (Qfile_already_exists, Qerror_conditions,
5896 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5897 Fput (Qfile_already_exists, Qerror_message,
5898 build_pure_c_string ("File already exists"));
5900 Fput (Qfile_date_error, Qerror_conditions,
5901 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5902 Fput (Qfile_date_error, Qerror_message,
5903 build_pure_c_string ("Cannot set file date"));
5905 Fput (Qfile_notify_error, Qerror_conditions,
5906 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5907 Fput (Qfile_notify_error, Qerror_message,
5908 build_pure_c_string ("File notification error"));
5910 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5911 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5912 If a file name matches REGEXP, all I/O on that file is done by calling
5913 HANDLER. If a file name matches more than one handler, the handler
5914 whose match starts last in the file name gets precedence. The
5915 function `find-file-name-handler' checks this list for a handler for
5916 its argument.
5918 HANDLER should be a function. The first argument given to it is the
5919 name of the I/O primitive to be handled; the remaining arguments are
5920 the arguments that were passed to that primitive. For example, if you
5921 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5922 HANDLER is called like this:
5924 (funcall HANDLER \\='file-exists-p FILENAME)
5926 Note that HANDLER must be able to handle all I/O primitives; if it has
5927 nothing special to do for a primitive, it should reinvoke the
5928 primitive to handle the operation \"the usual way\".
5929 See Info node `(elisp)Magic File Names' for more details. */);
5930 Vfile_name_handler_alist = Qnil;
5932 DEFVAR_LISP ("set-auto-coding-function",
5933 Vset_auto_coding_function,
5934 doc: /* If non-nil, a function to call to decide a coding system of file.
5935 Two arguments are passed to this function: the file name
5936 and the length of a file contents following the point.
5937 This function should return a coding system to decode the file contents.
5938 It should check the file name against `auto-coding-alist'.
5939 If no coding system is decided, it should check a coding system
5940 specified in the heading lines with the format:
5941 -*- ... coding: CODING-SYSTEM; ... -*-
5942 or local variable spec of the tailing lines with `coding:' tag. */);
5943 Vset_auto_coding_function = Qnil;
5945 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5946 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5947 Each is passed one argument, the number of characters inserted,
5948 with point at the start of the inserted text. Each function
5949 should leave point the same, and return the new character count.
5950 If `insert-file-contents' is intercepted by a handler from
5951 `file-name-handler-alist', that handler is responsible for calling the
5952 functions in `after-insert-file-functions' if appropriate. */);
5953 Vafter_insert_file_functions = Qnil;
5955 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5956 doc: /* A list of functions to be called at the start of `write-region'.
5957 Each is passed two arguments, START and END as for `write-region'.
5958 These are usually two numbers but not always; see the documentation
5959 for `write-region'. The function should return a list of pairs
5960 of the form (POSITION . STRING), consisting of strings to be effectively
5961 inserted at the specified positions of the file being written (1 means to
5962 insert before the first byte written). The POSITIONs must be sorted into
5963 increasing order.
5965 If there are several annotation functions, the lists returned by these
5966 functions are merged destructively. As each annotation function runs,
5967 the variable `write-region-annotations-so-far' contains a list of all
5968 annotations returned by previous annotation functions.
5970 An annotation function can return with a different buffer current.
5971 Doing so removes the annotations returned by previous functions, and
5972 resets START and END to `point-min' and `point-max' of the new buffer.
5974 After `write-region' completes, Emacs calls the function stored in
5975 `write-region-post-annotation-function', once for each buffer that was
5976 current when building the annotations (i.e., at least once), with that
5977 buffer current. */);
5978 Vwrite_region_annotate_functions = Qnil;
5979 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5981 DEFVAR_LISP ("write-region-post-annotation-function",
5982 Vwrite_region_post_annotation_function,
5983 doc: /* Function to call after `write-region' completes.
5984 The function is called with no arguments. If one or more of the
5985 annotation functions in `write-region-annotate-functions' changed the
5986 current buffer, the function stored in this variable is called for
5987 each of those additional buffers as well, in addition to the original
5988 buffer. The relevant buffer is current during each function call. */);
5989 Vwrite_region_post_annotation_function = Qnil;
5990 staticpro (&Vwrite_region_annotation_buffers);
5992 DEFVAR_LISP ("write-region-annotations-so-far",
5993 Vwrite_region_annotations_so_far,
5994 doc: /* When an annotation function is called, this holds the previous annotations.
5995 These are the annotations made by other annotation functions
5996 that were already called. See also `write-region-annotate-functions'. */);
5997 Vwrite_region_annotations_so_far = Qnil;
5999 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6000 doc: /* A list of file name handlers that temporarily should not be used.
6001 This applies only to the operation `inhibit-file-name-operation'. */);
6002 Vinhibit_file_name_handlers = Qnil;
6004 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6005 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6006 Vinhibit_file_name_operation = Qnil;
6008 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6009 doc: /* File name in which we write a list of all auto save file names.
6010 This variable is initialized automatically from `auto-save-list-file-prefix'
6011 shortly after Emacs reads your init file, if you have not yet given it
6012 a non-nil value. */);
6013 Vauto_save_list_file_name = Qnil;
6015 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6016 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6017 Normally auto-save files are written under other names. */);
6018 Vauto_save_visited_file_name = Qnil;
6020 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6021 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6022 If nil, deleting a substantial portion of the text disables auto-save
6023 in the buffer; this is the default behavior, because the auto-save
6024 file is usually more useful if it contains the deleted text. */);
6025 Vauto_save_include_big_deletions = Qnil;
6027 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6028 doc: /* Non-nil means don't call fsync in `write-region'.
6029 This variable affects calls to `write-region' as well as save commands.
6030 Setting this to nil may avoid data loss if the system loses power or
6031 the operating system crashes. By default, it is non-nil in batch mode. */);
6032 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6034 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6035 doc: /* Specifies whether to use the system's trash can.
6036 When non-nil, certain file deletion commands use the function
6037 `move-file-to-trash' instead of deleting files outright.
6038 This includes interactive calls to `delete-file' and
6039 `delete-directory' and the Dired deletion commands. */);
6040 delete_by_moving_to_trash = 0;
6041 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6043 /* Lisp function for moving files to trash. */
6044 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6046 /* Lisp function for recursively copying directories. */
6047 DEFSYM (Qcopy_directory, "copy-directory");
6049 /* Lisp function for recursively deleting directories. */
6050 DEFSYM (Qdelete_directory, "delete-directory");
6052 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6053 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6055 DEFSYM (Qstdin, "stdin");
6056 DEFSYM (Qstdout, "stdout");
6057 DEFSYM (Qstderr, "stderr");
6059 defsubr (&Sfind_file_name_handler);
6060 defsubr (&Sfile_name_directory);
6061 defsubr (&Sfile_name_nondirectory);
6062 defsubr (&Sunhandled_file_name_directory);
6063 defsubr (&Sfile_name_as_directory);
6064 defsubr (&Sdirectory_file_name);
6065 defsubr (&Smake_temp_name);
6066 defsubr (&Sexpand_file_name);
6067 defsubr (&Ssubstitute_in_file_name);
6068 defsubr (&Scopy_file);
6069 defsubr (&Smake_directory_internal);
6070 defsubr (&Sdelete_directory_internal);
6071 defsubr (&Sdelete_file);
6072 defsubr (&Srename_file);
6073 defsubr (&Sadd_name_to_file);
6074 defsubr (&Smake_symbolic_link);
6075 defsubr (&Sfile_name_absolute_p);
6076 defsubr (&Sfile_exists_p);
6077 defsubr (&Sfile_executable_p);
6078 defsubr (&Sfile_readable_p);
6079 defsubr (&Sfile_writable_p);
6080 defsubr (&Saccess_file);
6081 defsubr (&Sfile_symlink_p);
6082 defsubr (&Sfile_directory_p);
6083 defsubr (&Sfile_accessible_directory_p);
6084 defsubr (&Sfile_regular_p);
6085 defsubr (&Sfile_modes);
6086 defsubr (&Sset_file_modes);
6087 defsubr (&Sset_file_times);
6088 defsubr (&Sfile_selinux_context);
6089 defsubr (&Sfile_acl);
6090 defsubr (&Sset_file_acl);
6091 defsubr (&Sset_file_selinux_context);
6092 defsubr (&Sset_default_file_modes);
6093 defsubr (&Sdefault_file_modes);
6094 defsubr (&Sfile_newer_than_file_p);
6095 defsubr (&Sinsert_file_contents);
6096 defsubr (&Swrite_region);
6097 defsubr (&Scar_less_than_car);
6098 defsubr (&Sverify_visited_file_modtime);
6099 defsubr (&Svisited_file_modtime);
6100 defsubr (&Sset_visited_file_modtime);
6101 defsubr (&Sdo_auto_save);
6102 defsubr (&Sset_buffer_auto_saved);
6103 defsubr (&Sclear_buffer_auto_save_failure);
6104 defsubr (&Srecent_auto_save_p);
6106 defsubr (&Snext_read_file_uses_dialog_p);
6108 defsubr (&Sset_binary_mode);
6110 #ifdef HAVE_SYNC
6111 defsubr (&Sunix_sync);
6112 #endif