* admin/update_autogen (changelog_files): Remove gitlog-to-emacslog.
[emacs.git] / src / fileio.c
blobaad0270a1d29ab1bc05c45881c6b8a938efd2ae8
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2015 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
10 (at 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 #ifdef HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "intervals.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"
54 #include "dispextern.h"
56 #ifdef WINDOWSNT
57 #define NOMINMAX 1
58 #include <windows.h>
59 #include <sys/file.h>
60 #include "w32.h"
61 #endif /* not WINDOWSNT */
63 #ifdef MSDOS
64 #include "msdos.h"
65 #include <sys/param.h>
66 #endif
68 #ifdef DOS_NT
69 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
70 redirector allows the six letters between 'Z' and 'a' as well. */
71 #ifdef MSDOS
72 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
73 #endif
74 #ifdef WINDOWSNT
75 #define IS_DRIVE(x) c_isalpha (x)
76 #endif
77 /* Need to lower-case the drive letter, or else expanded
78 filenames will sometimes compare unequal, because
79 `expand-file-name' doesn't always down-case the drive letter. */
80 #define DRIVE_LETTER(x) c_tolower (x)
81 #endif
83 #include "systime.h"
84 #include <acl.h>
85 #include <allocator.h>
86 #include <careadlinkat.h>
87 #include <stat-time.h>
89 #include <binary-io.h>
91 #ifdef HPUX
92 #include <netio.h>
93 #endif
95 #include "commands.h"
97 /* True during writing of auto-save files. */
98 static bool auto_saving;
100 /* Emacs's real umask. */
101 static mode_t realmask;
103 /* Nonzero umask during creation of auto-save directories. */
104 static mode_t auto_saving_dir_umask;
106 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
107 a new file with the same mode as the original. */
108 static mode_t auto_save_mode_bits;
110 /* Set by auto_save_1 if an error occurred during the last auto-save. */
111 static bool auto_save_error_occurred;
113 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
114 number of a file system where time stamps were observed to to work. */
115 static bool valid_timestamp_file_system;
116 static dev_t timestamp_file_system;
118 /* Each time an annotation function changes the buffer, the new buffer
119 is added here. */
120 static Lisp_Object Vwrite_region_annotation_buffers;
122 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
123 Lisp_Object *, struct coding_system *);
124 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
125 struct coding_system *);
128 /* Return true if FILENAME exists. */
130 static bool
131 check_existing (const char *filename)
133 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
136 /* Return true if file FILENAME exists and can be executed. */
138 static bool
139 check_executable (char *filename)
141 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
144 /* Return true if file FILENAME exists and can be accessed
145 according to AMODE, which should include W_OK.
146 On failure, return false and set errno. */
148 static bool
149 check_writable (const char *filename, int amode)
151 #ifdef MSDOS
152 /* FIXME: an faccessat implementation should be added to the
153 DOS/Windows ports and this #ifdef branch should be removed. */
154 struct stat st;
155 if (stat (filename, &st) < 0)
156 return 0;
157 errno = EPERM;
158 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
159 #else /* not MSDOS */
160 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
161 #ifdef CYGWIN
162 /* faccessat may have returned failure because Cygwin couldn't
163 determine the file's UID or GID; if so, we return success. */
164 if (!res)
166 int faccessat_errno = errno;
167 struct stat st;
168 if (stat (filename, &st) < 0)
169 return 0;
170 res = (st.st_uid == -1 || st.st_gid == -1);
171 errno = faccessat_errno;
173 #endif /* CYGWIN */
174 return res;
175 #endif /* not MSDOS */
178 /* Signal a file-access failure. STRING describes the failure,
179 NAME the file involved, and ERRORNO the errno value.
181 If NAME is neither null nor a pair, package it up as a singleton
182 list before reporting it; this saves report_file_errno's caller the
183 trouble of preserving errno before calling list1. */
185 void
186 report_file_errno (char const *string, Lisp_Object name, int errorno)
188 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
189 synchronize_system_messages_locale ();
190 char *str = strerror (errorno);
191 Lisp_Object errstring
192 = code_convert_string_norecord (build_unibyte_string (str),
193 Vlocale_coding_system, 0);
194 Lisp_Object errdata = Fcons (errstring, data);
196 if (errorno == EEXIST)
197 xsignal (Qfile_already_exists, errdata);
198 else
199 xsignal (Qfile_error, Fcons (build_string (string), errdata));
202 /* Signal a file-access failure that set errno. STRING describes the
203 failure, NAME the file involved. When invoking this function, take
204 care to not use arguments such as build_string ("foo") that involve
205 side effects that may set errno. */
207 void
208 report_file_error (char const *string, Lisp_Object name)
210 report_file_errno (string, name, errno);
213 void
214 close_file_unwind (int fd)
216 emacs_close (fd);
219 void
220 fclose_unwind (void *arg)
222 FILE *stream = arg;
223 fclose (stream);
226 /* Restore point, having saved it as a marker. */
228 void
229 restore_point_unwind (Lisp_Object location)
231 Fgoto_char (location);
232 unchain_marker (XMARKER (location));
236 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
237 Sfind_file_name_handler, 2, 2, 0,
238 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
239 Otherwise, return nil.
240 A file name is handled if one of the regular expressions in
241 `file-name-handler-alist' matches it.
243 If OPERATION equals `inhibit-file-name-operation', then we ignore
244 any handlers that are members of `inhibit-file-name-handlers',
245 but we still do run any other handlers. This lets handlers
246 use the standard functions without calling themselves recursively. */)
247 (Lisp_Object filename, Lisp_Object operation)
249 /* This function must not munge the match data. */
250 Lisp_Object chain, inhibited_handlers, result;
251 ptrdiff_t pos = -1;
253 result = Qnil;
254 CHECK_STRING (filename);
256 if (EQ (operation, Vinhibit_file_name_operation))
257 inhibited_handlers = Vinhibit_file_name_handlers;
258 else
259 inhibited_handlers = Qnil;
261 for (chain = Vfile_name_handler_alist; CONSP (chain);
262 chain = XCDR (chain))
264 Lisp_Object elt;
265 elt = XCAR (chain);
266 if (CONSP (elt))
268 Lisp_Object string = XCAR (elt);
269 ptrdiff_t match_pos;
270 Lisp_Object handler = XCDR (elt);
271 Lisp_Object operations = Qnil;
273 if (SYMBOLP (handler))
274 operations = Fget (handler, Qoperations);
276 if (STRINGP (string)
277 && (match_pos = fast_string_match (string, filename)) > pos
278 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
280 Lisp_Object tem;
282 handler = XCDR (elt);
283 tem = Fmemq (handler, inhibited_handlers);
284 if (NILP (tem))
286 result = handler;
287 pos = match_pos;
292 QUIT;
294 return result;
297 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
298 1, 1, 0,
299 doc: /* Return the directory component in file name FILENAME.
300 Return nil if FILENAME does not include a directory.
301 Otherwise return a directory name.
302 Given a Unix syntax file name, returns a string ending in slash. */)
303 (Lisp_Object filename)
305 Lisp_Object handler;
307 CHECK_STRING (filename);
309 /* If the file name has special constructs in it,
310 call the corresponding file handler. */
311 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
312 if (!NILP (handler))
314 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
315 filename);
316 return STRINGP (handled_name) ? handled_name : Qnil;
319 char *beg = SSDATA (filename);
320 char const *p = beg + SBYTES (filename);
322 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
323 #ifdef DOS_NT
324 /* only recognize drive specifier at the beginning */
325 && !(p[-1] == ':'
326 /* handle the "/:d:foo" and "/:foo" cases correctly */
327 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
328 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
329 #endif
330 ) p--;
332 if (p == beg)
333 return Qnil;
334 #ifdef DOS_NT
335 /* Expansion of "c:" to drive and default directory. */
336 Lisp_Object tem_fn;
337 USE_SAFE_ALLOCA;
338 SAFE_ALLOCA_STRING (beg, filename);
339 p = beg + (p - SSDATA (filename));
341 if (p[-1] == ':')
343 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
344 char *res = alloca (MAXPATHLEN + 1);
345 char *r = res;
347 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
349 memcpy (res, beg, 2);
350 beg += 2;
351 r += 2;
354 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
356 size_t l = strlen (res);
358 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
359 strcat (res, "/");
360 beg = res;
361 p = beg + strlen (beg);
362 dostounix_filename (beg);
363 tem_fn = make_specified_string (beg, -1, p - beg,
364 STRING_MULTIBYTE (filename));
366 else
367 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
368 STRING_MULTIBYTE (filename));
370 else if (STRING_MULTIBYTE (filename))
372 tem_fn = make_specified_string (beg, -1, p - beg, 1);
373 dostounix_filename (SSDATA (tem_fn));
374 #ifdef WINDOWSNT
375 if (!NILP (Vw32_downcase_file_names))
376 tem_fn = Fdowncase (tem_fn);
377 #endif
379 else
381 dostounix_filename (beg);
382 tem_fn = make_specified_string (beg, -1, p - beg, 0);
384 SAFE_FREE ();
385 return tem_fn;
386 #else /* DOS_NT */
387 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
388 #endif /* DOS_NT */
391 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
392 Sfile_name_nondirectory, 1, 1, 0,
393 doc: /* Return file name FILENAME sans its directory.
394 For example, in a Unix-syntax file name,
395 this is everything after the last slash,
396 or the entire name if it contains no slash. */)
397 (Lisp_Object filename)
399 register const char *beg, *p, *end;
400 Lisp_Object handler;
402 CHECK_STRING (filename);
404 /* If the file name has special constructs in it,
405 call the corresponding file handler. */
406 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
407 if (!NILP (handler))
409 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
410 filename);
411 if (STRINGP (handled_name))
412 return handled_name;
413 error ("Invalid handler in `file-name-handler-alist'");
416 beg = SSDATA (filename);
417 end = p = beg + SBYTES (filename);
419 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
420 #ifdef DOS_NT
421 /* only recognize drive specifier at beginning */
422 && !(p[-1] == ':'
423 /* handle the "/:d:foo" case correctly */
424 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
425 #endif
427 p--;
429 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
432 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
433 Sunhandled_file_name_directory, 1, 1, 0,
434 doc: /* Return a directly usable directory name somehow associated with FILENAME.
435 A `directly usable' directory name is one that may be used without the
436 intervention of any file handler.
437 If FILENAME is a directly usable file itself, return
438 \(file-name-directory FILENAME).
439 If FILENAME refers to a file which is not accessible from a local process,
440 then this should return nil.
441 The `call-process' and `start-process' functions use this function to
442 get a current directory to run processes in. */)
443 (Lisp_Object filename)
445 Lisp_Object handler;
447 /* If the file name has special constructs in it,
448 call the corresponding file handler. */
449 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
450 if (!NILP (handler))
452 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
453 filename);
454 return STRINGP (handled_name) ? handled_name : Qnil;
457 return Ffile_name_directory (filename);
460 /* Maximum number of bytes that DST will be longer than SRC
461 in file_name_as_directory. This occurs when SRCLEN == 0. */
462 enum { file_name_as_directory_slop = 2 };
464 /* Convert from file name SRC of length SRCLEN to directory name in
465 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
466 string. On UNIX, just make sure there is a terminating /. Return
467 the length of DST in bytes. */
469 static ptrdiff_t
470 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
471 bool multibyte)
473 if (srclen == 0)
475 dst[0] = '.';
476 dst[1] = '/';
477 dst[2] = '\0';
478 return 2;
481 memcpy (dst, src, srclen);
482 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
483 dst[srclen++] = DIRECTORY_SEP;
484 dst[srclen] = 0;
485 #ifdef DOS_NT
486 dostounix_filename (dst);
487 #endif
488 return srclen;
491 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
492 Sfile_name_as_directory, 1, 1, 0,
493 doc: /* Return a string representing the file name FILE interpreted as a directory.
494 This operation exists because a directory is also a file, but its name as
495 a directory is different from its name as a file.
496 The result can be used as the value of `default-directory'
497 or passed as second argument to `expand-file-name'.
498 For a Unix-syntax file name, just appends a slash. */)
499 (Lisp_Object file)
501 char *buf;
502 ptrdiff_t length;
503 Lisp_Object handler, val;
504 USE_SAFE_ALLOCA;
506 CHECK_STRING (file);
508 /* If the file name has special constructs in it,
509 call the corresponding file handler. */
510 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
511 if (!NILP (handler))
513 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
514 file);
515 if (STRINGP (handled_name))
516 return handled_name;
517 error ("Invalid handler in `file-name-handler-alist'");
520 #ifdef WINDOWSNT
521 if (!NILP (Vw32_downcase_file_names))
522 file = Fdowncase (file);
523 #endif
524 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
525 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
526 STRING_MULTIBYTE (file));
527 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
528 SAFE_FREE ();
529 return val;
532 /* Convert from directory name SRC of length SRCLEN to file name in
533 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
534 string. On UNIX, just make sure there isn't a terminating /.
535 Return the length of DST in bytes. */
537 static ptrdiff_t
538 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
540 /* Process as Unix format: just remove any final slash.
541 But leave "/" and "//" unchanged. */
542 while (srclen > 1
543 #ifdef DOS_NT
544 && !IS_ANY_SEP (src[srclen - 2])
545 #endif
546 && IS_DIRECTORY_SEP (src[srclen - 1])
547 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
548 srclen--;
550 memcpy (dst, src, srclen);
551 dst[srclen] = 0;
552 #ifdef DOS_NT
553 dostounix_filename (dst);
554 #endif
555 return srclen;
558 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
559 1, 1, 0,
560 doc: /* Returns the file name of the directory named DIRECTORY.
561 This is the name of the file that holds the data for the directory DIRECTORY.
562 This operation exists because a directory is also a file, but its name as
563 a directory is different from its name as a file.
564 In Unix-syntax, this function just removes the final slash. */)
565 (Lisp_Object directory)
567 char *buf;
568 ptrdiff_t length;
569 Lisp_Object handler, val;
570 USE_SAFE_ALLOCA;
572 CHECK_STRING (directory);
574 /* If the file name has special constructs in it,
575 call the corresponding file handler. */
576 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
577 if (!NILP (handler))
579 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
580 directory);
581 if (STRINGP (handled_name))
582 return handled_name;
583 error ("Invalid handler in `file-name-handler-alist'");
586 #ifdef WINDOWSNT
587 if (!NILP (Vw32_downcase_file_names))
588 directory = Fdowncase (directory);
589 #endif
590 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
591 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
592 STRING_MULTIBYTE (directory));
593 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
594 SAFE_FREE ();
595 return val;
598 static const char make_temp_name_tbl[64] =
600 'A','B','C','D','E','F','G','H',
601 'I','J','K','L','M','N','O','P',
602 'Q','R','S','T','U','V','W','X',
603 'Y','Z','a','b','c','d','e','f',
604 'g','h','i','j','k','l','m','n',
605 'o','p','q','r','s','t','u','v',
606 'w','x','y','z','0','1','2','3',
607 '4','5','6','7','8','9','-','_'
610 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
612 /* Value is a temporary file name starting with PREFIX, a string.
614 The Emacs process number forms part of the result, so there is
615 no danger of generating a name being used by another process.
616 In addition, this function makes an attempt to choose a name
617 which has no existing file. To make this work, PREFIX should be
618 an absolute file name.
620 BASE64_P means add the pid as 3 characters in base64
621 encoding. In this case, 6 characters will be added to PREFIX to
622 form the file name. Otherwise, if Emacs is running on a system
623 with long file names, add the pid as a decimal number.
625 This function signals an error if no unique file name could be
626 generated. */
628 Lisp_Object
629 make_temp_name (Lisp_Object prefix, bool base64_p)
631 Lisp_Object val, encoded_prefix;
632 ptrdiff_t len;
633 printmax_t pid;
634 char *p, *data;
635 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
636 int pidlen;
638 CHECK_STRING (prefix);
640 /* VAL is created by adding 6 characters to PREFIX. The first
641 three are the PID of this process, in base 64, and the second
642 three are incremented if the file already exists. This ensures
643 262144 unique file names per PID per PREFIX. */
645 pid = getpid ();
647 if (base64_p)
649 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
650 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
651 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
652 pidlen = 3;
654 else
656 #ifdef HAVE_LONG_FILE_NAMES
657 pidlen = sprintf (pidbuf, "%"pMd, pid);
658 #else
659 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
660 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
661 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
662 pidlen = 3;
663 #endif
666 encoded_prefix = ENCODE_FILE (prefix);
667 len = SBYTES (encoded_prefix);
668 val = make_uninit_string (len + 3 + pidlen);
669 data = SSDATA (val);
670 memcpy (data, SSDATA (encoded_prefix), len);
671 p = data + len;
673 memcpy (p, pidbuf, pidlen);
674 p += pidlen;
676 /* Here we try to minimize useless stat'ing when this function is
677 invoked many times successively with the same PREFIX. We achieve
678 this by initializing count to a random value, and incrementing it
679 afterwards.
681 We don't want make-temp-name to be called while dumping,
682 because then make_temp_name_count_initialized_p would get set
683 and then make_temp_name_count would not be set when Emacs starts. */
685 if (!make_temp_name_count_initialized_p)
687 make_temp_name_count = time (NULL);
688 make_temp_name_count_initialized_p = 1;
691 while (1)
693 unsigned num = make_temp_name_count;
695 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
696 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
697 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
699 /* Poor man's congruential RN generator. Replace with
700 ++make_temp_name_count for debugging. */
701 make_temp_name_count += 25229;
702 make_temp_name_count %= 225307;
704 if (!check_existing (data))
706 /* We want to return only if errno is ENOENT. */
707 if (errno == ENOENT)
708 return DECODE_FILE (val);
709 else
710 /* The error here is dubious, but there is little else we
711 can do. The alternatives are to return nil, which is
712 as bad as (and in many cases worse than) throwing the
713 error, or to ignore the error, which will likely result
714 in looping through 225307 stat's, which is not only
715 dog-slow, but also useless since eventually nil would
716 have to be returned anyway. */
717 report_file_error ("Cannot create temporary name for prefix",
718 prefix);
719 /* not reached */
725 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
726 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
727 The Emacs process number forms part of the result, so there is no
728 danger of generating a name being used by another Emacs process
729 \(so long as only a single host can access the containing directory...).
731 This function tries to choose a name that has no existing file.
732 For this to work, PREFIX should be an absolute file name.
734 There is a race condition between calling `make-temp-name' and creating the
735 file, which opens all kinds of security holes. For that reason, you should
736 normally use `make-temp-file' instead. */)
737 (Lisp_Object prefix)
739 return make_temp_name (prefix, 0);
742 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
743 doc: /* Convert filename NAME to absolute, and canonicalize it.
744 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
745 \(does not start with slash or tilde); both the directory name and
746 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
747 missing, the current buffer's value of `default-directory' is used.
748 NAME should be a string that is a valid file name for the underlying
749 filesystem.
750 File name components that are `.' are removed, and
751 so are file name components followed by `..', along with the `..' itself;
752 note that these simplifications are done without checking the resulting
753 file names in the file system.
754 Multiple consecutive slashes are collapsed into a single slash,
755 except at the beginning of the file name when they are significant (e.g.,
756 UNC file names on MS-Windows.)
757 An initial `~/' expands to your home directory.
758 An initial `~USER/' expands to USER's home directory.
759 See also the function `substitute-in-file-name'.
761 For technical reasons, this function can return correct but
762 non-intuitive results for the root directory; for instance,
763 \(expand-file-name ".." "/") returns "/..". For this reason, use
764 \(directory-file-name (file-name-directory dirname)) to traverse a
765 filesystem tree, not (expand-file-name ".." dirname). */)
766 (Lisp_Object name, Lisp_Object default_directory)
768 /* These point to SDATA and need to be careful with string-relocation
769 during GC (via DECODE_FILE). */
770 char *nm;
771 char *nmlim;
772 const char *newdir;
773 const char *newdirlim;
774 /* This should only point to alloca'd data. */
775 char *target;
777 ptrdiff_t tlen;
778 struct passwd *pw;
779 #ifdef DOS_NT
780 int drive = 0;
781 bool collapse_newdir = true;
782 bool is_escaped = 0;
783 #endif /* DOS_NT */
784 ptrdiff_t length, nbytes;
785 Lisp_Object handler, result, handled_name;
786 bool multibyte;
787 Lisp_Object hdir;
788 USE_SAFE_ALLOCA;
790 CHECK_STRING (name);
792 /* If the file name has special constructs in it,
793 call the corresponding file handler. */
794 handler = Ffind_file_name_handler (name, Qexpand_file_name);
795 if (!NILP (handler))
797 handled_name = call3 (handler, Qexpand_file_name,
798 name, default_directory);
799 if (STRINGP (handled_name))
800 return handled_name;
801 error ("Invalid handler in `file-name-handler-alist'");
805 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
806 if (NILP (default_directory))
807 default_directory = BVAR (current_buffer, directory);
808 if (! STRINGP (default_directory))
810 #ifdef DOS_NT
811 /* "/" is not considered a root directory on DOS_NT, so using "/"
812 here causes an infinite recursion in, e.g., the following:
814 (let (default-directory)
815 (expand-file-name "a"))
817 To avoid this, we set default_directory to the root of the
818 current drive. */
819 default_directory = build_string (emacs_root_dir ());
820 #else
821 default_directory = build_string ("/");
822 #endif
825 if (!NILP (default_directory))
827 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
828 if (!NILP (handler))
830 handled_name = call3 (handler, Qexpand_file_name,
831 name, default_directory);
832 if (STRINGP (handled_name))
833 return handled_name;
834 error ("Invalid handler in `file-name-handler-alist'");
839 char *o = SSDATA (default_directory);
841 /* Make sure DEFAULT_DIRECTORY is properly expanded.
842 It would be better to do this down below where we actually use
843 default_directory. Unfortunately, calling Fexpand_file_name recursively
844 could invoke GC, and the strings might be relocated. This would
845 be annoying because we have pointers into strings lying around
846 that would need adjusting, and people would add new pointers to
847 the code and forget to adjust them, resulting in intermittent bugs.
848 Putting this call here avoids all that crud.
850 The EQ test avoids infinite recursion. */
851 if (! NILP (default_directory) && !EQ (default_directory, name)
852 /* Save time in some common cases - as long as default_directory
853 is not relative, it can be canonicalized with name below (if it
854 is needed at all) without requiring it to be expanded now. */
855 #ifdef DOS_NT
856 /* Detect MSDOS file names with drive specifiers. */
857 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
858 && IS_DIRECTORY_SEP (o[2]))
859 #ifdef WINDOWSNT
860 /* Detect Windows file names in UNC format. */
861 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
862 #endif
863 #else /* not DOS_NT */
864 /* Detect Unix absolute file names (/... alone is not absolute on
865 DOS or Windows). */
866 && ! (IS_DIRECTORY_SEP (o[0]))
867 #endif /* not DOS_NT */
870 struct gcpro gcpro1;
872 GCPRO1 (name);
873 default_directory = Fexpand_file_name (default_directory, Qnil);
874 UNGCPRO;
877 multibyte = STRING_MULTIBYTE (name);
878 if (multibyte != STRING_MULTIBYTE (default_directory))
880 if (multibyte)
882 unsigned char *p = SDATA (name);
884 while (*p && ASCII_CHAR_P (*p))
885 p++;
886 if (*p == '\0')
888 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
889 unibyte. Do not convert DEFAULT_DIRECTORY to
890 multibyte; instead, convert NAME to a unibyte string,
891 so that the result of this function is also a unibyte
892 string. This is needed during bootstrapping and
893 dumping, when Emacs cannot decode file names, because
894 the locale environment is not set up. */
895 name = make_unibyte_string (SSDATA (name), SBYTES (name));
896 multibyte = 0;
898 else
899 default_directory = string_to_multibyte (default_directory);
901 else
903 name = string_to_multibyte (name);
904 multibyte = 1;
908 #ifdef WINDOWSNT
909 if (!NILP (Vw32_downcase_file_names))
910 default_directory = Fdowncase (default_directory);
911 #endif
913 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
914 SAFE_ALLOCA_STRING (nm, name);
915 nmlim = nm + SBYTES (name);
917 #ifdef DOS_NT
918 /* Note if special escape prefix is present, but remove for now. */
919 if (nm[0] == '/' && nm[1] == ':')
921 is_escaped = 1;
922 nm += 2;
925 /* Find and remove drive specifier if present; this makes nm absolute
926 even if the rest of the name appears to be relative. Only look for
927 drive specifier at the beginning. */
928 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
930 drive = (unsigned char) nm[0];
931 nm += 2;
934 #ifdef WINDOWSNT
935 /* If we see "c://somedir", we want to strip the first slash after the
936 colon when stripping the drive letter. Otherwise, this expands to
937 "//somedir". */
938 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
939 nm++;
941 /* Discard any previous drive specifier if nm is now in UNC format. */
942 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
943 && !IS_DIRECTORY_SEP (nm[2]))
944 drive = 0;
945 #endif /* WINDOWSNT */
946 #endif /* DOS_NT */
948 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
949 none are found, we can probably return right away. We will avoid
950 allocating a new string if name is already fully expanded. */
951 if (
952 IS_DIRECTORY_SEP (nm[0])
953 #ifdef MSDOS
954 && drive && !is_escaped
955 #endif
956 #ifdef WINDOWSNT
957 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
958 #endif
961 /* If it turns out that the filename we want to return is just a
962 suffix of FILENAME, we don't need to go through and edit
963 things; we just need to construct a new string using data
964 starting at the middle of FILENAME. If we set LOSE, that
965 means we've discovered that we can't do that cool trick. */
966 bool lose = 0;
967 char *p = nm;
969 while (*p)
971 /* Since we know the name is absolute, we can assume that each
972 element starts with a "/". */
974 /* "." and ".." are hairy. */
975 if (IS_DIRECTORY_SEP (p[0])
976 && p[1] == '.'
977 && (IS_DIRECTORY_SEP (p[2])
978 || p[2] == 0
979 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
980 || p[3] == 0))))
981 lose = 1;
982 /* Replace multiple slashes with a single one, except
983 leave leading "//" alone. */
984 else if (IS_DIRECTORY_SEP (p[0])
985 && IS_DIRECTORY_SEP (p[1])
986 && (p != nm || IS_DIRECTORY_SEP (p[2])))
987 lose = 1;
988 p++;
990 if (!lose)
992 #ifdef DOS_NT
993 /* Make sure directories are all separated with /, but
994 avoid allocation of a new string when not required. */
995 dostounix_filename (nm);
996 #ifdef WINDOWSNT
997 if (IS_DIRECTORY_SEP (nm[1]))
999 if (strcmp (nm, SSDATA (name)) != 0)
1000 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1002 else
1003 #endif
1004 /* Drive must be set, so this is okay. */
1005 if (strcmp (nm - 2, SSDATA (name)) != 0)
1007 char temp[] = " :";
1009 name = make_specified_string (nm, -1, p - nm, multibyte);
1010 temp[0] = DRIVE_LETTER (drive);
1011 AUTO_STRING (drive_prefix, temp);
1012 name = concat2 (drive_prefix, name);
1014 #ifdef WINDOWSNT
1015 if (!NILP (Vw32_downcase_file_names))
1016 name = Fdowncase (name);
1017 #endif
1018 #else /* not DOS_NT */
1019 if (strcmp (nm, SSDATA (name)) != 0)
1020 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1021 #endif /* not DOS_NT */
1022 SAFE_FREE ();
1023 return name;
1027 /* At this point, nm might or might not be an absolute file name. We
1028 need to expand ~ or ~user if present, otherwise prefix nm with
1029 default_directory if nm is not absolute, and finally collapse /./
1030 and /foo/../ sequences.
1032 We set newdir to be the appropriate prefix if one is needed:
1033 - the relevant user directory if nm starts with ~ or ~user
1034 - the specified drive's working dir (DOS/NT only) if nm does not
1035 start with /
1036 - the value of default_directory.
1038 Note that these prefixes are not guaranteed to be absolute (except
1039 for the working dir of a drive). Therefore, to ensure we always
1040 return an absolute name, if the final prefix is not absolute we
1041 append it to the current working directory. */
1043 newdir = newdirlim = 0;
1045 if (nm[0] == '~') /* prefix ~ */
1047 if (IS_DIRECTORY_SEP (nm[1])
1048 || nm[1] == 0) /* ~ by itself */
1050 Lisp_Object tem;
1052 if (!(newdir = egetenv ("HOME")))
1053 newdir = newdirlim = "";
1054 nm++;
1055 /* `egetenv' may return a unibyte string, which will bite us since
1056 we expect the directory to be multibyte. */
1057 #ifdef WINDOWSNT
1058 if (newdir[0])
1060 char newdir_utf8[MAX_UTF8_PATH];
1062 filename_from_ansi (newdir, newdir_utf8);
1063 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1065 else
1066 #endif
1067 tem = build_string (newdir);
1068 newdirlim = newdir + SBYTES (tem);
1069 if (multibyte && !STRING_MULTIBYTE (tem))
1071 hdir = DECODE_FILE (tem);
1072 newdir = SSDATA (hdir);
1073 newdirlim = newdir + SBYTES (hdir);
1075 #ifdef DOS_NT
1076 collapse_newdir = false;
1077 #endif
1079 else /* ~user/filename */
1081 char *o, *p;
1082 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1083 continue;
1084 o = SAFE_ALLOCA (p - nm + 1);
1085 memcpy (o, nm, p - nm);
1086 o[p - nm] = 0;
1088 block_input ();
1089 pw = getpwnam (o + 1);
1090 unblock_input ();
1091 if (pw)
1093 Lisp_Object tem;
1095 newdir = pw->pw_dir;
1096 /* `getpwnam' may return a unibyte string, which will
1097 bite us since we expect the directory to be
1098 multibyte. */
1099 tem = make_unibyte_string (newdir, strlen (newdir));
1100 newdirlim = newdir + SBYTES (tem);
1101 if (multibyte && !STRING_MULTIBYTE (tem))
1103 hdir = DECODE_FILE (tem);
1104 newdir = SSDATA (hdir);
1105 newdirlim = newdir + SBYTES (hdir);
1107 nm = p;
1108 #ifdef DOS_NT
1109 collapse_newdir = false;
1110 #endif
1113 /* If we don't find a user of that name, leave the name
1114 unchanged; don't move nm forward to p. */
1118 #ifdef DOS_NT
1119 /* On DOS and Windows, nm is absolute if a drive name was specified;
1120 use the drive's current directory as the prefix if needed. */
1121 if (!newdir && drive)
1123 /* Get default directory if needed to make nm absolute. */
1124 char *adir = NULL;
1125 if (!IS_DIRECTORY_SEP (nm[0]))
1127 adir = alloca (MAXPATHLEN + 1);
1128 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1129 adir = NULL;
1130 else if (multibyte)
1132 Lisp_Object tem = build_string (adir);
1134 tem = DECODE_FILE (tem);
1135 newdirlim = adir + SBYTES (tem);
1136 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1138 else
1139 newdirlim = adir + strlen (adir);
1141 if (!adir)
1143 /* Either nm starts with /, or drive isn't mounted. */
1144 adir = alloca (4);
1145 adir[0] = DRIVE_LETTER (drive);
1146 adir[1] = ':';
1147 adir[2] = '/';
1148 adir[3] = 0;
1149 newdirlim = adir + 3;
1151 newdir = adir;
1153 #endif /* DOS_NT */
1155 /* Finally, if no prefix has been specified and nm is not absolute,
1156 then it must be expanded relative to default_directory. */
1158 if (1
1159 #ifndef DOS_NT
1160 /* /... alone is not absolute on DOS and Windows. */
1161 && !IS_DIRECTORY_SEP (nm[0])
1162 #endif
1163 #ifdef WINDOWSNT
1164 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1165 && !IS_DIRECTORY_SEP (nm[2]))
1166 #endif
1167 && !newdir)
1169 newdir = SSDATA (default_directory);
1170 newdirlim = newdir + SBYTES (default_directory);
1171 #ifdef DOS_NT
1172 /* Note if special escape prefix is present, but remove for now. */
1173 if (newdir[0] == '/' && newdir[1] == ':')
1175 is_escaped = 1;
1176 newdir += 2;
1178 #endif
1181 #ifdef DOS_NT
1182 if (newdir)
1184 /* First ensure newdir is an absolute name. */
1185 if (
1186 /* Detect MSDOS file names with drive specifiers. */
1187 ! (IS_DRIVE (newdir[0])
1188 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1189 #ifdef WINDOWSNT
1190 /* Detect Windows file names in UNC format. */
1191 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1192 && !IS_DIRECTORY_SEP (newdir[2]))
1193 #endif
1196 /* Effectively, let newdir be (expand-file-name newdir cwd).
1197 Because of the admonition against calling expand-file-name
1198 when we have pointers into lisp strings, we accomplish this
1199 indirectly by prepending newdir to nm if necessary, and using
1200 cwd (or the wd of newdir's drive) as the new newdir. */
1201 char *adir;
1202 #ifdef WINDOWSNT
1203 const int adir_size = MAX_UTF8_PATH;
1204 #else
1205 const int adir_size = MAXPATHLEN + 1;
1206 #endif
1208 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1210 drive = (unsigned char) newdir[0];
1211 newdir += 2;
1213 if (!IS_DIRECTORY_SEP (nm[0]))
1215 ptrdiff_t nmlen = nmlim - nm;
1216 ptrdiff_t newdirlen = newdirlim - newdir;
1217 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1218 + nmlen + 1);
1219 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1220 multibyte);
1221 memcpy (tmp + dlen, nm, nmlen + 1);
1222 nm = tmp;
1223 nmlim = nm + dlen + nmlen;
1225 adir = alloca (adir_size);
1226 if (drive)
1228 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1229 strcpy (adir, "/");
1231 else
1232 getcwd (adir, adir_size);
1233 if (multibyte)
1235 Lisp_Object tem = build_string (adir);
1237 tem = DECODE_FILE (tem);
1238 newdirlim = adir + SBYTES (tem);
1239 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1241 else
1242 newdirlim = adir + strlen (adir);
1243 newdir = adir;
1246 /* Strip off drive name from prefix, if present. */
1247 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1249 drive = newdir[0];
1250 newdir += 2;
1253 /* Keep only a prefix from newdir if nm starts with slash
1254 (//server/share for UNC, nothing otherwise). */
1255 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1257 #ifdef WINDOWSNT
1258 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1259 && !IS_DIRECTORY_SEP (newdir[2]))
1261 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1262 char *p = adir + 2;
1263 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1264 p++;
1265 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1266 *p = 0;
1267 newdir = adir;
1268 newdirlim = newdir + strlen (adir);
1270 else
1271 #endif
1272 newdir = newdirlim = "";
1275 #endif /* DOS_NT */
1277 /* Ignore any slash at the end of newdir, unless newdir is
1278 just "/" or "//". */
1279 length = newdirlim - newdir;
1280 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1281 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1282 length--;
1284 /* Now concatenate the directory and name to new space in the stack frame. */
1285 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1286 eassert (tlen > file_name_as_directory_slop + 1);
1287 #ifdef DOS_NT
1288 /* Reserve space for drive specifier and escape prefix, since either
1289 or both may need to be inserted. (The Microsoft x86 compiler
1290 produces incorrect code if the following two lines are combined.) */
1291 target = alloca (tlen + 4);
1292 target += 4;
1293 #else /* not DOS_NT */
1294 target = SAFE_ALLOCA (tlen);
1295 #endif /* not DOS_NT */
1296 *target = 0;
1297 nbytes = 0;
1299 if (newdir)
1301 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1303 #ifdef DOS_NT
1304 /* If newdir is effectively "C:/", then the drive letter will have
1305 been stripped and newdir will be "/". Concatenating with an
1306 absolute directory in nm produces "//", which will then be
1307 incorrectly treated as a network share. Ignore newdir in
1308 this case (keeping the drive letter). */
1309 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1310 && newdir[1] == '\0'))
1311 #endif
1313 memcpy (target, newdir, length);
1314 target[length] = 0;
1315 nbytes = length;
1318 else
1319 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1322 memcpy (target + nbytes, nm, nmlim - nm + 1);
1324 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1325 appear. */
1327 char *p = target;
1328 char *o = target;
1330 while (*p)
1332 if (!IS_DIRECTORY_SEP (*p))
1334 *o++ = *p++;
1336 else if (p[1] == '.'
1337 && (IS_DIRECTORY_SEP (p[2])
1338 || p[2] == 0))
1340 /* If "/." is the entire filename, keep the "/". Otherwise,
1341 just delete the whole "/.". */
1342 if (o == target && p[2] == '\0')
1343 *o++ = *p;
1344 p += 2;
1346 else if (p[1] == '.' && p[2] == '.'
1347 /* `/../' is the "superroot" on certain file systems.
1348 Turned off on DOS_NT systems because they have no
1349 "superroot" and because this causes us to produce
1350 file names like "d:/../foo" which fail file-related
1351 functions of the underlying OS. (To reproduce, try a
1352 long series of "../../" in default_directory, longer
1353 than the number of levels from the root.) */
1354 #ifndef DOS_NT
1355 && o != target
1356 #endif
1357 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1359 #ifdef WINDOWSNT
1360 char *prev_o = o;
1361 #endif
1362 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1363 continue;
1364 #ifdef WINDOWSNT
1365 /* Don't go below server level in UNC filenames. */
1366 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1367 && IS_DIRECTORY_SEP (*target))
1368 o = prev_o;
1369 else
1370 #endif
1371 /* Keep initial / only if this is the whole name. */
1372 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1373 ++o;
1374 p += 3;
1376 else if (IS_DIRECTORY_SEP (p[1])
1377 && (p != target || IS_DIRECTORY_SEP (p[2])))
1378 /* Collapse multiple "/", except leave leading "//" alone. */
1379 p++;
1380 else
1382 *o++ = *p++;
1386 #ifdef DOS_NT
1387 /* At last, set drive name. */
1388 #ifdef WINDOWSNT
1389 /* Except for network file name. */
1390 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1391 #endif /* WINDOWSNT */
1393 if (!drive) emacs_abort ();
1394 target -= 2;
1395 target[0] = DRIVE_LETTER (drive);
1396 target[1] = ':';
1398 /* Reinsert the escape prefix if required. */
1399 if (is_escaped)
1401 target -= 2;
1402 target[0] = '/';
1403 target[1] = ':';
1405 result = make_specified_string (target, -1, o - target, multibyte);
1406 dostounix_filename (SSDATA (result));
1407 #ifdef WINDOWSNT
1408 if (!NILP (Vw32_downcase_file_names))
1409 result = Fdowncase (result);
1410 #endif
1411 #else /* !DOS_NT */
1412 result = make_specified_string (target, -1, o - target, multibyte);
1413 #endif /* !DOS_NT */
1416 /* Again look to see if the file name has special constructs in it
1417 and perhaps call the corresponding file handler. This is needed
1418 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1419 the ".." component gives us "/user@host:/bar/../baz" which needs
1420 to be expanded again. */
1421 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1422 if (!NILP (handler))
1424 handled_name = call3 (handler, Qexpand_file_name,
1425 result, default_directory);
1426 if (! STRINGP (handled_name))
1427 error ("Invalid handler in `file-name-handler-alist'");
1428 result = handled_name;
1431 SAFE_FREE ();
1432 return result;
1435 #if 0
1436 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1437 This is the old version of expand-file-name, before it was thoroughly
1438 rewritten for Emacs 10.31. We leave this version here commented-out,
1439 because the code is very complex and likely to have subtle bugs. If
1440 bugs _are_ found, it might be of interest to look at the old code and
1441 see what did it do in the relevant situation.
1443 Don't remove this code: it's true that it will be accessible
1444 from the repository, but a few years from deletion, people will
1445 forget it is there. */
1447 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1448 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1449 "Convert FILENAME to absolute, and canonicalize it.\n\
1450 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1451 \(does not start with slash); if DEFAULT is nil or missing,\n\
1452 the current buffer's value of default-directory is used.\n\
1453 Filenames containing `.' or `..' as components are simplified;\n\
1454 initial `~/' expands to your home directory.\n\
1455 See also the function `substitute-in-file-name'.")
1456 (name, defalt)
1457 Lisp_Object name, defalt;
1459 unsigned char *nm;
1461 register unsigned char *newdir, *p, *o;
1462 ptrdiff_t tlen;
1463 unsigned char *target;
1464 struct passwd *pw;
1466 CHECK_STRING (name);
1467 nm = SDATA (name);
1469 /* If nm is absolute, flush ...// and detect /./ and /../.
1470 If no /./ or /../ we can return right away. */
1471 if (nm[0] == '/')
1473 bool lose = 0;
1474 p = nm;
1475 while (*p)
1477 if (p[0] == '/' && p[1] == '/')
1478 nm = p + 1;
1479 if (p[0] == '/' && p[1] == '~')
1480 nm = p + 1, lose = 1;
1481 if (p[0] == '/' && p[1] == '.'
1482 && (p[2] == '/' || p[2] == 0
1483 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1484 lose = 1;
1485 p++;
1487 if (!lose)
1489 if (nm == SDATA (name))
1490 return name;
1491 return build_string (nm);
1495 /* Now determine directory to start with and put it in NEWDIR. */
1497 newdir = 0;
1499 if (nm[0] == '~') /* prefix ~ */
1500 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1502 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1503 newdir = (unsigned char *) "";
1504 nm++;
1506 else /* ~user/filename */
1508 /* Get past ~ to user. */
1509 unsigned char *user = nm + 1;
1510 /* Find end of name. */
1511 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1512 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1513 /* Copy the user name into temp storage. */
1514 o = alloca (len + 1);
1515 memcpy (o, user, len);
1516 o[len] = 0;
1518 /* Look up the user name. */
1519 block_input ();
1520 pw = (struct passwd *) getpwnam (o + 1);
1521 unblock_input ();
1522 if (!pw)
1523 error ("\"%s\" isn't a registered user", o + 1);
1525 newdir = (unsigned char *) pw->pw_dir;
1527 /* Discard the user name from NM. */
1528 nm += len;
1531 if (nm[0] != '/' && !newdir)
1533 if (NILP (defalt))
1534 defalt = current_buffer->directory;
1535 CHECK_STRING (defalt);
1536 newdir = SDATA (defalt);
1539 /* Now concatenate the directory and name to new space in the stack frame. */
1541 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1542 target = alloca (tlen);
1543 *target = 0;
1545 if (newdir)
1547 if (nm[0] == 0 || nm[0] == '/')
1548 strcpy (target, newdir);
1549 else
1550 file_name_as_directory (target, newdir);
1553 strcat (target, nm);
1555 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1557 p = target;
1558 o = target;
1560 while (*p)
1562 if (*p != '/')
1564 *o++ = *p++;
1566 else if (!strncmp (p, "//", 2)
1569 o = target;
1570 p++;
1572 else if (p[0] == '/' && p[1] == '.'
1573 && (p[2] == '/' || p[2] == 0))
1574 p += 2;
1575 else if (!strncmp (p, "/..", 3)
1576 /* `/../' is the "superroot" on certain file systems. */
1577 && o != target
1578 && (p[3] == '/' || p[3] == 0))
1580 while (o != target && *--o != '/')
1582 if (o == target && *o == '/')
1583 ++o;
1584 p += 3;
1586 else
1588 *o++ = *p++;
1592 return make_string (target, o - target);
1594 #endif
1596 /* If /~ or // appears, discard everything through first slash. */
1597 static bool
1598 file_name_absolute_p (const char *filename)
1600 return
1601 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1602 #ifdef DOS_NT
1603 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1604 && IS_DIRECTORY_SEP (filename[2]))
1605 #endif
1609 static char *
1610 search_embedded_absfilename (char *nm, char *endp)
1612 char *p, *s;
1614 for (p = nm + 1; p < endp; p++)
1616 if (IS_DIRECTORY_SEP (p[-1])
1617 && file_name_absolute_p (p)
1618 #if defined (WINDOWSNT) || defined (CYGWIN)
1619 /* // at start of file name is meaningful in Apollo,
1620 WindowsNT and Cygwin systems. */
1621 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1622 #endif /* not (WINDOWSNT || CYGWIN) */
1625 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1626 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1628 USE_SAFE_ALLOCA;
1629 char *o = SAFE_ALLOCA (s - p + 1);
1630 struct passwd *pw;
1631 memcpy (o, p, s - p);
1632 o [s - p] = 0;
1634 /* If we have ~user and `user' exists, discard
1635 everything up to ~. But if `user' does not exist, leave
1636 ~user alone, it might be a literal file name. */
1637 block_input ();
1638 pw = getpwnam (o + 1);
1639 unblock_input ();
1640 SAFE_FREE ();
1641 if (pw)
1642 return p;
1644 else
1645 return p;
1648 return NULL;
1651 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1652 Ssubstitute_in_file_name, 1, 1, 0,
1653 doc: /* Substitute environment variables referred to in FILENAME.
1654 `$FOO' where FOO is an environment variable name means to substitute
1655 the value of that variable. The variable name should be terminated
1656 with a character not a letter, digit or underscore; otherwise, enclose
1657 the entire variable name in braces.
1659 If `/~' appears, all of FILENAME through that `/' is discarded.
1660 If `//' appears, everything up to and including the first of
1661 those `/' is discarded. */)
1662 (Lisp_Object filename)
1664 char *nm, *p, *x, *endp;
1665 bool substituted = false;
1666 bool multibyte;
1667 char *xnm;
1668 Lisp_Object handler;
1670 CHECK_STRING (filename);
1672 multibyte = STRING_MULTIBYTE (filename);
1674 /* If the file name has special constructs in it,
1675 call the corresponding file handler. */
1676 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1677 if (!NILP (handler))
1679 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1680 filename);
1681 if (STRINGP (handled_name))
1682 return handled_name;
1683 error ("Invalid handler in `file-name-handler-alist'");
1686 /* Always work on a copy of the string, in case GC happens during
1687 decode of environment variables, causing the original Lisp_String
1688 data to be relocated. */
1689 USE_SAFE_ALLOCA;
1690 SAFE_ALLOCA_STRING (nm, filename);
1692 #ifdef DOS_NT
1693 dostounix_filename (nm);
1694 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1695 #endif
1696 endp = nm + SBYTES (filename);
1698 /* If /~ or // appears, discard everything through first slash. */
1699 p = search_embedded_absfilename (nm, endp);
1700 if (p)
1701 /* Start over with the new string, so we check the file-name-handler
1702 again. Important with filenames like "/home/foo//:/hello///there"
1703 which would substitute to "/:/hello///there" rather than "/there". */
1705 Lisp_Object result
1706 = (Fsubstitute_in_file_name
1707 (make_specified_string (p, -1, endp - p, multibyte)));
1708 SAFE_FREE ();
1709 return result;
1712 /* See if any variables are substituted into the string. */
1714 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1716 Lisp_Object name
1717 = (!substituted ? filename
1718 : make_specified_string (nm, -1, endp - nm, multibyte));
1719 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1720 CHECK_STRING (tmp);
1721 if (!EQ (tmp, name))
1722 substituted = true;
1723 filename = tmp;
1726 if (!substituted)
1728 #ifdef WINDOWSNT
1729 if (!NILP (Vw32_downcase_file_names))
1730 filename = Fdowncase (filename);
1731 #endif
1732 SAFE_FREE ();
1733 return filename;
1736 xnm = SSDATA (filename);
1737 x = xnm + SBYTES (filename);
1739 /* If /~ or // appears, discard everything through first slash. */
1740 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1741 /* This time we do not start over because we've already expanded envvars
1742 and replaced $$ with $. Maybe we should start over as well, but we'd
1743 need to quote some $ to $$ first. */
1744 xnm = p;
1746 #ifdef WINDOWSNT
1747 if (!NILP (Vw32_downcase_file_names))
1749 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1751 filename = Fdowncase (xname);
1753 else
1754 #endif
1755 if (xnm != SSDATA (filename))
1756 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1757 SAFE_FREE ();
1758 return filename;
1761 /* A slightly faster and more convenient way to get
1762 (directory-file-name (expand-file-name FOO)). */
1764 Lisp_Object
1765 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1767 register Lisp_Object absname;
1769 absname = Fexpand_file_name (filename, defdir);
1771 /* Remove final slash, if any (unless this is the root dir).
1772 stat behaves differently depending! */
1773 if (SCHARS (absname) > 1
1774 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1775 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1776 /* We cannot take shortcuts; they might be wrong for magic file names. */
1777 absname = Fdirectory_file_name (absname);
1778 return absname;
1781 /* Signal an error if the file ABSNAME already exists.
1782 If KNOWN_TO_EXIST, the file is known to exist.
1783 QUERYSTRING is a name for the action that is being considered
1784 to alter the file.
1785 If INTERACTIVE, ask the user whether to proceed,
1786 and bypass the error if the user says to go ahead.
1787 If QUICK, ask for y or n, not yes or no. */
1789 static void
1790 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1791 const char *querystring, bool interactive,
1792 bool quick)
1794 Lisp_Object tem, encoded_filename;
1795 struct stat statbuf;
1796 struct gcpro gcpro1;
1798 encoded_filename = ENCODE_FILE (absname);
1800 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1802 if (S_ISDIR (statbuf.st_mode))
1803 xsignal2 (Qfile_error,
1804 build_string ("File is a directory"), absname);
1805 known_to_exist = true;
1808 if (known_to_exist)
1810 if (! interactive)
1811 xsignal2 (Qfile_already_exists,
1812 build_string ("File already exists"), absname);
1813 GCPRO1 (absname);
1814 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1815 tem = CALLN (Fformat, format, absname, build_string (querystring));
1816 if (quick)
1817 tem = call1 (intern ("y-or-n-p"), tem);
1818 else
1819 tem = do_yes_or_no_p (tem);
1820 UNGCPRO;
1821 if (NILP (tem))
1822 xsignal2 (Qfile_already_exists,
1823 build_string ("File already exists"), absname);
1827 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1828 "fCopy file: \nGCopy %s to file: \np\nP",
1829 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1830 If NEWNAME names a directory, copy FILE there.
1832 This function always sets the file modes of the output file to match
1833 the input file.
1835 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1836 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1837 signal a `file-already-exists' error without overwriting. If
1838 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1839 about overwriting; this is what happens in interactive use with M-x.
1840 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1841 existing file.
1843 Fourth arg KEEP-TIME non-nil means give the output file the same
1844 last-modified time as the old one. (This works on only some systems.)
1846 A prefix arg makes KEEP-TIME non-nil.
1848 If PRESERVE-UID-GID is non-nil, we try to transfer the
1849 uid and gid of FILE to NEWNAME.
1851 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1852 this includes the file modes, along with ACL entries and SELinux
1853 context if present. Otherwise, if NEWNAME is created its file
1854 permission bits are those of FILE, masked by the default file
1855 permissions. */)
1856 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1857 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1858 Lisp_Object preserve_permissions)
1860 Lisp_Object handler;
1861 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1862 ptrdiff_t count = SPECPDL_INDEX ();
1863 Lisp_Object encoded_file, encoded_newname;
1864 #if HAVE_LIBSELINUX
1865 security_context_t con;
1866 int conlength = 0;
1867 #endif
1868 #ifdef WINDOWSNT
1869 int result;
1870 #else
1871 bool already_exists = false;
1872 mode_t new_mask;
1873 int ifd, ofd;
1874 struct stat st;
1875 #endif
1877 encoded_file = encoded_newname = Qnil;
1878 GCPRO4 (file, newname, encoded_file, encoded_newname);
1879 CHECK_STRING (file);
1880 CHECK_STRING (newname);
1882 if (!NILP (Ffile_directory_p (newname)))
1883 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1884 else
1885 newname = Fexpand_file_name (newname, Qnil);
1887 file = Fexpand_file_name (file, Qnil);
1889 /* If the input file name has special constructs in it,
1890 call the corresponding file handler. */
1891 handler = Ffind_file_name_handler (file, Qcopy_file);
1892 /* Likewise for output file name. */
1893 if (NILP (handler))
1894 handler = Ffind_file_name_handler (newname, Qcopy_file);
1895 if (!NILP (handler))
1896 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1897 ok_if_already_exists, keep_time, preserve_uid_gid,
1898 preserve_permissions));
1900 encoded_file = ENCODE_FILE (file);
1901 encoded_newname = ENCODE_FILE (newname);
1903 #ifdef WINDOWSNT
1904 if (NILP (ok_if_already_exists)
1905 || INTEGERP (ok_if_already_exists))
1906 barf_or_query_if_file_exists (newname, false, "copy to it",
1907 INTEGERP (ok_if_already_exists), false);
1909 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1910 !NILP (keep_time), !NILP (preserve_uid_gid),
1911 !NILP (preserve_permissions));
1912 switch (result)
1914 case -1:
1915 report_file_error ("Copying file", list2 (file, newname));
1916 case -2:
1917 report_file_error ("Copying permissions from", file);
1918 case -3:
1919 xsignal2 (Qfile_date_error,
1920 build_string ("Resetting file times"), newname);
1921 case -4:
1922 report_file_error ("Copying permissions to", newname);
1924 #else /* not WINDOWSNT */
1925 immediate_quit = 1;
1926 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1927 immediate_quit = 0;
1929 if (ifd < 0)
1930 report_file_error ("Opening input file", file);
1932 record_unwind_protect_int (close_file_unwind, ifd);
1934 if (fstat (ifd, &st) != 0)
1935 report_file_error ("Input file status", file);
1937 if (!NILP (preserve_permissions))
1939 #if HAVE_LIBSELINUX
1940 if (is_selinux_enabled ())
1942 conlength = fgetfilecon (ifd, &con);
1943 if (conlength == -1)
1944 report_file_error ("Doing fgetfilecon", file);
1946 #endif
1949 /* We can copy only regular files. */
1950 if (!S_ISREG (st.st_mode))
1951 report_file_errno ("Non-regular file", file,
1952 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1954 #ifndef MSDOS
1955 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1956 #else
1957 new_mask = S_IREAD | S_IWRITE;
1958 #endif
1960 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1961 new_mask);
1962 if (ofd < 0 && errno == EEXIST)
1964 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1965 barf_or_query_if_file_exists (newname, true, "copy to it",
1966 INTEGERP (ok_if_already_exists), false);
1967 already_exists = true;
1968 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1970 if (ofd < 0)
1971 report_file_error ("Opening output file", newname);
1973 record_unwind_protect_int (close_file_unwind, ofd);
1975 off_t oldsize = 0, newsize = 0;
1977 if (already_exists)
1979 struct stat out_st;
1980 if (fstat (ofd, &out_st) != 0)
1981 report_file_error ("Output file status", newname);
1982 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1983 report_file_errno ("Input and output files are the same",
1984 list2 (file, newname), 0);
1985 if (S_ISREG (out_st.st_mode))
1986 oldsize = out_st.st_size;
1989 immediate_quit = 1;
1990 QUIT;
1991 while (true)
1993 char buf[MAX_ALLOCA];
1994 ptrdiff_t n = emacs_read (ifd, buf, sizeof buf);
1995 if (n < 0)
1996 report_file_error ("Read error", file);
1997 if (n == 0)
1998 break;
1999 if (emacs_write_sig (ofd, buf, n) != n)
2000 report_file_error ("Write error", newname);
2001 newsize += n;
2004 /* Truncate any existing output file after writing the data. This
2005 is more likely to work than truncation before writing, if the
2006 file system is out of space or the user is over disk quota. */
2007 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2008 report_file_error ("Truncating output file", newname);
2010 immediate_quit = 0;
2012 #ifndef MSDOS
2013 /* Preserve the original file permissions, and if requested, also its
2014 owner and group. */
2016 mode_t preserved_permissions = st.st_mode & 07777;
2017 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2018 if (!NILP (preserve_uid_gid))
2020 /* Attempt to change owner and group. If that doesn't work
2021 attempt to change just the group, as that is sometimes allowed.
2022 Adjust the mode mask to eliminate setuid or setgid bits
2023 or group permissions bits that are inappropriate if the
2024 owner or group are wrong. */
2025 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2027 if (fchown (ofd, -1, st.st_gid) == 0)
2028 preserved_permissions &= ~04000;
2029 else
2031 preserved_permissions &= ~06000;
2033 /* Copy the other bits to the group bits, since the
2034 group is wrong. */
2035 preserved_permissions &= ~070;
2036 preserved_permissions |= (preserved_permissions & 7) << 3;
2037 default_permissions &= ~070;
2038 default_permissions |= (default_permissions & 7) << 3;
2043 switch (!NILP (preserve_permissions)
2044 ? qcopy_acl (SSDATA (encoded_file), ifd,
2045 SSDATA (encoded_newname), ofd,
2046 preserved_permissions)
2047 : (already_exists
2048 || (new_mask & ~realmask) == default_permissions)
2050 : fchmod (ofd, default_permissions))
2052 case -2: report_file_error ("Copying permissions from", file);
2053 case -1: report_file_error ("Copying permissions to", newname);
2056 #endif /* not MSDOS */
2058 #if HAVE_LIBSELINUX
2059 if (conlength > 0)
2061 /* Set the modified context back to the file. */
2062 bool fail = fsetfilecon (ofd, con) != 0;
2063 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2064 if (fail && errno != ENOTSUP)
2065 report_file_error ("Doing fsetfilecon", newname);
2067 freecon (con);
2069 #endif
2071 if (!NILP (keep_time))
2073 struct timespec atime = get_stat_atime (&st);
2074 struct timespec mtime = get_stat_mtime (&st);
2075 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2076 xsignal2 (Qfile_date_error,
2077 build_string ("Cannot set file date"), newname);
2080 if (emacs_close (ofd) < 0)
2081 report_file_error ("Write error", newname);
2083 emacs_close (ifd);
2085 #ifdef MSDOS
2086 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2087 and if it can't, it tells so. Otherwise, under MSDOS we usually
2088 get only the READ bit, which will make the copied file read-only,
2089 so it's better not to chmod at all. */
2090 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2091 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2092 #endif /* MSDOS */
2093 #endif /* not WINDOWSNT */
2095 /* Discard the unwind protects. */
2096 specpdl_ptr = specpdl + count;
2098 UNGCPRO;
2099 return Qnil;
2102 DEFUN ("make-directory-internal", Fmake_directory_internal,
2103 Smake_directory_internal, 1, 1, 0,
2104 doc: /* Create a new directory named DIRECTORY. */)
2105 (Lisp_Object directory)
2107 const char *dir;
2108 Lisp_Object handler;
2109 Lisp_Object encoded_dir;
2111 CHECK_STRING (directory);
2112 directory = Fexpand_file_name (directory, Qnil);
2114 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2115 if (!NILP (handler))
2116 return call2 (handler, Qmake_directory_internal, directory);
2118 encoded_dir = ENCODE_FILE (directory);
2120 dir = SSDATA (encoded_dir);
2122 #ifdef WINDOWSNT
2123 if (mkdir (dir) != 0)
2124 #else
2125 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2126 #endif
2127 report_file_error ("Creating directory", directory);
2129 return Qnil;
2132 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2133 Sdelete_directory_internal, 1, 1, 0,
2134 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2135 (Lisp_Object directory)
2137 const char *dir;
2138 Lisp_Object encoded_dir;
2140 CHECK_STRING (directory);
2141 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2142 encoded_dir = ENCODE_FILE (directory);
2143 dir = SSDATA (encoded_dir);
2145 if (rmdir (dir) != 0)
2146 report_file_error ("Removing directory", directory);
2148 return Qnil;
2151 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2152 "(list (read-file-name \
2153 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2154 \"Move file to trash: \" \"Delete file: \") \
2155 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2156 (null current-prefix-arg))",
2157 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2158 If file has multiple names, it continues to exist with the other names.
2159 TRASH non-nil means to trash the file instead of deleting, provided
2160 `delete-by-moving-to-trash' is non-nil.
2162 When called interactively, TRASH is t if no prefix argument is given.
2163 With a prefix argument, TRASH is nil. */)
2164 (Lisp_Object filename, Lisp_Object trash)
2166 Lisp_Object handler;
2167 Lisp_Object encoded_file;
2168 struct gcpro gcpro1;
2170 GCPRO1 (filename);
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 UNGCPRO;
2177 filename = Fexpand_file_name (filename, Qnil);
2179 handler = Ffind_file_name_handler (filename, Qdelete_file);
2180 if (!NILP (handler))
2181 return call3 (handler, Qdelete_file, filename, trash);
2183 if (delete_by_moving_to_trash && !NILP (trash))
2184 return call1 (Qmove_file_to_trash, filename);
2186 encoded_file = ENCODE_FILE (filename);
2188 if (unlink (SSDATA (encoded_file)) < 0)
2189 report_file_error ("Removing old name", filename);
2190 return Qnil;
2193 static Lisp_Object
2194 internal_delete_file_1 (Lisp_Object ignore)
2196 return Qt;
2199 /* Delete file FILENAME, returning true if successful.
2200 This ignores `delete-by-moving-to-trash'. */
2202 bool
2203 internal_delete_file (Lisp_Object filename)
2205 Lisp_Object tem;
2207 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2208 Qt, internal_delete_file_1);
2209 return NILP (tem);
2212 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2213 "fRename file: \nGRename %s to file: \np",
2214 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2215 If file has names other than FILE, it continues to have those names.
2216 Signals a `file-already-exists' error if a file NEWNAME already exists
2217 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2218 A number as third arg means request confirmation if NEWNAME already exists.
2219 This is what happens in interactive use with M-x. */)
2220 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2222 Lisp_Object handler;
2223 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2224 Lisp_Object encoded_file, encoded_newname, symlink_target;
2226 symlink_target = encoded_file = encoded_newname = Qnil;
2227 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2228 CHECK_STRING (file);
2229 CHECK_STRING (newname);
2230 file = Fexpand_file_name (file, Qnil);
2232 if ((!NILP (Ffile_directory_p (newname)))
2233 #ifdef DOS_NT
2234 /* If the file names are identical but for the case,
2235 don't attempt to move directory to itself. */
2236 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2237 #endif
2240 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2241 ? file : Fdirectory_file_name (file));
2242 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2244 else
2245 newname = Fexpand_file_name (newname, Qnil);
2247 /* If the file name has special constructs in it,
2248 call the corresponding file handler. */
2249 handler = Ffind_file_name_handler (file, Qrename_file);
2250 if (NILP (handler))
2251 handler = Ffind_file_name_handler (newname, Qrename_file);
2252 if (!NILP (handler))
2253 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2254 file, newname, ok_if_already_exists));
2256 encoded_file = ENCODE_FILE (file);
2257 encoded_newname = ENCODE_FILE (newname);
2259 #ifdef DOS_NT
2260 /* If the file names are identical but for the case, don't ask for
2261 confirmation: they simply want to change the letter-case of the
2262 file name. */
2263 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2264 #endif
2265 if (NILP (ok_if_already_exists)
2266 || INTEGERP (ok_if_already_exists))
2267 barf_or_query_if_file_exists (newname, false, "rename to it",
2268 INTEGERP (ok_if_already_exists), false);
2269 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2271 int rename_errno = errno;
2272 if (rename_errno == EXDEV)
2274 ptrdiff_t count;
2275 symlink_target = Ffile_symlink_p (file);
2276 if (! NILP (symlink_target))
2277 Fmake_symbolic_link (symlink_target, newname,
2278 NILP (ok_if_already_exists) ? Qnil : Qt);
2279 else if (!NILP (Ffile_directory_p (file)))
2280 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2281 else
2282 /* We have already prompted if it was an integer, so don't
2283 have copy-file prompt again. */
2284 Fcopy_file (file, newname,
2285 NILP (ok_if_already_exists) ? Qnil : Qt,
2286 Qt, Qt, Qt);
2288 count = SPECPDL_INDEX ();
2289 specbind (Qdelete_by_moving_to_trash, Qnil);
2291 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2292 call2 (Qdelete_directory, file, Qt);
2293 else
2294 Fdelete_file (file, Qnil);
2295 unbind_to (count, Qnil);
2297 else
2298 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2300 UNGCPRO;
2301 return Qnil;
2304 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2305 "fAdd name to file: \nGName to add to %s: \np",
2306 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2307 Signals a `file-already-exists' error if a file NEWNAME already exists
2308 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2309 A number as third arg means request confirmation if NEWNAME already exists.
2310 This is what happens in interactive use with M-x. */)
2311 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2313 Lisp_Object handler;
2314 Lisp_Object encoded_file, encoded_newname;
2315 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2317 GCPRO4 (file, newname, encoded_file, encoded_newname);
2318 encoded_file = encoded_newname = Qnil;
2319 CHECK_STRING (file);
2320 CHECK_STRING (newname);
2321 file = Fexpand_file_name (file, Qnil);
2323 if (!NILP (Ffile_directory_p (newname)))
2324 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2325 else
2326 newname = Fexpand_file_name (newname, Qnil);
2328 /* If the file name has special constructs in it,
2329 call the corresponding file handler. */
2330 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2331 if (!NILP (handler))
2332 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2333 newname, ok_if_already_exists));
2335 /* If the new name has special constructs in it,
2336 call the corresponding file handler. */
2337 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2338 if (!NILP (handler))
2339 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2340 newname, ok_if_already_exists));
2342 encoded_file = ENCODE_FILE (file);
2343 encoded_newname = ENCODE_FILE (newname);
2345 if (NILP (ok_if_already_exists)
2346 || INTEGERP (ok_if_already_exists))
2347 barf_or_query_if_file_exists (newname, false, "make it a new name",
2348 INTEGERP (ok_if_already_exists), false);
2350 unlink (SSDATA (newname));
2351 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2353 int link_errno = errno;
2354 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2357 UNGCPRO;
2358 return Qnil;
2361 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2362 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2363 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2364 Both args must be strings.
2365 Signals a `file-already-exists' error if a file LINKNAME already exists
2366 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2367 A number as third arg means request confirmation if LINKNAME already exists.
2368 This happens for interactive use with M-x. */)
2369 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2371 Lisp_Object handler;
2372 Lisp_Object encoded_target, encoded_linkname;
2373 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2375 GCPRO4 (target, linkname, encoded_target, encoded_linkname);
2376 encoded_target = encoded_linkname = Qnil;
2377 CHECK_STRING (target);
2378 CHECK_STRING (linkname);
2379 /* If the link target has a ~, we must expand it to get
2380 a truly valid file name. Otherwise, do not expand;
2381 we want to permit links to relative file names. */
2382 if (SREF (target, 0) == '~')
2383 target = Fexpand_file_name (target, Qnil);
2385 if (!NILP (Ffile_directory_p (linkname)))
2386 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2387 else
2388 linkname = Fexpand_file_name (linkname, Qnil);
2390 /* If the file name has special constructs in it,
2391 call the corresponding file handler. */
2392 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2393 if (!NILP (handler))
2394 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, target,
2395 linkname, ok_if_already_exists));
2397 /* If the new link name has special constructs in it,
2398 call the corresponding file handler. */
2399 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2400 if (!NILP (handler))
2401 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, target,
2402 linkname, ok_if_already_exists));
2404 encoded_target = ENCODE_FILE (target);
2405 encoded_linkname = ENCODE_FILE (linkname);
2407 if (NILP (ok_if_already_exists)
2408 || INTEGERP (ok_if_already_exists))
2409 barf_or_query_if_file_exists (linkname, false, "make it a link",
2410 INTEGERP (ok_if_already_exists), false);
2411 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2413 /* If we didn't complain already, silently delete existing file. */
2414 int symlink_errno;
2415 if (errno == EEXIST)
2417 unlink (SSDATA (encoded_linkname));
2418 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2419 >= 0)
2421 UNGCPRO;
2422 return Qnil;
2425 if (errno == ENOSYS)
2427 UNGCPRO;
2428 xsignal1 (Qfile_error,
2429 build_string ("Symbolic links are not supported"));
2432 symlink_errno = errno;
2433 report_file_errno ("Making symbolic link", list2 (target, linkname),
2434 symlink_errno);
2436 UNGCPRO;
2437 return Qnil;
2441 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2442 1, 1, 0,
2443 doc: /* Return t if file FILENAME specifies an absolute file name.
2444 On Unix, this is a name starting with a `/' or a `~'. */)
2445 (Lisp_Object filename)
2447 CHECK_STRING (filename);
2448 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2451 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2452 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2453 See also `file-readable-p' and `file-attributes'.
2454 This returns nil for a symlink to a nonexistent file.
2455 Use `file-symlink-p' to test for such links. */)
2456 (Lisp_Object filename)
2458 Lisp_Object absname;
2459 Lisp_Object handler;
2461 CHECK_STRING (filename);
2462 absname = Fexpand_file_name (filename, Qnil);
2464 /* If the file name has special constructs in it,
2465 call the corresponding file handler. */
2466 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2467 if (!NILP (handler))
2469 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2470 errno = 0;
2471 return result;
2474 absname = ENCODE_FILE (absname);
2476 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2479 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2480 doc: /* Return t if FILENAME can be executed by you.
2481 For a directory, this means you can access files in that directory.
2482 \(It is generally better to use `file-accessible-directory-p' for that
2483 purpose, though.) */)
2484 (Lisp_Object filename)
2486 Lisp_Object absname;
2487 Lisp_Object handler;
2489 CHECK_STRING (filename);
2490 absname = Fexpand_file_name (filename, Qnil);
2492 /* If the file name has special constructs in it,
2493 call the corresponding file handler. */
2494 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2495 if (!NILP (handler))
2496 return call2 (handler, Qfile_executable_p, absname);
2498 absname = ENCODE_FILE (absname);
2500 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2503 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2504 doc: /* Return t if file FILENAME exists and you can read it.
2505 See also `file-exists-p' and `file-attributes'. */)
2506 (Lisp_Object filename)
2508 Lisp_Object absname;
2509 Lisp_Object handler;
2511 CHECK_STRING (filename);
2512 absname = Fexpand_file_name (filename, Qnil);
2514 /* If the file name has special constructs in it,
2515 call the corresponding file handler. */
2516 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2517 if (!NILP (handler))
2518 return call2 (handler, Qfile_readable_p, absname);
2520 absname = ENCODE_FILE (absname);
2521 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2522 ? Qt : Qnil);
2525 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2526 doc: /* Return t if file FILENAME can be written or created by you. */)
2527 (Lisp_Object filename)
2529 Lisp_Object absname, dir, encoded;
2530 Lisp_Object handler;
2532 CHECK_STRING (filename);
2533 absname = Fexpand_file_name (filename, Qnil);
2535 /* If the file name has special constructs in it,
2536 call the corresponding file handler. */
2537 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2538 if (!NILP (handler))
2539 return call2 (handler, Qfile_writable_p, absname);
2541 encoded = ENCODE_FILE (absname);
2542 if (check_writable (SSDATA (encoded), W_OK))
2543 return Qt;
2544 if (errno != ENOENT)
2545 return Qnil;
2547 dir = Ffile_name_directory (absname);
2548 eassert (!NILP (dir));
2549 #ifdef MSDOS
2550 dir = Fdirectory_file_name (dir);
2551 #endif /* MSDOS */
2553 dir = ENCODE_FILE (dir);
2554 #ifdef WINDOWSNT
2555 /* The read-only attribute of the parent directory doesn't affect
2556 whether a file or directory can be created within it. Some day we
2557 should check ACLs though, which do affect this. */
2558 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2559 #else
2560 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2561 #endif
2564 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2565 doc: /* Access file FILENAME, and get an error if that does not work.
2566 The second argument STRING is used in the error message.
2567 If there is no error, returns nil. */)
2568 (Lisp_Object filename, Lisp_Object string)
2570 Lisp_Object handler, encoded_filename, absname;
2572 CHECK_STRING (filename);
2573 absname = Fexpand_file_name (filename, Qnil);
2575 CHECK_STRING (string);
2577 /* If the file name has special constructs in it,
2578 call the corresponding file handler. */
2579 handler = Ffind_file_name_handler (absname, Qaccess_file);
2580 if (!NILP (handler))
2581 return call3 (handler, Qaccess_file, absname, string);
2583 encoded_filename = ENCODE_FILE (absname);
2585 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2586 report_file_error (SSDATA (string), filename);
2588 return Qnil;
2591 /* Relative to directory FD, return the symbolic link value of FILENAME.
2592 On failure, return nil. */
2593 Lisp_Object
2594 emacs_readlinkat (int fd, char const *filename)
2596 static struct allocator const emacs_norealloc_allocator =
2597 { xmalloc, NULL, xfree, memory_full };
2598 Lisp_Object val;
2599 char readlink_buf[1024];
2600 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2601 &emacs_norealloc_allocator, readlinkat);
2602 if (!buf)
2603 return Qnil;
2605 val = build_unibyte_string (buf);
2606 if (buf[0] == '/' && strchr (buf, ':'))
2608 AUTO_STRING (slash_colon, "/:");
2609 val = concat2 (slash_colon, val);
2611 if (buf != readlink_buf)
2612 xfree (buf);
2613 val = DECODE_FILE (val);
2614 return val;
2617 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2618 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2619 The value is the link target, as a string.
2620 Otherwise it returns nil.
2622 This function does not check whether the link target exists. */)
2623 (Lisp_Object filename)
2625 Lisp_Object handler;
2627 CHECK_STRING (filename);
2628 filename = Fexpand_file_name (filename, Qnil);
2630 /* If the file name has special constructs in it,
2631 call the corresponding file handler. */
2632 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2633 if (!NILP (handler))
2634 return call2 (handler, Qfile_symlink_p, filename);
2636 filename = ENCODE_FILE (filename);
2638 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2641 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2642 doc: /* Return t if FILENAME names an existing directory.
2643 Symbolic links to directories count as directories.
2644 See `file-symlink-p' to distinguish symlinks. */)
2645 (Lisp_Object filename)
2647 Lisp_Object absname;
2648 Lisp_Object handler;
2650 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2652 /* If the file name has special constructs in it,
2653 call the corresponding file handler. */
2654 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2655 if (!NILP (handler))
2656 return call2 (handler, Qfile_directory_p, absname);
2658 absname = ENCODE_FILE (absname);
2660 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2663 /* Return true if FILE is a directory or a symlink to a directory. */
2664 bool
2665 file_directory_p (char const *file)
2667 #ifdef WINDOWSNT
2668 /* This is cheaper than 'stat'. */
2669 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2670 #else
2671 struct stat st;
2672 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2673 #endif
2676 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2677 Sfile_accessible_directory_p, 1, 1, 0,
2678 doc: /* Return t if file FILENAME names a directory you can open.
2679 For the value to be t, FILENAME must specify the name of a directory as a file,
2680 and the directory must allow you to open files in it. In order to use a
2681 directory as a buffer's current directory, this predicate must return true.
2682 A directory name spec may be given instead; then the value is t
2683 if the directory so specified exists and really is a readable and
2684 searchable directory. */)
2685 (Lisp_Object filename)
2687 Lisp_Object absname;
2688 Lisp_Object handler;
2690 CHECK_STRING (filename);
2691 absname = Fexpand_file_name (filename, Qnil);
2693 /* If the file name has special constructs in it,
2694 call the corresponding file handler. */
2695 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2696 if (!NILP (handler))
2698 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2699 errno = 0;
2700 return r;
2703 absname = ENCODE_FILE (absname);
2704 return file_accessible_directory_p (absname) ? Qt : Qnil;
2707 /* If FILE is a searchable directory or a symlink to a
2708 searchable directory, return true. Otherwise return
2709 false and set errno to an error number. */
2710 bool
2711 file_accessible_directory_p (Lisp_Object file)
2713 #ifdef DOS_NT
2714 /* There's no need to test whether FILE is searchable, as the
2715 searchable/executable bit is invented on DOS_NT platforms. */
2716 return file_directory_p (SSDATA (file));
2717 #else
2718 /* On POSIXish platforms, use just one system call; this avoids a
2719 race and is typically faster. */
2720 const char *data = SSDATA (file);
2721 ptrdiff_t len = SBYTES (file);
2722 char const *dir;
2723 bool ok;
2724 int saved_errno;
2725 USE_SAFE_ALLOCA;
2727 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2728 There are three exceptions: "", "/", and "//". Leave "" alone,
2729 as it's invalid. Append only "." to the other two exceptions as
2730 "/" and "//" are distinct on some platforms, whereas "/", "///",
2731 "////", etc. are all equivalent. */
2732 if (! len)
2733 dir = data;
2734 else
2736 /* Just check for trailing '/' when deciding whether to append '/'.
2737 That's simpler than testing the two special cases "/" and "//",
2738 and it's a safe optimization here. */
2739 char *buf = SAFE_ALLOCA (len + 3);
2740 memcpy (buf, data, len);
2741 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2742 dir = buf;
2745 ok = check_existing (dir);
2746 saved_errno = errno;
2747 SAFE_FREE ();
2748 errno = saved_errno;
2749 return ok;
2750 #endif
2753 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2754 doc: /* Return t if FILENAME names a regular file.
2755 This is the sort of file that holds an ordinary stream of data bytes.
2756 Symbolic links to regular files count as regular files.
2757 See `file-symlink-p' to distinguish symlinks. */)
2758 (Lisp_Object filename)
2760 register Lisp_Object absname;
2761 struct stat st;
2762 Lisp_Object handler;
2764 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2766 /* If the file name has special constructs in it,
2767 call the corresponding file handler. */
2768 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2769 if (!NILP (handler))
2770 return call2 (handler, Qfile_regular_p, absname);
2772 absname = ENCODE_FILE (absname);
2774 #ifdef WINDOWSNT
2776 int result;
2777 Lisp_Object tem = Vw32_get_true_file_attributes;
2779 /* Tell stat to use expensive method to get accurate info. */
2780 Vw32_get_true_file_attributes = Qt;
2781 result = stat (SDATA (absname), &st);
2782 Vw32_get_true_file_attributes = tem;
2784 if (result < 0)
2785 return Qnil;
2786 return S_ISREG (st.st_mode) ? Qt : Qnil;
2788 #else
2789 if (stat (SSDATA (absname), &st) < 0)
2790 return Qnil;
2791 return S_ISREG (st.st_mode) ? Qt : Qnil;
2792 #endif
2795 DEFUN ("file-selinux-context", Ffile_selinux_context,
2796 Sfile_selinux_context, 1, 1, 0,
2797 doc: /* Return SELinux context of file named FILENAME.
2798 The return value is a list (USER ROLE TYPE RANGE), where the list
2799 elements are strings naming the user, role, type, and range of the
2800 file's SELinux security context.
2802 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2803 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2804 (Lisp_Object filename)
2806 Lisp_Object absname;
2807 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2809 Lisp_Object handler;
2810 #if HAVE_LIBSELINUX
2811 security_context_t con;
2812 int conlength;
2813 context_t context;
2814 #endif
2816 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2818 /* If the file name has special constructs in it,
2819 call the corresponding file handler. */
2820 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2821 if (!NILP (handler))
2822 return call2 (handler, Qfile_selinux_context, absname);
2824 absname = ENCODE_FILE (absname);
2826 #if HAVE_LIBSELINUX
2827 if (is_selinux_enabled ())
2829 conlength = lgetfilecon (SSDATA (absname), &con);
2830 if (conlength > 0)
2832 context = context_new (con);
2833 if (context_user_get (context))
2834 user = build_string (context_user_get (context));
2835 if (context_role_get (context))
2836 role = build_string (context_role_get (context));
2837 if (context_type_get (context))
2838 type = build_string (context_type_get (context));
2839 if (context_range_get (context))
2840 range = build_string (context_range_get (context));
2841 context_free (context);
2842 freecon (con);
2845 #endif
2847 return list4 (user, role, type, range);
2850 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2851 Sset_file_selinux_context, 2, 2, 0,
2852 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2853 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2854 elements are strings naming the components of a SELinux context.
2856 Value is t if setting of SELinux context was successful, nil otherwise.
2858 This function does nothing and returns nil if SELinux is disabled,
2859 or if Emacs was not compiled with SELinux support. */)
2860 (Lisp_Object filename, Lisp_Object context)
2862 Lisp_Object absname;
2863 Lisp_Object handler;
2864 #if HAVE_LIBSELINUX
2865 Lisp_Object encoded_absname;
2866 Lisp_Object user = CAR_SAFE (context);
2867 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2868 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2869 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2870 security_context_t con;
2871 bool fail;
2872 int conlength;
2873 context_t parsed_con;
2874 #endif
2876 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2878 /* If the file name has special constructs in it,
2879 call the corresponding file handler. */
2880 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2881 if (!NILP (handler))
2882 return call3 (handler, Qset_file_selinux_context, absname, context);
2884 #if HAVE_LIBSELINUX
2885 if (is_selinux_enabled ())
2887 /* Get current file context. */
2888 encoded_absname = ENCODE_FILE (absname);
2889 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2890 if (conlength > 0)
2892 parsed_con = context_new (con);
2893 /* Change the parts defined in the parameter.*/
2894 if (STRINGP (user))
2896 if (context_user_set (parsed_con, SSDATA (user)))
2897 error ("Doing context_user_set");
2899 if (STRINGP (role))
2901 if (context_role_set (parsed_con, SSDATA (role)))
2902 error ("Doing context_role_set");
2904 if (STRINGP (type))
2906 if (context_type_set (parsed_con, SSDATA (type)))
2907 error ("Doing context_type_set");
2909 if (STRINGP (range))
2911 if (context_range_set (parsed_con, SSDATA (range)))
2912 error ("Doing context_range_set");
2915 /* Set the modified context back to the file. */
2916 fail = (lsetfilecon (SSDATA (encoded_absname),
2917 context_str (parsed_con))
2918 != 0);
2919 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2920 if (fail && errno != ENOTSUP)
2921 report_file_error ("Doing lsetfilecon", absname);
2923 context_free (parsed_con);
2924 freecon (con);
2925 return fail ? Qnil : Qt;
2927 else
2928 report_file_error ("Doing lgetfilecon", absname);
2930 #endif
2932 return Qnil;
2935 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2936 doc: /* Return ACL entries of file named FILENAME.
2937 The entries are returned in a format suitable for use in `set-file-acl'
2938 but is otherwise undocumented and subject to change.
2939 Return nil if file does not exist or is not accessible, or if Emacs
2940 was unable to determine the ACL entries. */)
2941 (Lisp_Object filename)
2943 Lisp_Object absname;
2944 Lisp_Object handler;
2945 #ifdef HAVE_ACL_SET_FILE
2946 acl_t acl;
2947 Lisp_Object acl_string;
2948 char *str;
2949 # ifndef HAVE_ACL_TYPE_EXTENDED
2950 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2951 # endif
2952 #endif
2954 absname = expand_and_dir_to_file (filename,
2955 BVAR (current_buffer, directory));
2957 /* If the file name has special constructs in it,
2958 call the corresponding file handler. */
2959 handler = Ffind_file_name_handler (absname, Qfile_acl);
2960 if (!NILP (handler))
2961 return call2 (handler, Qfile_acl, absname);
2963 #ifdef HAVE_ACL_SET_FILE
2964 absname = ENCODE_FILE (absname);
2966 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2967 if (acl == NULL)
2968 return Qnil;
2970 str = acl_to_text (acl, NULL);
2971 if (str == NULL)
2973 acl_free (acl);
2974 return Qnil;
2977 acl_string = build_string (str);
2978 acl_free (str);
2979 acl_free (acl);
2981 return acl_string;
2982 #endif
2984 return Qnil;
2987 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
2988 2, 2, 0,
2989 doc: /* Set ACL of file named FILENAME to ACL-STRING.
2990 ACL-STRING should contain the textual representation of the ACL
2991 entries in a format suitable for the platform.
2993 Value is t if setting of ACL was successful, nil otherwise.
2995 Setting ACL for local files requires Emacs to be built with ACL
2996 support. */)
2997 (Lisp_Object filename, Lisp_Object acl_string)
2999 Lisp_Object absname;
3000 Lisp_Object handler;
3001 #ifdef HAVE_ACL_SET_FILE
3002 Lisp_Object encoded_absname;
3003 acl_t acl;
3004 bool fail;
3005 #endif
3007 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3009 /* If the file name has special constructs in it,
3010 call the corresponding file handler. */
3011 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3012 if (!NILP (handler))
3013 return call3 (handler, Qset_file_acl, absname, acl_string);
3015 #ifdef HAVE_ACL_SET_FILE
3016 if (STRINGP (acl_string))
3018 acl = acl_from_text (SSDATA (acl_string));
3019 if (acl == NULL)
3021 report_file_error ("Converting ACL", absname);
3022 return Qnil;
3025 encoded_absname = ENCODE_FILE (absname);
3027 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3028 acl)
3029 != 0);
3030 if (fail && acl_errno_valid (errno))
3031 report_file_error ("Setting ACL", absname);
3033 acl_free (acl);
3034 return fail ? Qnil : Qt;
3036 #endif
3038 return Qnil;
3041 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3042 doc: /* Return mode bits of file named FILENAME, as an integer.
3043 Return nil, if file does not exist or is not accessible. */)
3044 (Lisp_Object filename)
3046 Lisp_Object absname;
3047 struct stat st;
3048 Lisp_Object handler;
3050 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3052 /* If the file name has special constructs in it,
3053 call the corresponding file handler. */
3054 handler = Ffind_file_name_handler (absname, Qfile_modes);
3055 if (!NILP (handler))
3056 return call2 (handler, Qfile_modes, absname);
3058 absname = ENCODE_FILE (absname);
3060 if (stat (SSDATA (absname), &st) < 0)
3061 return Qnil;
3063 return make_number (st.st_mode & 07777);
3066 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3067 "(let ((file (read-file-name \"File: \"))) \
3068 (list file (read-file-modes nil file)))",
3069 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3070 Only the 12 low bits of MODE are used.
3072 Interactively, mode bits are read by `read-file-modes', which accepts
3073 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3074 (Lisp_Object filename, Lisp_Object mode)
3076 Lisp_Object absname, encoded_absname;
3077 Lisp_Object handler;
3079 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3080 CHECK_NUMBER (mode);
3082 /* If the file name has special constructs in it,
3083 call the corresponding file handler. */
3084 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3085 if (!NILP (handler))
3086 return call3 (handler, Qset_file_modes, absname, mode);
3088 encoded_absname = ENCODE_FILE (absname);
3090 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3091 report_file_error ("Doing chmod", absname);
3093 return Qnil;
3096 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3097 doc: /* Set the file permission bits for newly created files.
3098 The argument MODE should be an integer; only the low 9 bits are used.
3099 This setting is inherited by subprocesses. */)
3100 (Lisp_Object mode)
3102 mode_t oldrealmask, oldumask, newumask;
3103 CHECK_NUMBER (mode);
3104 oldrealmask = realmask;
3105 newumask = ~ XINT (mode) & 0777;
3107 block_input ();
3108 realmask = newumask;
3109 oldumask = umask (newumask);
3110 unblock_input ();
3112 eassert (oldumask == oldrealmask);
3113 return Qnil;
3116 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3117 doc: /* Return the default file protection for created files.
3118 The value is an integer. */)
3119 (void)
3121 Lisp_Object value;
3122 XSETINT (value, (~ realmask) & 0777);
3123 return value;
3127 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3128 doc: /* Set times of file FILENAME to TIMESTAMP.
3129 Set both access and modification times.
3130 Return t on success, else nil.
3131 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3132 `current-time'. */)
3133 (Lisp_Object filename, Lisp_Object timestamp)
3135 Lisp_Object absname, encoded_absname;
3136 Lisp_Object handler;
3137 struct timespec t = lisp_time_argument (timestamp);
3139 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3141 /* If the file name has special constructs in it,
3142 call the corresponding file handler. */
3143 handler = Ffind_file_name_handler (absname, Qset_file_times);
3144 if (!NILP (handler))
3145 return call3 (handler, Qset_file_times, absname, timestamp);
3147 encoded_absname = ENCODE_FILE (absname);
3150 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3152 #ifdef MSDOS
3153 /* Setting times on a directory always fails. */
3154 if (file_directory_p (SSDATA (encoded_absname)))
3155 return Qnil;
3156 #endif
3157 report_file_error ("Setting file times", absname);
3161 return Qt;
3164 #ifdef HAVE_SYNC
3165 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3166 doc: /* Tell Unix to finish all pending disk updates. */)
3167 (void)
3169 sync ();
3170 return Qnil;
3173 #endif /* HAVE_SYNC */
3175 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3176 doc: /* Return t if file FILE1 is newer than file FILE2.
3177 If FILE1 does not exist, the answer is nil;
3178 otherwise, if FILE2 does not exist, the answer is t. */)
3179 (Lisp_Object file1, Lisp_Object file2)
3181 Lisp_Object absname1, absname2;
3182 struct stat st1, st2;
3183 Lisp_Object handler;
3184 struct gcpro gcpro1, gcpro2;
3186 CHECK_STRING (file1);
3187 CHECK_STRING (file2);
3189 absname1 = Qnil;
3190 GCPRO2 (absname1, file2);
3191 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3192 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3193 UNGCPRO;
3195 /* If the file name has special constructs in it,
3196 call the corresponding file handler. */
3197 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3198 if (NILP (handler))
3199 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3200 if (!NILP (handler))
3201 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3203 GCPRO2 (absname1, absname2);
3204 absname1 = ENCODE_FILE (absname1);
3205 absname2 = ENCODE_FILE (absname2);
3206 UNGCPRO;
3208 if (stat (SSDATA (absname1), &st1) < 0)
3209 return Qnil;
3211 if (stat (SSDATA (absname2), &st2) < 0)
3212 return Qt;
3214 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3215 ? Qt : Qnil);
3218 #ifndef READ_BUF_SIZE
3219 #define READ_BUF_SIZE (64 << 10)
3220 #endif
3221 /* Some buffer offsets are stored in 'int' variables. */
3222 verify (READ_BUF_SIZE <= INT_MAX);
3224 /* This function is called after Lisp functions to decide a coding
3225 system are called, or when they cause an error. Before they are
3226 called, the current buffer is set unibyte and it contains only a
3227 newly inserted text (thus the buffer was empty before the
3228 insertion).
3230 The functions may set markers, overlays, text properties, or even
3231 alter the buffer contents, change the current buffer.
3233 Here, we reset all those changes by:
3234 o set back the current buffer.
3235 o move all markers and overlays to BEG.
3236 o remove all text properties.
3237 o set back the buffer multibyteness. */
3239 static void
3240 decide_coding_unwind (Lisp_Object unwind_data)
3242 Lisp_Object multibyte, undo_list, buffer;
3244 multibyte = XCAR (unwind_data);
3245 unwind_data = XCDR (unwind_data);
3246 undo_list = XCAR (unwind_data);
3247 buffer = XCDR (unwind_data);
3249 set_buffer_internal (XBUFFER (buffer));
3250 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3251 adjust_overlays_for_delete (BEG, Z - BEG);
3252 set_buffer_intervals (current_buffer, NULL);
3253 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3255 /* Now we are safe to change the buffer's multibyteness directly. */
3256 bset_enable_multibyte_characters (current_buffer, multibyte);
3257 bset_undo_list (current_buffer, undo_list);
3260 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3261 object where slot 0 is the file descriptor, slot 1 specifies
3262 an offset to put the read bytes, and slot 2 is the maximum
3263 amount of bytes to read. Value is the number of bytes read. */
3265 static Lisp_Object
3266 read_non_regular (Lisp_Object state)
3268 int nbytes;
3270 immediate_quit = 1;
3271 QUIT;
3272 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3273 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3274 + XSAVE_INTEGER (state, 1)),
3275 XSAVE_INTEGER (state, 2));
3276 immediate_quit = 0;
3277 /* Fast recycle this object for the likely next call. */
3278 free_misc (state);
3279 return make_number (nbytes);
3283 /* Condition-case handler used when reading from non-regular files
3284 in insert-file-contents. */
3286 static Lisp_Object
3287 read_non_regular_quit (Lisp_Object ignore)
3289 return Qnil;
3292 /* Return the file offset that VAL represents, checking for type
3293 errors and overflow. */
3294 static off_t
3295 file_offset (Lisp_Object val)
3297 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3298 return XINT (val);
3300 if (FLOATP (val))
3302 double v = XFLOAT_DATA (val);
3303 if (0 <= v
3304 && (sizeof (off_t) < sizeof v
3305 ? v <= TYPE_MAXIMUM (off_t)
3306 : v < TYPE_MAXIMUM (off_t)))
3307 return v;
3310 wrong_type_argument (intern ("file-offset"), val);
3313 /* Return a special time value indicating the error number ERRNUM. */
3314 static struct timespec
3315 time_error_value (int errnum)
3317 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3318 ? NONEXISTENT_MODTIME_NSECS
3319 : UNKNOWN_MODTIME_NSECS);
3320 return make_timespec (0, ns);
3323 static Lisp_Object
3324 get_window_points_and_markers (void)
3326 Lisp_Object pt_marker = Fpoint_marker ();
3327 Lisp_Object windows
3328 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3329 Lisp_Object window_markers = windows;
3330 /* Window markers (and point) are handled specially: rather than move to
3331 just before or just after the modified text, we try to keep the
3332 markers at the same distance (bug#19161).
3333 In general, this is wrong, but for window-markers, this should be harmless
3334 and is convenient for the end user when most of the file is unmodified,
3335 except for a few minor details near the beginning and near the end. */
3336 for (; CONSP (windows); windows = XCDR (windows))
3337 if (WINDOWP (XCAR (windows)))
3339 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3340 XSETCAR (windows,
3341 Fcons (window_marker, Fmarker_position (window_marker)));
3343 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3346 static void
3347 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3348 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3350 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3351 if (CONSP (XCAR (window_markers)))
3353 Lisp_Object car = XCAR (window_markers);
3354 Lisp_Object marker = XCAR (car);
3355 Lisp_Object oldpos = XCDR (car);
3356 if (MARKERP (marker) && INTEGERP (oldpos)
3357 && XINT (oldpos) > same_at_start
3358 && XINT (oldpos) < same_at_end)
3360 ptrdiff_t oldsize = same_at_end - same_at_start;
3361 ptrdiff_t newsize = inserted;
3362 double growth = newsize / (double)oldsize;
3363 ptrdiff_t newpos
3364 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3365 Fset_marker (marker, make_number (newpos), Qnil);
3370 /* FIXME: insert-file-contents should be split with the top-level moved to
3371 Elisp and only the core kept in C. */
3373 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3374 1, 5, 0,
3375 doc: /* Insert contents of file FILENAME after point.
3376 Returns list of absolute file name and number of characters inserted.
3377 If second argument VISIT is non-nil, the buffer's visited filename and
3378 last save file modtime are set, and it is marked unmodified. If
3379 visiting and the file does not exist, visiting is completed before the
3380 error is signaled.
3382 The optional third and fourth arguments BEG and END specify what portion
3383 of the file to insert. These arguments count bytes in the file, not
3384 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3386 If optional fifth argument REPLACE is non-nil, replace the current
3387 buffer contents (in the accessible portion) with the file contents.
3388 This is better than simply deleting and inserting the whole thing
3389 because (1) it preserves some marker positions and (2) it puts less data
3390 in the undo list. When REPLACE is non-nil, the second return value is
3391 the number of characters that replace previous buffer contents.
3393 This function does code conversion according to the value of
3394 `coding-system-for-read' or `file-coding-system-alist', and sets the
3395 variable `last-coding-system-used' to the coding system actually used.
3397 In addition, this function decodes the inserted text from known formats
3398 by calling `format-decode', which see. */)
3399 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3401 struct stat st;
3402 struct timespec mtime;
3403 int fd;
3404 ptrdiff_t inserted = 0;
3405 ptrdiff_t how_much;
3406 off_t beg_offset, end_offset;
3407 int unprocessed;
3408 ptrdiff_t count = SPECPDL_INDEX ();
3409 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3410 Lisp_Object handler, val, insval, orig_filename, old_undo;
3411 Lisp_Object p;
3412 ptrdiff_t total = 0;
3413 bool not_regular = 0;
3414 int save_errno = 0;
3415 char read_buf[READ_BUF_SIZE];
3416 struct coding_system coding;
3417 bool replace_handled = false;
3418 bool set_coding_system = false;
3419 Lisp_Object coding_system;
3420 bool read_quit = false;
3421 /* If the undo log only contains the insertion, there's no point
3422 keeping it. It's typically when we first fill a file-buffer. */
3423 bool empty_undo_list_p
3424 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3425 && BEG == Z);
3426 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3427 bool we_locked_file = false;
3428 ptrdiff_t fd_index;
3429 Lisp_Object window_markers = Qnil;
3430 /* same_at_start and same_at_end count bytes, because file access counts
3431 bytes and BEG and END count bytes. */
3432 ptrdiff_t same_at_start = BEGV_BYTE;
3433 ptrdiff_t same_at_end = ZV_BYTE;
3434 /* SAME_AT_END_CHARPOS counts characters, because
3435 restore_window_points needs the old character count. */
3436 ptrdiff_t same_at_end_charpos = ZV;
3438 if (current_buffer->base_buffer && ! NILP (visit))
3439 error ("Cannot do file visiting in an indirect buffer");
3441 if (!NILP (BVAR (current_buffer, read_only)))
3442 Fbarf_if_buffer_read_only (Qnil);
3444 val = Qnil;
3445 p = Qnil;
3446 orig_filename = Qnil;
3447 old_undo = Qnil;
3449 GCPRO5 (filename, val, p, orig_filename, old_undo);
3451 CHECK_STRING (filename);
3452 filename = Fexpand_file_name (filename, Qnil);
3454 /* The value Qnil means that the coding system is not yet
3455 decided. */
3456 coding_system = Qnil;
3458 /* If the file name has special constructs in it,
3459 call the corresponding file handler. */
3460 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3461 if (!NILP (handler))
3463 val = call6 (handler, Qinsert_file_contents, filename,
3464 visit, beg, end, replace);
3465 if (CONSP (val) && CONSP (XCDR (val))
3466 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3467 inserted = XINT (XCAR (XCDR (val)));
3468 goto handled;
3471 orig_filename = filename;
3472 filename = ENCODE_FILE (filename);
3474 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3475 if (fd < 0)
3477 save_errno = errno;
3478 if (NILP (visit))
3479 report_file_error ("Opening input file", orig_filename);
3480 mtime = time_error_value (save_errno);
3481 st.st_size = -1;
3482 if (!NILP (Vcoding_system_for_read))
3483 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3484 goto notfound;
3487 fd_index = SPECPDL_INDEX ();
3488 record_unwind_protect_int (close_file_unwind, fd);
3490 /* Replacement should preserve point as it preserves markers. */
3491 if (!NILP (replace))
3493 window_markers = get_window_points_and_markers ();
3494 record_unwind_protect (restore_point_unwind,
3495 XCAR (XCAR (window_markers)));
3498 if (fstat (fd, &st) != 0)
3499 report_file_error ("Input file status", orig_filename);
3500 mtime = get_stat_mtime (&st);
3502 /* This code will need to be changed in order to work on named
3503 pipes, and it's probably just not worth it. So we should at
3504 least signal an error. */
3505 if (!S_ISREG (st.st_mode))
3507 not_regular = 1;
3509 if (! NILP (visit))
3510 goto notfound;
3512 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3513 xsignal2 (Qfile_error,
3514 build_string ("not a regular file"), orig_filename);
3517 if (!NILP (visit))
3519 if (!NILP (beg) || !NILP (end))
3520 error ("Attempt to visit less than an entire file");
3521 if (BEG < Z && NILP (replace))
3522 error ("Cannot do file visiting in a non-empty buffer");
3525 if (!NILP (beg))
3526 beg_offset = file_offset (beg);
3527 else
3528 beg_offset = 0;
3530 if (!NILP (end))
3531 end_offset = file_offset (end);
3532 else
3534 if (not_regular)
3535 end_offset = TYPE_MAXIMUM (off_t);
3536 else
3538 end_offset = st.st_size;
3540 /* A negative size can happen on a platform that allows file
3541 sizes greater than the maximum off_t value. */
3542 if (end_offset < 0)
3543 buffer_overflow ();
3545 /* The file size returned from stat may be zero, but data
3546 may be readable nonetheless, for example when this is a
3547 file in the /proc filesystem. */
3548 if (end_offset == 0)
3549 end_offset = READ_BUF_SIZE;
3553 /* Check now whether the buffer will become too large,
3554 in the likely case where the file's length is not changing.
3555 This saves a lot of needless work before a buffer overflow. */
3556 if (! not_regular)
3558 /* The likely offset where we will stop reading. We could read
3559 more (or less), if the file grows (or shrinks) as we read it. */
3560 off_t likely_end = min (end_offset, st.st_size);
3562 if (beg_offset < likely_end)
3564 ptrdiff_t buf_bytes
3565 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3566 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3567 off_t likely_growth = likely_end - beg_offset;
3568 if (buf_growth_max < likely_growth)
3569 buffer_overflow ();
3573 /* Prevent redisplay optimizations. */
3574 current_buffer->clip_changed = true;
3576 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3578 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3579 setup_coding_system (coding_system, &coding);
3580 /* Ensure we set Vlast_coding_system_used. */
3581 set_coding_system = true;
3583 else if (BEG < Z)
3585 /* Decide the coding system to use for reading the file now
3586 because we can't use an optimized method for handling
3587 `coding:' tag if the current buffer is not empty. */
3588 if (!NILP (Vcoding_system_for_read))
3589 coding_system = Vcoding_system_for_read;
3590 else
3592 /* Don't try looking inside a file for a coding system
3593 specification if it is not seekable. */
3594 if (! not_regular && ! NILP (Vset_auto_coding_function))
3596 /* Find a coding system specified in the heading two
3597 lines or in the tailing several lines of the file.
3598 We assume that the 1K-byte and 3K-byte for heading
3599 and tailing respectively are sufficient for this
3600 purpose. */
3601 int nread;
3603 if (st.st_size <= (1024 * 4))
3604 nread = emacs_read (fd, read_buf, 1024 * 4);
3605 else
3607 nread = emacs_read (fd, read_buf, 1024);
3608 if (nread == 1024)
3610 int ntail;
3611 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3612 report_file_error ("Setting file position",
3613 orig_filename);
3614 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3615 nread = ntail < 0 ? ntail : nread + ntail;
3619 if (nread < 0)
3620 report_file_error ("Read error", orig_filename);
3621 else if (nread > 0)
3623 AUTO_STRING (name, " *code-converting-work*");
3624 struct buffer *prev = current_buffer;
3625 Lisp_Object workbuf;
3626 struct buffer *buf;
3628 record_unwind_current_buffer ();
3630 workbuf = Fget_buffer_create (name);
3631 buf = XBUFFER (workbuf);
3633 delete_all_overlays (buf);
3634 bset_directory (buf, BVAR (current_buffer, directory));
3635 bset_read_only (buf, Qnil);
3636 bset_filename (buf, Qnil);
3637 bset_undo_list (buf, Qt);
3638 eassert (buf->overlays_before == NULL);
3639 eassert (buf->overlays_after == NULL);
3641 set_buffer_internal (buf);
3642 Ferase_buffer ();
3643 bset_enable_multibyte_characters (buf, Qnil);
3645 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3646 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3647 coding_system = call2 (Vset_auto_coding_function,
3648 filename, make_number (nread));
3649 set_buffer_internal (prev);
3651 /* Discard the unwind protect for recovering the
3652 current buffer. */
3653 specpdl_ptr--;
3655 /* Rewind the file for the actual read done later. */
3656 if (lseek (fd, 0, SEEK_SET) < 0)
3657 report_file_error ("Setting file position", orig_filename);
3661 if (NILP (coding_system))
3663 /* If we have not yet decided a coding system, check
3664 file-coding-system-alist. */
3665 coding_system = CALLN (Ffind_operation_coding_system,
3666 Qinsert_file_contents, orig_filename,
3667 visit, beg, end, replace);
3668 if (CONSP (coding_system))
3669 coding_system = XCAR (coding_system);
3673 if (NILP (coding_system))
3674 coding_system = Qundecided;
3675 else
3676 CHECK_CODING_SYSTEM (coding_system);
3678 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3679 /* We must suppress all character code conversion except for
3680 end-of-line conversion. */
3681 coding_system = raw_text_coding_system (coding_system);
3683 setup_coding_system (coding_system, &coding);
3684 /* Ensure we set Vlast_coding_system_used. */
3685 set_coding_system = true;
3688 /* If requested, replace the accessible part of the buffer
3689 with the file contents. Avoid replacing text at the
3690 beginning or end of the buffer that matches the file contents;
3691 that preserves markers pointing to the unchanged parts.
3693 Here we implement this feature in an optimized way
3694 for the case where code conversion is NOT needed.
3695 The following if-statement handles the case of conversion
3696 in a less optimal way.
3698 If the code conversion is "automatic" then we try using this
3699 method and hope for the best.
3700 But if we discover the need for conversion, we give up on this method
3701 and let the following if-statement handle the replace job. */
3702 if (!NILP (replace)
3703 && BEGV < ZV
3704 && (NILP (coding_system)
3705 || ! CODING_REQUIRE_DECODING (&coding)))
3707 ptrdiff_t overlap;
3708 /* There is still a possibility we will find the need to do code
3709 conversion. If that happens, set this variable to
3710 give up on handling REPLACE in the optimized way. */
3711 bool giveup_match_end = false;
3713 if (beg_offset != 0)
3715 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3716 report_file_error ("Setting file position", orig_filename);
3719 immediate_quit = 1;
3720 QUIT;
3721 /* Count how many chars at the start of the file
3722 match the text at the beginning of the buffer. */
3723 while (1)
3725 int nread, bufpos;
3727 nread = emacs_read (fd, read_buf, sizeof read_buf);
3728 if (nread < 0)
3729 report_file_error ("Read error", orig_filename);
3730 else if (nread == 0)
3731 break;
3733 if (CODING_REQUIRE_DETECTION (&coding))
3735 coding_system = detect_coding_system ((unsigned char *) read_buf,
3736 nread, nread, 1, 0,
3737 coding_system);
3738 setup_coding_system (coding_system, &coding);
3741 if (CODING_REQUIRE_DECODING (&coding))
3742 /* We found that the file should be decoded somehow.
3743 Let's give up here. */
3745 giveup_match_end = true;
3746 break;
3749 bufpos = 0;
3750 while (bufpos < nread && same_at_start < ZV_BYTE
3751 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3752 same_at_start++, bufpos++;
3753 /* If we found a discrepancy, stop the scan.
3754 Otherwise loop around and scan the next bufferful. */
3755 if (bufpos != nread)
3756 break;
3758 immediate_quit = false;
3759 /* If the file matches the buffer completely,
3760 there's no need to replace anything. */
3761 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3763 emacs_close (fd);
3764 clear_unwind_protect (fd_index);
3766 /* Truncate the buffer to the size of the file. */
3767 del_range_1 (same_at_start, same_at_end, 0, 0);
3768 goto handled;
3770 immediate_quit = true;
3771 QUIT;
3772 /* Count how many chars at the end of the file
3773 match the text at the end of the buffer. But, if we have
3774 already found that decoding is necessary, don't waste time. */
3775 while (!giveup_match_end)
3777 int total_read, nread, bufpos, trial;
3778 off_t curpos;
3780 /* At what file position are we now scanning? */
3781 curpos = end_offset - (ZV_BYTE - same_at_end);
3782 /* If the entire file matches the buffer tail, stop the scan. */
3783 if (curpos == 0)
3784 break;
3785 /* How much can we scan in the next step? */
3786 trial = min (curpos, sizeof read_buf);
3787 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3788 report_file_error ("Setting file position", orig_filename);
3790 total_read = nread = 0;
3791 while (total_read < trial)
3793 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3794 if (nread < 0)
3795 report_file_error ("Read error", orig_filename);
3796 else if (nread == 0)
3797 break;
3798 total_read += nread;
3801 /* Scan this bufferful from the end, comparing with
3802 the Emacs buffer. */
3803 bufpos = total_read;
3805 /* Compare with same_at_start to avoid counting some buffer text
3806 as matching both at the file's beginning and at the end. */
3807 while (bufpos > 0 && same_at_end > same_at_start
3808 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3809 same_at_end--, bufpos--;
3811 /* If we found a discrepancy, stop the scan.
3812 Otherwise loop around and scan the preceding bufferful. */
3813 if (bufpos != 0)
3815 /* If this discrepancy is because of code conversion,
3816 we cannot use this method; giveup and try the other. */
3817 if (same_at_end > same_at_start
3818 && FETCH_BYTE (same_at_end - 1) >= 0200
3819 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3820 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3821 giveup_match_end = true;
3822 break;
3825 if (nread == 0)
3826 break;
3828 immediate_quit = 0;
3830 if (! giveup_match_end)
3832 ptrdiff_t temp;
3834 /* We win! We can handle REPLACE the optimized way. */
3836 /* Extend the start of non-matching text area to multibyte
3837 character boundary. */
3838 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3839 while (same_at_start > BEGV_BYTE
3840 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3841 same_at_start--;
3843 /* Extend the end of non-matching text area to multibyte
3844 character boundary. */
3845 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3846 while (same_at_end < ZV_BYTE
3847 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3848 same_at_end++;
3850 /* Don't try to reuse the same piece of text twice. */
3851 overlap = (same_at_start - BEGV_BYTE
3852 - (same_at_end
3853 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3854 if (overlap > 0)
3855 same_at_end += overlap;
3856 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3858 /* Arrange to read only the nonmatching middle part of the file. */
3859 beg_offset += same_at_start - BEGV_BYTE;
3860 end_offset -= ZV_BYTE - same_at_end;
3862 invalidate_buffer_caches (current_buffer,
3863 BYTE_TO_CHAR (same_at_start),
3864 same_at_end_charpos);
3865 del_range_byte (same_at_start, same_at_end, 0);
3866 /* Insert from the file at the proper position. */
3867 temp = BYTE_TO_CHAR (same_at_start);
3868 SET_PT_BOTH (temp, same_at_start);
3870 /* If display currently starts at beginning of line,
3871 keep it that way. */
3872 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3873 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3875 replace_handled = true;
3879 /* If requested, replace the accessible part of the buffer
3880 with the file contents. Avoid replacing text at the
3881 beginning or end of the buffer that matches the file contents;
3882 that preserves markers pointing to the unchanged parts.
3884 Here we implement this feature for the case where code conversion
3885 is needed, in a simple way that needs a lot of memory.
3886 The preceding if-statement handles the case of no conversion
3887 in a more optimized way. */
3888 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3890 ptrdiff_t same_at_start_charpos;
3891 ptrdiff_t inserted_chars;
3892 ptrdiff_t overlap;
3893 ptrdiff_t bufpos;
3894 unsigned char *decoded;
3895 ptrdiff_t temp;
3896 ptrdiff_t this = 0;
3897 ptrdiff_t this_count = SPECPDL_INDEX ();
3898 bool multibyte
3899 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3900 Lisp_Object conversion_buffer;
3901 struct gcpro gcpro1;
3903 conversion_buffer = code_conversion_save (1, multibyte);
3905 /* First read the whole file, performing code conversion into
3906 CONVERSION_BUFFER. */
3908 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3909 report_file_error ("Setting file position", orig_filename);
3911 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3912 unprocessed = 0; /* Bytes not processed in previous loop. */
3914 GCPRO1 (conversion_buffer);
3915 while (1)
3917 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3918 quitting while reading a huge file. */
3920 /* Allow quitting out of the actual I/O. */
3921 immediate_quit = 1;
3922 QUIT;
3923 this = emacs_read (fd, read_buf + unprocessed,
3924 READ_BUF_SIZE - unprocessed);
3925 immediate_quit = 0;
3927 if (this <= 0)
3928 break;
3930 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3931 BUF_Z (XBUFFER (conversion_buffer)));
3932 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3933 unprocessed + this, conversion_buffer);
3934 unprocessed = coding.carryover_bytes;
3935 if (coding.carryover_bytes > 0)
3936 memcpy (read_buf, coding.carryover, unprocessed);
3938 UNGCPRO;
3939 if (this < 0)
3940 report_file_error ("Read error", orig_filename);
3941 emacs_close (fd);
3942 clear_unwind_protect (fd_index);
3944 if (unprocessed > 0)
3946 coding.mode |= CODING_MODE_LAST_BLOCK;
3947 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3948 unprocessed, conversion_buffer);
3949 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3952 coding_system = CODING_ID_NAME (coding.id);
3953 set_coding_system = true;
3954 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3955 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3956 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3958 /* Compare the beginning of the converted string with the buffer
3959 text. */
3961 bufpos = 0;
3962 while (bufpos < inserted && same_at_start < same_at_end
3963 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3964 same_at_start++, bufpos++;
3966 /* If the file matches the head of buffer completely,
3967 there's no need to replace anything. */
3969 if (bufpos == inserted)
3971 /* Truncate the buffer to the size of the file. */
3972 if (same_at_start != same_at_end)
3974 invalidate_buffer_caches (current_buffer,
3975 BYTE_TO_CHAR (same_at_start),
3976 BYTE_TO_CHAR (same_at_end));
3977 del_range_byte (same_at_start, same_at_end, 0);
3979 inserted = 0;
3981 unbind_to (this_count, Qnil);
3982 goto handled;
3985 /* Extend the start of non-matching text area to the previous
3986 multibyte character boundary. */
3987 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3988 while (same_at_start > BEGV_BYTE
3989 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3990 same_at_start--;
3992 /* Scan this bufferful from the end, comparing with
3993 the Emacs buffer. */
3994 bufpos = inserted;
3996 /* Compare with same_at_start to avoid counting some buffer text
3997 as matching both at the file's beginning and at the end. */
3998 while (bufpos > 0 && same_at_end > same_at_start
3999 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4000 same_at_end--, bufpos--;
4002 /* Extend the end of non-matching text area to the next
4003 multibyte character boundary. */
4004 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4005 while (same_at_end < ZV_BYTE
4006 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4007 same_at_end++;
4009 /* Don't try to reuse the same piece of text twice. */
4010 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4011 if (overlap > 0)
4012 same_at_end += overlap;
4013 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4015 /* If display currently starts at beginning of line,
4016 keep it that way. */
4017 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4018 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4020 /* Replace the chars that we need to replace,
4021 and update INSERTED to equal the number of bytes
4022 we are taking from the decoded string. */
4023 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4025 if (same_at_end != same_at_start)
4027 invalidate_buffer_caches (current_buffer,
4028 BYTE_TO_CHAR (same_at_start),
4029 same_at_end_charpos);
4030 del_range_byte (same_at_start, same_at_end, 0);
4031 temp = GPT;
4032 eassert (same_at_start == GPT_BYTE);
4033 same_at_start = GPT_BYTE;
4035 else
4037 temp = same_at_end_charpos;
4039 /* Insert from the file at the proper position. */
4040 SET_PT_BOTH (temp, same_at_start);
4041 same_at_start_charpos
4042 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4043 same_at_start - BEGV_BYTE
4044 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4045 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4046 inserted_chars
4047 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4048 same_at_start + inserted - BEGV_BYTE
4049 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4050 - same_at_start_charpos);
4051 /* This binding is to avoid ask-user-about-supersession-threat
4052 being called in insert_from_buffer (via in
4053 prepare_to_modify_buffer). */
4054 specbind (intern ("buffer-file-name"), Qnil);
4055 insert_from_buffer (XBUFFER (conversion_buffer),
4056 same_at_start_charpos, inserted_chars, 0);
4057 /* Set `inserted' to the number of inserted characters. */
4058 inserted = PT - temp;
4059 /* Set point before the inserted characters. */
4060 SET_PT_BOTH (temp, same_at_start);
4062 unbind_to (this_count, Qnil);
4064 goto handled;
4067 if (! not_regular)
4068 total = end_offset - beg_offset;
4069 else
4070 /* For a special file, all we can do is guess. */
4071 total = READ_BUF_SIZE;
4073 if (NILP (visit) && total > 0)
4075 if (!NILP (BVAR (current_buffer, file_truename))
4076 /* Make binding buffer-file-name to nil effective. */
4077 && !NILP (BVAR (current_buffer, filename))
4078 && SAVE_MODIFF >= MODIFF)
4079 we_locked_file = true;
4080 prepare_to_modify_buffer (PT, PT, NULL);
4083 move_gap_both (PT, PT_BYTE);
4084 if (GAP_SIZE < total)
4085 make_gap (total - GAP_SIZE);
4087 if (beg_offset != 0 || !NILP (replace))
4089 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4090 report_file_error ("Setting file position", orig_filename);
4093 /* In the following loop, HOW_MUCH contains the total bytes read so
4094 far for a regular file, and not changed for a special file. But,
4095 before exiting the loop, it is set to a negative value if I/O
4096 error occurs. */
4097 how_much = 0;
4099 /* Total bytes inserted. */
4100 inserted = 0;
4102 /* Here, we don't do code conversion in the loop. It is done by
4103 decode_coding_gap after all data are read into the buffer. */
4105 ptrdiff_t gap_size = GAP_SIZE;
4107 while (how_much < total)
4109 /* `try' is reserved in some compilers (Microsoft C). */
4110 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4111 ptrdiff_t this;
4113 if (not_regular)
4115 Lisp_Object nbytes;
4117 /* Maybe make more room. */
4118 if (gap_size < trytry)
4120 make_gap (trytry - gap_size);
4121 gap_size = GAP_SIZE - inserted;
4124 /* Read from the file, capturing `quit'. When an
4125 error occurs, end the loop, and arrange for a quit
4126 to be signaled after decoding the text we read. */
4127 nbytes = internal_condition_case_1
4128 (read_non_regular,
4129 make_save_int_int_int (fd, inserted, trytry),
4130 Qerror, read_non_regular_quit);
4132 if (NILP (nbytes))
4134 read_quit = true;
4135 break;
4138 this = XINT (nbytes);
4140 else
4142 /* Allow quitting out of the actual I/O. We don't make text
4143 part of the buffer until all the reading is done, so a C-g
4144 here doesn't do any harm. */
4145 immediate_quit = 1;
4146 QUIT;
4147 this = emacs_read (fd,
4148 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4149 + inserted),
4150 trytry);
4151 immediate_quit = 0;
4154 if (this <= 0)
4156 how_much = this;
4157 break;
4160 gap_size -= this;
4162 /* For a regular file, where TOTAL is the real size,
4163 count HOW_MUCH to compare with it.
4164 For a special file, where TOTAL is just a buffer size,
4165 so don't bother counting in HOW_MUCH.
4166 (INSERTED is where we count the number of characters inserted.) */
4167 if (! not_regular)
4168 how_much += this;
4169 inserted += this;
4173 /* Now we have either read all the file data into the gap,
4174 or stop reading on I/O error or quit. If nothing was
4175 read, undo marking the buffer modified. */
4177 if (inserted == 0)
4179 if (we_locked_file)
4180 unlock_file (BVAR (current_buffer, file_truename));
4181 Vdeactivate_mark = old_Vdeactivate_mark;
4183 else
4184 Fset (Qdeactivate_mark, Qt);
4186 emacs_close (fd);
4187 clear_unwind_protect (fd_index);
4189 if (how_much < 0)
4190 report_file_error ("Read error", orig_filename);
4192 /* Make the text read part of the buffer. */
4193 GAP_SIZE -= inserted;
4194 GPT += inserted;
4195 GPT_BYTE += inserted;
4196 ZV += inserted;
4197 ZV_BYTE += inserted;
4198 Z += inserted;
4199 Z_BYTE += inserted;
4201 if (GAP_SIZE > 0)
4202 /* Put an anchor to ensure multi-byte form ends at gap. */
4203 *GPT_ADDR = 0;
4205 notfound:
4207 if (NILP (coding_system))
4209 /* The coding system is not yet decided. Decide it by an
4210 optimized method for handling `coding:' tag.
4212 Note that we can get here only if the buffer was empty
4213 before the insertion. */
4215 if (!NILP (Vcoding_system_for_read))
4216 coding_system = Vcoding_system_for_read;
4217 else
4219 /* Since we are sure that the current buffer was empty
4220 before the insertion, we can toggle
4221 enable-multibyte-characters directly here without taking
4222 care of marker adjustment. By this way, we can run Lisp
4223 program safely before decoding the inserted text. */
4224 Lisp_Object unwind_data;
4225 ptrdiff_t count1 = SPECPDL_INDEX ();
4227 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4228 Fcons (BVAR (current_buffer, undo_list),
4229 Fcurrent_buffer ()));
4230 bset_enable_multibyte_characters (current_buffer, Qnil);
4231 bset_undo_list (current_buffer, Qt);
4232 record_unwind_protect (decide_coding_unwind, unwind_data);
4234 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4236 coding_system = call2 (Vset_auto_coding_function,
4237 filename, make_number (inserted));
4240 if (NILP (coding_system))
4242 /* If the coding system is not yet decided, check
4243 file-coding-system-alist. */
4244 coding_system = CALLN (Ffind_operation_coding_system,
4245 Qinsert_file_contents, orig_filename,
4246 visit, beg, end, Qnil);
4247 if (CONSP (coding_system))
4248 coding_system = XCAR (coding_system);
4250 unbind_to (count1, Qnil);
4251 inserted = Z_BYTE - BEG_BYTE;
4254 if (NILP (coding_system))
4255 coding_system = Qundecided;
4256 else
4257 CHECK_CODING_SYSTEM (coding_system);
4259 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4260 /* We must suppress all character code conversion except for
4261 end-of-line conversion. */
4262 coding_system = raw_text_coding_system (coding_system);
4263 setup_coding_system (coding_system, &coding);
4264 /* Ensure we set Vlast_coding_system_used. */
4265 set_coding_system = true;
4268 if (!NILP (visit))
4270 /* When we visit a file by raw-text, we change the buffer to
4271 unibyte. */
4272 if (CODING_FOR_UNIBYTE (&coding)
4273 /* Can't do this if part of the buffer might be preserved. */
4274 && NILP (replace))
4275 /* Visiting a file with these coding system makes the buffer
4276 unibyte. */
4277 bset_enable_multibyte_characters (current_buffer, Qnil);
4280 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4281 if (CODING_MAY_REQUIRE_DECODING (&coding)
4282 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4284 move_gap_both (PT, PT_BYTE);
4285 GAP_SIZE += inserted;
4286 ZV_BYTE -= inserted;
4287 Z_BYTE -= inserted;
4288 ZV -= inserted;
4289 Z -= inserted;
4290 decode_coding_gap (&coding, inserted, inserted);
4291 inserted = coding.produced_char;
4292 coding_system = CODING_ID_NAME (coding.id);
4294 else if (inserted > 0)
4296 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4297 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4298 inserted);
4301 /* Call after-change hooks for the inserted text, aside from the case
4302 of normal visiting (not with REPLACE), which is done in a new buffer
4303 "before" the buffer is changed. */
4304 if (inserted > 0 && total > 0
4305 && (NILP (visit) || !NILP (replace)))
4307 signal_after_change (PT, 0, inserted);
4308 update_compositions (PT, PT, CHECK_BORDER);
4311 /* Now INSERTED is measured in characters. */
4313 handled:
4315 if (inserted > 0)
4316 restore_window_points (window_markers, inserted,
4317 BYTE_TO_CHAR (same_at_start),
4318 same_at_end_charpos);
4320 if (!NILP (visit))
4322 if (empty_undo_list_p)
4323 bset_undo_list (current_buffer, Qnil);
4325 if (NILP (handler))
4327 current_buffer->modtime = mtime;
4328 current_buffer->modtime_size = st.st_size;
4329 bset_filename (current_buffer, orig_filename);
4332 SAVE_MODIFF = MODIFF;
4333 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4334 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4335 if (NILP (handler))
4337 if (!NILP (BVAR (current_buffer, file_truename)))
4338 unlock_file (BVAR (current_buffer, file_truename));
4339 unlock_file (filename);
4341 if (not_regular)
4342 xsignal2 (Qfile_error,
4343 build_string ("not a regular file"), orig_filename);
4346 if (set_coding_system)
4347 Vlast_coding_system_used = coding_system;
4349 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4351 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4352 visit);
4353 if (! NILP (insval))
4355 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4356 wrong_type_argument (intern ("inserted-chars"), insval);
4357 inserted = XFASTINT (insval);
4361 /* Decode file format. */
4362 if (inserted > 0)
4364 /* Don't run point motion or modification hooks when decoding. */
4365 ptrdiff_t count1 = SPECPDL_INDEX ();
4366 ptrdiff_t old_inserted = inserted;
4367 specbind (Qinhibit_point_motion_hooks, Qt);
4368 specbind (Qinhibit_modification_hooks, Qt);
4370 /* Save old undo list and don't record undo for decoding. */
4371 old_undo = BVAR (current_buffer, undo_list);
4372 bset_undo_list (current_buffer, Qt);
4374 if (NILP (replace))
4376 insval = call3 (Qformat_decode,
4377 Qnil, make_number (inserted), visit);
4378 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4379 wrong_type_argument (intern ("inserted-chars"), insval);
4380 inserted = XFASTINT (insval);
4382 else
4384 /* If REPLACE is non-nil and we succeeded in not replacing the
4385 beginning or end of the buffer text with the file's contents,
4386 call format-decode with `point' positioned at the beginning
4387 of the buffer and `inserted' equaling the number of
4388 characters in the buffer. Otherwise, format-decode might
4389 fail to correctly analyze the beginning or end of the buffer.
4390 Hence we temporarily save `point' and `inserted' here and
4391 restore `point' iff format-decode did not insert or delete
4392 any text. Otherwise we leave `point' at point-min. */
4393 ptrdiff_t opoint = PT;
4394 ptrdiff_t opoint_byte = PT_BYTE;
4395 ptrdiff_t oinserted = ZV - BEGV;
4396 EMACS_INT ochars_modiff = CHARS_MODIFF;
4398 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4399 insval = call3 (Qformat_decode,
4400 Qnil, make_number (oinserted), visit);
4401 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4402 wrong_type_argument (intern ("inserted-chars"), insval);
4403 if (ochars_modiff == CHARS_MODIFF)
4404 /* format_decode didn't modify buffer's characters => move
4405 point back to position before inserted text and leave
4406 value of inserted alone. */
4407 SET_PT_BOTH (opoint, opoint_byte);
4408 else
4409 /* format_decode modified buffer's characters => consider
4410 entire buffer changed and leave point at point-min. */
4411 inserted = XFASTINT (insval);
4414 /* For consistency with format-decode call these now iff inserted > 0
4415 (martin 2007-06-28). */
4416 p = Vafter_insert_file_functions;
4417 while (CONSP (p))
4419 if (NILP (replace))
4421 insval = call1 (XCAR (p), make_number (inserted));
4422 if (!NILP (insval))
4424 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4425 wrong_type_argument (intern ("inserted-chars"), insval);
4426 inserted = XFASTINT (insval);
4429 else
4431 /* For the rationale of this see the comment on
4432 format-decode above. */
4433 ptrdiff_t opoint = PT;
4434 ptrdiff_t opoint_byte = PT_BYTE;
4435 ptrdiff_t oinserted = ZV - BEGV;
4436 EMACS_INT ochars_modiff = CHARS_MODIFF;
4438 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4439 insval = call1 (XCAR (p), make_number (oinserted));
4440 if (!NILP (insval))
4442 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4443 wrong_type_argument (intern ("inserted-chars"), insval);
4444 if (ochars_modiff == CHARS_MODIFF)
4445 /* after_insert_file_functions didn't modify
4446 buffer's characters => move point back to
4447 position before inserted text and leave value of
4448 inserted alone. */
4449 SET_PT_BOTH (opoint, opoint_byte);
4450 else
4451 /* after_insert_file_functions did modify buffer's
4452 characters => consider entire buffer changed and
4453 leave point at point-min. */
4454 inserted = XFASTINT (insval);
4458 QUIT;
4459 p = XCDR (p);
4462 if (!empty_undo_list_p)
4464 bset_undo_list (current_buffer, old_undo);
4465 if (CONSP (old_undo) && inserted != old_inserted)
4467 /* Adjust the last undo record for the size change during
4468 the format conversion. */
4469 Lisp_Object tem = XCAR (old_undo);
4470 if (CONSP (tem) && INTEGERP (XCAR (tem))
4471 && INTEGERP (XCDR (tem))
4472 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4473 XSETCDR (tem, make_number (PT + inserted));
4476 else
4477 /* If undo_list was Qt before, keep it that way.
4478 Otherwise start with an empty undo_list. */
4479 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4481 unbind_to (count1, Qnil);
4484 if (!NILP (visit)
4485 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4487 /* If visiting nonexistent file, return nil. */
4488 report_file_errno ("Opening input file", orig_filename, save_errno);
4491 /* We made a lot of deletions and insertions above, so invalidate
4492 the newline cache for the entire region of the inserted
4493 characters. */
4494 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4495 invalidate_region_cache (current_buffer->base_buffer,
4496 current_buffer->base_buffer->newline_cache,
4497 PT - BEG, Z - PT - inserted);
4498 else if (current_buffer->newline_cache)
4499 invalidate_region_cache (current_buffer,
4500 current_buffer->newline_cache,
4501 PT - BEG, Z - PT - inserted);
4503 if (read_quit)
4504 Fsignal (Qquit, Qnil);
4506 /* Retval needs to be dealt with in all cases consistently. */
4507 if (NILP (val))
4508 val = list2 (orig_filename, make_number (inserted));
4510 RETURN_UNGCPRO (unbind_to (count, val));
4513 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4515 static void
4516 build_annotations_unwind (Lisp_Object arg)
4518 Vwrite_region_annotation_buffers = arg;
4521 /* Decide the coding-system to encode the data with. */
4523 static Lisp_Object
4524 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4525 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4526 struct coding_system *coding)
4528 Lisp_Object val;
4529 Lisp_Object eol_parent = Qnil;
4531 if (auto_saving
4532 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4533 BVAR (current_buffer, auto_save_file_name))))
4535 val = Qutf_8_emacs;
4536 eol_parent = Qunix;
4538 else if (!NILP (Vcoding_system_for_write))
4540 val = Vcoding_system_for_write;
4541 if (coding_system_require_warning
4542 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4543 /* Confirm that VAL can surely encode the current region. */
4544 val = call5 (Vselect_safe_coding_system_function,
4545 start, end, list2 (Qt, val),
4546 Qnil, filename);
4548 else
4550 /* If the variable `buffer-file-coding-system' is set locally,
4551 it means that the file was read with some kind of code
4552 conversion or the variable is explicitly set by users. We
4553 had better write it out with the same coding system even if
4554 `enable-multibyte-characters' is nil.
4556 If it is not set locally, we anyway have to convert EOL
4557 format if the default value of `buffer-file-coding-system'
4558 tells that it is not Unix-like (LF only) format. */
4559 bool using_default_coding = 0;
4560 bool force_raw_text = 0;
4562 val = BVAR (current_buffer, buffer_file_coding_system);
4563 if (NILP (val)
4564 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4566 val = Qnil;
4567 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4568 force_raw_text = 1;
4571 if (NILP (val))
4573 /* Check file-coding-system-alist. */
4574 Lisp_Object coding_systems
4575 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4576 filename, append, visit, lockname);
4577 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4578 val = XCDR (coding_systems);
4581 if (NILP (val))
4583 /* If we still have not decided a coding system, use the
4584 default value of buffer-file-coding-system. */
4585 val = BVAR (current_buffer, buffer_file_coding_system);
4586 using_default_coding = 1;
4589 if (! NILP (val) && ! force_raw_text)
4591 Lisp_Object spec, attrs;
4593 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4594 attrs = AREF (spec, 0);
4595 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4596 force_raw_text = 1;
4599 if (!force_raw_text
4600 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4601 /* Confirm that VAL can surely encode the current region. */
4602 val = call5 (Vselect_safe_coding_system_function,
4603 start, end, val, Qnil, filename);
4605 /* If the decided coding-system doesn't specify end-of-line
4606 format, we use that of
4607 `default-buffer-file-coding-system'. */
4608 if (! using_default_coding
4609 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4610 val = (coding_inherit_eol_type
4611 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4613 /* If we decide not to encode text, use `raw-text' or one of its
4614 subsidiaries. */
4615 if (force_raw_text)
4616 val = raw_text_coding_system (val);
4619 val = coding_inherit_eol_type (val, eol_parent);
4620 setup_coding_system (val, coding);
4622 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4623 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4624 return val;
4627 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4628 "r\nFWrite region to file: \ni\ni\ni\np",
4629 doc: /* Write current region into specified file.
4630 When called from a program, requires three arguments:
4631 START, END and FILENAME. START and END are normally buffer positions
4632 specifying the part of the buffer to write.
4633 If START is nil, that means to use the entire buffer contents.
4634 If START is a string, then output that string to the file
4635 instead of any buffer contents; END is ignored.
4637 Optional fourth argument APPEND if non-nil means
4638 append to existing file contents (if any). If it is a number,
4639 seek to that offset in the file before writing.
4640 Optional fifth argument VISIT, if t or a string, means
4641 set the last-save-file-modtime of buffer to this file's modtime
4642 and mark buffer not modified.
4643 If VISIT is a string, it is a second file name;
4644 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4645 VISIT is also the file name to lock and unlock for clash detection.
4646 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4647 do not display the \"Wrote file\" message.
4648 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4649 use for locking and unlocking, overriding FILENAME and VISIT.
4650 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4651 for an existing file with the same name. If MUSTBENEW is `excl',
4652 that means to get an error if the file already exists; never overwrite.
4653 If MUSTBENEW is neither nil nor `excl', that means ask for
4654 confirmation before overwriting, but do go ahead and overwrite the file
4655 if the user confirms.
4657 This does code conversion according to the value of
4658 `coding-system-for-write', `buffer-file-coding-system', or
4659 `file-coding-system-alist', and sets the variable
4660 `last-coding-system-used' to the coding system actually used.
4662 This calls `write-region-annotate-functions' at the start, and
4663 `write-region-post-annotation-function' at the end. */)
4664 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4665 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4667 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4668 -1);
4671 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4672 descriptor for FILENAME, so do not open or close FILENAME. */
4674 Lisp_Object
4675 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4676 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4677 Lisp_Object mustbenew, int desc)
4679 int open_flags;
4680 int mode;
4681 off_t offset IF_LINT (= 0);
4682 bool open_and_close_file = desc < 0;
4683 bool ok;
4684 int save_errno = 0;
4685 const char *fn;
4686 struct stat st;
4687 struct timespec modtime;
4688 ptrdiff_t count = SPECPDL_INDEX ();
4689 ptrdiff_t count1 IF_LINT (= 0);
4690 Lisp_Object handler;
4691 Lisp_Object visit_file;
4692 Lisp_Object annotations;
4693 Lisp_Object encoded_filename;
4694 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4695 bool quietly = !NILP (visit);
4696 bool file_locked = 0;
4697 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4698 struct buffer *given_buffer;
4699 struct coding_system coding;
4701 if (current_buffer->base_buffer && visiting)
4702 error ("Cannot do file visiting in an indirect buffer");
4704 if (!NILP (start) && !STRINGP (start))
4705 validate_region (&start, &end);
4707 visit_file = Qnil;
4708 GCPRO5 (start, filename, visit, visit_file, lockname);
4710 filename = Fexpand_file_name (filename, Qnil);
4712 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4713 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4715 if (STRINGP (visit))
4716 visit_file = Fexpand_file_name (visit, Qnil);
4717 else
4718 visit_file = filename;
4720 if (NILP (lockname))
4721 lockname = visit_file;
4723 annotations = Qnil;
4725 /* If the file name has special constructs in it,
4726 call the corresponding file handler. */
4727 handler = Ffind_file_name_handler (filename, Qwrite_region);
4728 /* If FILENAME has no handler, see if VISIT has one. */
4729 if (NILP (handler) && STRINGP (visit))
4730 handler = Ffind_file_name_handler (visit, Qwrite_region);
4732 if (!NILP (handler))
4734 Lisp_Object val;
4735 val = call6 (handler, Qwrite_region, start, end,
4736 filename, append, visit);
4738 if (visiting)
4740 SAVE_MODIFF = MODIFF;
4741 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4742 bset_filename (current_buffer, visit_file);
4744 UNGCPRO;
4745 return val;
4748 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4750 /* Special kludge to simplify auto-saving. */
4751 if (NILP (start))
4753 /* Do it later, so write-region-annotate-function can work differently
4754 if we save "the buffer" vs "a region".
4755 This is useful in tar-mode. --Stef
4756 XSETFASTINT (start, BEG);
4757 XSETFASTINT (end, Z); */
4758 Fwiden ();
4761 record_unwind_protect (build_annotations_unwind,
4762 Vwrite_region_annotation_buffers);
4763 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4765 given_buffer = current_buffer;
4767 if (!STRINGP (start))
4769 annotations = build_annotations (start, end);
4771 if (current_buffer != given_buffer)
4773 XSETFASTINT (start, BEGV);
4774 XSETFASTINT (end, ZV);
4778 if (NILP (start))
4780 XSETFASTINT (start, BEGV);
4781 XSETFASTINT (end, ZV);
4784 UNGCPRO;
4786 GCPRO5 (start, filename, annotations, visit_file, lockname);
4788 /* Decide the coding-system to encode the data with.
4789 We used to make this choice before calling build_annotations, but that
4790 leads to problems when a write-annotate-function takes care of
4791 unsavable chars (as was the case with X-Symbol). */
4792 Vlast_coding_system_used
4793 = choose_write_coding_system (start, end, filename,
4794 append, visit, lockname, &coding);
4796 if (open_and_close_file && !auto_saving)
4798 lock_file (lockname);
4799 file_locked = 1;
4802 encoded_filename = ENCODE_FILE (filename);
4803 fn = SSDATA (encoded_filename);
4804 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4805 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4806 if (NUMBERP (append))
4807 offset = file_offset (append);
4808 else if (!NILP (append))
4809 open_flags |= O_APPEND;
4810 #ifdef DOS_NT
4811 mode = S_IREAD | S_IWRITE;
4812 #else
4813 mode = auto_saving ? auto_save_mode_bits : 0666;
4814 #endif
4816 if (open_and_close_file)
4818 desc = emacs_open (fn, open_flags, mode);
4819 if (desc < 0)
4821 int open_errno = errno;
4822 if (file_locked)
4823 unlock_file (lockname);
4824 UNGCPRO;
4825 report_file_errno ("Opening output file", filename, open_errno);
4828 count1 = SPECPDL_INDEX ();
4829 record_unwind_protect_int (close_file_unwind, desc);
4832 if (NUMBERP (append))
4834 off_t ret = lseek (desc, offset, SEEK_SET);
4835 if (ret < 0)
4837 int lseek_errno = errno;
4838 if (file_locked)
4839 unlock_file (lockname);
4840 UNGCPRO;
4841 report_file_errno ("Lseek error", filename, lseek_errno);
4845 UNGCPRO;
4847 immediate_quit = 1;
4849 if (STRINGP (start))
4850 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4851 else if (XINT (start) != XINT (end))
4852 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4853 &annotations, &coding);
4854 else
4856 /* If file was empty, still need to write the annotations. */
4857 coding.mode |= CODING_MODE_LAST_BLOCK;
4858 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4860 save_errno = errno;
4862 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4863 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4865 /* We have to flush out a data. */
4866 coding.mode |= CODING_MODE_LAST_BLOCK;
4867 ok = e_write (desc, Qnil, 1, 1, &coding);
4868 save_errno = errno;
4871 immediate_quit = 0;
4873 /* fsync is not crucial for temporary files. Nor for auto-save
4874 files, since they might lose some work anyway. */
4875 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4877 /* Transfer data and metadata to disk, retrying if interrupted.
4878 fsync can report a write failure here, e.g., due to disk full
4879 under NFS. But ignore EINVAL, which means fsync is not
4880 supported on this file. */
4881 while (fsync (desc) != 0)
4882 if (errno != EINTR)
4884 if (errno != EINVAL)
4885 ok = 0, save_errno = errno;
4886 break;
4890 modtime = invalid_timespec ();
4891 if (visiting)
4893 if (fstat (desc, &st) == 0)
4894 modtime = get_stat_mtime (&st);
4895 else
4896 ok = 0, save_errno = errno;
4899 if (open_and_close_file)
4901 /* NFS can report a write failure now. */
4902 if (emacs_close (desc) < 0)
4903 ok = 0, save_errno = errno;
4905 /* Discard the unwind protect for close_file_unwind. */
4906 specpdl_ptr = specpdl + count1;
4909 /* Some file systems have a bug where st_mtime is not updated
4910 properly after a write. For example, CIFS might not see the
4911 st_mtime change until after the file is opened again.
4913 Attempt to detect this file system bug, and update MODTIME to the
4914 newer st_mtime if the bug appears to be present. This introduces
4915 a race condition, so to avoid most instances of the race condition
4916 on non-buggy file systems, skip this check if the most recently
4917 encountered non-buggy file system was the current file system.
4919 A race condition can occur if some other process modifies the
4920 file between the fstat above and the fstat below, but the race is
4921 unlikely and a similar race between the last write and the fstat
4922 above cannot possibly be closed anyway. */
4924 if (timespec_valid_p (modtime)
4925 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4927 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4928 if (desc1 >= 0)
4930 struct stat st1;
4931 if (fstat (desc1, &st1) == 0
4932 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4934 /* Use the heuristic if it appears to be valid. With neither
4935 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4936 file, the time stamp won't change. Also, some non-POSIX
4937 systems don't update an empty file's time stamp when
4938 truncating it. Finally, file systems with 100 ns or worse
4939 resolution sometimes seem to have bugs: on a system with ns
4940 resolution, checking ns % 100 incorrectly avoids the heuristic
4941 1% of the time, but the problem should be temporary as we will
4942 try again on the next time stamp. */
4943 bool use_heuristic
4944 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4945 && st.st_size != 0
4946 && modtime.tv_nsec % 100 != 0);
4948 struct timespec modtime1 = get_stat_mtime (&st1);
4949 if (use_heuristic
4950 && timespec_cmp (modtime, modtime1) == 0
4951 && st.st_size == st1.st_size)
4953 timestamp_file_system = st.st_dev;
4954 valid_timestamp_file_system = 1;
4956 else
4958 st.st_size = st1.st_size;
4959 modtime = modtime1;
4962 emacs_close (desc1);
4966 /* Call write-region-post-annotation-function. */
4967 while (CONSP (Vwrite_region_annotation_buffers))
4969 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4970 if (!NILP (Fbuffer_live_p (buf)))
4972 Fset_buffer (buf);
4973 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4974 call0 (Vwrite_region_post_annotation_function);
4976 Vwrite_region_annotation_buffers
4977 = XCDR (Vwrite_region_annotation_buffers);
4980 unbind_to (count, Qnil);
4982 if (file_locked)
4983 unlock_file (lockname);
4985 /* Do this before reporting IO error
4986 to avoid a "file has changed on disk" warning on
4987 next attempt to save. */
4988 if (timespec_valid_p (modtime))
4990 current_buffer->modtime = modtime;
4991 current_buffer->modtime_size = st.st_size;
4994 if (! ok)
4995 report_file_errno ("Write error", filename, save_errno);
4997 if (visiting)
4999 SAVE_MODIFF = MODIFF;
5000 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5001 bset_filename (current_buffer, visit_file);
5002 update_mode_lines = 14;
5004 else if (quietly)
5006 if (auto_saving
5007 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5008 BVAR (current_buffer, auto_save_file_name))))
5009 SAVE_MODIFF = MODIFF;
5011 return Qnil;
5014 if (!auto_saving && !noninteractive)
5015 message_with_string ((NUMBERP (append)
5016 ? "Updated %s"
5017 : ! NILP (append)
5018 ? "Added to %s"
5019 : "Wrote %s"),
5020 visit_file, 1);
5022 return Qnil;
5025 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5026 doc: /* Return t if (car A) is numerically less than (car B). */)
5027 (Lisp_Object a, Lisp_Object b)
5029 return CALLN (Flss, Fcar (a), Fcar (b));
5032 /* Build the complete list of annotations appropriate for writing out
5033 the text between START and END, by calling all the functions in
5034 write-region-annotate-functions and merging the lists they return.
5035 If one of these functions switches to a different buffer, we assume
5036 that buffer contains altered text. Therefore, the caller must
5037 make sure to restore the current buffer in all cases,
5038 as save-excursion would do. */
5040 static Lisp_Object
5041 build_annotations (Lisp_Object start, Lisp_Object end)
5043 Lisp_Object annotations;
5044 Lisp_Object p, res;
5045 struct gcpro gcpro1, gcpro2;
5046 Lisp_Object original_buffer;
5047 int i;
5048 bool used_global = false;
5050 XSETBUFFER (original_buffer, current_buffer);
5052 annotations = Qnil;
5053 p = Vwrite_region_annotate_functions;
5054 GCPRO2 (annotations, p);
5055 while (CONSP (p))
5057 struct buffer *given_buffer = current_buffer;
5058 if (EQ (Qt, XCAR (p)) && !used_global)
5059 { /* Use the global value of the hook. */
5060 used_global = true;
5061 p = CALLN (Fappend,
5062 Fdefault_value (Qwrite_region_annotate_functions),
5063 XCDR (p));
5064 continue;
5066 Vwrite_region_annotations_so_far = annotations;
5067 res = call2 (XCAR (p), start, end);
5068 /* If the function makes a different buffer current,
5069 assume that means this buffer contains altered text to be output.
5070 Reset START and END from the buffer bounds
5071 and discard all previous annotations because they should have
5072 been dealt with by this function. */
5073 if (current_buffer != given_buffer)
5075 Vwrite_region_annotation_buffers
5076 = Fcons (Fcurrent_buffer (),
5077 Vwrite_region_annotation_buffers);
5078 XSETFASTINT (start, BEGV);
5079 XSETFASTINT (end, ZV);
5080 annotations = Qnil;
5082 Flength (res); /* Check basic validity of return value */
5083 annotations = merge (annotations, res, Qcar_less_than_car);
5084 p = XCDR (p);
5087 /* Now do the same for annotation functions implied by the file-format */
5088 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5089 p = BVAR (current_buffer, auto_save_file_format);
5090 else
5091 p = BVAR (current_buffer, file_format);
5092 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5094 struct buffer *given_buffer = current_buffer;
5096 Vwrite_region_annotations_so_far = annotations;
5098 /* Value is either a list of annotations or nil if the function
5099 has written annotations to a temporary buffer, which is now
5100 current. */
5101 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5102 original_buffer, make_number (i));
5103 if (current_buffer != given_buffer)
5105 XSETFASTINT (start, BEGV);
5106 XSETFASTINT (end, ZV);
5107 annotations = Qnil;
5110 if (CONSP (res))
5111 annotations = merge (annotations, res, Qcar_less_than_car);
5114 UNGCPRO;
5115 return annotations;
5119 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5120 If STRING is nil, POS is the character position in the current buffer.
5121 Intersperse with them the annotations from *ANNOT
5122 which fall within the range of POS to POS + NCHARS,
5123 each at its appropriate position.
5125 We modify *ANNOT by discarding elements as we use them up.
5127 Return true if successful. */
5129 static bool
5130 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5131 ptrdiff_t nchars, Lisp_Object *annot,
5132 struct coding_system *coding)
5134 Lisp_Object tem;
5135 ptrdiff_t nextpos;
5136 ptrdiff_t lastpos = pos + nchars;
5138 while (NILP (*annot) || CONSP (*annot))
5140 tem = Fcar_safe (Fcar (*annot));
5141 nextpos = pos - 1;
5142 if (INTEGERP (tem))
5143 nextpos = XFASTINT (tem);
5145 /* If there are no more annotations in this range,
5146 output the rest of the range all at once. */
5147 if (! (nextpos >= pos && nextpos <= lastpos))
5148 return e_write (desc, string, pos, lastpos, coding);
5150 /* Output buffer text up to the next annotation's position. */
5151 if (nextpos > pos)
5153 if (!e_write (desc, string, pos, nextpos, coding))
5154 return 0;
5155 pos = nextpos;
5157 /* Output the annotation. */
5158 tem = Fcdr (Fcar (*annot));
5159 if (STRINGP (tem))
5161 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5162 return 0;
5164 *annot = Fcdr (*annot);
5166 return 1;
5169 /* Maximum number of characters that the next
5170 function encodes per one loop iteration. */
5172 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5174 /* Write text in the range START and END into descriptor DESC,
5175 encoding them with coding system CODING. If STRING is nil, START
5176 and END are character positions of the current buffer, else they
5177 are indexes to the string STRING. Return true if successful. */
5179 static bool
5180 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5181 struct coding_system *coding)
5183 if (STRINGP (string))
5185 start = 0;
5186 end = SCHARS (string);
5189 /* We used to have a code for handling selective display here. But,
5190 now it is handled within encode_coding. */
5192 while (start < end)
5194 if (STRINGP (string))
5196 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5197 if (CODING_REQUIRE_ENCODING (coding))
5199 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5201 /* Avoid creating huge Lisp string in encode_coding_object. */
5202 if (nchars == E_WRITE_MAX)
5203 coding->raw_destination = 1;
5205 encode_coding_object
5206 (coding, string, start, string_char_to_byte (string, start),
5207 start + nchars, string_char_to_byte (string, start + nchars),
5208 Qt);
5210 else
5212 coding->dst_object = string;
5213 coding->consumed_char = SCHARS (string);
5214 coding->produced = SBYTES (string);
5217 else
5219 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5220 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5222 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5223 if (CODING_REQUIRE_ENCODING (coding))
5225 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5227 /* Likewise. */
5228 if (nchars == E_WRITE_MAX)
5229 coding->raw_destination = 1;
5231 encode_coding_object
5232 (coding, Fcurrent_buffer (), start, start_byte,
5233 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5235 else
5237 coding->dst_object = Qnil;
5238 coding->dst_pos_byte = start_byte;
5239 if (start >= GPT || end <= GPT)
5241 coding->consumed_char = end - start;
5242 coding->produced = end_byte - start_byte;
5244 else
5246 coding->consumed_char = GPT - start;
5247 coding->produced = GPT_BYTE - start_byte;
5252 if (coding->produced > 0)
5254 char *buf = (coding->raw_destination ? (char *) coding->destination
5255 : (STRINGP (coding->dst_object)
5256 ? SSDATA (coding->dst_object)
5257 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5258 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5260 if (coding->raw_destination)
5262 /* We're responsible for freeing this, see
5263 encode_coding_object to check why. */
5264 xfree (coding->destination);
5265 coding->raw_destination = 0;
5267 if (coding->produced)
5268 return 0;
5270 start += coding->consumed_char;
5273 return 1;
5276 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5277 Sverify_visited_file_modtime, 0, 1, 0,
5278 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5279 This means that the file has not been changed since it was visited or saved.
5280 If BUF is omitted or nil, it defaults to the current buffer.
5281 See Info node `(elisp)Modification Time' for more details. */)
5282 (Lisp_Object buf)
5284 struct buffer *b = decode_buffer (buf);
5285 struct stat st;
5286 Lisp_Object handler;
5287 Lisp_Object filename;
5288 struct timespec mtime;
5290 if (!STRINGP (BVAR (b, filename))) return Qt;
5291 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5293 /* If the file name has special constructs in it,
5294 call the corresponding file handler. */
5295 handler = Ffind_file_name_handler (BVAR (b, filename),
5296 Qverify_visited_file_modtime);
5297 if (!NILP (handler))
5298 return call2 (handler, Qverify_visited_file_modtime, buf);
5300 filename = ENCODE_FILE (BVAR (b, filename));
5302 mtime = (stat (SSDATA (filename), &st) == 0
5303 ? get_stat_mtime (&st)
5304 : time_error_value (errno));
5305 if (timespec_cmp (mtime, b->modtime) == 0
5306 && (b->modtime_size < 0
5307 || st.st_size == b->modtime_size))
5308 return Qt;
5309 return Qnil;
5312 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5313 Svisited_file_modtime, 0, 0, 0,
5314 doc: /* Return the current buffer's recorded visited file modification time.
5315 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5316 `file-attributes' returns. If the current buffer has no recorded file
5317 modification time, this function returns 0. If the visited file
5318 doesn't exist, return -1.
5319 See Info node `(elisp)Modification Time' for more details. */)
5320 (void)
5322 int ns = current_buffer->modtime.tv_nsec;
5323 if (ns < 0)
5324 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5325 return make_lisp_time (current_buffer->modtime);
5328 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5329 Sset_visited_file_modtime, 0, 1, 0,
5330 doc: /* Update buffer's recorded modification time from the visited file's time.
5331 Useful if the buffer was not read from the file normally
5332 or if the file itself has been changed for some known benign reason.
5333 An argument specifies the modification time value to use
5334 \(instead of that of the visited file), in the form of a list
5335 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5336 `visited-file-modtime'. */)
5337 (Lisp_Object time_flag)
5339 if (!NILP (time_flag))
5341 struct timespec mtime;
5342 if (INTEGERP (time_flag))
5344 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5345 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5347 else
5348 mtime = lisp_time_argument (time_flag);
5350 current_buffer->modtime = mtime;
5351 current_buffer->modtime_size = -1;
5353 else
5355 register Lisp_Object filename;
5356 struct stat st;
5357 Lisp_Object handler;
5359 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5361 /* If the file name has special constructs in it,
5362 call the corresponding file handler. */
5363 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5364 if (!NILP (handler))
5365 /* The handler can find the file name the same way we did. */
5366 return call2 (handler, Qset_visited_file_modtime, Qnil);
5368 filename = ENCODE_FILE (filename);
5370 if (stat (SSDATA (filename), &st) >= 0)
5372 current_buffer->modtime = get_stat_mtime (&st);
5373 current_buffer->modtime_size = st.st_size;
5377 return Qnil;
5380 static Lisp_Object
5381 auto_save_error (Lisp_Object error_val)
5383 Lisp_Object msg;
5384 int i;
5385 struct gcpro gcpro1;
5387 auto_save_error_occurred = 1;
5389 ring_bell (XFRAME (selected_frame));
5391 AUTO_STRING (format, "Auto-saving %s: %s");
5392 msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5393 Ferror_message_string (error_val));
5394 GCPRO1 (msg);
5396 for (i = 0; i < 3; ++i)
5398 if (i == 0)
5399 message3 (msg);
5400 else
5401 message3_nolog (msg);
5402 Fsleep_for (make_number (1), Qnil);
5405 UNGCPRO;
5406 return Qnil;
5409 static Lisp_Object
5410 auto_save_1 (void)
5412 struct stat st;
5413 Lisp_Object modes;
5415 auto_save_mode_bits = 0666;
5417 /* Get visited file's mode to become the auto save file's mode. */
5418 if (! NILP (BVAR (current_buffer, filename)))
5420 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5421 /* But make sure we can overwrite it later! */
5422 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5423 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5424 INTEGERP (modes))
5425 /* Remote files don't cooperate with stat. */
5426 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5429 return
5430 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5431 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5432 Qnil, Qnil);
5435 struct auto_save_unwind
5437 FILE *stream;
5438 bool auto_raise;
5441 static void
5442 do_auto_save_unwind (void *arg)
5444 struct auto_save_unwind *p = arg;
5445 FILE *stream = p->stream;
5446 minibuffer_auto_raise = p->auto_raise;
5447 auto_saving = 0;
5448 if (stream != NULL)
5450 block_input ();
5451 fclose (stream);
5452 unblock_input ();
5456 static Lisp_Object
5457 do_auto_save_make_dir (Lisp_Object dir)
5459 Lisp_Object result;
5461 auto_saving_dir_umask = 077;
5462 result = call2 (Qmake_directory, dir, Qt);
5463 auto_saving_dir_umask = 0;
5464 return result;
5467 static Lisp_Object
5468 do_auto_save_eh (Lisp_Object ignore)
5470 auto_saving_dir_umask = 0;
5471 return Qnil;
5474 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5475 doc: /* Auto-save all buffers that need it.
5476 This is all buffers that have auto-saving enabled
5477 and are changed since last auto-saved.
5478 Auto-saving writes the buffer into a file
5479 so that your editing is not lost if the system crashes.
5480 This file is not the file you visited; that changes only when you save.
5481 Normally we run the normal hook `auto-save-hook' before saving.
5483 A non-nil NO-MESSAGE argument means do not print any message if successful.
5484 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5485 (Lisp_Object no_message, Lisp_Object current_only)
5487 struct buffer *old = current_buffer, *b;
5488 Lisp_Object tail, buf, hook;
5489 bool auto_saved = 0;
5490 int do_handled_files;
5491 Lisp_Object oquit;
5492 FILE *stream = NULL;
5493 ptrdiff_t count = SPECPDL_INDEX ();
5494 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5495 bool old_message_p = 0;
5496 struct auto_save_unwind auto_save_unwind;
5497 struct gcpro gcpro1, gcpro2;
5499 if (max_specpdl_size < specpdl_size + 40)
5500 max_specpdl_size = specpdl_size + 40;
5502 if (minibuf_level)
5503 no_message = Qt;
5505 if (NILP (no_message))
5507 old_message_p = push_message ();
5508 record_unwind_protect_void (pop_message_unwind);
5511 /* Ordinarily don't quit within this function,
5512 but don't make it impossible to quit (in case we get hung in I/O). */
5513 oquit = Vquit_flag;
5514 Vquit_flag = Qnil;
5516 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5517 point to non-strings reached from Vbuffer_alist. */
5519 hook = intern ("auto-save-hook");
5520 safe_run_hooks (hook);
5522 if (STRINGP (Vauto_save_list_file_name))
5524 Lisp_Object listfile;
5526 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5528 /* Don't try to create the directory when shutting down Emacs,
5529 because creating the directory might signal an error, and
5530 that would leave Emacs in a strange state. */
5531 if (!NILP (Vrun_hooks))
5533 Lisp_Object dir;
5534 dir = Qnil;
5535 GCPRO2 (dir, listfile);
5536 dir = Ffile_name_directory (listfile);
5537 if (NILP (Ffile_directory_p (dir)))
5538 internal_condition_case_1 (do_auto_save_make_dir,
5539 dir, Qt,
5540 do_auto_save_eh);
5541 UNGCPRO;
5544 stream = emacs_fopen (SSDATA (listfile), "w");
5547 auto_save_unwind.stream = stream;
5548 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5549 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5550 minibuffer_auto_raise = 0;
5551 auto_saving = 1;
5552 auto_save_error_occurred = 0;
5554 /* On first pass, save all files that don't have handlers.
5555 On second pass, save all files that do have handlers.
5557 If Emacs is crashing, the handlers may tweak what is causing
5558 Emacs to crash in the first place, and it would be a shame if
5559 Emacs failed to autosave perfectly ordinary files because it
5560 couldn't handle some ange-ftp'd file. */
5562 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5563 FOR_EACH_LIVE_BUFFER (tail, buf)
5565 b = XBUFFER (buf);
5567 /* Record all the buffers that have auto save mode
5568 in the special file that lists them. For each of these buffers,
5569 Record visited name (if any) and auto save name. */
5570 if (STRINGP (BVAR (b, auto_save_file_name))
5571 && stream != NULL && do_handled_files == 0)
5573 block_input ();
5574 if (!NILP (BVAR (b, filename)))
5576 fwrite (SDATA (BVAR (b, filename)), 1,
5577 SBYTES (BVAR (b, filename)), stream);
5579 putc ('\n', stream);
5580 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5581 SBYTES (BVAR (b, auto_save_file_name)), stream);
5582 putc ('\n', stream);
5583 unblock_input ();
5586 if (!NILP (current_only)
5587 && b != current_buffer)
5588 continue;
5590 /* Don't auto-save indirect buffers.
5591 The base buffer takes care of it. */
5592 if (b->base_buffer)
5593 continue;
5595 /* Check for auto save enabled
5596 and file changed since last auto save
5597 and file changed since last real save. */
5598 if (STRINGP (BVAR (b, auto_save_file_name))
5599 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5600 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5601 /* -1 means we've turned off autosaving for a while--see below. */
5602 && XINT (BVAR (b, save_length)) >= 0
5603 && (do_handled_files
5604 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5605 Qwrite_region))))
5607 struct timespec before_time = current_timespec ();
5608 struct timespec after_time;
5610 /* If we had a failure, don't try again for 20 minutes. */
5611 if (b->auto_save_failure_time > 0
5612 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5613 continue;
5615 set_buffer_internal (b);
5616 if (NILP (Vauto_save_include_big_deletions)
5617 && (XFASTINT (BVAR (b, save_length)) * 10
5618 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5619 /* A short file is likely to change a large fraction;
5620 spare the user annoying messages. */
5621 && XFASTINT (BVAR (b, save_length)) > 5000
5622 /* These messages are frequent and annoying for `*mail*'. */
5623 && !EQ (BVAR (b, filename), Qnil)
5624 && NILP (no_message))
5626 /* It has shrunk too much; turn off auto-saving here. */
5627 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5628 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5629 BVAR (b, name), 1);
5630 minibuffer_auto_raise = 0;
5631 /* Turn off auto-saving until there's a real save,
5632 and prevent any more warnings. */
5633 XSETINT (BVAR (b, save_length), -1);
5634 Fsleep_for (make_number (1), Qnil);
5635 continue;
5637 if (!auto_saved && NILP (no_message))
5638 message1 ("Auto-saving...");
5639 internal_condition_case (auto_save_1, Qt, auto_save_error);
5640 auto_saved = 1;
5641 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5642 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5643 set_buffer_internal (old);
5645 after_time = current_timespec ();
5647 /* If auto-save took more than 60 seconds,
5648 assume it was an NFS failure that got a timeout. */
5649 if (after_time.tv_sec - before_time.tv_sec > 60)
5650 b->auto_save_failure_time = after_time.tv_sec;
5654 /* Prevent another auto save till enough input events come in. */
5655 record_auto_save ();
5657 if (auto_saved && NILP (no_message))
5659 if (old_message_p)
5661 /* If we are going to restore an old message,
5662 give time to read ours. */
5663 sit_for (make_number (1), 0, 0);
5664 restore_message ();
5666 else if (!auto_save_error_occurred)
5667 /* Don't overwrite the error message if an error occurred.
5668 If we displayed a message and then restored a state
5669 with no message, leave a "done" message on the screen. */
5670 message1 ("Auto-saving...done");
5673 Vquit_flag = oquit;
5675 /* This restores the message-stack status. */
5676 unbind_to (count, Qnil);
5677 return Qnil;
5680 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5681 Sset_buffer_auto_saved, 0, 0, 0,
5682 doc: /* Mark current buffer as auto-saved with its current text.
5683 No auto-save file will be written until the buffer changes again. */)
5684 (void)
5686 /* FIXME: This should not be called in indirect buffers, since
5687 they're not autosaved. */
5688 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5689 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5690 current_buffer->auto_save_failure_time = 0;
5691 return Qnil;
5694 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5695 Sclear_buffer_auto_save_failure, 0, 0, 0,
5696 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5697 (void)
5699 current_buffer->auto_save_failure_time = 0;
5700 return Qnil;
5703 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5704 0, 0, 0,
5705 doc: /* Return t if current buffer has been auto-saved recently.
5706 More precisely, if it has been auto-saved since last read from or saved
5707 in the visited file. If the buffer has no visited file,
5708 then any auto-save counts as "recent". */)
5709 (void)
5711 /* FIXME: maybe we should return nil for indirect buffers since
5712 they're never autosaved. */
5713 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5716 /* Reading and completing file names. */
5718 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5719 Snext_read_file_uses_dialog_p, 0, 0, 0,
5720 doc: /* Return t if a call to `read-file-name' will use a dialog.
5721 The return value is only relevant for a call to `read-file-name' that happens
5722 before any other event (mouse or keypress) is handled. */)
5723 (void)
5725 #if (defined USE_GTK || defined USE_MOTIF \
5726 || defined HAVE_NS || defined HAVE_NTGUI)
5727 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5728 && use_dialog_box
5729 && use_file_dialog
5730 && window_system_available (SELECTED_FRAME ()))
5731 return Qt;
5732 #endif
5733 return Qnil;
5737 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5738 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5739 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5740 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5741 it to text mode.
5743 As a side effect, this function flushes any pending STREAM's data.
5745 Value is the previous value of STREAM's I/O mode, nil for text mode,
5746 non-nil for binary mode.
5748 On MS-Windows and MS-DOS, binary mode is needed to read or write
5749 arbitrary binary data, and for disabling translation between CR-LF
5750 pairs and a single newline character. Examples include generation
5751 of text files with Unix-style end-of-line format using `princ' in
5752 batch mode, with standard output redirected to a file.
5754 On Posix systems, this function always returns non-nil, and has no
5755 effect except for flushing STREAM's data. */)
5756 (Lisp_Object stream, Lisp_Object mode)
5758 FILE *fp = NULL;
5759 int binmode;
5761 CHECK_SYMBOL (stream);
5762 if (EQ (stream, Qstdin))
5763 fp = stdin;
5764 else if (EQ (stream, Qstdout))
5765 fp = stdout;
5766 else if (EQ (stream, Qstderr))
5767 fp = stderr;
5768 else
5769 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5771 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5772 if (fp != stdin)
5773 fflush (fp);
5775 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5778 void
5779 init_fileio (void)
5781 realmask = umask (0);
5782 umask (realmask);
5784 valid_timestamp_file_system = 0;
5786 /* fsync can be a significant performance hit. Often it doesn't
5787 suffice to make the file-save operation survive a crash. For
5788 batch scripts, which are typically part of larger shell commands
5789 that don't fsync other files, its effect on performance can be
5790 significant so its utility is particularly questionable.
5791 Hence, for now by default fsync is used only when interactive.
5793 For more on why fsync often fails to work on today's hardware, see:
5794 Zheng M et al. Understanding the robustness of SSDs under power fault.
5795 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5796 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5798 For more on why fsync does not suffice even if it works properly, see:
5799 Roche X. Necessary step(s) to synchronize filename operations on disk.
5800 Austin Group Defect 672, 2013-03-19
5801 http://austingroupbugs.net/view.php?id=672 */
5802 write_region_inhibit_fsync = noninteractive;
5805 void
5806 syms_of_fileio (void)
5808 /* Property name of a file name handler,
5809 which gives a list of operations it handles. */
5810 DEFSYM (Qoperations, "operations");
5812 DEFSYM (Qexpand_file_name, "expand-file-name");
5813 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5814 DEFSYM (Qdirectory_file_name, "directory-file-name");
5815 DEFSYM (Qfile_name_directory, "file-name-directory");
5816 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5817 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5818 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5819 DEFSYM (Qcopy_file, "copy-file");
5820 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5821 DEFSYM (Qmake_directory, "make-directory");
5822 DEFSYM (Qdelete_file, "delete-file");
5823 DEFSYM (Qrename_file, "rename-file");
5824 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5825 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5826 DEFSYM (Qfile_exists_p, "file-exists-p");
5827 DEFSYM (Qfile_executable_p, "file-executable-p");
5828 DEFSYM (Qfile_readable_p, "file-readable-p");
5829 DEFSYM (Qfile_writable_p, "file-writable-p");
5830 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5831 DEFSYM (Qaccess_file, "access-file");
5832 DEFSYM (Qfile_directory_p, "file-directory-p");
5833 DEFSYM (Qfile_regular_p, "file-regular-p");
5834 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5835 DEFSYM (Qfile_modes, "file-modes");
5836 DEFSYM (Qset_file_modes, "set-file-modes");
5837 DEFSYM (Qset_file_times, "set-file-times");
5838 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5839 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5840 DEFSYM (Qfile_acl, "file-acl");
5841 DEFSYM (Qset_file_acl, "set-file-acl");
5842 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5843 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5844 DEFSYM (Qwrite_region, "write-region");
5845 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5846 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5848 /* The symbol bound to coding-system-for-read when
5849 insert-file-contents is called for recovering a file. This is not
5850 an actual coding system name, but just an indicator to tell
5851 insert-file-contents to use `emacs-mule' with a special flag for
5852 auto saving and recovering a file. */
5853 DEFSYM (Qauto_save_coding, "auto-save-coding");
5855 DEFSYM (Qfile_name_history, "file-name-history");
5856 Fset (Qfile_name_history, Qnil);
5858 DEFSYM (Qfile_error, "file-error");
5859 DEFSYM (Qfile_already_exists, "file-already-exists");
5860 DEFSYM (Qfile_date_error, "file-date-error");
5861 DEFSYM (Qfile_notify_error, "file-notify-error");
5862 DEFSYM (Qexcl, "excl");
5864 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5865 doc: /* Coding system for encoding file names.
5866 If it is nil, `default-file-name-coding-system' (which see) is used.
5868 On MS-Windows, the value of this variable is largely ignored if
5869 \`w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5870 behaves as if file names were encoded in `utf-8'. */);
5871 Vfile_name_coding_system = Qnil;
5873 DEFVAR_LISP ("default-file-name-coding-system",
5874 Vdefault_file_name_coding_system,
5875 doc: /* Default coding system for encoding file names.
5876 This variable is used only when `file-name-coding-system' is nil.
5878 This variable is set/changed by the command `set-language-environment'.
5879 User should not set this variable manually,
5880 instead use `file-name-coding-system' to get a constant encoding
5881 of file names regardless of the current language environment.
5883 On MS-Windows, the value of this variable is largely ignored if
5884 \`w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5885 behaves as if file names were encoded in `utf-8'. */);
5886 Vdefault_file_name_coding_system = Qnil;
5888 /* Lisp functions for translating file formats. */
5889 DEFSYM (Qformat_decode, "format-decode");
5890 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5892 /* Lisp function for setting buffer-file-coding-system and the
5893 multibyteness of the current buffer after inserting a file. */
5894 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5896 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5898 Fput (Qfile_error, Qerror_conditions,
5899 Fpurecopy (list2 (Qfile_error, Qerror)));
5900 Fput (Qfile_error, Qerror_message,
5901 build_pure_c_string ("File error"));
5903 Fput (Qfile_already_exists, Qerror_conditions,
5904 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5905 Fput (Qfile_already_exists, Qerror_message,
5906 build_pure_c_string ("File already exists"));
5908 Fput (Qfile_date_error, Qerror_conditions,
5909 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5910 Fput (Qfile_date_error, Qerror_message,
5911 build_pure_c_string ("Cannot set file date"));
5913 Fput (Qfile_notify_error, Qerror_conditions,
5914 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5915 Fput (Qfile_notify_error, Qerror_message,
5916 build_pure_c_string ("File notification error"));
5918 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5919 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5920 If a file name matches REGEXP, all I/O on that file is done by calling
5921 HANDLER. If a file name matches more than one handler, the handler
5922 whose match starts last in the file name gets precedence. The
5923 function `find-file-name-handler' checks this list for a handler for
5924 its argument.
5926 HANDLER should be a function. The first argument given to it is the
5927 name of the I/O primitive to be handled; the remaining arguments are
5928 the arguments that were passed to that primitive. For example, if you
5929 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5930 HANDLER is called like this:
5932 (funcall HANDLER 'file-exists-p FILENAME)
5934 Note that HANDLER must be able to handle all I/O primitives; if it has
5935 nothing special to do for a primitive, it should reinvoke the
5936 primitive to handle the operation \"the usual way\".
5937 See Info node `(elisp)Magic File Names' for more details. */);
5938 Vfile_name_handler_alist = Qnil;
5940 DEFVAR_LISP ("set-auto-coding-function",
5941 Vset_auto_coding_function,
5942 doc: /* If non-nil, a function to call to decide a coding system of file.
5943 Two arguments are passed to this function: the file name
5944 and the length of a file contents following the point.
5945 This function should return a coding system to decode the file contents.
5946 It should check the file name against `auto-coding-alist'.
5947 If no coding system is decided, it should check a coding system
5948 specified in the heading lines with the format:
5949 -*- ... coding: CODING-SYSTEM; ... -*-
5950 or local variable spec of the tailing lines with `coding:' tag. */);
5951 Vset_auto_coding_function = Qnil;
5953 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5954 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5955 Each is passed one argument, the number of characters inserted,
5956 with point at the start of the inserted text. Each function
5957 should leave point the same, and return the new character count.
5958 If `insert-file-contents' is intercepted by a handler from
5959 `file-name-handler-alist', that handler is responsible for calling the
5960 functions in `after-insert-file-functions' if appropriate. */);
5961 Vafter_insert_file_functions = Qnil;
5963 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5964 doc: /* A list of functions to be called at the start of `write-region'.
5965 Each is passed two arguments, START and END as for `write-region'.
5966 These are usually two numbers but not always; see the documentation
5967 for `write-region'. The function should return a list of pairs
5968 of the form (POSITION . STRING), consisting of strings to be effectively
5969 inserted at the specified positions of the file being written (1 means to
5970 insert before the first byte written). The POSITIONs must be sorted into
5971 increasing order.
5973 If there are several annotation functions, the lists returned by these
5974 functions are merged destructively. As each annotation function runs,
5975 the variable `write-region-annotations-so-far' contains a list of all
5976 annotations returned by previous annotation functions.
5978 An annotation function can return with a different buffer current.
5979 Doing so removes the annotations returned by previous functions, and
5980 resets START and END to `point-min' and `point-max' of the new buffer.
5982 After `write-region' completes, Emacs calls the function stored in
5983 `write-region-post-annotation-function', once for each buffer that was
5984 current when building the annotations (i.e., at least once), with that
5985 buffer current. */);
5986 Vwrite_region_annotate_functions = Qnil;
5987 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5989 DEFVAR_LISP ("write-region-post-annotation-function",
5990 Vwrite_region_post_annotation_function,
5991 doc: /* Function to call after `write-region' completes.
5992 The function is called with no arguments. If one or more of the
5993 annotation functions in `write-region-annotate-functions' changed the
5994 current buffer, the function stored in this variable is called for
5995 each of those additional buffers as well, in addition to the original
5996 buffer. The relevant buffer is current during each function call. */);
5997 Vwrite_region_post_annotation_function = Qnil;
5998 staticpro (&Vwrite_region_annotation_buffers);
6000 DEFVAR_LISP ("write-region-annotations-so-far",
6001 Vwrite_region_annotations_so_far,
6002 doc: /* When an annotation function is called, this holds the previous annotations.
6003 These are the annotations made by other annotation functions
6004 that were already called. See also `write-region-annotate-functions'. */);
6005 Vwrite_region_annotations_so_far = Qnil;
6007 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6008 doc: /* A list of file name handlers that temporarily should not be used.
6009 This applies only to the operation `inhibit-file-name-operation'. */);
6010 Vinhibit_file_name_handlers = Qnil;
6012 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6013 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6014 Vinhibit_file_name_operation = Qnil;
6016 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6017 doc: /* File name in which we write a list of all auto save file names.
6018 This variable is initialized automatically from `auto-save-list-file-prefix'
6019 shortly after Emacs reads your init file, if you have not yet given it
6020 a non-nil value. */);
6021 Vauto_save_list_file_name = Qnil;
6023 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6024 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6025 Normally auto-save files are written under other names. */);
6026 Vauto_save_visited_file_name = Qnil;
6028 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6029 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6030 If nil, deleting a substantial portion of the text disables auto-save
6031 in the buffer; this is the default behavior, because the auto-save
6032 file is usually more useful if it contains the deleted text. */);
6033 Vauto_save_include_big_deletions = Qnil;
6035 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6036 doc: /* Non-nil means don't call fsync in `write-region'.
6037 This variable affects calls to `write-region' as well as save commands.
6038 Setting this to nil may avoid data loss if the system loses power or
6039 the operating system crashes. By default, it is non-nil in batch mode. */);
6040 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6042 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6043 doc: /* Specifies whether to use the system's trash can.
6044 When non-nil, certain file deletion commands use the function
6045 `move-file-to-trash' instead of deleting files outright.
6046 This includes interactive calls to `delete-file' and
6047 `delete-directory' and the Dired deletion commands. */);
6048 delete_by_moving_to_trash = 0;
6049 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6051 /* Lisp function for moving files to trash. */
6052 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6054 /* Lisp function for recursively copying directories. */
6055 DEFSYM (Qcopy_directory, "copy-directory");
6057 /* Lisp function for recursively deleting directories. */
6058 DEFSYM (Qdelete_directory, "delete-directory");
6060 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6061 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6063 DEFSYM (Qstdin, "stdin");
6064 DEFSYM (Qstdout, "stdout");
6065 DEFSYM (Qstderr, "stderr");
6067 defsubr (&Sfind_file_name_handler);
6068 defsubr (&Sfile_name_directory);
6069 defsubr (&Sfile_name_nondirectory);
6070 defsubr (&Sunhandled_file_name_directory);
6071 defsubr (&Sfile_name_as_directory);
6072 defsubr (&Sdirectory_file_name);
6073 defsubr (&Smake_temp_name);
6074 defsubr (&Sexpand_file_name);
6075 defsubr (&Ssubstitute_in_file_name);
6076 defsubr (&Scopy_file);
6077 defsubr (&Smake_directory_internal);
6078 defsubr (&Sdelete_directory_internal);
6079 defsubr (&Sdelete_file);
6080 defsubr (&Srename_file);
6081 defsubr (&Sadd_name_to_file);
6082 defsubr (&Smake_symbolic_link);
6083 defsubr (&Sfile_name_absolute_p);
6084 defsubr (&Sfile_exists_p);
6085 defsubr (&Sfile_executable_p);
6086 defsubr (&Sfile_readable_p);
6087 defsubr (&Sfile_writable_p);
6088 defsubr (&Saccess_file);
6089 defsubr (&Sfile_symlink_p);
6090 defsubr (&Sfile_directory_p);
6091 defsubr (&Sfile_accessible_directory_p);
6092 defsubr (&Sfile_regular_p);
6093 defsubr (&Sfile_modes);
6094 defsubr (&Sset_file_modes);
6095 defsubr (&Sset_file_times);
6096 defsubr (&Sfile_selinux_context);
6097 defsubr (&Sfile_acl);
6098 defsubr (&Sset_file_acl);
6099 defsubr (&Sset_file_selinux_context);
6100 defsubr (&Sset_default_file_modes);
6101 defsubr (&Sdefault_file_modes);
6102 defsubr (&Sfile_newer_than_file_p);
6103 defsubr (&Sinsert_file_contents);
6104 defsubr (&Swrite_region);
6105 defsubr (&Scar_less_than_car);
6106 defsubr (&Sverify_visited_file_modtime);
6107 defsubr (&Svisited_file_modtime);
6108 defsubr (&Sset_visited_file_modtime);
6109 defsubr (&Sdo_auto_save);
6110 defsubr (&Sset_buffer_auto_saved);
6111 defsubr (&Sclear_buffer_auto_save_failure);
6112 defsubr (&Srecent_auto_save_p);
6114 defsubr (&Snext_read_file_uses_dialog_p);
6116 defsubr (&Sset_binary_mode);
6118 #ifdef HAVE_SYNC
6119 defsubr (&Sunix_sync);
6120 #endif