* Makefile.in: Fixes for recent change-history changes.
[emacs.git] / src / fileio.c
blob796f08d3c58526c298ae6b700564cf072667ccf9
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 tem = format2 ("File %s already exists; %s anyway? ",
1815 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 int n;
1875 char buf[16 * 1024];
1876 struct stat st;
1877 #endif
1879 encoded_file = encoded_newname = Qnil;
1880 GCPRO4 (file, newname, encoded_file, encoded_newname);
1881 CHECK_STRING (file);
1882 CHECK_STRING (newname);
1884 if (!NILP (Ffile_directory_p (newname)))
1885 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1886 else
1887 newname = Fexpand_file_name (newname, Qnil);
1889 file = Fexpand_file_name (file, Qnil);
1891 /* If the input file name has special constructs in it,
1892 call the corresponding file handler. */
1893 handler = Ffind_file_name_handler (file, Qcopy_file);
1894 /* Likewise for output file name. */
1895 if (NILP (handler))
1896 handler = Ffind_file_name_handler (newname, Qcopy_file);
1897 if (!NILP (handler))
1898 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1899 ok_if_already_exists, keep_time, preserve_uid_gid,
1900 preserve_permissions));
1902 encoded_file = ENCODE_FILE (file);
1903 encoded_newname = ENCODE_FILE (newname);
1905 #ifdef WINDOWSNT
1906 if (NILP (ok_if_already_exists)
1907 || INTEGERP (ok_if_already_exists))
1908 barf_or_query_if_file_exists (newname, false, "copy to it",
1909 INTEGERP (ok_if_already_exists), false);
1911 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1912 !NILP (keep_time), !NILP (preserve_uid_gid),
1913 !NILP (preserve_permissions));
1914 switch (result)
1916 case -1:
1917 report_file_error ("Copying file", list2 (file, newname));
1918 case -2:
1919 report_file_error ("Copying permissions from", file);
1920 case -3:
1921 xsignal2 (Qfile_date_error,
1922 build_string ("Resetting file times"), newname);
1923 case -4:
1924 report_file_error ("Copying permissions to", newname);
1926 #else /* not WINDOWSNT */
1927 immediate_quit = 1;
1928 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1929 immediate_quit = 0;
1931 if (ifd < 0)
1932 report_file_error ("Opening input file", file);
1934 record_unwind_protect_int (close_file_unwind, ifd);
1936 if (fstat (ifd, &st) != 0)
1937 report_file_error ("Input file status", file);
1939 if (!NILP (preserve_permissions))
1941 #if HAVE_LIBSELINUX
1942 if (is_selinux_enabled ())
1944 conlength = fgetfilecon (ifd, &con);
1945 if (conlength == -1)
1946 report_file_error ("Doing fgetfilecon", file);
1948 #endif
1951 /* We can copy only regular files. */
1952 if (!S_ISREG (st.st_mode))
1953 report_file_errno ("Non-regular file", file,
1954 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1956 #ifndef MSDOS
1957 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1958 #else
1959 new_mask = S_IREAD | S_IWRITE;
1960 #endif
1962 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1963 new_mask);
1964 if (ofd < 0 && errno == EEXIST)
1966 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1967 barf_or_query_if_file_exists (newname, true, "copy to it",
1968 INTEGERP (ok_if_already_exists), false);
1969 already_exists = true;
1970 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1972 if (ofd < 0)
1973 report_file_error ("Opening output file", newname);
1975 record_unwind_protect_int (close_file_unwind, ofd);
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 (ftruncate (ofd, 0) != 0)
1986 report_file_error ("Truncating output file", newname);
1989 immediate_quit = 1;
1990 QUIT;
1991 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
1992 if (emacs_write_sig (ofd, buf, n) != n)
1993 report_file_error ("Write error", newname);
1994 immediate_quit = 0;
1996 #ifndef MSDOS
1997 /* Preserve the original file permissions, and if requested, also its
1998 owner and group. */
2000 mode_t preserved_permissions = st.st_mode & 07777;
2001 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2002 if (!NILP (preserve_uid_gid))
2004 /* Attempt to change owner and group. If that doesn't work
2005 attempt to change just the group, as that is sometimes allowed.
2006 Adjust the mode mask to eliminate setuid or setgid bits
2007 or group permissions bits that are inappropriate if the
2008 owner or group are wrong. */
2009 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2011 if (fchown (ofd, -1, st.st_gid) == 0)
2012 preserved_permissions &= ~04000;
2013 else
2015 preserved_permissions &= ~06000;
2017 /* Copy the other bits to the group bits, since the
2018 group is wrong. */
2019 preserved_permissions &= ~070;
2020 preserved_permissions |= (preserved_permissions & 7) << 3;
2021 default_permissions &= ~070;
2022 default_permissions |= (default_permissions & 7) << 3;
2027 switch (!NILP (preserve_permissions)
2028 ? qcopy_acl (SSDATA (encoded_file), ifd,
2029 SSDATA (encoded_newname), ofd,
2030 preserved_permissions)
2031 : (already_exists
2032 || (new_mask & ~realmask) == default_permissions)
2034 : fchmod (ofd, default_permissions))
2036 case -2: report_file_error ("Copying permissions from", file);
2037 case -1: report_file_error ("Copying permissions to", newname);
2040 #endif /* not MSDOS */
2042 #if HAVE_LIBSELINUX
2043 if (conlength > 0)
2045 /* Set the modified context back to the file. */
2046 bool fail = fsetfilecon (ofd, con) != 0;
2047 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2048 if (fail && errno != ENOTSUP)
2049 report_file_error ("Doing fsetfilecon", newname);
2051 freecon (con);
2053 #endif
2055 if (!NILP (keep_time))
2057 struct timespec atime = get_stat_atime (&st);
2058 struct timespec mtime = get_stat_mtime (&st);
2059 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2060 xsignal2 (Qfile_date_error,
2061 build_string ("Cannot set file date"), newname);
2064 if (emacs_close (ofd) < 0)
2065 report_file_error ("Write error", newname);
2067 emacs_close (ifd);
2069 #ifdef MSDOS
2070 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2071 and if it can't, it tells so. Otherwise, under MSDOS we usually
2072 get only the READ bit, which will make the copied file read-only,
2073 so it's better not to chmod at all. */
2074 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2075 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2076 #endif /* MSDOS */
2077 #endif /* not WINDOWSNT */
2079 /* Discard the unwind protects. */
2080 specpdl_ptr = specpdl + count;
2082 UNGCPRO;
2083 return Qnil;
2086 DEFUN ("make-directory-internal", Fmake_directory_internal,
2087 Smake_directory_internal, 1, 1, 0,
2088 doc: /* Create a new directory named DIRECTORY. */)
2089 (Lisp_Object directory)
2091 const char *dir;
2092 Lisp_Object handler;
2093 Lisp_Object encoded_dir;
2095 CHECK_STRING (directory);
2096 directory = Fexpand_file_name (directory, Qnil);
2098 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2099 if (!NILP (handler))
2100 return call2 (handler, Qmake_directory_internal, directory);
2102 encoded_dir = ENCODE_FILE (directory);
2104 dir = SSDATA (encoded_dir);
2106 #ifdef WINDOWSNT
2107 if (mkdir (dir) != 0)
2108 #else
2109 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2110 #endif
2111 report_file_error ("Creating directory", directory);
2113 return Qnil;
2116 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2117 Sdelete_directory_internal, 1, 1, 0,
2118 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2119 (Lisp_Object directory)
2121 const char *dir;
2122 Lisp_Object encoded_dir;
2124 CHECK_STRING (directory);
2125 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2126 encoded_dir = ENCODE_FILE (directory);
2127 dir = SSDATA (encoded_dir);
2129 if (rmdir (dir) != 0)
2130 report_file_error ("Removing directory", directory);
2132 return Qnil;
2135 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2136 "(list (read-file-name \
2137 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2138 \"Move file to trash: \" \"Delete file: \") \
2139 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2140 (null current-prefix-arg))",
2141 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2142 If file has multiple names, it continues to exist with the other names.
2143 TRASH non-nil means to trash the file instead of deleting, provided
2144 `delete-by-moving-to-trash' is non-nil.
2146 When called interactively, TRASH is t if no prefix argument is given.
2147 With a prefix argument, TRASH is nil. */)
2148 (Lisp_Object filename, Lisp_Object trash)
2150 Lisp_Object handler;
2151 Lisp_Object encoded_file;
2152 struct gcpro gcpro1;
2154 GCPRO1 (filename);
2155 if (!NILP (Ffile_directory_p (filename))
2156 && NILP (Ffile_symlink_p (filename)))
2157 xsignal2 (Qfile_error,
2158 build_string ("Removing old name: is a directory"),
2159 filename);
2160 UNGCPRO;
2161 filename = Fexpand_file_name (filename, Qnil);
2163 handler = Ffind_file_name_handler (filename, Qdelete_file);
2164 if (!NILP (handler))
2165 return call3 (handler, Qdelete_file, filename, trash);
2167 if (delete_by_moving_to_trash && !NILP (trash))
2168 return call1 (Qmove_file_to_trash, filename);
2170 encoded_file = ENCODE_FILE (filename);
2172 if (unlink (SSDATA (encoded_file)) < 0)
2173 report_file_error ("Removing old name", filename);
2174 return Qnil;
2177 static Lisp_Object
2178 internal_delete_file_1 (Lisp_Object ignore)
2180 return Qt;
2183 /* Delete file FILENAME, returning true if successful.
2184 This ignores `delete-by-moving-to-trash'. */
2186 bool
2187 internal_delete_file (Lisp_Object filename)
2189 Lisp_Object tem;
2191 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2192 Qt, internal_delete_file_1);
2193 return NILP (tem);
2196 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2197 "fRename file: \nGRename %s to file: \np",
2198 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2199 If file has names other than FILE, it continues to have those names.
2200 Signals a `file-already-exists' error if a file NEWNAME already exists
2201 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2202 A number as third arg means request confirmation if NEWNAME already exists.
2203 This is what happens in interactive use with M-x. */)
2204 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2206 Lisp_Object handler;
2207 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2208 Lisp_Object encoded_file, encoded_newname, symlink_target;
2210 symlink_target = encoded_file = encoded_newname = Qnil;
2211 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2212 CHECK_STRING (file);
2213 CHECK_STRING (newname);
2214 file = Fexpand_file_name (file, Qnil);
2216 if ((!NILP (Ffile_directory_p (newname)))
2217 #ifdef DOS_NT
2218 /* If the file names are identical but for the case,
2219 don't attempt to move directory to itself. */
2220 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2221 #endif
2224 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2225 ? file : Fdirectory_file_name (file));
2226 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2228 else
2229 newname = Fexpand_file_name (newname, Qnil);
2231 /* If the file name has special constructs in it,
2232 call the corresponding file handler. */
2233 handler = Ffind_file_name_handler (file, Qrename_file);
2234 if (NILP (handler))
2235 handler = Ffind_file_name_handler (newname, Qrename_file);
2236 if (!NILP (handler))
2237 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2238 file, newname, ok_if_already_exists));
2240 encoded_file = ENCODE_FILE (file);
2241 encoded_newname = ENCODE_FILE (newname);
2243 #ifdef DOS_NT
2244 /* If the file names are identical but for the case, don't ask for
2245 confirmation: they simply want to change the letter-case of the
2246 file name. */
2247 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2248 #endif
2249 if (NILP (ok_if_already_exists)
2250 || INTEGERP (ok_if_already_exists))
2251 barf_or_query_if_file_exists (newname, false, "rename to it",
2252 INTEGERP (ok_if_already_exists), false);
2253 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2255 int rename_errno = errno;
2256 if (rename_errno == EXDEV)
2258 ptrdiff_t count;
2259 symlink_target = Ffile_symlink_p (file);
2260 if (! NILP (symlink_target))
2261 Fmake_symbolic_link (symlink_target, newname,
2262 NILP (ok_if_already_exists) ? Qnil : Qt);
2263 else if (!NILP (Ffile_directory_p (file)))
2264 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2265 else
2266 /* We have already prompted if it was an integer, so don't
2267 have copy-file prompt again. */
2268 Fcopy_file (file, newname,
2269 NILP (ok_if_already_exists) ? Qnil : Qt,
2270 Qt, Qt, Qt);
2272 count = SPECPDL_INDEX ();
2273 specbind (Qdelete_by_moving_to_trash, Qnil);
2275 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2276 call2 (Qdelete_directory, file, Qt);
2277 else
2278 Fdelete_file (file, Qnil);
2279 unbind_to (count, Qnil);
2281 else
2282 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2284 UNGCPRO;
2285 return Qnil;
2288 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2289 "fAdd name to file: \nGName to add to %s: \np",
2290 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2291 Signals a `file-already-exists' error if a file NEWNAME already exists
2292 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2293 A number as third arg means request confirmation if NEWNAME already exists.
2294 This is what happens in interactive use with M-x. */)
2295 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2297 Lisp_Object handler;
2298 Lisp_Object encoded_file, encoded_newname;
2299 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2301 GCPRO4 (file, newname, encoded_file, encoded_newname);
2302 encoded_file = encoded_newname = Qnil;
2303 CHECK_STRING (file);
2304 CHECK_STRING (newname);
2305 file = Fexpand_file_name (file, Qnil);
2307 if (!NILP (Ffile_directory_p (newname)))
2308 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2309 else
2310 newname = Fexpand_file_name (newname, Qnil);
2312 /* If the file name has special constructs in it,
2313 call the corresponding file handler. */
2314 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2315 if (!NILP (handler))
2316 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2317 newname, ok_if_already_exists));
2319 /* If the new name has special constructs in it,
2320 call the corresponding file handler. */
2321 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2322 if (!NILP (handler))
2323 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2324 newname, ok_if_already_exists));
2326 encoded_file = ENCODE_FILE (file);
2327 encoded_newname = ENCODE_FILE (newname);
2329 if (NILP (ok_if_already_exists)
2330 || INTEGERP (ok_if_already_exists))
2331 barf_or_query_if_file_exists (newname, false, "make it a new name",
2332 INTEGERP (ok_if_already_exists), false);
2334 unlink (SSDATA (newname));
2335 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2337 int link_errno = errno;
2338 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2341 UNGCPRO;
2342 return Qnil;
2345 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2346 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2347 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2348 Both args must be strings.
2349 Signals a `file-already-exists' error if a file LINKNAME already exists
2350 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2351 A number as third arg means request confirmation if LINKNAME already exists.
2352 This happens for interactive use with M-x. */)
2353 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2355 Lisp_Object handler;
2356 Lisp_Object encoded_target, encoded_linkname;
2357 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2359 GCPRO4 (target, linkname, encoded_target, encoded_linkname);
2360 encoded_target = encoded_linkname = Qnil;
2361 CHECK_STRING (target);
2362 CHECK_STRING (linkname);
2363 /* If the link target has a ~, we must expand it to get
2364 a truly valid file name. Otherwise, do not expand;
2365 we want to permit links to relative file names. */
2366 if (SREF (target, 0) == '~')
2367 target = Fexpand_file_name (target, Qnil);
2369 if (!NILP (Ffile_directory_p (linkname)))
2370 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2371 else
2372 linkname = Fexpand_file_name (linkname, Qnil);
2374 /* If the file name has special constructs in it,
2375 call the corresponding file handler. */
2376 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2377 if (!NILP (handler))
2378 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, target,
2379 linkname, ok_if_already_exists));
2381 /* If the new link name has special constructs in it,
2382 call the corresponding file handler. */
2383 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2384 if (!NILP (handler))
2385 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, target,
2386 linkname, ok_if_already_exists));
2388 encoded_target = ENCODE_FILE (target);
2389 encoded_linkname = ENCODE_FILE (linkname);
2391 if (NILP (ok_if_already_exists)
2392 || INTEGERP (ok_if_already_exists))
2393 barf_or_query_if_file_exists (linkname, false, "make it a link",
2394 INTEGERP (ok_if_already_exists), false);
2395 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2397 /* If we didn't complain already, silently delete existing file. */
2398 int symlink_errno;
2399 if (errno == EEXIST)
2401 unlink (SSDATA (encoded_linkname));
2402 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2403 >= 0)
2405 UNGCPRO;
2406 return Qnil;
2409 if (errno == ENOSYS)
2411 UNGCPRO;
2412 xsignal1 (Qfile_error,
2413 build_string ("Symbolic links are not supported"));
2416 symlink_errno = errno;
2417 report_file_errno ("Making symbolic link", list2 (target, linkname),
2418 symlink_errno);
2420 UNGCPRO;
2421 return Qnil;
2425 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2426 1, 1, 0,
2427 doc: /* Return t if file FILENAME specifies an absolute file name.
2428 On Unix, this is a name starting with a `/' or a `~'. */)
2429 (Lisp_Object filename)
2431 CHECK_STRING (filename);
2432 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2435 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2436 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2437 See also `file-readable-p' and `file-attributes'.
2438 This returns nil for a symlink to a nonexistent file.
2439 Use `file-symlink-p' to test for such links. */)
2440 (Lisp_Object filename)
2442 Lisp_Object absname;
2443 Lisp_Object handler;
2445 CHECK_STRING (filename);
2446 absname = Fexpand_file_name (filename, Qnil);
2448 /* If the file name has special constructs in it,
2449 call the corresponding file handler. */
2450 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2451 if (!NILP (handler))
2453 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2454 errno = 0;
2455 return result;
2458 absname = ENCODE_FILE (absname);
2460 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2463 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2464 doc: /* Return t if FILENAME can be executed by you.
2465 For a directory, this means you can access files in that directory.
2466 \(It is generally better to use `file-accessible-directory-p' for that
2467 purpose, though.) */)
2468 (Lisp_Object filename)
2470 Lisp_Object absname;
2471 Lisp_Object handler;
2473 CHECK_STRING (filename);
2474 absname = Fexpand_file_name (filename, Qnil);
2476 /* If the file name has special constructs in it,
2477 call the corresponding file handler. */
2478 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2479 if (!NILP (handler))
2480 return call2 (handler, Qfile_executable_p, absname);
2482 absname = ENCODE_FILE (absname);
2484 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2487 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2488 doc: /* Return t if file FILENAME exists and you can read it.
2489 See also `file-exists-p' and `file-attributes'. */)
2490 (Lisp_Object filename)
2492 Lisp_Object absname;
2493 Lisp_Object handler;
2495 CHECK_STRING (filename);
2496 absname = Fexpand_file_name (filename, Qnil);
2498 /* If the file name has special constructs in it,
2499 call the corresponding file handler. */
2500 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2501 if (!NILP (handler))
2502 return call2 (handler, Qfile_readable_p, absname);
2504 absname = ENCODE_FILE (absname);
2505 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2506 ? Qt : Qnil);
2509 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2510 doc: /* Return t if file FILENAME can be written or created by you. */)
2511 (Lisp_Object filename)
2513 Lisp_Object absname, dir, encoded;
2514 Lisp_Object handler;
2516 CHECK_STRING (filename);
2517 absname = Fexpand_file_name (filename, Qnil);
2519 /* If the file name has special constructs in it,
2520 call the corresponding file handler. */
2521 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2522 if (!NILP (handler))
2523 return call2 (handler, Qfile_writable_p, absname);
2525 encoded = ENCODE_FILE (absname);
2526 if (check_writable (SSDATA (encoded), W_OK))
2527 return Qt;
2528 if (errno != ENOENT)
2529 return Qnil;
2531 dir = Ffile_name_directory (absname);
2532 eassert (!NILP (dir));
2533 #ifdef MSDOS
2534 dir = Fdirectory_file_name (dir);
2535 #endif /* MSDOS */
2537 dir = ENCODE_FILE (dir);
2538 #ifdef WINDOWSNT
2539 /* The read-only attribute of the parent directory doesn't affect
2540 whether a file or directory can be created within it. Some day we
2541 should check ACLs though, which do affect this. */
2542 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2543 #else
2544 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2545 #endif
2548 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2549 doc: /* Access file FILENAME, and get an error if that does not work.
2550 The second argument STRING is used in the error message.
2551 If there is no error, returns nil. */)
2552 (Lisp_Object filename, Lisp_Object string)
2554 Lisp_Object handler, encoded_filename, absname;
2556 CHECK_STRING (filename);
2557 absname = Fexpand_file_name (filename, Qnil);
2559 CHECK_STRING (string);
2561 /* If the file name has special constructs in it,
2562 call the corresponding file handler. */
2563 handler = Ffind_file_name_handler (absname, Qaccess_file);
2564 if (!NILP (handler))
2565 return call3 (handler, Qaccess_file, absname, string);
2567 encoded_filename = ENCODE_FILE (absname);
2569 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2570 report_file_error (SSDATA (string), filename);
2572 return Qnil;
2575 /* Relative to directory FD, return the symbolic link value of FILENAME.
2576 On failure, return nil. */
2577 Lisp_Object
2578 emacs_readlinkat (int fd, char const *filename)
2580 static struct allocator const emacs_norealloc_allocator =
2581 { xmalloc, NULL, xfree, memory_full };
2582 Lisp_Object val;
2583 char readlink_buf[1024];
2584 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2585 &emacs_norealloc_allocator, readlinkat);
2586 if (!buf)
2587 return Qnil;
2589 val = build_unibyte_string (buf);
2590 if (buf[0] == '/' && strchr (buf, ':'))
2592 AUTO_STRING (slash_colon, "/:");
2593 val = concat2 (slash_colon, val);
2595 if (buf != readlink_buf)
2596 xfree (buf);
2597 val = DECODE_FILE (val);
2598 return val;
2601 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2602 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2603 The value is the link target, as a string.
2604 Otherwise it returns nil.
2606 This function does not check whether the link target exists. */)
2607 (Lisp_Object filename)
2609 Lisp_Object handler;
2611 CHECK_STRING (filename);
2612 filename = Fexpand_file_name (filename, Qnil);
2614 /* If the file name has special constructs in it,
2615 call the corresponding file handler. */
2616 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2617 if (!NILP (handler))
2618 return call2 (handler, Qfile_symlink_p, filename);
2620 filename = ENCODE_FILE (filename);
2622 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2625 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2626 doc: /* Return t if FILENAME names an existing directory.
2627 Symbolic links to directories count as directories.
2628 See `file-symlink-p' to distinguish symlinks. */)
2629 (Lisp_Object filename)
2631 Lisp_Object absname;
2632 Lisp_Object handler;
2634 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2636 /* If the file name has special constructs in it,
2637 call the corresponding file handler. */
2638 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2639 if (!NILP (handler))
2640 return call2 (handler, Qfile_directory_p, absname);
2642 absname = ENCODE_FILE (absname);
2644 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2647 /* Return true if FILE is a directory or a symlink to a directory. */
2648 bool
2649 file_directory_p (char const *file)
2651 #ifdef WINDOWSNT
2652 /* This is cheaper than 'stat'. */
2653 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2654 #else
2655 struct stat st;
2656 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2657 #endif
2660 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2661 Sfile_accessible_directory_p, 1, 1, 0,
2662 doc: /* Return t if file FILENAME names a directory you can open.
2663 For the value to be t, FILENAME must specify the name of a directory as a file,
2664 and the directory must allow you to open files in it. In order to use a
2665 directory as a buffer's current directory, this predicate must return true.
2666 A directory name spec may be given instead; then the value is t
2667 if the directory so specified exists and really is a readable and
2668 searchable directory. */)
2669 (Lisp_Object filename)
2671 Lisp_Object absname;
2672 Lisp_Object handler;
2674 CHECK_STRING (filename);
2675 absname = Fexpand_file_name (filename, Qnil);
2677 /* If the file name has special constructs in it,
2678 call the corresponding file handler. */
2679 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2680 if (!NILP (handler))
2682 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2683 errno = 0;
2684 return r;
2687 absname = ENCODE_FILE (absname);
2688 return file_accessible_directory_p (absname) ? Qt : Qnil;
2691 /* If FILE is a searchable directory or a symlink to a
2692 searchable directory, return true. Otherwise return
2693 false and set errno to an error number. */
2694 bool
2695 file_accessible_directory_p (Lisp_Object file)
2697 #ifdef DOS_NT
2698 /* There's no need to test whether FILE is searchable, as the
2699 searchable/executable bit is invented on DOS_NT platforms. */
2700 return file_directory_p (SSDATA (file));
2701 #else
2702 /* On POSIXish platforms, use just one system call; this avoids a
2703 race and is typically faster. */
2704 const char *data = SSDATA (file);
2705 ptrdiff_t len = SBYTES (file);
2706 char const *dir;
2707 bool ok;
2708 int saved_errno;
2709 USE_SAFE_ALLOCA;
2711 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2712 There are three exceptions: "", "/", and "//". Leave "" alone,
2713 as it's invalid. Append only "." to the other two exceptions as
2714 "/" and "//" are distinct on some platforms, whereas "/", "///",
2715 "////", etc. are all equivalent. */
2716 if (! len)
2717 dir = data;
2718 else
2720 /* Just check for trailing '/' when deciding whether to append '/'.
2721 That's simpler than testing the two special cases "/" and "//",
2722 and it's a safe optimization here. */
2723 char *buf = SAFE_ALLOCA (len + 3);
2724 memcpy (buf, data, len);
2725 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2726 dir = buf;
2729 ok = check_existing (dir);
2730 saved_errno = errno;
2731 SAFE_FREE ();
2732 errno = saved_errno;
2733 return ok;
2734 #endif
2737 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2738 doc: /* Return t if FILENAME names a regular file.
2739 This is the sort of file that holds an ordinary stream of data bytes.
2740 Symbolic links to regular files count as regular files.
2741 See `file-symlink-p' to distinguish symlinks. */)
2742 (Lisp_Object filename)
2744 register Lisp_Object absname;
2745 struct stat st;
2746 Lisp_Object handler;
2748 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2750 /* If the file name has special constructs in it,
2751 call the corresponding file handler. */
2752 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2753 if (!NILP (handler))
2754 return call2 (handler, Qfile_regular_p, absname);
2756 absname = ENCODE_FILE (absname);
2758 #ifdef WINDOWSNT
2760 int result;
2761 Lisp_Object tem = Vw32_get_true_file_attributes;
2763 /* Tell stat to use expensive method to get accurate info. */
2764 Vw32_get_true_file_attributes = Qt;
2765 result = stat (SDATA (absname), &st);
2766 Vw32_get_true_file_attributes = tem;
2768 if (result < 0)
2769 return Qnil;
2770 return S_ISREG (st.st_mode) ? Qt : Qnil;
2772 #else
2773 if (stat (SSDATA (absname), &st) < 0)
2774 return Qnil;
2775 return S_ISREG (st.st_mode) ? Qt : Qnil;
2776 #endif
2779 DEFUN ("file-selinux-context", Ffile_selinux_context,
2780 Sfile_selinux_context, 1, 1, 0,
2781 doc: /* Return SELinux context of file named FILENAME.
2782 The return value is a list (USER ROLE TYPE RANGE), where the list
2783 elements are strings naming the user, role, type, and range of the
2784 file's SELinux security context.
2786 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2787 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2788 (Lisp_Object filename)
2790 Lisp_Object absname;
2791 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2793 Lisp_Object handler;
2794 #if HAVE_LIBSELINUX
2795 security_context_t con;
2796 int conlength;
2797 context_t context;
2798 #endif
2800 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2802 /* If the file name has special constructs in it,
2803 call the corresponding file handler. */
2804 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2805 if (!NILP (handler))
2806 return call2 (handler, Qfile_selinux_context, absname);
2808 absname = ENCODE_FILE (absname);
2810 #if HAVE_LIBSELINUX
2811 if (is_selinux_enabled ())
2813 conlength = lgetfilecon (SSDATA (absname), &con);
2814 if (conlength > 0)
2816 context = context_new (con);
2817 if (context_user_get (context))
2818 user = build_string (context_user_get (context));
2819 if (context_role_get (context))
2820 role = build_string (context_role_get (context));
2821 if (context_type_get (context))
2822 type = build_string (context_type_get (context));
2823 if (context_range_get (context))
2824 range = build_string (context_range_get (context));
2825 context_free (context);
2826 freecon (con);
2829 #endif
2831 return list4 (user, role, type, range);
2834 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2835 Sset_file_selinux_context, 2, 2, 0,
2836 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2837 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2838 elements are strings naming the components of a SELinux context.
2840 Value is t if setting of SELinux context was successful, nil otherwise.
2842 This function does nothing and returns nil if SELinux is disabled,
2843 or if Emacs was not compiled with SELinux support. */)
2844 (Lisp_Object filename, Lisp_Object context)
2846 Lisp_Object absname;
2847 Lisp_Object handler;
2848 #if HAVE_LIBSELINUX
2849 Lisp_Object encoded_absname;
2850 Lisp_Object user = CAR_SAFE (context);
2851 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2852 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2853 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2854 security_context_t con;
2855 bool fail;
2856 int conlength;
2857 context_t parsed_con;
2858 #endif
2860 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2862 /* If the file name has special constructs in it,
2863 call the corresponding file handler. */
2864 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2865 if (!NILP (handler))
2866 return call3 (handler, Qset_file_selinux_context, absname, context);
2868 #if HAVE_LIBSELINUX
2869 if (is_selinux_enabled ())
2871 /* Get current file context. */
2872 encoded_absname = ENCODE_FILE (absname);
2873 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2874 if (conlength > 0)
2876 parsed_con = context_new (con);
2877 /* Change the parts defined in the parameter.*/
2878 if (STRINGP (user))
2880 if (context_user_set (parsed_con, SSDATA (user)))
2881 error ("Doing context_user_set");
2883 if (STRINGP (role))
2885 if (context_role_set (parsed_con, SSDATA (role)))
2886 error ("Doing context_role_set");
2888 if (STRINGP (type))
2890 if (context_type_set (parsed_con, SSDATA (type)))
2891 error ("Doing context_type_set");
2893 if (STRINGP (range))
2895 if (context_range_set (parsed_con, SSDATA (range)))
2896 error ("Doing context_range_set");
2899 /* Set the modified context back to the file. */
2900 fail = (lsetfilecon (SSDATA (encoded_absname),
2901 context_str (parsed_con))
2902 != 0);
2903 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2904 if (fail && errno != ENOTSUP)
2905 report_file_error ("Doing lsetfilecon", absname);
2907 context_free (parsed_con);
2908 freecon (con);
2909 return fail ? Qnil : Qt;
2911 else
2912 report_file_error ("Doing lgetfilecon", absname);
2914 #endif
2916 return Qnil;
2919 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2920 doc: /* Return ACL entries of file named FILENAME.
2921 The entries are returned in a format suitable for use in `set-file-acl'
2922 but is otherwise undocumented and subject to change.
2923 Return nil if file does not exist or is not accessible, or if Emacs
2924 was unable to determine the ACL entries. */)
2925 (Lisp_Object filename)
2927 Lisp_Object absname;
2928 Lisp_Object handler;
2929 #ifdef HAVE_ACL_SET_FILE
2930 acl_t acl;
2931 Lisp_Object acl_string;
2932 char *str;
2933 # ifndef HAVE_ACL_TYPE_EXTENDED
2934 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2935 # endif
2936 #endif
2938 absname = expand_and_dir_to_file (filename,
2939 BVAR (current_buffer, directory));
2941 /* If the file name has special constructs in it,
2942 call the corresponding file handler. */
2943 handler = Ffind_file_name_handler (absname, Qfile_acl);
2944 if (!NILP (handler))
2945 return call2 (handler, Qfile_acl, absname);
2947 #ifdef HAVE_ACL_SET_FILE
2948 absname = ENCODE_FILE (absname);
2950 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2951 if (acl == NULL)
2952 return Qnil;
2954 str = acl_to_text (acl, NULL);
2955 if (str == NULL)
2957 acl_free (acl);
2958 return Qnil;
2961 acl_string = build_string (str);
2962 acl_free (str);
2963 acl_free (acl);
2965 return acl_string;
2966 #endif
2968 return Qnil;
2971 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
2972 2, 2, 0,
2973 doc: /* Set ACL of file named FILENAME to ACL-STRING.
2974 ACL-STRING should contain the textual representation of the ACL
2975 entries in a format suitable for the platform.
2977 Value is t if setting of ACL was successful, nil otherwise.
2979 Setting ACL for local files requires Emacs to be built with ACL
2980 support. */)
2981 (Lisp_Object filename, Lisp_Object acl_string)
2983 Lisp_Object absname;
2984 Lisp_Object handler;
2985 #ifdef HAVE_ACL_SET_FILE
2986 Lisp_Object encoded_absname;
2987 acl_t acl;
2988 bool fail;
2989 #endif
2991 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2993 /* If the file name has special constructs in it,
2994 call the corresponding file handler. */
2995 handler = Ffind_file_name_handler (absname, Qset_file_acl);
2996 if (!NILP (handler))
2997 return call3 (handler, Qset_file_acl, absname, acl_string);
2999 #ifdef HAVE_ACL_SET_FILE
3000 if (STRINGP (acl_string))
3002 acl = acl_from_text (SSDATA (acl_string));
3003 if (acl == NULL)
3005 report_file_error ("Converting ACL", absname);
3006 return Qnil;
3009 encoded_absname = ENCODE_FILE (absname);
3011 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3012 acl)
3013 != 0);
3014 if (fail && acl_errno_valid (errno))
3015 report_file_error ("Setting ACL", absname);
3017 acl_free (acl);
3018 return fail ? Qnil : Qt;
3020 #endif
3022 return Qnil;
3025 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3026 doc: /* Return mode bits of file named FILENAME, as an integer.
3027 Return nil, if file does not exist or is not accessible. */)
3028 (Lisp_Object filename)
3030 Lisp_Object absname;
3031 struct stat st;
3032 Lisp_Object handler;
3034 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3036 /* If the file name has special constructs in it,
3037 call the corresponding file handler. */
3038 handler = Ffind_file_name_handler (absname, Qfile_modes);
3039 if (!NILP (handler))
3040 return call2 (handler, Qfile_modes, absname);
3042 absname = ENCODE_FILE (absname);
3044 if (stat (SSDATA (absname), &st) < 0)
3045 return Qnil;
3047 return make_number (st.st_mode & 07777);
3050 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3051 "(let ((file (read-file-name \"File: \"))) \
3052 (list file (read-file-modes nil file)))",
3053 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3054 Only the 12 low bits of MODE are used.
3056 Interactively, mode bits are read by `read-file-modes', which accepts
3057 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3058 (Lisp_Object filename, Lisp_Object mode)
3060 Lisp_Object absname, encoded_absname;
3061 Lisp_Object handler;
3063 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3064 CHECK_NUMBER (mode);
3066 /* If the file name has special constructs in it,
3067 call the corresponding file handler. */
3068 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3069 if (!NILP (handler))
3070 return call3 (handler, Qset_file_modes, absname, mode);
3072 encoded_absname = ENCODE_FILE (absname);
3074 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3075 report_file_error ("Doing chmod", absname);
3077 return Qnil;
3080 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3081 doc: /* Set the file permission bits for newly created files.
3082 The argument MODE should be an integer; only the low 9 bits are used.
3083 This setting is inherited by subprocesses. */)
3084 (Lisp_Object mode)
3086 mode_t oldrealmask, oldumask, newumask;
3087 CHECK_NUMBER (mode);
3088 oldrealmask = realmask;
3089 newumask = ~ XINT (mode) & 0777;
3091 block_input ();
3092 realmask = newumask;
3093 oldumask = umask (newumask);
3094 unblock_input ();
3096 eassert (oldumask == oldrealmask);
3097 return Qnil;
3100 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3101 doc: /* Return the default file protection for created files.
3102 The value is an integer. */)
3103 (void)
3105 Lisp_Object value;
3106 XSETINT (value, (~ realmask) & 0777);
3107 return value;
3111 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3112 doc: /* Set times of file FILENAME to TIMESTAMP.
3113 Set both access and modification times.
3114 Return t on success, else nil.
3115 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3116 `current-time'. */)
3117 (Lisp_Object filename, Lisp_Object timestamp)
3119 Lisp_Object absname, encoded_absname;
3120 Lisp_Object handler;
3121 struct timespec t = lisp_time_argument (timestamp);
3123 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3125 /* If the file name has special constructs in it,
3126 call the corresponding file handler. */
3127 handler = Ffind_file_name_handler (absname, Qset_file_times);
3128 if (!NILP (handler))
3129 return call3 (handler, Qset_file_times, absname, timestamp);
3131 encoded_absname = ENCODE_FILE (absname);
3134 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3136 #ifdef MSDOS
3137 /* Setting times on a directory always fails. */
3138 if (file_directory_p (SSDATA (encoded_absname)))
3139 return Qnil;
3140 #endif
3141 report_file_error ("Setting file times", absname);
3145 return Qt;
3148 #ifdef HAVE_SYNC
3149 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3150 doc: /* Tell Unix to finish all pending disk updates. */)
3151 (void)
3153 sync ();
3154 return Qnil;
3157 #endif /* HAVE_SYNC */
3159 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3160 doc: /* Return t if file FILE1 is newer than file FILE2.
3161 If FILE1 does not exist, the answer is nil;
3162 otherwise, if FILE2 does not exist, the answer is t. */)
3163 (Lisp_Object file1, Lisp_Object file2)
3165 Lisp_Object absname1, absname2;
3166 struct stat st1, st2;
3167 Lisp_Object handler;
3168 struct gcpro gcpro1, gcpro2;
3170 CHECK_STRING (file1);
3171 CHECK_STRING (file2);
3173 absname1 = Qnil;
3174 GCPRO2 (absname1, file2);
3175 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3176 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3177 UNGCPRO;
3179 /* If the file name has special constructs in it,
3180 call the corresponding file handler. */
3181 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3182 if (NILP (handler))
3183 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3184 if (!NILP (handler))
3185 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3187 GCPRO2 (absname1, absname2);
3188 absname1 = ENCODE_FILE (absname1);
3189 absname2 = ENCODE_FILE (absname2);
3190 UNGCPRO;
3192 if (stat (SSDATA (absname1), &st1) < 0)
3193 return Qnil;
3195 if (stat (SSDATA (absname2), &st2) < 0)
3196 return Qt;
3198 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3199 ? Qt : Qnil);
3202 #ifndef READ_BUF_SIZE
3203 #define READ_BUF_SIZE (64 << 10)
3204 #endif
3205 /* Some buffer offsets are stored in 'int' variables. */
3206 verify (READ_BUF_SIZE <= INT_MAX);
3208 /* This function is called after Lisp functions to decide a coding
3209 system are called, or when they cause an error. Before they are
3210 called, the current buffer is set unibyte and it contains only a
3211 newly inserted text (thus the buffer was empty before the
3212 insertion).
3214 The functions may set markers, overlays, text properties, or even
3215 alter the buffer contents, change the current buffer.
3217 Here, we reset all those changes by:
3218 o set back the current buffer.
3219 o move all markers and overlays to BEG.
3220 o remove all text properties.
3221 o set back the buffer multibyteness. */
3223 static void
3224 decide_coding_unwind (Lisp_Object unwind_data)
3226 Lisp_Object multibyte, undo_list, buffer;
3228 multibyte = XCAR (unwind_data);
3229 unwind_data = XCDR (unwind_data);
3230 undo_list = XCAR (unwind_data);
3231 buffer = XCDR (unwind_data);
3233 set_buffer_internal (XBUFFER (buffer));
3234 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3235 adjust_overlays_for_delete (BEG, Z - BEG);
3236 set_buffer_intervals (current_buffer, NULL);
3237 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3239 /* Now we are safe to change the buffer's multibyteness directly. */
3240 bset_enable_multibyte_characters (current_buffer, multibyte);
3241 bset_undo_list (current_buffer, undo_list);
3244 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3245 object where slot 0 is the file descriptor, slot 1 specifies
3246 an offset to put the read bytes, and slot 2 is the maximum
3247 amount of bytes to read. Value is the number of bytes read. */
3249 static Lisp_Object
3250 read_non_regular (Lisp_Object state)
3252 int nbytes;
3254 immediate_quit = 1;
3255 QUIT;
3256 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3257 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3258 + XSAVE_INTEGER (state, 1)),
3259 XSAVE_INTEGER (state, 2));
3260 immediate_quit = 0;
3261 /* Fast recycle this object for the likely next call. */
3262 free_misc (state);
3263 return make_number (nbytes);
3267 /* Condition-case handler used when reading from non-regular files
3268 in insert-file-contents. */
3270 static Lisp_Object
3271 read_non_regular_quit (Lisp_Object ignore)
3273 return Qnil;
3276 /* Return the file offset that VAL represents, checking for type
3277 errors and overflow. */
3278 static off_t
3279 file_offset (Lisp_Object val)
3281 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3282 return XINT (val);
3284 if (FLOATP (val))
3286 double v = XFLOAT_DATA (val);
3287 if (0 <= v
3288 && (sizeof (off_t) < sizeof v
3289 ? v <= TYPE_MAXIMUM (off_t)
3290 : v < TYPE_MAXIMUM (off_t)))
3291 return v;
3294 wrong_type_argument (intern ("file-offset"), val);
3297 /* Return a special time value indicating the error number ERRNUM. */
3298 static struct timespec
3299 time_error_value (int errnum)
3301 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3302 ? NONEXISTENT_MODTIME_NSECS
3303 : UNKNOWN_MODTIME_NSECS);
3304 return make_timespec (0, ns);
3307 static Lisp_Object
3308 get_window_points_and_markers (void)
3310 Lisp_Object pt_marker = Fpoint_marker ();
3311 Lisp_Object windows
3312 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3313 Lisp_Object window_markers = windows;
3314 /* Window markers (and point) are handled specially: rather than move to
3315 just before or just after the modified text, we try to keep the
3316 markers at the same distance (bug#19161).
3317 In general, this is wrong, but for window-markers, this should be harmless
3318 and is convenient for the end user when most of the file is unmodified,
3319 except for a few minor details near the beginning and near the end. */
3320 for (; CONSP (windows); windows = XCDR (windows))
3321 if (WINDOWP (XCAR (windows)))
3323 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3324 XSETCAR (windows,
3325 Fcons (window_marker, Fmarker_position (window_marker)));
3327 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3330 static void
3331 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3332 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3334 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3335 if (CONSP (XCAR (window_markers)))
3337 Lisp_Object car = XCAR (window_markers);
3338 Lisp_Object marker = XCAR (car);
3339 Lisp_Object oldpos = XCDR (car);
3340 if (MARKERP (marker) && INTEGERP (oldpos)
3341 && XINT (oldpos) > same_at_start
3342 && XINT (oldpos) < same_at_end)
3344 ptrdiff_t oldsize = same_at_end - same_at_start;
3345 ptrdiff_t newsize = inserted;
3346 double growth = newsize / (double)oldsize;
3347 ptrdiff_t newpos
3348 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3349 Fset_marker (marker, make_number (newpos), Qnil);
3354 /* FIXME: insert-file-contents should be split with the top-level moved to
3355 Elisp and only the core kept in C. */
3357 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3358 1, 5, 0,
3359 doc: /* Insert contents of file FILENAME after point.
3360 Returns list of absolute file name and number of characters inserted.
3361 If second argument VISIT is non-nil, the buffer's visited filename and
3362 last save file modtime are set, and it is marked unmodified. If
3363 visiting and the file does not exist, visiting is completed before the
3364 error is signaled.
3366 The optional third and fourth arguments BEG and END specify what portion
3367 of the file to insert. These arguments count bytes in the file, not
3368 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3370 If optional fifth argument REPLACE is non-nil, replace the current
3371 buffer contents (in the accessible portion) with the file contents.
3372 This is better than simply deleting and inserting the whole thing
3373 because (1) it preserves some marker positions and (2) it puts less data
3374 in the undo list. When REPLACE is non-nil, the second return value is
3375 the number of characters that replace previous buffer contents.
3377 This function does code conversion according to the value of
3378 `coding-system-for-read' or `file-coding-system-alist', and sets the
3379 variable `last-coding-system-used' to the coding system actually used.
3381 In addition, this function decodes the inserted text from known formats
3382 by calling `format-decode', which see. */)
3383 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3385 struct stat st;
3386 struct timespec mtime;
3387 int fd;
3388 ptrdiff_t inserted = 0;
3389 ptrdiff_t how_much;
3390 off_t beg_offset, end_offset;
3391 int unprocessed;
3392 ptrdiff_t count = SPECPDL_INDEX ();
3393 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3394 Lisp_Object handler, val, insval, orig_filename, old_undo;
3395 Lisp_Object p;
3396 ptrdiff_t total = 0;
3397 bool not_regular = 0;
3398 int save_errno = 0;
3399 char read_buf[READ_BUF_SIZE];
3400 struct coding_system coding;
3401 bool replace_handled = false;
3402 bool set_coding_system = false;
3403 Lisp_Object coding_system;
3404 bool read_quit = false;
3405 /* If the undo log only contains the insertion, there's no point
3406 keeping it. It's typically when we first fill a file-buffer. */
3407 bool empty_undo_list_p
3408 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3409 && BEG == Z);
3410 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3411 bool we_locked_file = false;
3412 ptrdiff_t fd_index;
3413 Lisp_Object window_markers = Qnil;
3414 /* same_at_start and same_at_end count bytes, because file access counts
3415 bytes and BEG and END count bytes. */
3416 ptrdiff_t same_at_start = BEGV_BYTE;
3417 ptrdiff_t same_at_end = ZV_BYTE;
3418 /* SAME_AT_END_CHARPOS counts characters, because
3419 restore_window_points needs the old character count. */
3420 ptrdiff_t same_at_end_charpos = ZV;
3422 if (current_buffer->base_buffer && ! NILP (visit))
3423 error ("Cannot do file visiting in an indirect buffer");
3425 if (!NILP (BVAR (current_buffer, read_only)))
3426 Fbarf_if_buffer_read_only (Qnil);
3428 val = Qnil;
3429 p = Qnil;
3430 orig_filename = Qnil;
3431 old_undo = Qnil;
3433 GCPRO5 (filename, val, p, orig_filename, old_undo);
3435 CHECK_STRING (filename);
3436 filename = Fexpand_file_name (filename, Qnil);
3438 /* The value Qnil means that the coding system is not yet
3439 decided. */
3440 coding_system = Qnil;
3442 /* If the file name has special constructs in it,
3443 call the corresponding file handler. */
3444 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3445 if (!NILP (handler))
3447 val = call6 (handler, Qinsert_file_contents, filename,
3448 visit, beg, end, replace);
3449 if (CONSP (val) && CONSP (XCDR (val))
3450 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3451 inserted = XINT (XCAR (XCDR (val)));
3452 goto handled;
3455 orig_filename = filename;
3456 filename = ENCODE_FILE (filename);
3458 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3459 if (fd < 0)
3461 save_errno = errno;
3462 if (NILP (visit))
3463 report_file_error ("Opening input file", orig_filename);
3464 mtime = time_error_value (save_errno);
3465 st.st_size = -1;
3466 if (!NILP (Vcoding_system_for_read))
3467 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3468 goto notfound;
3471 fd_index = SPECPDL_INDEX ();
3472 record_unwind_protect_int (close_file_unwind, fd);
3474 /* Replacement should preserve point as it preserves markers. */
3475 if (!NILP (replace))
3477 window_markers = get_window_points_and_markers ();
3478 record_unwind_protect (restore_point_unwind,
3479 XCAR (XCAR (window_markers)));
3482 if (fstat (fd, &st) != 0)
3483 report_file_error ("Input file status", orig_filename);
3484 mtime = get_stat_mtime (&st);
3486 /* This code will need to be changed in order to work on named
3487 pipes, and it's probably just not worth it. So we should at
3488 least signal an error. */
3489 if (!S_ISREG (st.st_mode))
3491 not_regular = 1;
3493 if (! NILP (visit))
3494 goto notfound;
3496 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3497 xsignal2 (Qfile_error,
3498 build_string ("not a regular file"), orig_filename);
3501 if (!NILP (visit))
3503 if (!NILP (beg) || !NILP (end))
3504 error ("Attempt to visit less than an entire file");
3505 if (BEG < Z && NILP (replace))
3506 error ("Cannot do file visiting in a non-empty buffer");
3509 if (!NILP (beg))
3510 beg_offset = file_offset (beg);
3511 else
3512 beg_offset = 0;
3514 if (!NILP (end))
3515 end_offset = file_offset (end);
3516 else
3518 if (not_regular)
3519 end_offset = TYPE_MAXIMUM (off_t);
3520 else
3522 end_offset = st.st_size;
3524 /* A negative size can happen on a platform that allows file
3525 sizes greater than the maximum off_t value. */
3526 if (end_offset < 0)
3527 buffer_overflow ();
3529 /* The file size returned from stat may be zero, but data
3530 may be readable nonetheless, for example when this is a
3531 file in the /proc filesystem. */
3532 if (end_offset == 0)
3533 end_offset = READ_BUF_SIZE;
3537 /* Check now whether the buffer will become too large,
3538 in the likely case where the file's length is not changing.
3539 This saves a lot of needless work before a buffer overflow. */
3540 if (! not_regular)
3542 /* The likely offset where we will stop reading. We could read
3543 more (or less), if the file grows (or shrinks) as we read it. */
3544 off_t likely_end = min (end_offset, st.st_size);
3546 if (beg_offset < likely_end)
3548 ptrdiff_t buf_bytes
3549 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3550 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3551 off_t likely_growth = likely_end - beg_offset;
3552 if (buf_growth_max < likely_growth)
3553 buffer_overflow ();
3557 /* Prevent redisplay optimizations. */
3558 current_buffer->clip_changed = true;
3560 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3562 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3563 setup_coding_system (coding_system, &coding);
3564 /* Ensure we set Vlast_coding_system_used. */
3565 set_coding_system = true;
3567 else if (BEG < Z)
3569 /* Decide the coding system to use for reading the file now
3570 because we can't use an optimized method for handling
3571 `coding:' tag if the current buffer is not empty. */
3572 if (!NILP (Vcoding_system_for_read))
3573 coding_system = Vcoding_system_for_read;
3574 else
3576 /* Don't try looking inside a file for a coding system
3577 specification if it is not seekable. */
3578 if (! not_regular && ! NILP (Vset_auto_coding_function))
3580 /* Find a coding system specified in the heading two
3581 lines or in the tailing several lines of the file.
3582 We assume that the 1K-byte and 3K-byte for heading
3583 and tailing respectively are sufficient for this
3584 purpose. */
3585 int nread;
3587 if (st.st_size <= (1024 * 4))
3588 nread = emacs_read (fd, read_buf, 1024 * 4);
3589 else
3591 nread = emacs_read (fd, read_buf, 1024);
3592 if (nread == 1024)
3594 int ntail;
3595 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3596 report_file_error ("Setting file position",
3597 orig_filename);
3598 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3599 nread = ntail < 0 ? ntail : nread + ntail;
3603 if (nread < 0)
3604 report_file_error ("Read error", orig_filename);
3605 else if (nread > 0)
3607 AUTO_STRING (name, " *code-converting-work*");
3608 struct buffer *prev = current_buffer;
3609 Lisp_Object workbuf;
3610 struct buffer *buf;
3612 record_unwind_current_buffer ();
3614 workbuf = Fget_buffer_create (name);
3615 buf = XBUFFER (workbuf);
3617 delete_all_overlays (buf);
3618 bset_directory (buf, BVAR (current_buffer, directory));
3619 bset_read_only (buf, Qnil);
3620 bset_filename (buf, Qnil);
3621 bset_undo_list (buf, Qt);
3622 eassert (buf->overlays_before == NULL);
3623 eassert (buf->overlays_after == NULL);
3625 set_buffer_internal (buf);
3626 Ferase_buffer ();
3627 bset_enable_multibyte_characters (buf, Qnil);
3629 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3630 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3631 coding_system = call2 (Vset_auto_coding_function,
3632 filename, make_number (nread));
3633 set_buffer_internal (prev);
3635 /* Discard the unwind protect for recovering the
3636 current buffer. */
3637 specpdl_ptr--;
3639 /* Rewind the file for the actual read done later. */
3640 if (lseek (fd, 0, SEEK_SET) < 0)
3641 report_file_error ("Setting file position", orig_filename);
3645 if (NILP (coding_system))
3647 /* If we have not yet decided a coding system, check
3648 file-coding-system-alist. */
3649 coding_system = CALLN (Ffind_operation_coding_system,
3650 Qinsert_file_contents, orig_filename,
3651 visit, beg, end, replace);
3652 if (CONSP (coding_system))
3653 coding_system = XCAR (coding_system);
3657 if (NILP (coding_system))
3658 coding_system = Qundecided;
3659 else
3660 CHECK_CODING_SYSTEM (coding_system);
3662 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3663 /* We must suppress all character code conversion except for
3664 end-of-line conversion. */
3665 coding_system = raw_text_coding_system (coding_system);
3667 setup_coding_system (coding_system, &coding);
3668 /* Ensure we set Vlast_coding_system_used. */
3669 set_coding_system = true;
3672 /* If requested, replace the accessible part of the buffer
3673 with the file contents. Avoid replacing text at the
3674 beginning or end of the buffer that matches the file contents;
3675 that preserves markers pointing to the unchanged parts.
3677 Here we implement this feature in an optimized way
3678 for the case where code conversion is NOT needed.
3679 The following if-statement handles the case of conversion
3680 in a less optimal way.
3682 If the code conversion is "automatic" then we try using this
3683 method and hope for the best.
3684 But if we discover the need for conversion, we give up on this method
3685 and let the following if-statement handle the replace job. */
3686 if (!NILP (replace)
3687 && BEGV < ZV
3688 && (NILP (coding_system)
3689 || ! CODING_REQUIRE_DECODING (&coding)))
3691 ptrdiff_t overlap;
3692 /* There is still a possibility we will find the need to do code
3693 conversion. If that happens, set this variable to
3694 give up on handling REPLACE in the optimized way. */
3695 bool giveup_match_end = false;
3697 if (beg_offset != 0)
3699 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3700 report_file_error ("Setting file position", orig_filename);
3703 immediate_quit = 1;
3704 QUIT;
3705 /* Count how many chars at the start of the file
3706 match the text at the beginning of the buffer. */
3707 while (1)
3709 int nread, bufpos;
3711 nread = emacs_read (fd, read_buf, sizeof read_buf);
3712 if (nread < 0)
3713 report_file_error ("Read error", orig_filename);
3714 else if (nread == 0)
3715 break;
3717 if (CODING_REQUIRE_DETECTION (&coding))
3719 coding_system = detect_coding_system ((unsigned char *) read_buf,
3720 nread, nread, 1, 0,
3721 coding_system);
3722 setup_coding_system (coding_system, &coding);
3725 if (CODING_REQUIRE_DECODING (&coding))
3726 /* We found that the file should be decoded somehow.
3727 Let's give up here. */
3729 giveup_match_end = true;
3730 break;
3733 bufpos = 0;
3734 while (bufpos < nread && same_at_start < ZV_BYTE
3735 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3736 same_at_start++, bufpos++;
3737 /* If we found a discrepancy, stop the scan.
3738 Otherwise loop around and scan the next bufferful. */
3739 if (bufpos != nread)
3740 break;
3742 immediate_quit = false;
3743 /* If the file matches the buffer completely,
3744 there's no need to replace anything. */
3745 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3747 emacs_close (fd);
3748 clear_unwind_protect (fd_index);
3750 /* Truncate the buffer to the size of the file. */
3751 del_range_1 (same_at_start, same_at_end, 0, 0);
3752 goto handled;
3754 immediate_quit = true;
3755 QUIT;
3756 /* Count how many chars at the end of the file
3757 match the text at the end of the buffer. But, if we have
3758 already found that decoding is necessary, don't waste time. */
3759 while (!giveup_match_end)
3761 int total_read, nread, bufpos, trial;
3762 off_t curpos;
3764 /* At what file position are we now scanning? */
3765 curpos = end_offset - (ZV_BYTE - same_at_end);
3766 /* If the entire file matches the buffer tail, stop the scan. */
3767 if (curpos == 0)
3768 break;
3769 /* How much can we scan in the next step? */
3770 trial = min (curpos, sizeof read_buf);
3771 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3772 report_file_error ("Setting file position", orig_filename);
3774 total_read = nread = 0;
3775 while (total_read < trial)
3777 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3778 if (nread < 0)
3779 report_file_error ("Read error", orig_filename);
3780 else if (nread == 0)
3781 break;
3782 total_read += nread;
3785 /* Scan this bufferful from the end, comparing with
3786 the Emacs buffer. */
3787 bufpos = total_read;
3789 /* Compare with same_at_start to avoid counting some buffer text
3790 as matching both at the file's beginning and at the end. */
3791 while (bufpos > 0 && same_at_end > same_at_start
3792 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3793 same_at_end--, bufpos--;
3795 /* If we found a discrepancy, stop the scan.
3796 Otherwise loop around and scan the preceding bufferful. */
3797 if (bufpos != 0)
3799 /* If this discrepancy is because of code conversion,
3800 we cannot use this method; giveup and try the other. */
3801 if (same_at_end > same_at_start
3802 && FETCH_BYTE (same_at_end - 1) >= 0200
3803 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3804 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3805 giveup_match_end = true;
3806 break;
3809 if (nread == 0)
3810 break;
3812 immediate_quit = 0;
3814 if (! giveup_match_end)
3816 ptrdiff_t temp;
3818 /* We win! We can handle REPLACE the optimized way. */
3820 /* Extend the start of non-matching text area to multibyte
3821 character boundary. */
3822 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3823 while (same_at_start > BEGV_BYTE
3824 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3825 same_at_start--;
3827 /* Extend the end of non-matching text area to multibyte
3828 character boundary. */
3829 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3830 while (same_at_end < ZV_BYTE
3831 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3832 same_at_end++;
3834 /* Don't try to reuse the same piece of text twice. */
3835 overlap = (same_at_start - BEGV_BYTE
3836 - (same_at_end
3837 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3838 if (overlap > 0)
3839 same_at_end += overlap;
3840 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3842 /* Arrange to read only the nonmatching middle part of the file. */
3843 beg_offset += same_at_start - BEGV_BYTE;
3844 end_offset -= ZV_BYTE - same_at_end;
3846 invalidate_buffer_caches (current_buffer,
3847 BYTE_TO_CHAR (same_at_start),
3848 same_at_end_charpos);
3849 del_range_byte (same_at_start, same_at_end, 0);
3850 /* Insert from the file at the proper position. */
3851 temp = BYTE_TO_CHAR (same_at_start);
3852 SET_PT_BOTH (temp, same_at_start);
3854 /* If display currently starts at beginning of line,
3855 keep it that way. */
3856 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3857 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3859 replace_handled = true;
3863 /* If requested, replace the accessible part of the buffer
3864 with the file contents. Avoid replacing text at the
3865 beginning or end of the buffer that matches the file contents;
3866 that preserves markers pointing to the unchanged parts.
3868 Here we implement this feature for the case where code conversion
3869 is needed, in a simple way that needs a lot of memory.
3870 The preceding if-statement handles the case of no conversion
3871 in a more optimized way. */
3872 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3874 ptrdiff_t same_at_start_charpos;
3875 ptrdiff_t inserted_chars;
3876 ptrdiff_t overlap;
3877 ptrdiff_t bufpos;
3878 unsigned char *decoded;
3879 ptrdiff_t temp;
3880 ptrdiff_t this = 0;
3881 ptrdiff_t this_count = SPECPDL_INDEX ();
3882 bool multibyte
3883 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3884 Lisp_Object conversion_buffer;
3885 struct gcpro gcpro1;
3887 conversion_buffer = code_conversion_save (1, multibyte);
3889 /* First read the whole file, performing code conversion into
3890 CONVERSION_BUFFER. */
3892 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3893 report_file_error ("Setting file position", orig_filename);
3895 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3896 unprocessed = 0; /* Bytes not processed in previous loop. */
3898 GCPRO1 (conversion_buffer);
3899 while (1)
3901 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3902 quitting while reading a huge file. */
3904 /* Allow quitting out of the actual I/O. */
3905 immediate_quit = 1;
3906 QUIT;
3907 this = emacs_read (fd, read_buf + unprocessed,
3908 READ_BUF_SIZE - unprocessed);
3909 immediate_quit = 0;
3911 if (this <= 0)
3912 break;
3914 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3915 BUF_Z (XBUFFER (conversion_buffer)));
3916 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3917 unprocessed + this, conversion_buffer);
3918 unprocessed = coding.carryover_bytes;
3919 if (coding.carryover_bytes > 0)
3920 memcpy (read_buf, coding.carryover, unprocessed);
3922 UNGCPRO;
3923 if (this < 0)
3924 report_file_error ("Read error", orig_filename);
3925 emacs_close (fd);
3926 clear_unwind_protect (fd_index);
3928 if (unprocessed > 0)
3930 coding.mode |= CODING_MODE_LAST_BLOCK;
3931 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3932 unprocessed, conversion_buffer);
3933 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3936 coding_system = CODING_ID_NAME (coding.id);
3937 set_coding_system = true;
3938 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3939 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3940 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3942 /* Compare the beginning of the converted string with the buffer
3943 text. */
3945 bufpos = 0;
3946 while (bufpos < inserted && same_at_start < same_at_end
3947 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3948 same_at_start++, bufpos++;
3950 /* If the file matches the head of buffer completely,
3951 there's no need to replace anything. */
3953 if (bufpos == inserted)
3955 /* Truncate the buffer to the size of the file. */
3956 if (same_at_start != same_at_end)
3958 invalidate_buffer_caches (current_buffer,
3959 BYTE_TO_CHAR (same_at_start),
3960 BYTE_TO_CHAR (same_at_end));
3961 del_range_byte (same_at_start, same_at_end, 0);
3963 inserted = 0;
3965 unbind_to (this_count, Qnil);
3966 goto handled;
3969 /* Extend the start of non-matching text area to the previous
3970 multibyte character boundary. */
3971 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3972 while (same_at_start > BEGV_BYTE
3973 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3974 same_at_start--;
3976 /* Scan this bufferful from the end, comparing with
3977 the Emacs buffer. */
3978 bufpos = inserted;
3980 /* Compare with same_at_start to avoid counting some buffer text
3981 as matching both at the file's beginning and at the end. */
3982 while (bufpos > 0 && same_at_end > same_at_start
3983 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3984 same_at_end--, bufpos--;
3986 /* Extend the end of non-matching text area to the next
3987 multibyte character boundary. */
3988 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3989 while (same_at_end < ZV_BYTE
3990 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3991 same_at_end++;
3993 /* Don't try to reuse the same piece of text twice. */
3994 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3995 if (overlap > 0)
3996 same_at_end += overlap;
3997 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3999 /* If display currently starts at beginning of line,
4000 keep it that way. */
4001 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4002 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4004 /* Replace the chars that we need to replace,
4005 and update INSERTED to equal the number of bytes
4006 we are taking from the decoded string. */
4007 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4009 if (same_at_end != same_at_start)
4011 invalidate_buffer_caches (current_buffer,
4012 BYTE_TO_CHAR (same_at_start),
4013 same_at_end_charpos);
4014 del_range_byte (same_at_start, same_at_end, 0);
4015 temp = GPT;
4016 eassert (same_at_start == GPT_BYTE);
4017 same_at_start = GPT_BYTE;
4019 else
4021 temp = same_at_end_charpos;
4023 /* Insert from the file at the proper position. */
4024 SET_PT_BOTH (temp, same_at_start);
4025 same_at_start_charpos
4026 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4027 same_at_start - BEGV_BYTE
4028 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4029 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4030 inserted_chars
4031 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4032 same_at_start + inserted - BEGV_BYTE
4033 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4034 - same_at_start_charpos);
4035 /* This binding is to avoid ask-user-about-supersession-threat
4036 being called in insert_from_buffer (via in
4037 prepare_to_modify_buffer). */
4038 specbind (intern ("buffer-file-name"), Qnil);
4039 insert_from_buffer (XBUFFER (conversion_buffer),
4040 same_at_start_charpos, inserted_chars, 0);
4041 /* Set `inserted' to the number of inserted characters. */
4042 inserted = PT - temp;
4043 /* Set point before the inserted characters. */
4044 SET_PT_BOTH (temp, same_at_start);
4046 unbind_to (this_count, Qnil);
4048 goto handled;
4051 if (! not_regular)
4052 total = end_offset - beg_offset;
4053 else
4054 /* For a special file, all we can do is guess. */
4055 total = READ_BUF_SIZE;
4057 if (NILP (visit) && total > 0)
4059 if (!NILP (BVAR (current_buffer, file_truename))
4060 /* Make binding buffer-file-name to nil effective. */
4061 && !NILP (BVAR (current_buffer, filename))
4062 && SAVE_MODIFF >= MODIFF)
4063 we_locked_file = true;
4064 prepare_to_modify_buffer (PT, PT, NULL);
4067 move_gap_both (PT, PT_BYTE);
4068 if (GAP_SIZE < total)
4069 make_gap (total - GAP_SIZE);
4071 if (beg_offset != 0 || !NILP (replace))
4073 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4074 report_file_error ("Setting file position", orig_filename);
4077 /* In the following loop, HOW_MUCH contains the total bytes read so
4078 far for a regular file, and not changed for a special file. But,
4079 before exiting the loop, it is set to a negative value if I/O
4080 error occurs. */
4081 how_much = 0;
4083 /* Total bytes inserted. */
4084 inserted = 0;
4086 /* Here, we don't do code conversion in the loop. It is done by
4087 decode_coding_gap after all data are read into the buffer. */
4089 ptrdiff_t gap_size = GAP_SIZE;
4091 while (how_much < total)
4093 /* `try' is reserved in some compilers (Microsoft C). */
4094 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4095 ptrdiff_t this;
4097 if (not_regular)
4099 Lisp_Object nbytes;
4101 /* Maybe make more room. */
4102 if (gap_size < trytry)
4104 make_gap (trytry - gap_size);
4105 gap_size = GAP_SIZE - inserted;
4108 /* Read from the file, capturing `quit'. When an
4109 error occurs, end the loop, and arrange for a quit
4110 to be signaled after decoding the text we read. */
4111 nbytes = internal_condition_case_1
4112 (read_non_regular,
4113 make_save_int_int_int (fd, inserted, trytry),
4114 Qerror, read_non_regular_quit);
4116 if (NILP (nbytes))
4118 read_quit = true;
4119 break;
4122 this = XINT (nbytes);
4124 else
4126 /* Allow quitting out of the actual I/O. We don't make text
4127 part of the buffer until all the reading is done, so a C-g
4128 here doesn't do any harm. */
4129 immediate_quit = 1;
4130 QUIT;
4131 this = emacs_read (fd,
4132 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4133 + inserted),
4134 trytry);
4135 immediate_quit = 0;
4138 if (this <= 0)
4140 how_much = this;
4141 break;
4144 gap_size -= this;
4146 /* For a regular file, where TOTAL is the real size,
4147 count HOW_MUCH to compare with it.
4148 For a special file, where TOTAL is just a buffer size,
4149 so don't bother counting in HOW_MUCH.
4150 (INSERTED is where we count the number of characters inserted.) */
4151 if (! not_regular)
4152 how_much += this;
4153 inserted += this;
4157 /* Now we have either read all the file data into the gap,
4158 or stop reading on I/O error or quit. If nothing was
4159 read, undo marking the buffer modified. */
4161 if (inserted == 0)
4163 if (we_locked_file)
4164 unlock_file (BVAR (current_buffer, file_truename));
4165 Vdeactivate_mark = old_Vdeactivate_mark;
4167 else
4168 Fset (Qdeactivate_mark, Qt);
4170 emacs_close (fd);
4171 clear_unwind_protect (fd_index);
4173 if (how_much < 0)
4174 report_file_error ("Read error", orig_filename);
4176 /* Make the text read part of the buffer. */
4177 GAP_SIZE -= inserted;
4178 GPT += inserted;
4179 GPT_BYTE += inserted;
4180 ZV += inserted;
4181 ZV_BYTE += inserted;
4182 Z += inserted;
4183 Z_BYTE += inserted;
4185 if (GAP_SIZE > 0)
4186 /* Put an anchor to ensure multi-byte form ends at gap. */
4187 *GPT_ADDR = 0;
4189 notfound:
4191 if (NILP (coding_system))
4193 /* The coding system is not yet decided. Decide it by an
4194 optimized method for handling `coding:' tag.
4196 Note that we can get here only if the buffer was empty
4197 before the insertion. */
4199 if (!NILP (Vcoding_system_for_read))
4200 coding_system = Vcoding_system_for_read;
4201 else
4203 /* Since we are sure that the current buffer was empty
4204 before the insertion, we can toggle
4205 enable-multibyte-characters directly here without taking
4206 care of marker adjustment. By this way, we can run Lisp
4207 program safely before decoding the inserted text. */
4208 Lisp_Object unwind_data;
4209 ptrdiff_t count1 = SPECPDL_INDEX ();
4211 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4212 Fcons (BVAR (current_buffer, undo_list),
4213 Fcurrent_buffer ()));
4214 bset_enable_multibyte_characters (current_buffer, Qnil);
4215 bset_undo_list (current_buffer, Qt);
4216 record_unwind_protect (decide_coding_unwind, unwind_data);
4218 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4220 coding_system = call2 (Vset_auto_coding_function,
4221 filename, make_number (inserted));
4224 if (NILP (coding_system))
4226 /* If the coding system is not yet decided, check
4227 file-coding-system-alist. */
4228 coding_system = CALLN (Ffind_operation_coding_system,
4229 Qinsert_file_contents, orig_filename,
4230 visit, beg, end, Qnil);
4231 if (CONSP (coding_system))
4232 coding_system = XCAR (coding_system);
4234 unbind_to (count1, Qnil);
4235 inserted = Z_BYTE - BEG_BYTE;
4238 if (NILP (coding_system))
4239 coding_system = Qundecided;
4240 else
4241 CHECK_CODING_SYSTEM (coding_system);
4243 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4244 /* We must suppress all character code conversion except for
4245 end-of-line conversion. */
4246 coding_system = raw_text_coding_system (coding_system);
4247 setup_coding_system (coding_system, &coding);
4248 /* Ensure we set Vlast_coding_system_used. */
4249 set_coding_system = true;
4252 if (!NILP (visit))
4254 /* When we visit a file by raw-text, we change the buffer to
4255 unibyte. */
4256 if (CODING_FOR_UNIBYTE (&coding)
4257 /* Can't do this if part of the buffer might be preserved. */
4258 && NILP (replace))
4259 /* Visiting a file with these coding system makes the buffer
4260 unibyte. */
4261 bset_enable_multibyte_characters (current_buffer, Qnil);
4264 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4265 if (CODING_MAY_REQUIRE_DECODING (&coding)
4266 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4268 move_gap_both (PT, PT_BYTE);
4269 GAP_SIZE += inserted;
4270 ZV_BYTE -= inserted;
4271 Z_BYTE -= inserted;
4272 ZV -= inserted;
4273 Z -= inserted;
4274 decode_coding_gap (&coding, inserted, inserted);
4275 inserted = coding.produced_char;
4276 coding_system = CODING_ID_NAME (coding.id);
4278 else if (inserted > 0)
4280 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4281 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4282 inserted);
4285 /* Call after-change hooks for the inserted text, aside from the case
4286 of normal visiting (not with REPLACE), which is done in a new buffer
4287 "before" the buffer is changed. */
4288 if (inserted > 0 && total > 0
4289 && (NILP (visit) || !NILP (replace)))
4291 signal_after_change (PT, 0, inserted);
4292 update_compositions (PT, PT, CHECK_BORDER);
4295 /* Now INSERTED is measured in characters. */
4297 handled:
4299 if (inserted > 0)
4300 restore_window_points (window_markers, inserted,
4301 BYTE_TO_CHAR (same_at_start),
4302 same_at_end_charpos);
4304 if (!NILP (visit))
4306 if (empty_undo_list_p)
4307 bset_undo_list (current_buffer, Qnil);
4309 if (NILP (handler))
4311 current_buffer->modtime = mtime;
4312 current_buffer->modtime_size = st.st_size;
4313 bset_filename (current_buffer, orig_filename);
4316 SAVE_MODIFF = MODIFF;
4317 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4318 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4319 if (NILP (handler))
4321 if (!NILP (BVAR (current_buffer, file_truename)))
4322 unlock_file (BVAR (current_buffer, file_truename));
4323 unlock_file (filename);
4325 if (not_regular)
4326 xsignal2 (Qfile_error,
4327 build_string ("not a regular file"), orig_filename);
4330 if (set_coding_system)
4331 Vlast_coding_system_used = coding_system;
4333 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4335 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4336 visit);
4337 if (! NILP (insval))
4339 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4340 wrong_type_argument (intern ("inserted-chars"), insval);
4341 inserted = XFASTINT (insval);
4345 /* Decode file format. */
4346 if (inserted > 0)
4348 /* Don't run point motion or modification hooks when decoding. */
4349 ptrdiff_t count1 = SPECPDL_INDEX ();
4350 ptrdiff_t old_inserted = inserted;
4351 specbind (Qinhibit_point_motion_hooks, Qt);
4352 specbind (Qinhibit_modification_hooks, Qt);
4354 /* Save old undo list and don't record undo for decoding. */
4355 old_undo = BVAR (current_buffer, undo_list);
4356 bset_undo_list (current_buffer, Qt);
4358 if (NILP (replace))
4360 insval = call3 (Qformat_decode,
4361 Qnil, make_number (inserted), visit);
4362 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4363 wrong_type_argument (intern ("inserted-chars"), insval);
4364 inserted = XFASTINT (insval);
4366 else
4368 /* If REPLACE is non-nil and we succeeded in not replacing the
4369 beginning or end of the buffer text with the file's contents,
4370 call format-decode with `point' positioned at the beginning
4371 of the buffer and `inserted' equaling the number of
4372 characters in the buffer. Otherwise, format-decode might
4373 fail to correctly analyze the beginning or end of the buffer.
4374 Hence we temporarily save `point' and `inserted' here and
4375 restore `point' iff format-decode did not insert or delete
4376 any text. Otherwise we leave `point' at point-min. */
4377 ptrdiff_t opoint = PT;
4378 ptrdiff_t opoint_byte = PT_BYTE;
4379 ptrdiff_t oinserted = ZV - BEGV;
4380 EMACS_INT ochars_modiff = CHARS_MODIFF;
4382 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4383 insval = call3 (Qformat_decode,
4384 Qnil, make_number (oinserted), visit);
4385 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4386 wrong_type_argument (intern ("inserted-chars"), insval);
4387 if (ochars_modiff == CHARS_MODIFF)
4388 /* format_decode didn't modify buffer's characters => move
4389 point back to position before inserted text and leave
4390 value of inserted alone. */
4391 SET_PT_BOTH (opoint, opoint_byte);
4392 else
4393 /* format_decode modified buffer's characters => consider
4394 entire buffer changed and leave point at point-min. */
4395 inserted = XFASTINT (insval);
4398 /* For consistency with format-decode call these now iff inserted > 0
4399 (martin 2007-06-28). */
4400 p = Vafter_insert_file_functions;
4401 while (CONSP (p))
4403 if (NILP (replace))
4405 insval = call1 (XCAR (p), make_number (inserted));
4406 if (!NILP (insval))
4408 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4409 wrong_type_argument (intern ("inserted-chars"), insval);
4410 inserted = XFASTINT (insval);
4413 else
4415 /* For the rationale of this see the comment on
4416 format-decode above. */
4417 ptrdiff_t opoint = PT;
4418 ptrdiff_t opoint_byte = PT_BYTE;
4419 ptrdiff_t oinserted = ZV - BEGV;
4420 EMACS_INT ochars_modiff = CHARS_MODIFF;
4422 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4423 insval = call1 (XCAR (p), make_number (oinserted));
4424 if (!NILP (insval))
4426 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4427 wrong_type_argument (intern ("inserted-chars"), insval);
4428 if (ochars_modiff == CHARS_MODIFF)
4429 /* after_insert_file_functions didn't modify
4430 buffer's characters => move point back to
4431 position before inserted text and leave value of
4432 inserted alone. */
4433 SET_PT_BOTH (opoint, opoint_byte);
4434 else
4435 /* after_insert_file_functions did modify buffer's
4436 characters => consider entire buffer changed and
4437 leave point at point-min. */
4438 inserted = XFASTINT (insval);
4442 QUIT;
4443 p = XCDR (p);
4446 if (!empty_undo_list_p)
4448 bset_undo_list (current_buffer, old_undo);
4449 if (CONSP (old_undo) && inserted != old_inserted)
4451 /* Adjust the last undo record for the size change during
4452 the format conversion. */
4453 Lisp_Object tem = XCAR (old_undo);
4454 if (CONSP (tem) && INTEGERP (XCAR (tem))
4455 && INTEGERP (XCDR (tem))
4456 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4457 XSETCDR (tem, make_number (PT + inserted));
4460 else
4461 /* If undo_list was Qt before, keep it that way.
4462 Otherwise start with an empty undo_list. */
4463 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4465 unbind_to (count1, Qnil);
4468 if (!NILP (visit)
4469 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4471 /* If visiting nonexistent file, return nil. */
4472 report_file_errno ("Opening input file", orig_filename, save_errno);
4475 /* We made a lot of deletions and insertions above, so invalidate
4476 the newline cache for the entire region of the inserted
4477 characters. */
4478 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4479 invalidate_region_cache (current_buffer->base_buffer,
4480 current_buffer->base_buffer->newline_cache,
4481 PT - BEG, Z - PT - inserted);
4482 else if (current_buffer->newline_cache)
4483 invalidate_region_cache (current_buffer,
4484 current_buffer->newline_cache,
4485 PT - BEG, Z - PT - inserted);
4487 if (read_quit)
4488 Fsignal (Qquit, Qnil);
4490 /* Retval needs to be dealt with in all cases consistently. */
4491 if (NILP (val))
4492 val = list2 (orig_filename, make_number (inserted));
4494 RETURN_UNGCPRO (unbind_to (count, val));
4497 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4499 static void
4500 build_annotations_unwind (Lisp_Object arg)
4502 Vwrite_region_annotation_buffers = arg;
4505 /* Decide the coding-system to encode the data with. */
4507 static Lisp_Object
4508 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4509 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4510 struct coding_system *coding)
4512 Lisp_Object val;
4513 Lisp_Object eol_parent = Qnil;
4515 if (auto_saving
4516 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4517 BVAR (current_buffer, auto_save_file_name))))
4519 val = Qutf_8_emacs;
4520 eol_parent = Qunix;
4522 else if (!NILP (Vcoding_system_for_write))
4524 val = Vcoding_system_for_write;
4525 if (coding_system_require_warning
4526 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4527 /* Confirm that VAL can surely encode the current region. */
4528 val = call5 (Vselect_safe_coding_system_function,
4529 start, end, list2 (Qt, val),
4530 Qnil, filename);
4532 else
4534 /* If the variable `buffer-file-coding-system' is set locally,
4535 it means that the file was read with some kind of code
4536 conversion or the variable is explicitly set by users. We
4537 had better write it out with the same coding system even if
4538 `enable-multibyte-characters' is nil.
4540 If it is not set locally, we anyway have to convert EOL
4541 format if the default value of `buffer-file-coding-system'
4542 tells that it is not Unix-like (LF only) format. */
4543 bool using_default_coding = 0;
4544 bool force_raw_text = 0;
4546 val = BVAR (current_buffer, buffer_file_coding_system);
4547 if (NILP (val)
4548 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4550 val = Qnil;
4551 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4552 force_raw_text = 1;
4555 if (NILP (val))
4557 /* Check file-coding-system-alist. */
4558 Lisp_Object coding_systems
4559 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4560 filename, append, visit, lockname);
4561 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4562 val = XCDR (coding_systems);
4565 if (NILP (val))
4567 /* If we still have not decided a coding system, use the
4568 default value of buffer-file-coding-system. */
4569 val = BVAR (current_buffer, buffer_file_coding_system);
4570 using_default_coding = 1;
4573 if (! NILP (val) && ! force_raw_text)
4575 Lisp_Object spec, attrs;
4577 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4578 attrs = AREF (spec, 0);
4579 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4580 force_raw_text = 1;
4583 if (!force_raw_text
4584 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4585 /* Confirm that VAL can surely encode the current region. */
4586 val = call5 (Vselect_safe_coding_system_function,
4587 start, end, val, Qnil, filename);
4589 /* If the decided coding-system doesn't specify end-of-line
4590 format, we use that of
4591 `default-buffer-file-coding-system'. */
4592 if (! using_default_coding
4593 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4594 val = (coding_inherit_eol_type
4595 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4597 /* If we decide not to encode text, use `raw-text' or one of its
4598 subsidiaries. */
4599 if (force_raw_text)
4600 val = raw_text_coding_system (val);
4603 val = coding_inherit_eol_type (val, eol_parent);
4604 setup_coding_system (val, coding);
4606 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4607 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4608 return val;
4611 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4612 "r\nFWrite region to file: \ni\ni\ni\np",
4613 doc: /* Write current region into specified file.
4614 When called from a program, requires three arguments:
4615 START, END and FILENAME. START and END are normally buffer positions
4616 specifying the part of the buffer to write.
4617 If START is nil, that means to use the entire buffer contents.
4618 If START is a string, then output that string to the file
4619 instead of any buffer contents; END is ignored.
4621 Optional fourth argument APPEND if non-nil means
4622 append to existing file contents (if any). If it is a number,
4623 seek to that offset in the file before writing.
4624 Optional fifth argument VISIT, if t or a string, means
4625 set the last-save-file-modtime of buffer to this file's modtime
4626 and mark buffer not modified.
4627 If VISIT is a string, it is a second file name;
4628 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4629 VISIT is also the file name to lock and unlock for clash detection.
4630 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4631 do not display the \"Wrote file\" message.
4632 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4633 use for locking and unlocking, overriding FILENAME and VISIT.
4634 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4635 for an existing file with the same name. If MUSTBENEW is `excl',
4636 that means to get an error if the file already exists; never overwrite.
4637 If MUSTBENEW is neither nil nor `excl', that means ask for
4638 confirmation before overwriting, but do go ahead and overwrite the file
4639 if the user confirms.
4641 This does code conversion according to the value of
4642 `coding-system-for-write', `buffer-file-coding-system', or
4643 `file-coding-system-alist', and sets the variable
4644 `last-coding-system-used' to the coding system actually used.
4646 This calls `write-region-annotate-functions' at the start, and
4647 `write-region-post-annotation-function' at the end. */)
4648 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4649 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4651 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4652 -1);
4655 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4656 descriptor for FILENAME, so do not open or close FILENAME. */
4658 Lisp_Object
4659 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4660 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4661 Lisp_Object mustbenew, int desc)
4663 int open_flags;
4664 int mode;
4665 off_t offset IF_LINT (= 0);
4666 bool open_and_close_file = desc < 0;
4667 bool ok;
4668 int save_errno = 0;
4669 const char *fn;
4670 struct stat st;
4671 struct timespec modtime;
4672 ptrdiff_t count = SPECPDL_INDEX ();
4673 ptrdiff_t count1 IF_LINT (= 0);
4674 Lisp_Object handler;
4675 Lisp_Object visit_file;
4676 Lisp_Object annotations;
4677 Lisp_Object encoded_filename;
4678 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4679 bool quietly = !NILP (visit);
4680 bool file_locked = 0;
4681 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4682 struct buffer *given_buffer;
4683 struct coding_system coding;
4685 if (current_buffer->base_buffer && visiting)
4686 error ("Cannot do file visiting in an indirect buffer");
4688 if (!NILP (start) && !STRINGP (start))
4689 validate_region (&start, &end);
4691 visit_file = Qnil;
4692 GCPRO5 (start, filename, visit, visit_file, lockname);
4694 filename = Fexpand_file_name (filename, Qnil);
4696 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4697 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4699 if (STRINGP (visit))
4700 visit_file = Fexpand_file_name (visit, Qnil);
4701 else
4702 visit_file = filename;
4704 if (NILP (lockname))
4705 lockname = visit_file;
4707 annotations = Qnil;
4709 /* If the file name has special constructs in it,
4710 call the corresponding file handler. */
4711 handler = Ffind_file_name_handler (filename, Qwrite_region);
4712 /* If FILENAME has no handler, see if VISIT has one. */
4713 if (NILP (handler) && STRINGP (visit))
4714 handler = Ffind_file_name_handler (visit, Qwrite_region);
4716 if (!NILP (handler))
4718 Lisp_Object val;
4719 val = call6 (handler, Qwrite_region, start, end,
4720 filename, append, visit);
4722 if (visiting)
4724 SAVE_MODIFF = MODIFF;
4725 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4726 bset_filename (current_buffer, visit_file);
4728 UNGCPRO;
4729 return val;
4732 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4734 /* Special kludge to simplify auto-saving. */
4735 if (NILP (start))
4737 /* Do it later, so write-region-annotate-function can work differently
4738 if we save "the buffer" vs "a region".
4739 This is useful in tar-mode. --Stef
4740 XSETFASTINT (start, BEG);
4741 XSETFASTINT (end, Z); */
4742 Fwiden ();
4745 record_unwind_protect (build_annotations_unwind,
4746 Vwrite_region_annotation_buffers);
4747 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4749 given_buffer = current_buffer;
4751 if (!STRINGP (start))
4753 annotations = build_annotations (start, end);
4755 if (current_buffer != given_buffer)
4757 XSETFASTINT (start, BEGV);
4758 XSETFASTINT (end, ZV);
4762 if (NILP (start))
4764 XSETFASTINT (start, BEGV);
4765 XSETFASTINT (end, ZV);
4768 UNGCPRO;
4770 GCPRO5 (start, filename, annotations, visit_file, lockname);
4772 /* Decide the coding-system to encode the data with.
4773 We used to make this choice before calling build_annotations, but that
4774 leads to problems when a write-annotate-function takes care of
4775 unsavable chars (as was the case with X-Symbol). */
4776 Vlast_coding_system_used
4777 = choose_write_coding_system (start, end, filename,
4778 append, visit, lockname, &coding);
4780 if (open_and_close_file && !auto_saving)
4782 lock_file (lockname);
4783 file_locked = 1;
4786 encoded_filename = ENCODE_FILE (filename);
4787 fn = SSDATA (encoded_filename);
4788 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4789 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4790 if (NUMBERP (append))
4791 offset = file_offset (append);
4792 else if (!NILP (append))
4793 open_flags |= O_APPEND;
4794 #ifdef DOS_NT
4795 mode = S_IREAD | S_IWRITE;
4796 #else
4797 mode = auto_saving ? auto_save_mode_bits : 0666;
4798 #endif
4800 if (open_and_close_file)
4802 desc = emacs_open (fn, open_flags, mode);
4803 if (desc < 0)
4805 int open_errno = errno;
4806 if (file_locked)
4807 unlock_file (lockname);
4808 UNGCPRO;
4809 report_file_errno ("Opening output file", filename, open_errno);
4812 count1 = SPECPDL_INDEX ();
4813 record_unwind_protect_int (close_file_unwind, desc);
4816 if (NUMBERP (append))
4818 off_t ret = lseek (desc, offset, SEEK_SET);
4819 if (ret < 0)
4821 int lseek_errno = errno;
4822 if (file_locked)
4823 unlock_file (lockname);
4824 UNGCPRO;
4825 report_file_errno ("Lseek error", filename, lseek_errno);
4829 UNGCPRO;
4831 immediate_quit = 1;
4833 if (STRINGP (start))
4834 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4835 else if (XINT (start) != XINT (end))
4836 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4837 &annotations, &coding);
4838 else
4840 /* If file was empty, still need to write the annotations. */
4841 coding.mode |= CODING_MODE_LAST_BLOCK;
4842 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4844 save_errno = errno;
4846 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4847 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4849 /* We have to flush out a data. */
4850 coding.mode |= CODING_MODE_LAST_BLOCK;
4851 ok = e_write (desc, Qnil, 1, 1, &coding);
4852 save_errno = errno;
4855 immediate_quit = 0;
4857 /* fsync is not crucial for temporary files. Nor for auto-save
4858 files, since they might lose some work anyway. */
4859 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4861 /* Transfer data and metadata to disk, retrying if interrupted.
4862 fsync can report a write failure here, e.g., due to disk full
4863 under NFS. But ignore EINVAL, which means fsync is not
4864 supported on this file. */
4865 while (fsync (desc) != 0)
4866 if (errno != EINTR)
4868 if (errno != EINVAL)
4869 ok = 0, save_errno = errno;
4870 break;
4874 modtime = invalid_timespec ();
4875 if (visiting)
4877 if (fstat (desc, &st) == 0)
4878 modtime = get_stat_mtime (&st);
4879 else
4880 ok = 0, save_errno = errno;
4883 if (open_and_close_file)
4885 /* NFS can report a write failure now. */
4886 if (emacs_close (desc) < 0)
4887 ok = 0, save_errno = errno;
4889 /* Discard the unwind protect for close_file_unwind. */
4890 specpdl_ptr = specpdl + count1;
4893 /* Some file systems have a bug where st_mtime is not updated
4894 properly after a write. For example, CIFS might not see the
4895 st_mtime change until after the file is opened again.
4897 Attempt to detect this file system bug, and update MODTIME to the
4898 newer st_mtime if the bug appears to be present. This introduces
4899 a race condition, so to avoid most instances of the race condition
4900 on non-buggy file systems, skip this check if the most recently
4901 encountered non-buggy file system was the current file system.
4903 A race condition can occur if some other process modifies the
4904 file between the fstat above and the fstat below, but the race is
4905 unlikely and a similar race between the last write and the fstat
4906 above cannot possibly be closed anyway. */
4908 if (timespec_valid_p (modtime)
4909 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4911 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4912 if (desc1 >= 0)
4914 struct stat st1;
4915 if (fstat (desc1, &st1) == 0
4916 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4918 /* Use the heuristic if it appears to be valid. With neither
4919 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4920 file, the time stamp won't change. Also, some non-POSIX
4921 systems don't update an empty file's time stamp when
4922 truncating it. Finally, file systems with 100 ns or worse
4923 resolution sometimes seem to have bugs: on a system with ns
4924 resolution, checking ns % 100 incorrectly avoids the heuristic
4925 1% of the time, but the problem should be temporary as we will
4926 try again on the next time stamp. */
4927 bool use_heuristic
4928 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4929 && st.st_size != 0
4930 && modtime.tv_nsec % 100 != 0);
4932 struct timespec modtime1 = get_stat_mtime (&st1);
4933 if (use_heuristic
4934 && timespec_cmp (modtime, modtime1) == 0
4935 && st.st_size == st1.st_size)
4937 timestamp_file_system = st.st_dev;
4938 valid_timestamp_file_system = 1;
4940 else
4942 st.st_size = st1.st_size;
4943 modtime = modtime1;
4946 emacs_close (desc1);
4950 /* Call write-region-post-annotation-function. */
4951 while (CONSP (Vwrite_region_annotation_buffers))
4953 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4954 if (!NILP (Fbuffer_live_p (buf)))
4956 Fset_buffer (buf);
4957 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4958 call0 (Vwrite_region_post_annotation_function);
4960 Vwrite_region_annotation_buffers
4961 = XCDR (Vwrite_region_annotation_buffers);
4964 unbind_to (count, Qnil);
4966 if (file_locked)
4967 unlock_file (lockname);
4969 /* Do this before reporting IO error
4970 to avoid a "file has changed on disk" warning on
4971 next attempt to save. */
4972 if (timespec_valid_p (modtime))
4974 current_buffer->modtime = modtime;
4975 current_buffer->modtime_size = st.st_size;
4978 if (! ok)
4979 report_file_errno ("Write error", filename, save_errno);
4981 if (visiting)
4983 SAVE_MODIFF = MODIFF;
4984 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4985 bset_filename (current_buffer, visit_file);
4986 update_mode_lines = 14;
4988 else if (quietly)
4990 if (auto_saving
4991 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
4992 BVAR (current_buffer, auto_save_file_name))))
4993 SAVE_MODIFF = MODIFF;
4995 return Qnil;
4998 if (!auto_saving && !noninteractive)
4999 message_with_string ((NUMBERP (append)
5000 ? "Updated %s"
5001 : ! NILP (append)
5002 ? "Added to %s"
5003 : "Wrote %s"),
5004 visit_file, 1);
5006 return Qnil;
5009 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5010 doc: /* Return t if (car A) is numerically less than (car B). */)
5011 (Lisp_Object a, Lisp_Object b)
5013 return CALLN (Flss, Fcar (a), Fcar (b));
5016 /* Build the complete list of annotations appropriate for writing out
5017 the text between START and END, by calling all the functions in
5018 write-region-annotate-functions and merging the lists they return.
5019 If one of these functions switches to a different buffer, we assume
5020 that buffer contains altered text. Therefore, the caller must
5021 make sure to restore the current buffer in all cases,
5022 as save-excursion would do. */
5024 static Lisp_Object
5025 build_annotations (Lisp_Object start, Lisp_Object end)
5027 Lisp_Object annotations;
5028 Lisp_Object p, res;
5029 struct gcpro gcpro1, gcpro2;
5030 Lisp_Object original_buffer;
5031 int i;
5032 bool used_global = false;
5034 XSETBUFFER (original_buffer, current_buffer);
5036 annotations = Qnil;
5037 p = Vwrite_region_annotate_functions;
5038 GCPRO2 (annotations, p);
5039 while (CONSP (p))
5041 struct buffer *given_buffer = current_buffer;
5042 if (EQ (Qt, XCAR (p)) && !used_global)
5043 { /* Use the global value of the hook. */
5044 used_global = true;
5045 p = CALLN (Fappend,
5046 Fdefault_value (Qwrite_region_annotate_functions),
5047 XCDR (p));
5048 continue;
5050 Vwrite_region_annotations_so_far = annotations;
5051 res = call2 (XCAR (p), start, end);
5052 /* If the function makes a different buffer current,
5053 assume that means this buffer contains altered text to be output.
5054 Reset START and END from the buffer bounds
5055 and discard all previous annotations because they should have
5056 been dealt with by this function. */
5057 if (current_buffer != given_buffer)
5059 Vwrite_region_annotation_buffers
5060 = Fcons (Fcurrent_buffer (),
5061 Vwrite_region_annotation_buffers);
5062 XSETFASTINT (start, BEGV);
5063 XSETFASTINT (end, ZV);
5064 annotations = Qnil;
5066 Flength (res); /* Check basic validity of return value */
5067 annotations = merge (annotations, res, Qcar_less_than_car);
5068 p = XCDR (p);
5071 /* Now do the same for annotation functions implied by the file-format */
5072 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5073 p = BVAR (current_buffer, auto_save_file_format);
5074 else
5075 p = BVAR (current_buffer, file_format);
5076 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5078 struct buffer *given_buffer = current_buffer;
5080 Vwrite_region_annotations_so_far = annotations;
5082 /* Value is either a list of annotations or nil if the function
5083 has written annotations to a temporary buffer, which is now
5084 current. */
5085 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5086 original_buffer, make_number (i));
5087 if (current_buffer != given_buffer)
5089 XSETFASTINT (start, BEGV);
5090 XSETFASTINT (end, ZV);
5091 annotations = Qnil;
5094 if (CONSP (res))
5095 annotations = merge (annotations, res, Qcar_less_than_car);
5098 UNGCPRO;
5099 return annotations;
5103 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5104 If STRING is nil, POS is the character position in the current buffer.
5105 Intersperse with them the annotations from *ANNOT
5106 which fall within the range of POS to POS + NCHARS,
5107 each at its appropriate position.
5109 We modify *ANNOT by discarding elements as we use them up.
5111 Return true if successful. */
5113 static bool
5114 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5115 ptrdiff_t nchars, Lisp_Object *annot,
5116 struct coding_system *coding)
5118 Lisp_Object tem;
5119 ptrdiff_t nextpos;
5120 ptrdiff_t lastpos = pos + nchars;
5122 while (NILP (*annot) || CONSP (*annot))
5124 tem = Fcar_safe (Fcar (*annot));
5125 nextpos = pos - 1;
5126 if (INTEGERP (tem))
5127 nextpos = XFASTINT (tem);
5129 /* If there are no more annotations in this range,
5130 output the rest of the range all at once. */
5131 if (! (nextpos >= pos && nextpos <= lastpos))
5132 return e_write (desc, string, pos, lastpos, coding);
5134 /* Output buffer text up to the next annotation's position. */
5135 if (nextpos > pos)
5137 if (!e_write (desc, string, pos, nextpos, coding))
5138 return 0;
5139 pos = nextpos;
5141 /* Output the annotation. */
5142 tem = Fcdr (Fcar (*annot));
5143 if (STRINGP (tem))
5145 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5146 return 0;
5148 *annot = Fcdr (*annot);
5150 return 1;
5153 /* Maximum number of characters that the next
5154 function encodes per one loop iteration. */
5156 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5158 /* Write text in the range START and END into descriptor DESC,
5159 encoding them with coding system CODING. If STRING is nil, START
5160 and END are character positions of the current buffer, else they
5161 are indexes to the string STRING. Return true if successful. */
5163 static bool
5164 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5165 struct coding_system *coding)
5167 if (STRINGP (string))
5169 start = 0;
5170 end = SCHARS (string);
5173 /* We used to have a code for handling selective display here. But,
5174 now it is handled within encode_coding. */
5176 while (start < end)
5178 if (STRINGP (string))
5180 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5181 if (CODING_REQUIRE_ENCODING (coding))
5183 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5185 /* Avoid creating huge Lisp string in encode_coding_object. */
5186 if (nchars == E_WRITE_MAX)
5187 coding->raw_destination = 1;
5189 encode_coding_object
5190 (coding, string, start, string_char_to_byte (string, start),
5191 start + nchars, string_char_to_byte (string, start + nchars),
5192 Qt);
5194 else
5196 coding->dst_object = string;
5197 coding->consumed_char = SCHARS (string);
5198 coding->produced = SBYTES (string);
5201 else
5203 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5204 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5206 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5207 if (CODING_REQUIRE_ENCODING (coding))
5209 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5211 /* Likewise. */
5212 if (nchars == E_WRITE_MAX)
5213 coding->raw_destination = 1;
5215 encode_coding_object
5216 (coding, Fcurrent_buffer (), start, start_byte,
5217 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5219 else
5221 coding->dst_object = Qnil;
5222 coding->dst_pos_byte = start_byte;
5223 if (start >= GPT || end <= GPT)
5225 coding->consumed_char = end - start;
5226 coding->produced = end_byte - start_byte;
5228 else
5230 coding->consumed_char = GPT - start;
5231 coding->produced = GPT_BYTE - start_byte;
5236 if (coding->produced > 0)
5238 char *buf = (coding->raw_destination ? (char *) coding->destination
5239 : (STRINGP (coding->dst_object)
5240 ? SSDATA (coding->dst_object)
5241 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5242 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5244 if (coding->raw_destination)
5246 /* We're responsible for freeing this, see
5247 encode_coding_object to check why. */
5248 xfree (coding->destination);
5249 coding->raw_destination = 0;
5251 if (coding->produced)
5252 return 0;
5254 start += coding->consumed_char;
5257 return 1;
5260 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5261 Sverify_visited_file_modtime, 0, 1, 0,
5262 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5263 This means that the file has not been changed since it was visited or saved.
5264 If BUF is omitted or nil, it defaults to the current buffer.
5265 See Info node `(elisp)Modification Time' for more details. */)
5266 (Lisp_Object buf)
5268 struct buffer *b = decode_buffer (buf);
5269 struct stat st;
5270 Lisp_Object handler;
5271 Lisp_Object filename;
5272 struct timespec mtime;
5274 if (!STRINGP (BVAR (b, filename))) return Qt;
5275 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5277 /* If the file name has special constructs in it,
5278 call the corresponding file handler. */
5279 handler = Ffind_file_name_handler (BVAR (b, filename),
5280 Qverify_visited_file_modtime);
5281 if (!NILP (handler))
5282 return call2 (handler, Qverify_visited_file_modtime, buf);
5284 filename = ENCODE_FILE (BVAR (b, filename));
5286 mtime = (stat (SSDATA (filename), &st) == 0
5287 ? get_stat_mtime (&st)
5288 : time_error_value (errno));
5289 if (timespec_cmp (mtime, b->modtime) == 0
5290 && (b->modtime_size < 0
5291 || st.st_size == b->modtime_size))
5292 return Qt;
5293 return Qnil;
5296 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5297 Svisited_file_modtime, 0, 0, 0,
5298 doc: /* Return the current buffer's recorded visited file modification time.
5299 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5300 `file-attributes' returns. If the current buffer has no recorded file
5301 modification time, this function returns 0. If the visited file
5302 doesn't exist, return -1.
5303 See Info node `(elisp)Modification Time' for more details. */)
5304 (void)
5306 int ns = current_buffer->modtime.tv_nsec;
5307 if (ns < 0)
5308 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5309 return make_lisp_time (current_buffer->modtime);
5312 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5313 Sset_visited_file_modtime, 0, 1, 0,
5314 doc: /* Update buffer's recorded modification time from the visited file's time.
5315 Useful if the buffer was not read from the file normally
5316 or if the file itself has been changed for some known benign reason.
5317 An argument specifies the modification time value to use
5318 \(instead of that of the visited file), in the form of a list
5319 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5320 `visited-file-modtime'. */)
5321 (Lisp_Object time_flag)
5323 if (!NILP (time_flag))
5325 struct timespec mtime;
5326 if (INTEGERP (time_flag))
5328 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5329 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5331 else
5332 mtime = lisp_time_argument (time_flag);
5334 current_buffer->modtime = mtime;
5335 current_buffer->modtime_size = -1;
5337 else
5339 register Lisp_Object filename;
5340 struct stat st;
5341 Lisp_Object handler;
5343 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5345 /* If the file name has special constructs in it,
5346 call the corresponding file handler. */
5347 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5348 if (!NILP (handler))
5349 /* The handler can find the file name the same way we did. */
5350 return call2 (handler, Qset_visited_file_modtime, Qnil);
5352 filename = ENCODE_FILE (filename);
5354 if (stat (SSDATA (filename), &st) >= 0)
5356 current_buffer->modtime = get_stat_mtime (&st);
5357 current_buffer->modtime_size = st.st_size;
5361 return Qnil;
5364 static Lisp_Object
5365 auto_save_error (Lisp_Object error_val)
5367 Lisp_Object msg;
5368 int i;
5369 struct gcpro gcpro1;
5371 auto_save_error_occurred = 1;
5373 ring_bell (XFRAME (selected_frame));
5375 AUTO_STRING (format, "Auto-saving %s: %s");
5376 msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5377 Ferror_message_string (error_val));
5378 GCPRO1 (msg);
5380 for (i = 0; i < 3; ++i)
5382 if (i == 0)
5383 message3 (msg);
5384 else
5385 message3_nolog (msg);
5386 Fsleep_for (make_number (1), Qnil);
5389 UNGCPRO;
5390 return Qnil;
5393 static Lisp_Object
5394 auto_save_1 (void)
5396 struct stat st;
5397 Lisp_Object modes;
5399 auto_save_mode_bits = 0666;
5401 /* Get visited file's mode to become the auto save file's mode. */
5402 if (! NILP (BVAR (current_buffer, filename)))
5404 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5405 /* But make sure we can overwrite it later! */
5406 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5407 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5408 INTEGERP (modes))
5409 /* Remote files don't cooperate with stat. */
5410 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5413 return
5414 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5415 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5416 Qnil, Qnil);
5419 struct auto_save_unwind
5421 FILE *stream;
5422 bool auto_raise;
5425 static void
5426 do_auto_save_unwind (void *arg)
5428 struct auto_save_unwind *p = arg;
5429 FILE *stream = p->stream;
5430 minibuffer_auto_raise = p->auto_raise;
5431 auto_saving = 0;
5432 if (stream != NULL)
5434 block_input ();
5435 fclose (stream);
5436 unblock_input ();
5440 static Lisp_Object
5441 do_auto_save_make_dir (Lisp_Object dir)
5443 Lisp_Object result;
5445 auto_saving_dir_umask = 077;
5446 result = call2 (Qmake_directory, dir, Qt);
5447 auto_saving_dir_umask = 0;
5448 return result;
5451 static Lisp_Object
5452 do_auto_save_eh (Lisp_Object ignore)
5454 auto_saving_dir_umask = 0;
5455 return Qnil;
5458 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5459 doc: /* Auto-save all buffers that need it.
5460 This is all buffers that have auto-saving enabled
5461 and are changed since last auto-saved.
5462 Auto-saving writes the buffer into a file
5463 so that your editing is not lost if the system crashes.
5464 This file is not the file you visited; that changes only when you save.
5465 Normally we run the normal hook `auto-save-hook' before saving.
5467 A non-nil NO-MESSAGE argument means do not print any message if successful.
5468 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5469 (Lisp_Object no_message, Lisp_Object current_only)
5471 struct buffer *old = current_buffer, *b;
5472 Lisp_Object tail, buf, hook;
5473 bool auto_saved = 0;
5474 int do_handled_files;
5475 Lisp_Object oquit;
5476 FILE *stream = NULL;
5477 ptrdiff_t count = SPECPDL_INDEX ();
5478 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5479 bool old_message_p = 0;
5480 struct auto_save_unwind auto_save_unwind;
5481 struct gcpro gcpro1, gcpro2;
5483 if (max_specpdl_size < specpdl_size + 40)
5484 max_specpdl_size = specpdl_size + 40;
5486 if (minibuf_level)
5487 no_message = Qt;
5489 if (NILP (no_message))
5491 old_message_p = push_message ();
5492 record_unwind_protect_void (pop_message_unwind);
5495 /* Ordinarily don't quit within this function,
5496 but don't make it impossible to quit (in case we get hung in I/O). */
5497 oquit = Vquit_flag;
5498 Vquit_flag = Qnil;
5500 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5501 point to non-strings reached from Vbuffer_alist. */
5503 hook = intern ("auto-save-hook");
5504 safe_run_hooks (hook);
5506 if (STRINGP (Vauto_save_list_file_name))
5508 Lisp_Object listfile;
5510 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5512 /* Don't try to create the directory when shutting down Emacs,
5513 because creating the directory might signal an error, and
5514 that would leave Emacs in a strange state. */
5515 if (!NILP (Vrun_hooks))
5517 Lisp_Object dir;
5518 dir = Qnil;
5519 GCPRO2 (dir, listfile);
5520 dir = Ffile_name_directory (listfile);
5521 if (NILP (Ffile_directory_p (dir)))
5522 internal_condition_case_1 (do_auto_save_make_dir,
5523 dir, Qt,
5524 do_auto_save_eh);
5525 UNGCPRO;
5528 stream = emacs_fopen (SSDATA (listfile), "w");
5531 auto_save_unwind.stream = stream;
5532 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5533 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5534 minibuffer_auto_raise = 0;
5535 auto_saving = 1;
5536 auto_save_error_occurred = 0;
5538 /* On first pass, save all files that don't have handlers.
5539 On second pass, save all files that do have handlers.
5541 If Emacs is crashing, the handlers may tweak what is causing
5542 Emacs to crash in the first place, and it would be a shame if
5543 Emacs failed to autosave perfectly ordinary files because it
5544 couldn't handle some ange-ftp'd file. */
5546 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5547 FOR_EACH_LIVE_BUFFER (tail, buf)
5549 b = XBUFFER (buf);
5551 /* Record all the buffers that have auto save mode
5552 in the special file that lists them. For each of these buffers,
5553 Record visited name (if any) and auto save name. */
5554 if (STRINGP (BVAR (b, auto_save_file_name))
5555 && stream != NULL && do_handled_files == 0)
5557 block_input ();
5558 if (!NILP (BVAR (b, filename)))
5560 fwrite (SDATA (BVAR (b, filename)), 1,
5561 SBYTES (BVAR (b, filename)), stream);
5563 putc ('\n', stream);
5564 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5565 SBYTES (BVAR (b, auto_save_file_name)), stream);
5566 putc ('\n', stream);
5567 unblock_input ();
5570 if (!NILP (current_only)
5571 && b != current_buffer)
5572 continue;
5574 /* Don't auto-save indirect buffers.
5575 The base buffer takes care of it. */
5576 if (b->base_buffer)
5577 continue;
5579 /* Check for auto save enabled
5580 and file changed since last auto save
5581 and file changed since last real save. */
5582 if (STRINGP (BVAR (b, auto_save_file_name))
5583 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5584 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5585 /* -1 means we've turned off autosaving for a while--see below. */
5586 && XINT (BVAR (b, save_length)) >= 0
5587 && (do_handled_files
5588 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5589 Qwrite_region))))
5591 struct timespec before_time = current_timespec ();
5592 struct timespec after_time;
5594 /* If we had a failure, don't try again for 20 minutes. */
5595 if (b->auto_save_failure_time > 0
5596 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5597 continue;
5599 set_buffer_internal (b);
5600 if (NILP (Vauto_save_include_big_deletions)
5601 && (XFASTINT (BVAR (b, save_length)) * 10
5602 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5603 /* A short file is likely to change a large fraction;
5604 spare the user annoying messages. */
5605 && XFASTINT (BVAR (b, save_length)) > 5000
5606 /* These messages are frequent and annoying for `*mail*'. */
5607 && !EQ (BVAR (b, filename), Qnil)
5608 && NILP (no_message))
5610 /* It has shrunk too much; turn off auto-saving here. */
5611 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5612 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5613 BVAR (b, name), 1);
5614 minibuffer_auto_raise = 0;
5615 /* Turn off auto-saving until there's a real save,
5616 and prevent any more warnings. */
5617 XSETINT (BVAR (b, save_length), -1);
5618 Fsleep_for (make_number (1), Qnil);
5619 continue;
5621 if (!auto_saved && NILP (no_message))
5622 message1 ("Auto-saving...");
5623 internal_condition_case (auto_save_1, Qt, auto_save_error);
5624 auto_saved = 1;
5625 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5626 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5627 set_buffer_internal (old);
5629 after_time = current_timespec ();
5631 /* If auto-save took more than 60 seconds,
5632 assume it was an NFS failure that got a timeout. */
5633 if (after_time.tv_sec - before_time.tv_sec > 60)
5634 b->auto_save_failure_time = after_time.tv_sec;
5638 /* Prevent another auto save till enough input events come in. */
5639 record_auto_save ();
5641 if (auto_saved && NILP (no_message))
5643 if (old_message_p)
5645 /* If we are going to restore an old message,
5646 give time to read ours. */
5647 sit_for (make_number (1), 0, 0);
5648 restore_message ();
5650 else if (!auto_save_error_occurred)
5651 /* Don't overwrite the error message if an error occurred.
5652 If we displayed a message and then restored a state
5653 with no message, leave a "done" message on the screen. */
5654 message1 ("Auto-saving...done");
5657 Vquit_flag = oquit;
5659 /* This restores the message-stack status. */
5660 unbind_to (count, Qnil);
5661 return Qnil;
5664 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5665 Sset_buffer_auto_saved, 0, 0, 0,
5666 doc: /* Mark current buffer as auto-saved with its current text.
5667 No auto-save file will be written until the buffer changes again. */)
5668 (void)
5670 /* FIXME: This should not be called in indirect buffers, since
5671 they're not autosaved. */
5672 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5673 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5674 current_buffer->auto_save_failure_time = 0;
5675 return Qnil;
5678 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5679 Sclear_buffer_auto_save_failure, 0, 0, 0,
5680 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5681 (void)
5683 current_buffer->auto_save_failure_time = 0;
5684 return Qnil;
5687 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5688 0, 0, 0,
5689 doc: /* Return t if current buffer has been auto-saved recently.
5690 More precisely, if it has been auto-saved since last read from or saved
5691 in the visited file. If the buffer has no visited file,
5692 then any auto-save counts as "recent". */)
5693 (void)
5695 /* FIXME: maybe we should return nil for indirect buffers since
5696 they're never autosaved. */
5697 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5700 /* Reading and completing file names. */
5702 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5703 Snext_read_file_uses_dialog_p, 0, 0, 0,
5704 doc: /* Return t if a call to `read-file-name' will use a dialog.
5705 The return value is only relevant for a call to `read-file-name' that happens
5706 before any other event (mouse or keypress) is handled. */)
5707 (void)
5709 #if (defined USE_GTK || defined USE_MOTIF \
5710 || defined HAVE_NS || defined HAVE_NTGUI)
5711 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5712 && use_dialog_box
5713 && use_file_dialog
5714 && window_system_available (SELECTED_FRAME ()))
5715 return Qt;
5716 #endif
5717 return Qnil;
5721 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5722 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5723 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5724 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5725 it to text mode.
5727 As a side effect, this function flushes any pending STREAM's data.
5729 Value is the previous value of STREAM's I/O mode, nil for text mode,
5730 non-nil for binary mode.
5732 On MS-Windows and MS-DOS, binary mode is needed to read or write
5733 arbitrary binary data, and for disabling translation between CR-LF
5734 pairs and a single newline character. Examples include generation
5735 of text files with Unix-style end-of-line format using `princ' in
5736 batch mode, with standard output redirected to a file.
5738 On Posix systems, this function always returns non-nil, and has no
5739 effect except for flushing STREAM's data. */)
5740 (Lisp_Object stream, Lisp_Object mode)
5742 FILE *fp = NULL;
5743 int binmode;
5745 CHECK_SYMBOL (stream);
5746 if (EQ (stream, Qstdin))
5747 fp = stdin;
5748 else if (EQ (stream, Qstdout))
5749 fp = stdout;
5750 else if (EQ (stream, Qstderr))
5751 fp = stderr;
5752 else
5753 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5755 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5756 if (fp != stdin)
5757 fflush (fp);
5759 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5762 void
5763 init_fileio (void)
5765 realmask = umask (0);
5766 umask (realmask);
5768 valid_timestamp_file_system = 0;
5770 /* fsync can be a significant performance hit. Often it doesn't
5771 suffice to make the file-save operation survive a crash. For
5772 batch scripts, which are typically part of larger shell commands
5773 that don't fsync other files, its effect on performance can be
5774 significant so its utility is particularly questionable.
5775 Hence, for now by default fsync is used only when interactive.
5777 For more on why fsync often fails to work on today's hardware, see:
5778 Zheng M et al. Understanding the robustness of SSDs under power fault.
5779 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5780 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5782 For more on why fsync does not suffice even if it works properly, see:
5783 Roche X. Necessary step(s) to synchronize filename operations on disk.
5784 Austin Group Defect 672, 2013-03-19
5785 http://austingroupbugs.net/view.php?id=672 */
5786 write_region_inhibit_fsync = noninteractive;
5789 void
5790 syms_of_fileio (void)
5792 /* Property name of a file name handler,
5793 which gives a list of operations it handles. */
5794 DEFSYM (Qoperations, "operations");
5796 DEFSYM (Qexpand_file_name, "expand-file-name");
5797 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5798 DEFSYM (Qdirectory_file_name, "directory-file-name");
5799 DEFSYM (Qfile_name_directory, "file-name-directory");
5800 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5801 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5802 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5803 DEFSYM (Qcopy_file, "copy-file");
5804 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5805 DEFSYM (Qmake_directory, "make-directory");
5806 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5807 DEFSYM (Qdelete_file, "delete-file");
5808 DEFSYM (Qrename_file, "rename-file");
5809 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5810 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5811 DEFSYM (Qfile_exists_p, "file-exists-p");
5812 DEFSYM (Qfile_executable_p, "file-executable-p");
5813 DEFSYM (Qfile_readable_p, "file-readable-p");
5814 DEFSYM (Qfile_writable_p, "file-writable-p");
5815 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5816 DEFSYM (Qaccess_file, "access-file");
5817 DEFSYM (Qfile_directory_p, "file-directory-p");
5818 DEFSYM (Qfile_regular_p, "file-regular-p");
5819 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5820 DEFSYM (Qfile_modes, "file-modes");
5821 DEFSYM (Qset_file_modes, "set-file-modes");
5822 DEFSYM (Qset_file_times, "set-file-times");
5823 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5824 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5825 DEFSYM (Qfile_acl, "file-acl");
5826 DEFSYM (Qset_file_acl, "set-file-acl");
5827 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5828 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5829 DEFSYM (Qwrite_region, "write-region");
5830 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5831 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5833 /* The symbol bound to coding-system-for-read when
5834 insert-file-contents is called for recovering a file. This is not
5835 an actual coding system name, but just an indicator to tell
5836 insert-file-contents to use `emacs-mule' with a special flag for
5837 auto saving and recovering a file. */
5838 DEFSYM (Qauto_save_coding, "auto-save-coding");
5840 DEFSYM (Qfile_name_history, "file-name-history");
5841 Fset (Qfile_name_history, Qnil);
5843 DEFSYM (Qfile_error, "file-error");
5844 DEFSYM (Qfile_already_exists, "file-already-exists");
5845 DEFSYM (Qfile_date_error, "file-date-error");
5846 DEFSYM (Qfile_notify_error, "file-notify-error");
5847 DEFSYM (Qexcl, "excl");
5849 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5850 doc: /* Coding system for encoding file names.
5851 If it is nil, `default-file-name-coding-system' (which see) is used.
5853 On MS-Windows, the value of this variable is largely ignored if
5854 \`w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5855 behaves as if file names were encoded in `utf-8'. */);
5856 Vfile_name_coding_system = Qnil;
5858 DEFVAR_LISP ("default-file-name-coding-system",
5859 Vdefault_file_name_coding_system,
5860 doc: /* Default coding system for encoding file names.
5861 This variable is used only when `file-name-coding-system' is nil.
5863 This variable is set/changed by the command `set-language-environment'.
5864 User should not set this variable manually,
5865 instead use `file-name-coding-system' to get a constant encoding
5866 of file names regardless of the current language environment.
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 Vdefault_file_name_coding_system = Qnil;
5873 /* Lisp functions for translating file formats. */
5874 DEFSYM (Qformat_decode, "format-decode");
5875 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5877 /* Lisp function for setting buffer-file-coding-system and the
5878 multibyteness of the current buffer after inserting a file. */
5879 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5881 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5883 Fput (Qfile_error, Qerror_conditions,
5884 Fpurecopy (list2 (Qfile_error, Qerror)));
5885 Fput (Qfile_error, Qerror_message,
5886 build_pure_c_string ("File error"));
5888 Fput (Qfile_already_exists, Qerror_conditions,
5889 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5890 Fput (Qfile_already_exists, Qerror_message,
5891 build_pure_c_string ("File already exists"));
5893 Fput (Qfile_date_error, Qerror_conditions,
5894 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5895 Fput (Qfile_date_error, Qerror_message,
5896 build_pure_c_string ("Cannot set file date"));
5898 Fput (Qfile_notify_error, Qerror_conditions,
5899 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5900 Fput (Qfile_notify_error, Qerror_message,
5901 build_pure_c_string ("File notification error"));
5903 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5904 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5905 If a file name matches REGEXP, all I/O on that file is done by calling
5906 HANDLER. If a file name matches more than one handler, the handler
5907 whose match starts last in the file name gets precedence. The
5908 function `find-file-name-handler' checks this list for a handler for
5909 its argument.
5911 HANDLER should be a function. The first argument given to it is the
5912 name of the I/O primitive to be handled; the remaining arguments are
5913 the arguments that were passed to that primitive. For example, if you
5914 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5915 HANDLER is called like this:
5917 (funcall HANDLER 'file-exists-p FILENAME)
5919 Note that HANDLER must be able to handle all I/O primitives; if it has
5920 nothing special to do for a primitive, it should reinvoke the
5921 primitive to handle the operation \"the usual way\".
5922 See Info node `(elisp)Magic File Names' for more details. */);
5923 Vfile_name_handler_alist = Qnil;
5925 DEFVAR_LISP ("set-auto-coding-function",
5926 Vset_auto_coding_function,
5927 doc: /* If non-nil, a function to call to decide a coding system of file.
5928 Two arguments are passed to this function: the file name
5929 and the length of a file contents following the point.
5930 This function should return a coding system to decode the file contents.
5931 It should check the file name against `auto-coding-alist'.
5932 If no coding system is decided, it should check a coding system
5933 specified in the heading lines with the format:
5934 -*- ... coding: CODING-SYSTEM; ... -*-
5935 or local variable spec of the tailing lines with `coding:' tag. */);
5936 Vset_auto_coding_function = Qnil;
5938 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5939 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5940 Each is passed one argument, the number of characters inserted,
5941 with point at the start of the inserted text. Each function
5942 should leave point the same, and return the new character count.
5943 If `insert-file-contents' is intercepted by a handler from
5944 `file-name-handler-alist', that handler is responsible for calling the
5945 functions in `after-insert-file-functions' if appropriate. */);
5946 Vafter_insert_file_functions = Qnil;
5948 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5949 doc: /* A list of functions to be called at the start of `write-region'.
5950 Each is passed two arguments, START and END as for `write-region'.
5951 These are usually two numbers but not always; see the documentation
5952 for `write-region'. The function should return a list of pairs
5953 of the form (POSITION . STRING), consisting of strings to be effectively
5954 inserted at the specified positions of the file being written (1 means to
5955 insert before the first byte written). The POSITIONs must be sorted into
5956 increasing order.
5958 If there are several annotation functions, the lists returned by these
5959 functions are merged destructively. As each annotation function runs,
5960 the variable `write-region-annotations-so-far' contains a list of all
5961 annotations returned by previous annotation functions.
5963 An annotation function can return with a different buffer current.
5964 Doing so removes the annotations returned by previous functions, and
5965 resets START and END to `point-min' and `point-max' of the new buffer.
5967 After `write-region' completes, Emacs calls the function stored in
5968 `write-region-post-annotation-function', once for each buffer that was
5969 current when building the annotations (i.e., at least once), with that
5970 buffer current. */);
5971 Vwrite_region_annotate_functions = Qnil;
5972 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5974 DEFVAR_LISP ("write-region-post-annotation-function",
5975 Vwrite_region_post_annotation_function,
5976 doc: /* Function to call after `write-region' completes.
5977 The function is called with no arguments. If one or more of the
5978 annotation functions in `write-region-annotate-functions' changed the
5979 current buffer, the function stored in this variable is called for
5980 each of those additional buffers as well, in addition to the original
5981 buffer. The relevant buffer is current during each function call. */);
5982 Vwrite_region_post_annotation_function = Qnil;
5983 staticpro (&Vwrite_region_annotation_buffers);
5985 DEFVAR_LISP ("write-region-annotations-so-far",
5986 Vwrite_region_annotations_so_far,
5987 doc: /* When an annotation function is called, this holds the previous annotations.
5988 These are the annotations made by other annotation functions
5989 that were already called. See also `write-region-annotate-functions'. */);
5990 Vwrite_region_annotations_so_far = Qnil;
5992 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5993 doc: /* A list of file name handlers that temporarily should not be used.
5994 This applies only to the operation `inhibit-file-name-operation'. */);
5995 Vinhibit_file_name_handlers = Qnil;
5997 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5998 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5999 Vinhibit_file_name_operation = Qnil;
6001 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6002 doc: /* File name in which we write a list of all auto save file names.
6003 This variable is initialized automatically from `auto-save-list-file-prefix'
6004 shortly after Emacs reads your init file, if you have not yet given it
6005 a non-nil value. */);
6006 Vauto_save_list_file_name = Qnil;
6008 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6009 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6010 Normally auto-save files are written under other names. */);
6011 Vauto_save_visited_file_name = Qnil;
6013 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6014 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6015 If nil, deleting a substantial portion of the text disables auto-save
6016 in the buffer; this is the default behavior, because the auto-save
6017 file is usually more useful if it contains the deleted text. */);
6018 Vauto_save_include_big_deletions = Qnil;
6020 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6021 doc: /* Non-nil means don't call fsync in `write-region'.
6022 This variable affects calls to `write-region' as well as save commands.
6023 Setting this to nil may avoid data loss if the system loses power or
6024 the operating system crashes. By default, it is non-nil in batch mode. */);
6025 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6027 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6028 doc: /* Specifies whether to use the system's trash can.
6029 When non-nil, certain file deletion commands use the function
6030 `move-file-to-trash' instead of deleting files outright.
6031 This includes interactive calls to `delete-file' and
6032 `delete-directory' and the Dired deletion commands. */);
6033 delete_by_moving_to_trash = 0;
6034 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6036 /* Lisp function for moving files to trash. */
6037 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6039 /* Lisp function for recursively copying directories. */
6040 DEFSYM (Qcopy_directory, "copy-directory");
6042 /* Lisp function for recursively deleting directories. */
6043 DEFSYM (Qdelete_directory, "delete-directory");
6045 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6046 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6048 DEFSYM (Qstdin, "stdin");
6049 DEFSYM (Qstdout, "stdout");
6050 DEFSYM (Qstderr, "stderr");
6052 defsubr (&Sfind_file_name_handler);
6053 defsubr (&Sfile_name_directory);
6054 defsubr (&Sfile_name_nondirectory);
6055 defsubr (&Sunhandled_file_name_directory);
6056 defsubr (&Sfile_name_as_directory);
6057 defsubr (&Sdirectory_file_name);
6058 defsubr (&Smake_temp_name);
6059 defsubr (&Sexpand_file_name);
6060 defsubr (&Ssubstitute_in_file_name);
6061 defsubr (&Scopy_file);
6062 defsubr (&Smake_directory_internal);
6063 defsubr (&Sdelete_directory_internal);
6064 defsubr (&Sdelete_file);
6065 defsubr (&Srename_file);
6066 defsubr (&Sadd_name_to_file);
6067 defsubr (&Smake_symbolic_link);
6068 defsubr (&Sfile_name_absolute_p);
6069 defsubr (&Sfile_exists_p);
6070 defsubr (&Sfile_executable_p);
6071 defsubr (&Sfile_readable_p);
6072 defsubr (&Sfile_writable_p);
6073 defsubr (&Saccess_file);
6074 defsubr (&Sfile_symlink_p);
6075 defsubr (&Sfile_directory_p);
6076 defsubr (&Sfile_accessible_directory_p);
6077 defsubr (&Sfile_regular_p);
6078 defsubr (&Sfile_modes);
6079 defsubr (&Sset_file_modes);
6080 defsubr (&Sset_file_times);
6081 defsubr (&Sfile_selinux_context);
6082 defsubr (&Sfile_acl);
6083 defsubr (&Sset_file_acl);
6084 defsubr (&Sset_file_selinux_context);
6085 defsubr (&Sset_default_file_modes);
6086 defsubr (&Sdefault_file_modes);
6087 defsubr (&Sfile_newer_than_file_p);
6088 defsubr (&Sinsert_file_contents);
6089 defsubr (&Swrite_region);
6090 defsubr (&Scar_less_than_car);
6091 defsubr (&Sverify_visited_file_modtime);
6092 defsubr (&Svisited_file_modtime);
6093 defsubr (&Sset_visited_file_modtime);
6094 defsubr (&Sdo_auto_save);
6095 defsubr (&Sset_buffer_auto_saved);
6096 defsubr (&Sclear_buffer_auto_save_failure);
6097 defsubr (&Srecent_auto_save_p);
6099 defsubr (&Snext_read_file_uses_dialog_p);
6101 defsubr (&Sset_binary_mode);
6103 #ifdef HAVE_SYNC
6104 defsubr (&Sunix_sync);
6105 #endif