Avoid compiler warnings
[emacs.git] / src / fileio.c
blob9da0bf0234b83b61dc728d29038e96f9d9b24458
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include "sysstdio.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #include <errno.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
37 #endif
39 #if USE_ACL && defined HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "composite.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "coding.h"
50 #include "window.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
53 #include "frame.h"
55 #ifdef WINDOWSNT
56 #define NOMINMAX 1
57 #include <windows.h>
58 #include <sys/file.h>
59 #include "w32.h"
60 #endif /* not WINDOWSNT */
62 #ifdef MSDOS
63 #include "msdos.h"
64 #include <sys/param.h>
65 #endif
67 #ifdef DOS_NT
68 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
69 redirector allows the six letters between 'Z' and 'a' as well. */
70 #ifdef MSDOS
71 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
72 #endif
73 #ifdef WINDOWSNT
74 #define IS_DRIVE(x) c_isalpha (x)
75 #endif
76 /* Need to lower-case the drive letter, or else expanded
77 filenames will sometimes compare unequal, because
78 `expand-file-name' doesn't always down-case the drive letter. */
79 #define DRIVE_LETTER(x) c_tolower (x)
80 #endif
82 #include "systime.h"
83 #include <acl.h>
84 #include <allocator.h>
85 #include <careadlinkat.h>
86 #include <stat-time.h>
88 #include <binary-io.h>
90 #ifdef HPUX
91 #include <netio.h>
92 #endif
94 #include "commands.h"
96 /* True during writing of auto-save files. */
97 static bool auto_saving;
99 /* Emacs's real umask. */
100 static mode_t realmask;
102 /* Nonzero umask during creation of auto-save directories. */
103 static mode_t auto_saving_dir_umask;
105 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
106 a new file with the same mode as the original. */
107 static mode_t auto_save_mode_bits;
109 /* Set by auto_save_1 if an error occurred during the last auto-save. */
110 static bool auto_save_error_occurred;
112 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
113 number of a file system where time stamps were observed to to work. */
114 static bool valid_timestamp_file_system;
115 static dev_t timestamp_file_system;
117 /* Each time an annotation function changes the buffer, the new buffer
118 is added here. */
119 static Lisp_Object Vwrite_region_annotation_buffers;
121 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
122 Lisp_Object *, struct coding_system *);
123 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
124 struct coding_system *);
127 /* Return true if FILENAME exists. */
129 static bool
130 check_existing (const char *filename)
132 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
135 /* Return true if file FILENAME exists and can be executed. */
137 static bool
138 check_executable (char *filename)
140 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
143 /* Return true if file FILENAME exists and can be accessed
144 according to AMODE, which should include W_OK.
145 On failure, return false and set errno. */
147 static bool
148 check_writable (const char *filename, int amode)
150 #ifdef MSDOS
151 /* FIXME: an faccessat implementation should be added to the
152 DOS/Windows ports and this #ifdef branch should be removed. */
153 struct stat st;
154 if (stat (filename, &st) < 0)
155 return 0;
156 errno = EPERM;
157 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
158 #else /* not MSDOS */
159 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
160 #ifdef CYGWIN
161 /* faccessat may have returned failure because Cygwin couldn't
162 determine the file's UID or GID; if so, we return success. */
163 if (!res)
165 int faccessat_errno = errno;
166 struct stat st;
167 if (stat (filename, &st) < 0)
168 return 0;
169 res = (st.st_uid == -1 || st.st_gid == -1);
170 errno = faccessat_errno;
172 #endif /* CYGWIN */
173 return res;
174 #endif /* not MSDOS */
177 /* Signal a file-access failure. STRING describes the failure,
178 NAME the file involved, and ERRORNO the errno value.
180 If NAME is neither null nor a pair, package it up as a singleton
181 list before reporting it; this saves report_file_errno's caller the
182 trouble of preserving errno before calling list1. */
184 void
185 report_file_errno (char const *string, Lisp_Object name, int errorno)
187 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
188 synchronize_system_messages_locale ();
189 char *str = strerror (errorno);
190 AUTO_STRING (unibyte_str, str);
191 Lisp_Object errstring
192 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
193 Lisp_Object errdata = Fcons (errstring, data);
195 if (errorno == EEXIST)
196 xsignal (Qfile_already_exists, errdata);
197 else
198 xsignal (Qfile_error, Fcons (build_string (string), errdata));
201 /* Signal a file-access failure that set errno. STRING describes the
202 failure, NAME the file involved. When invoking this function, take
203 care to not use arguments such as build_string ("foo") that involve
204 side effects that may set errno. */
206 void
207 report_file_error (char const *string, Lisp_Object name)
209 report_file_errno (string, name, errno);
212 /* Like report_file_error, but reports a file-notify-error instead. */
214 void
215 report_file_notify_error (const char *string, Lisp_Object name)
217 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
218 synchronize_system_messages_locale ();
219 char *str = strerror (errno);
220 AUTO_STRING (unibyte_str, str);
221 Lisp_Object errstring
222 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
223 Lisp_Object errdata = Fcons (errstring, data);
225 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
228 void
229 close_file_unwind (int fd)
231 emacs_close (fd);
234 void
235 fclose_unwind (void *arg)
237 FILE *stream = arg;
238 fclose (stream);
241 /* Restore point, having saved it as a marker. */
243 void
244 restore_point_unwind (Lisp_Object location)
246 Fgoto_char (location);
247 unchain_marker (XMARKER (location));
251 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
252 Sfind_file_name_handler, 2, 2, 0,
253 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
254 Otherwise, return nil.
255 A file name is handled if one of the regular expressions in
256 `file-name-handler-alist' matches it.
258 If OPERATION equals `inhibit-file-name-operation', then we ignore
259 any handlers that are members of `inhibit-file-name-handlers',
260 but we still do run any other handlers. This lets handlers
261 use the standard functions without calling themselves recursively. */)
262 (Lisp_Object filename, Lisp_Object operation)
264 /* This function must not munge the match data. */
265 Lisp_Object chain, inhibited_handlers, result;
266 ptrdiff_t pos = -1;
268 result = Qnil;
269 CHECK_STRING (filename);
271 if (EQ (operation, Vinhibit_file_name_operation))
272 inhibited_handlers = Vinhibit_file_name_handlers;
273 else
274 inhibited_handlers = Qnil;
276 for (chain = Vfile_name_handler_alist; CONSP (chain);
277 chain = XCDR (chain))
279 Lisp_Object elt;
280 elt = XCAR (chain);
281 if (CONSP (elt))
283 Lisp_Object string = XCAR (elt);
284 ptrdiff_t match_pos;
285 Lisp_Object handler = XCDR (elt);
286 Lisp_Object operations = Qnil;
288 if (SYMBOLP (handler))
289 operations = Fget (handler, Qoperations);
291 if (STRINGP (string)
292 && (match_pos = fast_string_match (string, filename)) > pos
293 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
295 Lisp_Object tem;
297 handler = XCDR (elt);
298 tem = Fmemq (handler, inhibited_handlers);
299 if (NILP (tem))
301 result = handler;
302 pos = match_pos;
307 QUIT;
309 return result;
312 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
313 1, 1, 0,
314 doc: /* Return the directory component in file name FILENAME.
315 Return nil if FILENAME does not include a directory.
316 Otherwise return a directory name.
317 Given a Unix syntax file name, returns a string ending in slash. */)
318 (Lisp_Object filename)
320 Lisp_Object handler;
322 CHECK_STRING (filename);
324 /* If the file name has special constructs in it,
325 call the corresponding file handler. */
326 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
327 if (!NILP (handler))
329 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
330 filename);
331 return STRINGP (handled_name) ? handled_name : Qnil;
334 char *beg = SSDATA (filename);
335 char const *p = beg + SBYTES (filename);
337 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
338 #ifdef DOS_NT
339 /* only recognize drive specifier at the beginning */
340 && !(p[-1] == ':'
341 /* handle the "/:d:foo" and "/:foo" cases correctly */
342 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
343 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
344 #endif
345 ) p--;
347 if (p == beg)
348 return Qnil;
349 #ifdef DOS_NT
350 /* Expansion of "c:" to drive and default directory. */
351 Lisp_Object tem_fn;
352 USE_SAFE_ALLOCA;
353 SAFE_ALLOCA_STRING (beg, filename);
354 p = beg + (p - SSDATA (filename));
356 if (p[-1] == ':')
358 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
359 char *res = alloca (MAXPATHLEN + 1);
360 char *r = res;
362 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
364 memcpy (res, beg, 2);
365 beg += 2;
366 r += 2;
369 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
371 size_t l = strlen (res);
373 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
374 strcat (res, "/");
375 beg = res;
376 p = beg + strlen (beg);
377 dostounix_filename (beg);
378 tem_fn = make_specified_string (beg, -1, p - beg,
379 STRING_MULTIBYTE (filename));
381 else
382 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
383 STRING_MULTIBYTE (filename));
385 else if (STRING_MULTIBYTE (filename))
387 tem_fn = make_specified_string (beg, -1, p - beg, 1);
388 dostounix_filename (SSDATA (tem_fn));
389 #ifdef WINDOWSNT
390 if (!NILP (Vw32_downcase_file_names))
391 tem_fn = Fdowncase (tem_fn);
392 #endif
394 else
396 dostounix_filename (beg);
397 tem_fn = make_specified_string (beg, -1, p - beg, 0);
399 SAFE_FREE ();
400 return tem_fn;
401 #else /* DOS_NT */
402 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
403 #endif /* DOS_NT */
406 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
407 Sfile_name_nondirectory, 1, 1, 0,
408 doc: /* Return file name FILENAME sans its directory.
409 For example, in a Unix-syntax file name,
410 this is everything after the last slash,
411 or the entire name if it contains no slash. */)
412 (Lisp_Object filename)
414 register const char *beg, *p, *end;
415 Lisp_Object handler;
417 CHECK_STRING (filename);
419 /* If the file name has special constructs in it,
420 call the corresponding file handler. */
421 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
422 if (!NILP (handler))
424 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
425 filename);
426 if (STRINGP (handled_name))
427 return handled_name;
428 error ("Invalid handler in `file-name-handler-alist'");
431 beg = SSDATA (filename);
432 end = p = beg + SBYTES (filename);
434 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
435 #ifdef DOS_NT
436 /* only recognize drive specifier at beginning */
437 && !(p[-1] == ':'
438 /* handle the "/:d:foo" case correctly */
439 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
440 #endif
442 p--;
444 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
447 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
448 Sunhandled_file_name_directory, 1, 1, 0,
449 doc: /* Return a directly usable directory name somehow associated with FILENAME.
450 A `directly usable' directory name is one that may be used without the
451 intervention of any file handler.
452 If FILENAME is a directly usable file itself, return
453 \(file-name-as-directory FILENAME).
454 If FILENAME refers to a file which is not accessible from a local process,
455 then this should return nil.
456 The `call-process' and `start-process' functions use this function to
457 get a current directory to run processes in. */)
458 (Lisp_Object filename)
460 Lisp_Object handler;
462 /* If the file name has special constructs in it,
463 call the corresponding file handler. */
464 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
465 if (!NILP (handler))
467 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
468 filename);
469 return STRINGP (handled_name) ? handled_name : Qnil;
472 return Ffile_name_as_directory (filename);
475 /* Maximum number of bytes that DST will be longer than SRC
476 in file_name_as_directory. This occurs when SRCLEN == 0. */
477 enum { file_name_as_directory_slop = 2 };
479 /* Convert from file name SRC of length SRCLEN to directory name in
480 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
481 string. On UNIX, just make sure there is a terminating /. Return
482 the length of DST in bytes. */
484 static ptrdiff_t
485 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
486 bool multibyte)
488 if (srclen == 0)
490 dst[0] = '.';
491 dst[1] = '/';
492 dst[2] = '\0';
493 return 2;
496 memcpy (dst, src, srclen);
497 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
498 dst[srclen++] = DIRECTORY_SEP;
499 dst[srclen] = 0;
500 #ifdef DOS_NT
501 dostounix_filename (dst);
502 #endif
503 return srclen;
506 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
507 Sfile_name_as_directory, 1, 1, 0,
508 doc: /* Return a string representing the file name FILE interpreted as a directory.
509 This operation exists because a directory is also a file, but its name as
510 a directory is different from its name as a file.
511 The result can be used as the value of `default-directory'
512 or passed as second argument to `expand-file-name'.
513 For a Unix-syntax file name, just appends a slash. */)
514 (Lisp_Object file)
516 char *buf;
517 ptrdiff_t length;
518 Lisp_Object handler, val;
519 USE_SAFE_ALLOCA;
521 CHECK_STRING (file);
523 /* If the file name has special constructs in it,
524 call the corresponding file handler. */
525 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
526 if (!NILP (handler))
528 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
529 file);
530 if (STRINGP (handled_name))
531 return handled_name;
532 error ("Invalid handler in `file-name-handler-alist'");
535 #ifdef WINDOWSNT
536 if (!NILP (Vw32_downcase_file_names))
537 file = Fdowncase (file);
538 #endif
539 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
540 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
541 STRING_MULTIBYTE (file));
542 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
543 SAFE_FREE ();
544 return val;
547 /* Convert from directory name SRC of length SRCLEN to file name in
548 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
549 string. On UNIX, just make sure there isn't a terminating /.
550 Return the length of DST in bytes. */
552 static ptrdiff_t
553 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
555 /* Process as Unix format: just remove any final slash.
556 But leave "/" and "//" unchanged. */
557 while (srclen > 1
558 #ifdef DOS_NT
559 && !IS_ANY_SEP (src[srclen - 2])
560 #endif
561 && IS_DIRECTORY_SEP (src[srclen - 1])
562 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
563 srclen--;
565 memcpy (dst, src, srclen);
566 dst[srclen] = 0;
567 #ifdef DOS_NT
568 dostounix_filename (dst);
569 #endif
570 return srclen;
573 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
574 1, 1, 0,
575 doc: /* Returns the file name of the directory named DIRECTORY.
576 This is the name of the file that holds the data for the directory DIRECTORY.
577 This operation exists because a directory is also a file, but its name as
578 a directory is different from its name as a file.
579 In Unix-syntax, this function just removes the final slash. */)
580 (Lisp_Object directory)
582 char *buf;
583 ptrdiff_t length;
584 Lisp_Object handler, val;
585 USE_SAFE_ALLOCA;
587 CHECK_STRING (directory);
589 /* If the file name has special constructs in it,
590 call the corresponding file handler. */
591 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
592 if (!NILP (handler))
594 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
595 directory);
596 if (STRINGP (handled_name))
597 return handled_name;
598 error ("Invalid handler in `file-name-handler-alist'");
601 #ifdef WINDOWSNT
602 if (!NILP (Vw32_downcase_file_names))
603 directory = Fdowncase (directory);
604 #endif
605 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
606 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
607 STRING_MULTIBYTE (directory));
608 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
609 SAFE_FREE ();
610 return val;
613 static const char make_temp_name_tbl[64] =
615 'A','B','C','D','E','F','G','H',
616 'I','J','K','L','M','N','O','P',
617 'Q','R','S','T','U','V','W','X',
618 'Y','Z','a','b','c','d','e','f',
619 'g','h','i','j','k','l','m','n',
620 'o','p','q','r','s','t','u','v',
621 'w','x','y','z','0','1','2','3',
622 '4','5','6','7','8','9','-','_'
625 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
627 /* Value is a temporary file name starting with PREFIX, a string.
629 The Emacs process number forms part of the result, so there is
630 no danger of generating a name being used by another process.
631 In addition, this function makes an attempt to choose a name
632 which has no existing file. To make this work, PREFIX should be
633 an absolute file name.
635 BASE64_P means add the pid as 3 characters in base64
636 encoding. In this case, 6 characters will be added to PREFIX to
637 form the file name. Otherwise, if Emacs is running on a system
638 with long file names, add the pid as a decimal number.
640 This function signals an error if no unique file name could be
641 generated. */
643 Lisp_Object
644 make_temp_name (Lisp_Object prefix, bool base64_p)
646 Lisp_Object val, encoded_prefix;
647 ptrdiff_t len;
648 printmax_t pid;
649 char *p, *data;
650 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
651 int pidlen;
653 CHECK_STRING (prefix);
655 /* VAL is created by adding 6 characters to PREFIX. The first
656 three are the PID of this process, in base 64, and the second
657 three are incremented if the file already exists. This ensures
658 262144 unique file names per PID per PREFIX. */
660 pid = getpid ();
662 if (base64_p)
664 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
665 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
666 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
667 pidlen = 3;
669 else
671 #ifdef HAVE_LONG_FILE_NAMES
672 pidlen = sprintf (pidbuf, "%"pMd, pid);
673 #else
674 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
675 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
676 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
677 pidlen = 3;
678 #endif
681 encoded_prefix = ENCODE_FILE (prefix);
682 len = SBYTES (encoded_prefix);
683 val = make_uninit_string (len + 3 + pidlen);
684 data = SSDATA (val);
685 memcpy (data, SSDATA (encoded_prefix), len);
686 p = data + len;
688 memcpy (p, pidbuf, pidlen);
689 p += pidlen;
691 /* Here we try to minimize useless stat'ing when this function is
692 invoked many times successively with the same PREFIX. We achieve
693 this by initializing count to a random value, and incrementing it
694 afterwards.
696 We don't want make-temp-name to be called while dumping,
697 because then make_temp_name_count_initialized_p would get set
698 and then make_temp_name_count would not be set when Emacs starts. */
700 if (!make_temp_name_count_initialized_p)
702 make_temp_name_count = time (NULL);
703 make_temp_name_count_initialized_p = 1;
706 while (1)
708 unsigned num = make_temp_name_count;
710 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
711 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
712 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
714 /* Poor man's congruential RN generator. Replace with
715 ++make_temp_name_count for debugging. */
716 make_temp_name_count += 25229;
717 make_temp_name_count %= 225307;
719 if (!check_existing (data))
721 /* We want to return only if errno is ENOENT. */
722 if (errno == ENOENT)
723 return DECODE_FILE (val);
724 else
725 /* The error here is dubious, but there is little else we
726 can do. The alternatives are to return nil, which is
727 as bad as (and in many cases worse than) throwing the
728 error, or to ignore the error, which will likely result
729 in looping through 225307 stat's, which is not only
730 dog-slow, but also useless since eventually nil would
731 have to be returned anyway. */
732 report_file_error ("Cannot create temporary name for prefix",
733 prefix);
734 /* not reached */
740 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
741 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
742 The Emacs process number forms part of the result, so there is no
743 danger of generating a name being used by another Emacs process
744 \(so long as only a single host can access the containing directory...).
746 This function tries to choose a name that has no existing file.
747 For this to work, PREFIX should be an absolute file name.
749 There is a race condition between calling `make-temp-name' and creating the
750 file, which opens all kinds of security holes. For that reason, you should
751 normally use `make-temp-file' instead. */)
752 (Lisp_Object prefix)
754 return make_temp_name (prefix, 0);
757 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
758 doc: /* Convert filename NAME to absolute, and canonicalize it.
759 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
760 \(does not start with slash or tilde); both the directory name and
761 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
762 missing, the current buffer's value of `default-directory' is used.
763 NAME should be a string that is a valid file name for the underlying
764 filesystem.
765 File name components that are `.' are removed, and
766 so are file name components followed by `..', along with the `..' itself;
767 note that these simplifications are done without checking the resulting
768 file names in the file system.
769 Multiple consecutive slashes are collapsed into a single slash,
770 except at the beginning of the file name when they are significant (e.g.,
771 UNC file names on MS-Windows.)
772 An initial `~/' expands to your home directory.
773 An initial `~USER/' expands to USER's home directory.
774 See also the function `substitute-in-file-name'.
776 For technical reasons, this function can return correct but
777 non-intuitive results for the root directory; for instance,
778 \(expand-file-name ".." "/") returns "/..". For this reason, use
779 \(directory-file-name (file-name-directory dirname)) to traverse a
780 filesystem tree, not (expand-file-name ".." dirname). */)
781 (Lisp_Object name, Lisp_Object default_directory)
783 /* These point to SDATA and need to be careful with string-relocation
784 during GC (via DECODE_FILE). */
785 char *nm;
786 char *nmlim;
787 const char *newdir;
788 const char *newdirlim;
789 /* This should only point to alloca'd data. */
790 char *target;
792 ptrdiff_t tlen;
793 struct passwd *pw;
794 #ifdef DOS_NT
795 int drive = 0;
796 bool collapse_newdir = true;
797 bool is_escaped = 0;
798 #endif /* DOS_NT */
799 ptrdiff_t length, nbytes;
800 Lisp_Object handler, result, handled_name;
801 bool multibyte;
802 Lisp_Object hdir;
803 USE_SAFE_ALLOCA;
805 CHECK_STRING (name);
807 /* If the file name has special constructs in it,
808 call the corresponding file handler. */
809 handler = Ffind_file_name_handler (name, Qexpand_file_name);
810 if (!NILP (handler))
812 handled_name = call3 (handler, Qexpand_file_name,
813 name, default_directory);
814 if (STRINGP (handled_name))
815 return handled_name;
816 error ("Invalid handler in `file-name-handler-alist'");
820 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
821 if (NILP (default_directory))
822 default_directory = BVAR (current_buffer, directory);
823 if (! STRINGP (default_directory))
825 #ifdef DOS_NT
826 /* "/" is not considered a root directory on DOS_NT, so using "/"
827 here causes an infinite recursion in, e.g., the following:
829 (let (default-directory)
830 (expand-file-name "a"))
832 To avoid this, we set default_directory to the root of the
833 current drive. */
834 default_directory = build_string (emacs_root_dir ());
835 #else
836 default_directory = build_string ("/");
837 #endif
840 if (!NILP (default_directory))
842 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
843 if (!NILP (handler))
845 handled_name = call3 (handler, Qexpand_file_name,
846 name, default_directory);
847 if (STRINGP (handled_name))
848 return handled_name;
849 error ("Invalid handler in `file-name-handler-alist'");
854 char *o = SSDATA (default_directory);
856 /* Make sure DEFAULT_DIRECTORY is properly expanded.
857 It would be better to do this down below where we actually use
858 default_directory. Unfortunately, calling Fexpand_file_name recursively
859 could invoke GC, and the strings might be relocated. This would
860 be annoying because we have pointers into strings lying around
861 that would need adjusting, and people would add new pointers to
862 the code and forget to adjust them, resulting in intermittent bugs.
863 Putting this call here avoids all that crud.
865 The EQ test avoids infinite recursion. */
866 if (! NILP (default_directory) && !EQ (default_directory, name)
867 /* Save time in some common cases - as long as default_directory
868 is not relative, it can be canonicalized with name below (if it
869 is needed at all) without requiring it to be expanded now. */
870 #ifdef DOS_NT
871 /* Detect MSDOS file names with drive specifiers. */
872 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
873 && IS_DIRECTORY_SEP (o[2]))
874 #ifdef WINDOWSNT
875 /* Detect Windows file names in UNC format. */
876 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
877 #endif
878 #else /* not DOS_NT */
879 /* Detect Unix absolute file names (/... alone is not absolute on
880 DOS or Windows). */
881 && ! (IS_DIRECTORY_SEP (o[0]))
882 #endif /* not DOS_NT */
885 default_directory = Fexpand_file_name (default_directory, Qnil);
888 multibyte = STRING_MULTIBYTE (name);
889 if (multibyte != STRING_MULTIBYTE (default_directory))
891 if (multibyte)
893 unsigned char *p = SDATA (name);
895 while (*p && ASCII_CHAR_P (*p))
896 p++;
897 if (*p == '\0')
899 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
900 unibyte. Do not convert DEFAULT_DIRECTORY to
901 multibyte; instead, convert NAME to a unibyte string,
902 so that the result of this function is also a unibyte
903 string. This is needed during bootstrapping and
904 dumping, when Emacs cannot decode file names, because
905 the locale environment is not set up. */
906 name = make_unibyte_string (SSDATA (name), SBYTES (name));
907 multibyte = 0;
909 else
910 default_directory = string_to_multibyte (default_directory);
912 else
914 name = string_to_multibyte (name);
915 multibyte = 1;
919 #ifdef WINDOWSNT
920 if (!NILP (Vw32_downcase_file_names))
921 default_directory = Fdowncase (default_directory);
922 #endif
924 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
925 SAFE_ALLOCA_STRING (nm, name);
926 nmlim = nm + SBYTES (name);
928 #ifdef DOS_NT
929 /* Note if special escape prefix is present, but remove for now. */
930 if (nm[0] == '/' && nm[1] == ':')
932 is_escaped = 1;
933 nm += 2;
936 /* Find and remove drive specifier if present; this makes nm absolute
937 even if the rest of the name appears to be relative. Only look for
938 drive specifier at the beginning. */
939 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
941 drive = (unsigned char) nm[0];
942 nm += 2;
945 #ifdef WINDOWSNT
946 /* If we see "c://somedir", we want to strip the first slash after the
947 colon when stripping the drive letter. Otherwise, this expands to
948 "//somedir". */
949 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
950 nm++;
952 /* Discard any previous drive specifier if nm is now in UNC format. */
953 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
954 && !IS_DIRECTORY_SEP (nm[2]))
955 drive = 0;
956 #endif /* WINDOWSNT */
957 #endif /* DOS_NT */
959 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
960 none are found, we can probably return right away. We will avoid
961 allocating a new string if name is already fully expanded. */
962 if (
963 IS_DIRECTORY_SEP (nm[0])
964 #ifdef MSDOS
965 && drive && !is_escaped
966 #endif
967 #ifdef WINDOWSNT
968 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
969 #endif
972 /* If it turns out that the filename we want to return is just a
973 suffix of FILENAME, we don't need to go through and edit
974 things; we just need to construct a new string using data
975 starting at the middle of FILENAME. If we set LOSE, that
976 means we've discovered that we can't do that cool trick. */
977 bool lose = 0;
978 char *p = nm;
980 while (*p)
982 /* Since we know the name is absolute, we can assume that each
983 element starts with a "/". */
985 /* "." and ".." are hairy. */
986 if (IS_DIRECTORY_SEP (p[0])
987 && p[1] == '.'
988 && (IS_DIRECTORY_SEP (p[2])
989 || p[2] == 0
990 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
991 || p[3] == 0))))
992 lose = 1;
993 /* Replace multiple slashes with a single one, except
994 leave leading "//" alone. */
995 else if (IS_DIRECTORY_SEP (p[0])
996 && IS_DIRECTORY_SEP (p[1])
997 && (p != nm || IS_DIRECTORY_SEP (p[2])))
998 lose = 1;
999 p++;
1001 if (!lose)
1003 #ifdef DOS_NT
1004 /* Make sure directories are all separated with /, but
1005 avoid allocation of a new string when not required. */
1006 dostounix_filename (nm);
1007 #ifdef WINDOWSNT
1008 if (IS_DIRECTORY_SEP (nm[1]))
1010 if (strcmp (nm, SSDATA (name)) != 0)
1011 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1013 else
1014 #endif
1015 /* Drive must be set, so this is okay. */
1016 if (strcmp (nm - 2, SSDATA (name)) != 0)
1018 name = make_specified_string (nm, -1, p - nm, multibyte);
1019 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1020 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1021 name = concat2 (drive_prefix, name);
1023 #ifdef WINDOWSNT
1024 if (!NILP (Vw32_downcase_file_names))
1025 name = Fdowncase (name);
1026 #endif
1027 #else /* not DOS_NT */
1028 if (strcmp (nm, SSDATA (name)) != 0)
1029 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1030 #endif /* not DOS_NT */
1031 SAFE_FREE ();
1032 return name;
1036 /* At this point, nm might or might not be an absolute file name. We
1037 need to expand ~ or ~user if present, otherwise prefix nm with
1038 default_directory if nm is not absolute, and finally collapse /./
1039 and /foo/../ sequences.
1041 We set newdir to be the appropriate prefix if one is needed:
1042 - the relevant user directory if nm starts with ~ or ~user
1043 - the specified drive's working dir (DOS/NT only) if nm does not
1044 start with /
1045 - the value of default_directory.
1047 Note that these prefixes are not guaranteed to be absolute (except
1048 for the working dir of a drive). Therefore, to ensure we always
1049 return an absolute name, if the final prefix is not absolute we
1050 append it to the current working directory. */
1052 newdir = newdirlim = 0;
1054 if (nm[0] == '~') /* prefix ~ */
1056 if (IS_DIRECTORY_SEP (nm[1])
1057 || nm[1] == 0) /* ~ by itself */
1059 Lisp_Object tem;
1061 if (!(newdir = egetenv ("HOME")))
1062 newdir = newdirlim = "";
1063 nm++;
1064 /* `egetenv' may return a unibyte string, which will bite us since
1065 we expect the directory to be multibyte. */
1066 #ifdef WINDOWSNT
1067 if (newdir[0])
1069 char newdir_utf8[MAX_UTF8_PATH];
1071 filename_from_ansi (newdir, newdir_utf8);
1072 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1074 else
1075 #endif
1076 tem = build_string (newdir);
1077 newdirlim = newdir + SBYTES (tem);
1078 if (multibyte && !STRING_MULTIBYTE (tem))
1080 hdir = DECODE_FILE (tem);
1081 newdir = SSDATA (hdir);
1082 newdirlim = newdir + SBYTES (hdir);
1084 #ifdef DOS_NT
1085 collapse_newdir = false;
1086 #endif
1088 else /* ~user/filename */
1090 char *o, *p;
1091 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1092 continue;
1093 o = SAFE_ALLOCA (p - nm + 1);
1094 memcpy (o, nm, p - nm);
1095 o[p - nm] = 0;
1097 block_input ();
1098 pw = getpwnam (o + 1);
1099 unblock_input ();
1100 if (pw)
1102 Lisp_Object tem;
1104 newdir = pw->pw_dir;
1105 /* `getpwnam' may return a unibyte string, which will
1106 bite us since we expect the directory to be
1107 multibyte. */
1108 tem = make_unibyte_string (newdir, strlen (newdir));
1109 newdirlim = newdir + SBYTES (tem);
1110 if (multibyte && !STRING_MULTIBYTE (tem))
1112 hdir = DECODE_FILE (tem);
1113 newdir = SSDATA (hdir);
1114 newdirlim = newdir + SBYTES (hdir);
1116 nm = p;
1117 #ifdef DOS_NT
1118 collapse_newdir = false;
1119 #endif
1122 /* If we don't find a user of that name, leave the name
1123 unchanged; don't move nm forward to p. */
1127 #ifdef DOS_NT
1128 /* On DOS and Windows, nm is absolute if a drive name was specified;
1129 use the drive's current directory as the prefix if needed. */
1130 if (!newdir && drive)
1132 /* Get default directory if needed to make nm absolute. */
1133 char *adir = NULL;
1134 if (!IS_DIRECTORY_SEP (nm[0]))
1136 adir = alloca (MAXPATHLEN + 1);
1137 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1138 adir = NULL;
1139 else if (multibyte)
1141 Lisp_Object tem = build_string (adir);
1143 tem = DECODE_FILE (tem);
1144 newdirlim = adir + SBYTES (tem);
1145 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1147 else
1148 newdirlim = adir + strlen (adir);
1150 if (!adir)
1152 /* Either nm starts with /, or drive isn't mounted. */
1153 adir = alloca (4);
1154 adir[0] = DRIVE_LETTER (drive);
1155 adir[1] = ':';
1156 adir[2] = '/';
1157 adir[3] = 0;
1158 newdirlim = adir + 3;
1160 newdir = adir;
1162 #endif /* DOS_NT */
1164 /* Finally, if no prefix has been specified and nm is not absolute,
1165 then it must be expanded relative to default_directory. */
1167 if (1
1168 #ifndef DOS_NT
1169 /* /... alone is not absolute on DOS and Windows. */
1170 && !IS_DIRECTORY_SEP (nm[0])
1171 #endif
1172 #ifdef WINDOWSNT
1173 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1174 && !IS_DIRECTORY_SEP (nm[2]))
1175 #endif
1176 && !newdir)
1178 newdir = SSDATA (default_directory);
1179 newdirlim = newdir + SBYTES (default_directory);
1180 #ifdef DOS_NT
1181 /* Note if special escape prefix is present, but remove for now. */
1182 if (newdir[0] == '/' && newdir[1] == ':')
1184 is_escaped = 1;
1185 newdir += 2;
1187 #endif
1190 #ifdef DOS_NT
1191 if (newdir)
1193 /* First ensure newdir is an absolute name. */
1194 if (
1195 /* Detect MSDOS file names with drive specifiers. */
1196 ! (IS_DRIVE (newdir[0])
1197 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1198 #ifdef WINDOWSNT
1199 /* Detect Windows file names in UNC format. */
1200 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1201 && !IS_DIRECTORY_SEP (newdir[2]))
1202 #endif
1205 /* Effectively, let newdir be (expand-file-name newdir cwd).
1206 Because of the admonition against calling expand-file-name
1207 when we have pointers into lisp strings, we accomplish this
1208 indirectly by prepending newdir to nm if necessary, and using
1209 cwd (or the wd of newdir's drive) as the new newdir. */
1210 char *adir;
1211 #ifdef WINDOWSNT
1212 const int adir_size = MAX_UTF8_PATH;
1213 #else
1214 const int adir_size = MAXPATHLEN + 1;
1215 #endif
1217 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1219 drive = (unsigned char) newdir[0];
1220 newdir += 2;
1222 if (!IS_DIRECTORY_SEP (nm[0]))
1224 ptrdiff_t nmlen = nmlim - nm;
1225 ptrdiff_t newdirlen = newdirlim - newdir;
1226 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1227 + nmlen + 1);
1228 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1229 multibyte);
1230 memcpy (tmp + dlen, nm, nmlen + 1);
1231 nm = tmp;
1232 nmlim = nm + dlen + nmlen;
1234 adir = alloca (adir_size);
1235 if (drive)
1237 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1238 strcpy (adir, "/");
1240 else
1241 getcwd (adir, adir_size);
1242 if (multibyte)
1244 Lisp_Object tem = build_string (adir);
1246 tem = DECODE_FILE (tem);
1247 newdirlim = adir + SBYTES (tem);
1248 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1250 else
1251 newdirlim = adir + strlen (adir);
1252 newdir = adir;
1255 /* Strip off drive name from prefix, if present. */
1256 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1258 drive = newdir[0];
1259 newdir += 2;
1262 /* Keep only a prefix from newdir if nm starts with slash
1263 (//server/share for UNC, nothing otherwise). */
1264 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1266 #ifdef WINDOWSNT
1267 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1268 && !IS_DIRECTORY_SEP (newdir[2]))
1270 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1271 char *p = adir + 2;
1272 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1273 p++;
1274 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1275 *p = 0;
1276 newdir = adir;
1277 newdirlim = newdir + strlen (adir);
1279 else
1280 #endif
1281 newdir = newdirlim = "";
1284 #endif /* DOS_NT */
1286 /* Ignore any slash at the end of newdir, unless newdir is
1287 just "/" or "//". */
1288 length = newdirlim - newdir;
1289 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1290 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1291 length--;
1293 /* Now concatenate the directory and name to new space in the stack frame. */
1294 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1295 eassert (tlen > file_name_as_directory_slop + 1);
1296 #ifdef DOS_NT
1297 /* Reserve space for drive specifier and escape prefix, since either
1298 or both may need to be inserted. (The Microsoft x86 compiler
1299 produces incorrect code if the following two lines are combined.) */
1300 target = alloca (tlen + 4);
1301 target += 4;
1302 #else /* not DOS_NT */
1303 target = SAFE_ALLOCA (tlen);
1304 #endif /* not DOS_NT */
1305 *target = 0;
1306 nbytes = 0;
1308 if (newdir)
1310 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1312 #ifdef DOS_NT
1313 /* If newdir is effectively "C:/", then the drive letter will have
1314 been stripped and newdir will be "/". Concatenating with an
1315 absolute directory in nm produces "//", which will then be
1316 incorrectly treated as a network share. Ignore newdir in
1317 this case (keeping the drive letter). */
1318 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1319 && newdir[1] == '\0'))
1320 #endif
1322 memcpy (target, newdir, length);
1323 target[length] = 0;
1324 nbytes = length;
1327 else
1328 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1331 memcpy (target + nbytes, nm, nmlim - nm + 1);
1333 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1334 appear. */
1336 char *p = target;
1337 char *o = target;
1339 while (*p)
1341 if (!IS_DIRECTORY_SEP (*p))
1343 *o++ = *p++;
1345 else if (p[1] == '.'
1346 && (IS_DIRECTORY_SEP (p[2])
1347 || p[2] == 0))
1349 /* If "/." is the entire filename, keep the "/". Otherwise,
1350 just delete the whole "/.". */
1351 if (o == target && p[2] == '\0')
1352 *o++ = *p;
1353 p += 2;
1355 else if (p[1] == '.' && p[2] == '.'
1356 /* `/../' is the "superroot" on certain file systems.
1357 Turned off on DOS_NT systems because they have no
1358 "superroot" and because this causes us to produce
1359 file names like "d:/../foo" which fail file-related
1360 functions of the underlying OS. (To reproduce, try a
1361 long series of "../../" in default_directory, longer
1362 than the number of levels from the root.) */
1363 #ifndef DOS_NT
1364 && o != target
1365 #endif
1366 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1368 #ifdef WINDOWSNT
1369 char *prev_o = o;
1370 #endif
1371 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1372 continue;
1373 #ifdef WINDOWSNT
1374 /* Don't go below server level in UNC filenames. */
1375 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1376 && IS_DIRECTORY_SEP (*target))
1377 o = prev_o;
1378 else
1379 #endif
1380 /* Keep initial / only if this is the whole name. */
1381 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1382 ++o;
1383 p += 3;
1385 else if (IS_DIRECTORY_SEP (p[1])
1386 && (p != target || IS_DIRECTORY_SEP (p[2])))
1387 /* Collapse multiple "/", except leave leading "//" alone. */
1388 p++;
1389 else
1391 *o++ = *p++;
1395 #ifdef DOS_NT
1396 /* At last, set drive name. */
1397 #ifdef WINDOWSNT
1398 /* Except for network file name. */
1399 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1400 #endif /* WINDOWSNT */
1402 if (!drive) emacs_abort ();
1403 target -= 2;
1404 target[0] = DRIVE_LETTER (drive);
1405 target[1] = ':';
1407 /* Reinsert the escape prefix if required. */
1408 if (is_escaped)
1410 target -= 2;
1411 target[0] = '/';
1412 target[1] = ':';
1414 result = make_specified_string (target, -1, o - target, multibyte);
1415 dostounix_filename (SSDATA (result));
1416 #ifdef WINDOWSNT
1417 if (!NILP (Vw32_downcase_file_names))
1418 result = Fdowncase (result);
1419 #endif
1420 #else /* !DOS_NT */
1421 result = make_specified_string (target, -1, o - target, multibyte);
1422 #endif /* !DOS_NT */
1425 /* Again look to see if the file name has special constructs in it
1426 and perhaps call the corresponding file handler. This is needed
1427 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1428 the ".." component gives us "/user@host:/bar/../baz" which needs
1429 to be expanded again. */
1430 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1431 if (!NILP (handler))
1433 handled_name = call3 (handler, Qexpand_file_name,
1434 result, default_directory);
1435 if (! STRINGP (handled_name))
1436 error ("Invalid handler in `file-name-handler-alist'");
1437 result = handled_name;
1440 SAFE_FREE ();
1441 return result;
1444 #if 0
1445 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1446 This is the old version of expand-file-name, before it was thoroughly
1447 rewritten for Emacs 10.31. We leave this version here commented-out,
1448 because the code is very complex and likely to have subtle bugs. If
1449 bugs _are_ found, it might be of interest to look at the old code and
1450 see what did it do in the relevant situation.
1452 Don't remove this code: it's true that it will be accessible
1453 from the repository, but a few years from deletion, people will
1454 forget it is there. */
1456 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1457 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1458 "Convert FILENAME to absolute, and canonicalize it.\n\
1459 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1460 \(does not start with slash); if DEFAULT is nil or missing,\n\
1461 the current buffer's value of default-directory is used.\n\
1462 Filenames containing `.' or `..' as components are simplified;\n\
1463 initial `~/' expands to your home directory.\n\
1464 See also the function `substitute-in-file-name'.")
1465 (name, defalt)
1466 Lisp_Object name, defalt;
1468 unsigned char *nm;
1470 register unsigned char *newdir, *p, *o;
1471 ptrdiff_t tlen;
1472 unsigned char *target;
1473 struct passwd *pw;
1475 CHECK_STRING (name);
1476 nm = SDATA (name);
1478 /* If nm is absolute, flush ...// and detect /./ and /../.
1479 If no /./ or /../ we can return right away. */
1480 if (nm[0] == '/')
1482 bool lose = 0;
1483 p = nm;
1484 while (*p)
1486 if (p[0] == '/' && p[1] == '/')
1487 nm = p + 1;
1488 if (p[0] == '/' && p[1] == '~')
1489 nm = p + 1, lose = 1;
1490 if (p[0] == '/' && p[1] == '.'
1491 && (p[2] == '/' || p[2] == 0
1492 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1493 lose = 1;
1494 p++;
1496 if (!lose)
1498 if (nm == SDATA (name))
1499 return name;
1500 return build_string (nm);
1504 /* Now determine directory to start with and put it in NEWDIR. */
1506 newdir = 0;
1508 if (nm[0] == '~') /* prefix ~ */
1509 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1511 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1512 newdir = (unsigned char *) "";
1513 nm++;
1515 else /* ~user/filename */
1517 /* Get past ~ to user. */
1518 unsigned char *user = nm + 1;
1519 /* Find end of name. */
1520 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1521 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1522 /* Copy the user name into temp storage. */
1523 o = alloca (len + 1);
1524 memcpy (o, user, len);
1525 o[len] = 0;
1527 /* Look up the user name. */
1528 block_input ();
1529 pw = (struct passwd *) getpwnam (o + 1);
1530 unblock_input ();
1531 if (!pw)
1532 error ("\"%s\" isn't a registered user", o + 1);
1534 newdir = (unsigned char *) pw->pw_dir;
1536 /* Discard the user name from NM. */
1537 nm += len;
1540 if (nm[0] != '/' && !newdir)
1542 if (NILP (defalt))
1543 defalt = current_buffer->directory;
1544 CHECK_STRING (defalt);
1545 newdir = SDATA (defalt);
1548 /* Now concatenate the directory and name to new space in the stack frame. */
1550 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1551 target = alloca (tlen);
1552 *target = 0;
1554 if (newdir)
1556 if (nm[0] == 0 || nm[0] == '/')
1557 strcpy (target, newdir);
1558 else
1559 file_name_as_directory (target, newdir);
1562 strcat (target, nm);
1564 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1566 p = target;
1567 o = target;
1569 while (*p)
1571 if (*p != '/')
1573 *o++ = *p++;
1575 else if (!strncmp (p, "//", 2)
1578 o = target;
1579 p++;
1581 else if (p[0] == '/' && p[1] == '.'
1582 && (p[2] == '/' || p[2] == 0))
1583 p += 2;
1584 else if (!strncmp (p, "/..", 3)
1585 /* `/../' is the "superroot" on certain file systems. */
1586 && o != target
1587 && (p[3] == '/' || p[3] == 0))
1589 while (o != target && *--o != '/')
1591 if (o == target && *o == '/')
1592 ++o;
1593 p += 3;
1595 else
1597 *o++ = *p++;
1601 return make_string (target, o - target);
1603 #endif
1605 /* If /~ or // appears, discard everything through first slash. */
1606 static bool
1607 file_name_absolute_p (const char *filename)
1609 return
1610 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1611 #ifdef DOS_NT
1612 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1613 && IS_DIRECTORY_SEP (filename[2]))
1614 #endif
1618 static char *
1619 search_embedded_absfilename (char *nm, char *endp)
1621 char *p, *s;
1623 for (p = nm + 1; p < endp; p++)
1625 if (IS_DIRECTORY_SEP (p[-1])
1626 && file_name_absolute_p (p)
1627 #if defined (WINDOWSNT) || defined (CYGWIN)
1628 /* // at start of file name is meaningful in Apollo,
1629 WindowsNT and Cygwin systems. */
1630 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1631 #endif /* not (WINDOWSNT || CYGWIN) */
1634 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1635 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1637 USE_SAFE_ALLOCA;
1638 char *o = SAFE_ALLOCA (s - p + 1);
1639 struct passwd *pw;
1640 memcpy (o, p, s - p);
1641 o [s - p] = 0;
1643 /* If we have ~user and `user' exists, discard
1644 everything up to ~. But if `user' does not exist, leave
1645 ~user alone, it might be a literal file name. */
1646 block_input ();
1647 pw = getpwnam (o + 1);
1648 unblock_input ();
1649 SAFE_FREE ();
1650 if (pw)
1651 return p;
1653 else
1654 return p;
1657 return NULL;
1660 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1661 Ssubstitute_in_file_name, 1, 1, 0,
1662 doc: /* Substitute environment variables referred to in FILENAME.
1663 `$FOO' where FOO is an environment variable name means to substitute
1664 the value of that variable. The variable name should be terminated
1665 with a character not a letter, digit or underscore; otherwise, enclose
1666 the entire variable name in braces.
1668 If `/~' appears, all of FILENAME through that `/' is discarded.
1669 If `//' appears, everything up to and including the first of
1670 those `/' is discarded. */)
1671 (Lisp_Object filename)
1673 char *nm, *p, *x, *endp;
1674 bool substituted = false;
1675 bool multibyte;
1676 char *xnm;
1677 Lisp_Object handler;
1679 CHECK_STRING (filename);
1681 multibyte = STRING_MULTIBYTE (filename);
1683 /* If the file name has special constructs in it,
1684 call the corresponding file handler. */
1685 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1686 if (!NILP (handler))
1688 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1689 filename);
1690 if (STRINGP (handled_name))
1691 return handled_name;
1692 error ("Invalid handler in `file-name-handler-alist'");
1695 /* Always work on a copy of the string, in case GC happens during
1696 decode of environment variables, causing the original Lisp_String
1697 data to be relocated. */
1698 USE_SAFE_ALLOCA;
1699 SAFE_ALLOCA_STRING (nm, filename);
1701 #ifdef DOS_NT
1702 dostounix_filename (nm);
1703 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1704 #endif
1705 endp = nm + SBYTES (filename);
1707 /* If /~ or // appears, discard everything through first slash. */
1708 p = search_embedded_absfilename (nm, endp);
1709 if (p)
1710 /* Start over with the new string, so we check the file-name-handler
1711 again. Important with filenames like "/home/foo//:/hello///there"
1712 which would substitute to "/:/hello///there" rather than "/there". */
1714 Lisp_Object result
1715 = (Fsubstitute_in_file_name
1716 (make_specified_string (p, -1, endp - p, multibyte)));
1717 SAFE_FREE ();
1718 return result;
1721 /* See if any variables are substituted into the string. */
1723 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1725 Lisp_Object name
1726 = (!substituted ? filename
1727 : make_specified_string (nm, -1, endp - nm, multibyte));
1728 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1729 CHECK_STRING (tmp);
1730 if (!EQ (tmp, name))
1731 substituted = true;
1732 filename = tmp;
1735 if (!substituted)
1737 #ifdef WINDOWSNT
1738 if (!NILP (Vw32_downcase_file_names))
1739 filename = Fdowncase (filename);
1740 #endif
1741 SAFE_FREE ();
1742 return filename;
1745 xnm = SSDATA (filename);
1746 x = xnm + SBYTES (filename);
1748 /* If /~ or // appears, discard everything through first slash. */
1749 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1750 /* This time we do not start over because we've already expanded envvars
1751 and replaced $$ with $. Maybe we should start over as well, but we'd
1752 need to quote some $ to $$ first. */
1753 xnm = p;
1755 #ifdef WINDOWSNT
1756 if (!NILP (Vw32_downcase_file_names))
1758 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1760 filename = Fdowncase (xname);
1762 else
1763 #endif
1764 if (xnm != SSDATA (filename))
1765 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1766 SAFE_FREE ();
1767 return filename;
1770 /* A slightly faster and more convenient way to get
1771 (directory-file-name (expand-file-name FOO)). */
1773 Lisp_Object
1774 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1776 register Lisp_Object absname;
1778 absname = Fexpand_file_name (filename, defdir);
1780 /* Remove final slash, if any (unless this is the root dir).
1781 stat behaves differently depending! */
1782 if (SCHARS (absname) > 1
1783 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1784 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1785 /* We cannot take shortcuts; they might be wrong for magic file names. */
1786 absname = Fdirectory_file_name (absname);
1787 return absname;
1790 /* Signal an error if the file ABSNAME already exists.
1791 If KNOWN_TO_EXIST, the file is known to exist.
1792 QUERYSTRING is a name for the action that is being considered
1793 to alter the file.
1794 If INTERACTIVE, ask the user whether to proceed,
1795 and bypass the error if the user says to go ahead.
1796 If QUICK, ask for y or n, not yes or no. */
1798 static void
1799 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1800 const char *querystring, bool interactive,
1801 bool quick)
1803 Lisp_Object tem, encoded_filename;
1804 struct stat statbuf;
1806 encoded_filename = ENCODE_FILE (absname);
1808 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1810 if (S_ISDIR (statbuf.st_mode))
1811 xsignal2 (Qfile_error,
1812 build_string ("File is a directory"), absname);
1813 known_to_exist = true;
1816 if (known_to_exist)
1818 if (! interactive)
1819 xsignal2 (Qfile_already_exists,
1820 build_string ("File already exists"), absname);
1821 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1822 tem = CALLN (Fformat, format, absname, build_string (querystring));
1823 if (quick)
1824 tem = call1 (intern ("y-or-n-p"), tem);
1825 else
1826 tem = do_yes_or_no_p (tem);
1827 if (NILP (tem))
1828 xsignal2 (Qfile_already_exists,
1829 build_string ("File already exists"), absname);
1833 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1834 "fCopy file: \nGCopy %s to file: \np\nP",
1835 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1836 If NEWNAME names a directory, copy FILE there.
1838 This function always sets the file modes of the output file to match
1839 the input file.
1841 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1842 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1843 signal a `file-already-exists' error without overwriting. If
1844 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1845 about overwriting; this is what happens in interactive use with M-x.
1846 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1847 existing file.
1849 Fourth arg KEEP-TIME non-nil means give the output file the same
1850 last-modified time as the old one. (This works on only some systems.)
1852 A prefix arg makes KEEP-TIME non-nil.
1854 If PRESERVE-UID-GID is non-nil, we try to transfer the
1855 uid and gid of FILE to NEWNAME.
1857 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1858 this includes the file modes, along with ACL entries and SELinux
1859 context if present. Otherwise, if NEWNAME is created its file
1860 permission bits are those of FILE, masked by the default file
1861 permissions. */)
1862 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1863 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1864 Lisp_Object preserve_permissions)
1866 Lisp_Object handler;
1867 ptrdiff_t count = SPECPDL_INDEX ();
1868 Lisp_Object encoded_file, encoded_newname;
1869 #if HAVE_LIBSELINUX
1870 security_context_t con;
1871 int conlength = 0;
1872 #endif
1873 #ifdef WINDOWSNT
1874 int result;
1875 #else
1876 bool already_exists = false;
1877 mode_t new_mask;
1878 int ifd, ofd;
1879 struct stat st;
1880 #endif
1882 encoded_file = encoded_newname = Qnil;
1883 CHECK_STRING (file);
1884 CHECK_STRING (newname);
1886 if (!NILP (Ffile_directory_p (newname)))
1887 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1888 else
1889 newname = Fexpand_file_name (newname, Qnil);
1891 file = Fexpand_file_name (file, Qnil);
1893 /* If the input file name has special constructs in it,
1894 call the corresponding file handler. */
1895 handler = Ffind_file_name_handler (file, Qcopy_file);
1896 /* Likewise for output file name. */
1897 if (NILP (handler))
1898 handler = Ffind_file_name_handler (newname, Qcopy_file);
1899 if (!NILP (handler))
1900 return call7 (handler, Qcopy_file, file, newname,
1901 ok_if_already_exists, keep_time, preserve_uid_gid,
1902 preserve_permissions);
1904 encoded_file = ENCODE_FILE (file);
1905 encoded_newname = ENCODE_FILE (newname);
1907 #ifdef WINDOWSNT
1908 if (NILP (ok_if_already_exists)
1909 || INTEGERP (ok_if_already_exists))
1910 barf_or_query_if_file_exists (newname, false, "copy to it",
1911 INTEGERP (ok_if_already_exists), false);
1913 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1914 !NILP (keep_time), !NILP (preserve_uid_gid),
1915 !NILP (preserve_permissions));
1916 switch (result)
1918 case -1:
1919 report_file_error ("Copying file", list2 (file, newname));
1920 case -2:
1921 report_file_error ("Copying permissions from", file);
1922 case -3:
1923 xsignal2 (Qfile_date_error,
1924 build_string ("Resetting file times"), newname);
1925 case -4:
1926 report_file_error ("Copying permissions to", newname);
1928 #else /* not WINDOWSNT */
1929 immediate_quit = 1;
1930 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1931 immediate_quit = 0;
1933 if (ifd < 0)
1934 report_file_error ("Opening input file", file);
1936 record_unwind_protect_int (close_file_unwind, ifd);
1938 if (fstat (ifd, &st) != 0)
1939 report_file_error ("Input file status", file);
1941 if (!NILP (preserve_permissions))
1943 #if HAVE_LIBSELINUX
1944 if (is_selinux_enabled ())
1946 conlength = fgetfilecon (ifd, &con);
1947 if (conlength == -1)
1948 report_file_error ("Doing fgetfilecon", file);
1950 #endif
1953 /* We can copy only regular files. */
1954 if (!S_ISREG (st.st_mode))
1955 report_file_errno ("Non-regular file", file,
1956 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1958 #ifndef MSDOS
1959 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1960 #else
1961 new_mask = S_IREAD | S_IWRITE;
1962 #endif
1964 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1965 new_mask);
1966 if (ofd < 0 && errno == EEXIST)
1968 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1969 barf_or_query_if_file_exists (newname, true, "copy to it",
1970 INTEGERP (ok_if_already_exists), false);
1971 already_exists = true;
1972 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1974 if (ofd < 0)
1975 report_file_error ("Opening output file", newname);
1977 record_unwind_protect_int (close_file_unwind, ofd);
1979 off_t oldsize = 0, newsize = 0;
1981 if (already_exists)
1983 struct stat out_st;
1984 if (fstat (ofd, &out_st) != 0)
1985 report_file_error ("Output file status", newname);
1986 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1987 report_file_errno ("Input and output files are the same",
1988 list2 (file, newname), 0);
1989 if (S_ISREG (out_st.st_mode))
1990 oldsize = out_st.st_size;
1993 immediate_quit = 1;
1994 QUIT;
1995 while (true)
1997 char buf[MAX_ALLOCA];
1998 ptrdiff_t n = emacs_read (ifd, buf, sizeof buf);
1999 if (n < 0)
2000 report_file_error ("Read error", file);
2001 if (n == 0)
2002 break;
2003 if (emacs_write_sig (ofd, buf, n) != n)
2004 report_file_error ("Write error", newname);
2005 newsize += n;
2008 /* Truncate any existing output file after writing the data. This
2009 is more likely to work than truncation before writing, if the
2010 file system is out of space or the user is over disk quota. */
2011 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2012 report_file_error ("Truncating output file", newname);
2014 immediate_quit = 0;
2016 #ifndef MSDOS
2017 /* Preserve the original file permissions, and if requested, also its
2018 owner and group. */
2020 mode_t preserved_permissions = st.st_mode & 07777;
2021 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2022 if (!NILP (preserve_uid_gid))
2024 /* Attempt to change owner and group. If that doesn't work
2025 attempt to change just the group, as that is sometimes allowed.
2026 Adjust the mode mask to eliminate setuid or setgid bits
2027 or group permissions bits that are inappropriate if the
2028 owner or group are wrong. */
2029 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2031 if (fchown (ofd, -1, st.st_gid) == 0)
2032 preserved_permissions &= ~04000;
2033 else
2035 preserved_permissions &= ~06000;
2037 /* Copy the other bits to the group bits, since the
2038 group is wrong. */
2039 preserved_permissions &= ~070;
2040 preserved_permissions |= (preserved_permissions & 7) << 3;
2041 default_permissions &= ~070;
2042 default_permissions |= (default_permissions & 7) << 3;
2047 switch (!NILP (preserve_permissions)
2048 ? qcopy_acl (SSDATA (encoded_file), ifd,
2049 SSDATA (encoded_newname), ofd,
2050 preserved_permissions)
2051 : (already_exists
2052 || (new_mask & ~realmask) == default_permissions)
2054 : fchmod (ofd, default_permissions))
2056 case -2: report_file_error ("Copying permissions from", file);
2057 case -1: report_file_error ("Copying permissions to", newname);
2060 #endif /* not MSDOS */
2062 #if HAVE_LIBSELINUX
2063 if (conlength > 0)
2065 /* Set the modified context back to the file. */
2066 bool fail = fsetfilecon (ofd, con) != 0;
2067 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2068 if (fail && errno != ENOTSUP)
2069 report_file_error ("Doing fsetfilecon", newname);
2071 freecon (con);
2073 #endif
2075 if (!NILP (keep_time))
2077 struct timespec atime = get_stat_atime (&st);
2078 struct timespec mtime = get_stat_mtime (&st);
2079 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2080 xsignal2 (Qfile_date_error,
2081 build_string ("Cannot set file date"), newname);
2084 if (emacs_close (ofd) < 0)
2085 report_file_error ("Write error", newname);
2087 emacs_close (ifd);
2089 #ifdef MSDOS
2090 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2091 and if it can't, it tells so. Otherwise, under MSDOS we usually
2092 get only the READ bit, which will make the copied file read-only,
2093 so it's better not to chmod at all. */
2094 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2095 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2096 #endif /* MSDOS */
2097 #endif /* not WINDOWSNT */
2099 /* Discard the unwind protects. */
2100 specpdl_ptr = specpdl + count;
2102 return Qnil;
2105 DEFUN ("make-directory-internal", Fmake_directory_internal,
2106 Smake_directory_internal, 1, 1, 0,
2107 doc: /* Create a new directory named DIRECTORY. */)
2108 (Lisp_Object directory)
2110 const char *dir;
2111 Lisp_Object handler;
2112 Lisp_Object encoded_dir;
2114 CHECK_STRING (directory);
2115 directory = Fexpand_file_name (directory, Qnil);
2117 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2118 if (!NILP (handler))
2119 return call2 (handler, Qmake_directory_internal, directory);
2121 encoded_dir = ENCODE_FILE (directory);
2123 dir = SSDATA (encoded_dir);
2125 #ifdef WINDOWSNT
2126 if (mkdir (dir) != 0)
2127 #else
2128 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2129 #endif
2130 report_file_error ("Creating directory", directory);
2132 return Qnil;
2135 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2136 Sdelete_directory_internal, 1, 1, 0,
2137 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2138 (Lisp_Object directory)
2140 const char *dir;
2141 Lisp_Object encoded_dir;
2143 CHECK_STRING (directory);
2144 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2145 encoded_dir = ENCODE_FILE (directory);
2146 dir = SSDATA (encoded_dir);
2148 if (rmdir (dir) != 0)
2149 report_file_error ("Removing directory", directory);
2151 return Qnil;
2154 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2155 "(list (read-file-name \
2156 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2157 \"Move file to trash: \" \"Delete file: \") \
2158 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2159 (null current-prefix-arg))",
2160 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2161 If file has multiple names, it continues to exist with the other names.
2162 TRASH non-nil means to trash the file instead of deleting, provided
2163 `delete-by-moving-to-trash' is non-nil.
2165 When called interactively, TRASH is t if no prefix argument is given.
2166 With a prefix argument, TRASH is nil. */)
2167 (Lisp_Object filename, Lisp_Object trash)
2169 Lisp_Object handler;
2170 Lisp_Object encoded_file;
2172 if (!NILP (Ffile_directory_p (filename))
2173 && NILP (Ffile_symlink_p (filename)))
2174 xsignal2 (Qfile_error,
2175 build_string ("Removing old name: is a directory"),
2176 filename);
2177 filename = Fexpand_file_name (filename, Qnil);
2179 handler = Ffind_file_name_handler (filename, Qdelete_file);
2180 if (!NILP (handler))
2181 return call3 (handler, Qdelete_file, filename, trash);
2183 if (delete_by_moving_to_trash && !NILP (trash))
2184 return call1 (Qmove_file_to_trash, filename);
2186 encoded_file = ENCODE_FILE (filename);
2188 if (unlink (SSDATA (encoded_file)) < 0)
2189 report_file_error ("Removing old name", filename);
2190 return Qnil;
2193 static Lisp_Object
2194 internal_delete_file_1 (Lisp_Object ignore)
2196 return Qt;
2199 /* Delete file FILENAME, returning true if successful.
2200 This ignores `delete-by-moving-to-trash'. */
2202 bool
2203 internal_delete_file (Lisp_Object filename)
2205 Lisp_Object tem;
2207 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2208 Qt, internal_delete_file_1);
2209 return NILP (tem);
2212 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2213 "fRename file: \nGRename %s to file: \np",
2214 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2215 If file has names other than FILE, it continues to have those names.
2216 Signals a `file-already-exists' error if a file NEWNAME already exists
2217 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2218 A number as third arg means request confirmation if NEWNAME already exists.
2219 This is what happens in interactive use with M-x. */)
2220 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2222 Lisp_Object handler;
2223 Lisp_Object encoded_file, encoded_newname, symlink_target;
2225 symlink_target = encoded_file = encoded_newname = Qnil;
2226 CHECK_STRING (file);
2227 CHECK_STRING (newname);
2228 file = Fexpand_file_name (file, Qnil);
2230 if ((!NILP (Ffile_directory_p (newname)))
2231 #ifdef DOS_NT
2232 /* If the file names are identical but for the case,
2233 don't attempt to move directory to itself. */
2234 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2235 #endif
2238 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2239 ? file : Fdirectory_file_name (file));
2240 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2242 else
2243 newname = Fexpand_file_name (newname, Qnil);
2245 /* If the file name has special constructs in it,
2246 call the corresponding file handler. */
2247 handler = Ffind_file_name_handler (file, Qrename_file);
2248 if (NILP (handler))
2249 handler = Ffind_file_name_handler (newname, Qrename_file);
2250 if (!NILP (handler))
2251 return call4 (handler, Qrename_file,
2252 file, newname, ok_if_already_exists);
2254 encoded_file = ENCODE_FILE (file);
2255 encoded_newname = ENCODE_FILE (newname);
2257 #ifdef DOS_NT
2258 /* If the file names are identical but for the case, don't ask for
2259 confirmation: they simply want to change the letter-case of the
2260 file name. */
2261 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2262 #endif
2263 if (NILP (ok_if_already_exists)
2264 || INTEGERP (ok_if_already_exists))
2265 barf_or_query_if_file_exists (newname, false, "rename to it",
2266 INTEGERP (ok_if_already_exists), false);
2267 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2269 int rename_errno = errno;
2270 if (rename_errno == EXDEV)
2272 ptrdiff_t count;
2273 symlink_target = Ffile_symlink_p (file);
2274 if (! NILP (symlink_target))
2275 Fmake_symbolic_link (symlink_target, newname,
2276 NILP (ok_if_already_exists) ? Qnil : Qt);
2277 else if (!NILP (Ffile_directory_p (file)))
2278 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2279 else
2280 /* We have already prompted if it was an integer, so don't
2281 have copy-file prompt again. */
2282 Fcopy_file (file, newname,
2283 NILP (ok_if_already_exists) ? Qnil : Qt,
2284 Qt, Qt, Qt);
2286 count = SPECPDL_INDEX ();
2287 specbind (Qdelete_by_moving_to_trash, Qnil);
2289 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2290 call2 (Qdelete_directory, file, Qt);
2291 else
2292 Fdelete_file (file, Qnil);
2293 unbind_to (count, Qnil);
2295 else
2296 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2299 return Qnil;
2302 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2303 "fAdd name to file: \nGName to add to %s: \np",
2304 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2305 Signals a `file-already-exists' error if a file NEWNAME already exists
2306 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2307 A number as third arg means request confirmation if NEWNAME already exists.
2308 This is what happens in interactive use with M-x. */)
2309 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2311 Lisp_Object handler;
2312 Lisp_Object encoded_file, encoded_newname;
2314 encoded_file = encoded_newname = Qnil;
2315 CHECK_STRING (file);
2316 CHECK_STRING (newname);
2317 file = Fexpand_file_name (file, Qnil);
2319 if (!NILP (Ffile_directory_p (newname)))
2320 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2321 else
2322 newname = Fexpand_file_name (newname, Qnil);
2324 /* If the file name has special constructs in it,
2325 call the corresponding file handler. */
2326 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2327 if (!NILP (handler))
2328 return call4 (handler, Qadd_name_to_file, file,
2329 newname, ok_if_already_exists);
2331 /* If the new name has special constructs in it,
2332 call the corresponding file handler. */
2333 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2334 if (!NILP (handler))
2335 return call4 (handler, Qadd_name_to_file, file,
2336 newname, ok_if_already_exists);
2338 encoded_file = ENCODE_FILE (file);
2339 encoded_newname = ENCODE_FILE (newname);
2341 if (NILP (ok_if_already_exists)
2342 || INTEGERP (ok_if_already_exists))
2343 barf_or_query_if_file_exists (newname, false, "make it a new name",
2344 INTEGERP (ok_if_already_exists), false);
2346 unlink (SSDATA (newname));
2347 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2349 int link_errno = errno;
2350 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2353 return Qnil;
2356 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2357 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2358 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2359 Both args must be strings.
2360 Signals a `file-already-exists' error if a file LINKNAME already exists
2361 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2362 A number as third arg means request confirmation if LINKNAME already exists.
2363 This happens for interactive use with M-x. */)
2364 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2366 Lisp_Object handler;
2367 Lisp_Object encoded_target, encoded_linkname;
2369 encoded_target = encoded_linkname = Qnil;
2370 CHECK_STRING (target);
2371 CHECK_STRING (linkname);
2372 /* If the link target has a ~, we must expand it to get
2373 a truly valid file name. Otherwise, do not expand;
2374 we want to permit links to relative file names. */
2375 if (SREF (target, 0) == '~')
2376 target = Fexpand_file_name (target, Qnil);
2378 if (!NILP (Ffile_directory_p (linkname)))
2379 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2380 else
2381 linkname = Fexpand_file_name (linkname, Qnil);
2383 /* If the file name has special constructs in it,
2384 call the corresponding file handler. */
2385 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2386 if (!NILP (handler))
2387 return call4 (handler, Qmake_symbolic_link, target,
2388 linkname, ok_if_already_exists);
2390 /* If the new link name has special constructs in it,
2391 call the corresponding file handler. */
2392 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2393 if (!NILP (handler))
2394 return call4 (handler, Qmake_symbolic_link, target,
2395 linkname, ok_if_already_exists);
2397 encoded_target = ENCODE_FILE (target);
2398 encoded_linkname = ENCODE_FILE (linkname);
2400 if (NILP (ok_if_already_exists)
2401 || INTEGERP (ok_if_already_exists))
2402 barf_or_query_if_file_exists (linkname, false, "make it a link",
2403 INTEGERP (ok_if_already_exists), false);
2404 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2406 /* If we didn't complain already, silently delete existing file. */
2407 int symlink_errno;
2408 if (errno == EEXIST)
2410 unlink (SSDATA (encoded_linkname));
2411 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2412 >= 0)
2413 return Qnil;
2415 if (errno == ENOSYS)
2416 xsignal1 (Qfile_error,
2417 build_string ("Symbolic links are not supported"));
2419 symlink_errno = errno;
2420 report_file_errno ("Making symbolic link", list2 (target, linkname),
2421 symlink_errno);
2424 return Qnil;
2428 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2429 1, 1, 0,
2430 doc: /* Return t if file FILENAME specifies an absolute file name.
2431 On Unix, this is a name starting with a `/' or a `~'. */)
2432 (Lisp_Object filename)
2434 CHECK_STRING (filename);
2435 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2438 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2439 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2440 See also `file-readable-p' and `file-attributes'.
2441 This returns nil for a symlink to a nonexistent file.
2442 Use `file-symlink-p' to test for such links. */)
2443 (Lisp_Object filename)
2445 Lisp_Object absname;
2446 Lisp_Object handler;
2448 CHECK_STRING (filename);
2449 absname = Fexpand_file_name (filename, Qnil);
2451 /* If the file name has special constructs in it,
2452 call the corresponding file handler. */
2453 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2454 if (!NILP (handler))
2456 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2457 errno = 0;
2458 return result;
2461 absname = ENCODE_FILE (absname);
2463 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2466 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2467 doc: /* Return t if FILENAME can be executed by you.
2468 For a directory, this means you can access files in that directory.
2469 \(It is generally better to use `file-accessible-directory-p' for that
2470 purpose, though.) */)
2471 (Lisp_Object filename)
2473 Lisp_Object absname;
2474 Lisp_Object handler;
2476 CHECK_STRING (filename);
2477 absname = Fexpand_file_name (filename, Qnil);
2479 /* If the file name has special constructs in it,
2480 call the corresponding file handler. */
2481 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2482 if (!NILP (handler))
2483 return call2 (handler, Qfile_executable_p, absname);
2485 absname = ENCODE_FILE (absname);
2487 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2490 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2491 doc: /* Return t if file FILENAME exists and you can read it.
2492 See also `file-exists-p' and `file-attributes'. */)
2493 (Lisp_Object filename)
2495 Lisp_Object absname;
2496 Lisp_Object handler;
2498 CHECK_STRING (filename);
2499 absname = Fexpand_file_name (filename, Qnil);
2501 /* If the file name has special constructs in it,
2502 call the corresponding file handler. */
2503 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2504 if (!NILP (handler))
2505 return call2 (handler, Qfile_readable_p, absname);
2507 absname = ENCODE_FILE (absname);
2508 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2509 ? Qt : Qnil);
2512 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2513 doc: /* Return t if file FILENAME can be written or created by you. */)
2514 (Lisp_Object filename)
2516 Lisp_Object absname, dir, encoded;
2517 Lisp_Object handler;
2519 CHECK_STRING (filename);
2520 absname = Fexpand_file_name (filename, Qnil);
2522 /* If the file name has special constructs in it,
2523 call the corresponding file handler. */
2524 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2525 if (!NILP (handler))
2526 return call2 (handler, Qfile_writable_p, absname);
2528 encoded = ENCODE_FILE (absname);
2529 if (check_writable (SSDATA (encoded), W_OK))
2530 return Qt;
2531 if (errno != ENOENT)
2532 return Qnil;
2534 dir = Ffile_name_directory (absname);
2535 eassert (!NILP (dir));
2536 #ifdef MSDOS
2537 dir = Fdirectory_file_name (dir);
2538 #endif /* MSDOS */
2540 dir = ENCODE_FILE (dir);
2541 #ifdef WINDOWSNT
2542 /* The read-only attribute of the parent directory doesn't affect
2543 whether a file or directory can be created within it. Some day we
2544 should check ACLs though, which do affect this. */
2545 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2546 #else
2547 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2548 #endif
2551 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2552 doc: /* Access file FILENAME, and get an error if that does not work.
2553 The second argument STRING is used in the error message.
2554 If there is no error, returns nil. */)
2555 (Lisp_Object filename, Lisp_Object string)
2557 Lisp_Object handler, encoded_filename, absname;
2559 CHECK_STRING (filename);
2560 absname = Fexpand_file_name (filename, Qnil);
2562 CHECK_STRING (string);
2564 /* If the file name has special constructs in it,
2565 call the corresponding file handler. */
2566 handler = Ffind_file_name_handler (absname, Qaccess_file);
2567 if (!NILP (handler))
2568 return call3 (handler, Qaccess_file, absname, string);
2570 encoded_filename = ENCODE_FILE (absname);
2572 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2573 report_file_error (SSDATA (string), filename);
2575 return Qnil;
2578 /* Relative to directory FD, return the symbolic link value of FILENAME.
2579 On failure, return nil. */
2580 Lisp_Object
2581 emacs_readlinkat (int fd, char const *filename)
2583 static struct allocator const emacs_norealloc_allocator =
2584 { xmalloc, NULL, xfree, memory_full };
2585 Lisp_Object val;
2586 char readlink_buf[1024];
2587 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2588 &emacs_norealloc_allocator, readlinkat);
2589 if (!buf)
2590 return Qnil;
2592 val = build_unibyte_string (buf);
2593 if (buf[0] == '/' && strchr (buf, ':'))
2595 AUTO_STRING (slash_colon, "/:");
2596 val = concat2 (slash_colon, val);
2598 if (buf != readlink_buf)
2599 xfree (buf);
2600 val = DECODE_FILE (val);
2601 return val;
2604 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2605 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2606 The value is the link target, as a string.
2607 Otherwise it returns nil.
2609 This function does not check whether the link target exists. */)
2610 (Lisp_Object filename)
2612 Lisp_Object handler;
2614 CHECK_STRING (filename);
2615 filename = Fexpand_file_name (filename, Qnil);
2617 /* If the file name has special constructs in it,
2618 call the corresponding file handler. */
2619 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2620 if (!NILP (handler))
2621 return call2 (handler, Qfile_symlink_p, filename);
2623 filename = ENCODE_FILE (filename);
2625 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2628 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2629 doc: /* Return t if FILENAME names an existing directory.
2630 Symbolic links to directories count as directories.
2631 See `file-symlink-p' to distinguish symlinks. */)
2632 (Lisp_Object filename)
2634 Lisp_Object absname;
2635 Lisp_Object handler;
2637 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2639 /* If the file name has special constructs in it,
2640 call the corresponding file handler. */
2641 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2642 if (!NILP (handler))
2643 return call2 (handler, Qfile_directory_p, absname);
2645 absname = ENCODE_FILE (absname);
2647 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2650 /* Return true if FILE is a directory or a symlink to a directory. */
2651 bool
2652 file_directory_p (char const *file)
2654 #ifdef WINDOWSNT
2655 /* This is cheaper than 'stat'. */
2656 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2657 #else
2658 struct stat st;
2659 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2660 #endif
2663 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2664 Sfile_accessible_directory_p, 1, 1, 0,
2665 doc: /* Return t if FILENAME names a directory you can open.
2666 For the value to be t, FILENAME must specify the name of a directory
2667 as a file, and the directory must allow you to open files in it. In
2668 order to use a directory as a buffer's current directory, this
2669 predicate must return true. A directory name spec may be given
2670 instead; then the value is t if the directory so specified exists and
2671 really is a readable and searchable directory. */)
2672 (Lisp_Object filename)
2674 Lisp_Object absname;
2675 Lisp_Object handler;
2677 CHECK_STRING (filename);
2678 absname = Fexpand_file_name (filename, Qnil);
2680 /* If the file name has special constructs in it,
2681 call the corresponding file handler. */
2682 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2683 if (!NILP (handler))
2685 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2686 errno = 0;
2687 return r;
2690 absname = ENCODE_FILE (absname);
2691 return file_accessible_directory_p (absname) ? Qt : Qnil;
2694 /* If FILE is a searchable directory or a symlink to a
2695 searchable directory, return true. Otherwise return
2696 false and set errno to an error number. */
2697 bool
2698 file_accessible_directory_p (Lisp_Object file)
2700 #ifdef DOS_NT
2701 # ifdef WINDOWSNT
2702 /* We need a special-purpose test because (a) NTFS security data is
2703 not reflected in Posix-style mode bits, and (b) the trick with
2704 accessing "DIR/.", used below on Posix hosts, doesn't work on
2705 Windows, because "DIR/." is normalized to just "DIR" before
2706 hitting the disk. */
2707 return (SBYTES (file) == 0
2708 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2709 # else /* MSDOS */
2710 return file_directory_p (SSDATA (file));
2711 # endif /* MSDOS */
2712 #else /* !DOS_NT */
2713 /* On POSIXish platforms, use just one system call; this avoids a
2714 race and is typically faster. */
2715 const char *data = SSDATA (file);
2716 ptrdiff_t len = SBYTES (file);
2717 char const *dir;
2718 bool ok;
2719 int saved_errno;
2720 USE_SAFE_ALLOCA;
2722 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2723 There are three exceptions: "", "/", and "//". Leave "" alone,
2724 as it's invalid. Append only "." to the other two exceptions as
2725 "/" and "//" are distinct on some platforms, whereas "/", "///",
2726 "////", etc. are all equivalent. */
2727 if (! len)
2728 dir = data;
2729 else
2731 /* Just check for trailing '/' when deciding whether to append '/'.
2732 That's simpler than testing the two special cases "/" and "//",
2733 and it's a safe optimization here. */
2734 char *buf = SAFE_ALLOCA (len + 3);
2735 memcpy (buf, data, len);
2736 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2737 dir = buf;
2740 ok = check_existing (dir);
2741 saved_errno = errno;
2742 SAFE_FREE ();
2743 errno = saved_errno;
2744 return ok;
2745 #endif /* !DOS_NT */
2748 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2749 doc: /* Return t if FILENAME names a regular file.
2750 This is the sort of file that holds an ordinary stream of data bytes.
2751 Symbolic links to regular files count as regular files.
2752 See `file-symlink-p' to distinguish symlinks. */)
2753 (Lisp_Object filename)
2755 register Lisp_Object absname;
2756 struct stat st;
2757 Lisp_Object handler;
2759 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2761 /* If the file name has special constructs in it,
2762 call the corresponding file handler. */
2763 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2764 if (!NILP (handler))
2765 return call2 (handler, Qfile_regular_p, absname);
2767 absname = ENCODE_FILE (absname);
2769 #ifdef WINDOWSNT
2771 int result;
2772 Lisp_Object tem = Vw32_get_true_file_attributes;
2774 /* Tell stat to use expensive method to get accurate info. */
2775 Vw32_get_true_file_attributes = Qt;
2776 result = stat (SSDATA (absname), &st);
2777 Vw32_get_true_file_attributes = tem;
2779 if (result < 0)
2780 return Qnil;
2781 return S_ISREG (st.st_mode) ? Qt : Qnil;
2783 #else
2784 if (stat (SSDATA (absname), &st) < 0)
2785 return Qnil;
2786 return S_ISREG (st.st_mode) ? Qt : Qnil;
2787 #endif
2790 DEFUN ("file-selinux-context", Ffile_selinux_context,
2791 Sfile_selinux_context, 1, 1, 0,
2792 doc: /* Return SELinux context of file named FILENAME.
2793 The return value is a list (USER ROLE TYPE RANGE), where the list
2794 elements are strings naming the user, role, type, and range of the
2795 file's SELinux security context.
2797 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2798 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2799 (Lisp_Object filename)
2801 Lisp_Object absname;
2802 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2804 Lisp_Object handler;
2805 #if HAVE_LIBSELINUX
2806 security_context_t con;
2807 int conlength;
2808 context_t context;
2809 #endif
2811 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2813 /* If the file name has special constructs in it,
2814 call the corresponding file handler. */
2815 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2816 if (!NILP (handler))
2817 return call2 (handler, Qfile_selinux_context, absname);
2819 absname = ENCODE_FILE (absname);
2821 #if HAVE_LIBSELINUX
2822 if (is_selinux_enabled ())
2824 conlength = lgetfilecon (SSDATA (absname), &con);
2825 if (conlength > 0)
2827 context = context_new (con);
2828 if (context_user_get (context))
2829 user = build_string (context_user_get (context));
2830 if (context_role_get (context))
2831 role = build_string (context_role_get (context));
2832 if (context_type_get (context))
2833 type = build_string (context_type_get (context));
2834 if (context_range_get (context))
2835 range = build_string (context_range_get (context));
2836 context_free (context);
2837 freecon (con);
2840 #endif
2842 return list4 (user, role, type, range);
2845 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2846 Sset_file_selinux_context, 2, 2, 0,
2847 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2848 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2849 elements are strings naming the components of a SELinux context.
2851 Value is t if setting of SELinux context was successful, nil otherwise.
2853 This function does nothing and returns nil if SELinux is disabled,
2854 or if Emacs was not compiled with SELinux support. */)
2855 (Lisp_Object filename, Lisp_Object context)
2857 Lisp_Object absname;
2858 Lisp_Object handler;
2859 #if HAVE_LIBSELINUX
2860 Lisp_Object encoded_absname;
2861 Lisp_Object user = CAR_SAFE (context);
2862 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2863 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2864 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2865 security_context_t con;
2866 bool fail;
2867 int conlength;
2868 context_t parsed_con;
2869 #endif
2871 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2873 /* If the file name has special constructs in it,
2874 call the corresponding file handler. */
2875 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2876 if (!NILP (handler))
2877 return call3 (handler, Qset_file_selinux_context, absname, context);
2879 #if HAVE_LIBSELINUX
2880 if (is_selinux_enabled ())
2882 /* Get current file context. */
2883 encoded_absname = ENCODE_FILE (absname);
2884 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2885 if (conlength > 0)
2887 parsed_con = context_new (con);
2888 /* Change the parts defined in the parameter.*/
2889 if (STRINGP (user))
2891 if (context_user_set (parsed_con, SSDATA (user)))
2892 error ("Doing context_user_set");
2894 if (STRINGP (role))
2896 if (context_role_set (parsed_con, SSDATA (role)))
2897 error ("Doing context_role_set");
2899 if (STRINGP (type))
2901 if (context_type_set (parsed_con, SSDATA (type)))
2902 error ("Doing context_type_set");
2904 if (STRINGP (range))
2906 if (context_range_set (parsed_con, SSDATA (range)))
2907 error ("Doing context_range_set");
2910 /* Set the modified context back to the file. */
2911 fail = (lsetfilecon (SSDATA (encoded_absname),
2912 context_str (parsed_con))
2913 != 0);
2914 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2915 if (fail && errno != ENOTSUP)
2916 report_file_error ("Doing lsetfilecon", absname);
2918 context_free (parsed_con);
2919 freecon (con);
2920 return fail ? Qnil : Qt;
2922 else
2923 report_file_error ("Doing lgetfilecon", absname);
2925 #endif
2927 return Qnil;
2930 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2931 doc: /* Return ACL entries of file named FILENAME.
2932 The entries are returned in a format suitable for use in `set-file-acl'
2933 but is otherwise undocumented and subject to change.
2934 Return nil if file does not exist or is not accessible, or if Emacs
2935 was unable to determine the ACL entries. */)
2936 (Lisp_Object filename)
2938 #if USE_ACL
2939 Lisp_Object absname;
2940 Lisp_Object handler;
2941 # ifdef HAVE_ACL_SET_FILE
2942 acl_t acl;
2943 Lisp_Object acl_string;
2944 char *str;
2945 # ifndef HAVE_ACL_TYPE_EXTENDED
2946 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2947 # endif
2948 # endif
2950 absname = expand_and_dir_to_file (filename,
2951 BVAR (current_buffer, directory));
2953 /* If the file name has special constructs in it,
2954 call the corresponding file handler. */
2955 handler = Ffind_file_name_handler (absname, Qfile_acl);
2956 if (!NILP (handler))
2957 return call2 (handler, Qfile_acl, absname);
2959 # ifdef HAVE_ACL_SET_FILE
2960 absname = ENCODE_FILE (absname);
2962 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2963 if (acl == NULL)
2964 return Qnil;
2966 str = acl_to_text (acl, NULL);
2967 if (str == NULL)
2969 acl_free (acl);
2970 return Qnil;
2973 acl_string = build_string (str);
2974 acl_free (str);
2975 acl_free (acl);
2977 return acl_string;
2978 # endif
2979 #endif
2981 return Qnil;
2984 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
2985 2, 2, 0,
2986 doc: /* Set ACL of file named FILENAME to ACL-STRING.
2987 ACL-STRING should contain the textual representation of the ACL
2988 entries in a format suitable for the platform.
2990 Value is t if setting of ACL was successful, nil otherwise.
2992 Setting ACL for local files requires Emacs to be built with ACL
2993 support. */)
2994 (Lisp_Object filename, Lisp_Object acl_string)
2996 #if USE_ACL
2997 Lisp_Object absname;
2998 Lisp_Object handler;
2999 # ifdef HAVE_ACL_SET_FILE
3000 Lisp_Object encoded_absname;
3001 acl_t acl;
3002 bool fail;
3003 # endif
3005 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3007 /* If the file name has special constructs in it,
3008 call the corresponding file handler. */
3009 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3010 if (!NILP (handler))
3011 return call3 (handler, Qset_file_acl, absname, acl_string);
3013 # ifdef HAVE_ACL_SET_FILE
3014 if (STRINGP (acl_string))
3016 acl = acl_from_text (SSDATA (acl_string));
3017 if (acl == NULL)
3019 report_file_error ("Converting ACL", absname);
3020 return Qnil;
3023 encoded_absname = ENCODE_FILE (absname);
3025 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3026 acl)
3027 != 0);
3028 if (fail && acl_errno_valid (errno))
3029 report_file_error ("Setting ACL", absname);
3031 acl_free (acl);
3032 return fail ? Qnil : Qt;
3034 # endif
3035 #endif
3037 return Qnil;
3040 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3041 doc: /* Return mode bits of file named FILENAME, as an integer.
3042 Return nil, if file does not exist or is not accessible. */)
3043 (Lisp_Object filename)
3045 Lisp_Object absname;
3046 struct stat st;
3047 Lisp_Object handler;
3049 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3051 /* If the file name has special constructs in it,
3052 call the corresponding file handler. */
3053 handler = Ffind_file_name_handler (absname, Qfile_modes);
3054 if (!NILP (handler))
3055 return call2 (handler, Qfile_modes, absname);
3057 absname = ENCODE_FILE (absname);
3059 if (stat (SSDATA (absname), &st) < 0)
3060 return Qnil;
3062 return make_number (st.st_mode & 07777);
3065 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3066 "(let ((file (read-file-name \"File: \"))) \
3067 (list file (read-file-modes nil file)))",
3068 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3069 Only the 12 low bits of MODE are used.
3071 Interactively, mode bits are read by `read-file-modes', which accepts
3072 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3073 (Lisp_Object filename, Lisp_Object mode)
3075 Lisp_Object absname, encoded_absname;
3076 Lisp_Object handler;
3078 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3079 CHECK_NUMBER (mode);
3081 /* If the file name has special constructs in it,
3082 call the corresponding file handler. */
3083 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3084 if (!NILP (handler))
3085 return call3 (handler, Qset_file_modes, absname, mode);
3087 encoded_absname = ENCODE_FILE (absname);
3089 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3090 report_file_error ("Doing chmod", absname);
3092 return Qnil;
3095 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3096 doc: /* Set the file permission bits for newly created files.
3097 The argument MODE should be an integer; only the low 9 bits are used.
3098 This setting is inherited by subprocesses. */)
3099 (Lisp_Object mode)
3101 mode_t oldrealmask, oldumask, newumask;
3102 CHECK_NUMBER (mode);
3103 oldrealmask = realmask;
3104 newumask = ~ XINT (mode) & 0777;
3106 block_input ();
3107 realmask = newumask;
3108 oldumask = umask (newumask);
3109 unblock_input ();
3111 eassert (oldumask == oldrealmask);
3112 return Qnil;
3115 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3116 doc: /* Return the default file protection for created files.
3117 The value is an integer. */)
3118 (void)
3120 Lisp_Object value;
3121 XSETINT (value, (~ realmask) & 0777);
3122 return value;
3126 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3127 doc: /* Set times of file FILENAME to TIMESTAMP.
3128 Set both access and modification times.
3129 Return t on success, else nil.
3130 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3131 `current-time'. */)
3132 (Lisp_Object filename, Lisp_Object timestamp)
3134 Lisp_Object absname, encoded_absname;
3135 Lisp_Object handler;
3136 struct timespec t = lisp_time_argument (timestamp);
3138 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3140 /* If the file name has special constructs in it,
3141 call the corresponding file handler. */
3142 handler = Ffind_file_name_handler (absname, Qset_file_times);
3143 if (!NILP (handler))
3144 return call3 (handler, Qset_file_times, absname, timestamp);
3146 encoded_absname = ENCODE_FILE (absname);
3149 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3151 #ifdef MSDOS
3152 /* Setting times on a directory always fails. */
3153 if (file_directory_p (SSDATA (encoded_absname)))
3154 return Qnil;
3155 #endif
3156 report_file_error ("Setting file times", absname);
3160 return Qt;
3163 #ifdef HAVE_SYNC
3164 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3165 doc: /* Tell Unix to finish all pending disk updates. */)
3166 (void)
3168 sync ();
3169 return Qnil;
3172 #endif /* HAVE_SYNC */
3174 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3175 doc: /* Return t if file FILE1 is newer than file FILE2.
3176 If FILE1 does not exist, the answer is nil;
3177 otherwise, if FILE2 does not exist, the answer is t. */)
3178 (Lisp_Object file1, Lisp_Object file2)
3180 Lisp_Object absname1, absname2;
3181 struct stat st1, st2;
3182 Lisp_Object handler;
3184 CHECK_STRING (file1);
3185 CHECK_STRING (file2);
3187 absname1 = Qnil;
3188 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3189 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3191 /* If the file name has special constructs in it,
3192 call the corresponding file handler. */
3193 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3194 if (NILP (handler))
3195 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3196 if (!NILP (handler))
3197 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3199 absname1 = ENCODE_FILE (absname1);
3200 absname2 = ENCODE_FILE (absname2);
3202 if (stat (SSDATA (absname1), &st1) < 0)
3203 return Qnil;
3205 if (stat (SSDATA (absname2), &st2) < 0)
3206 return Qt;
3208 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3209 ? Qt : Qnil);
3212 #ifndef READ_BUF_SIZE
3213 #define READ_BUF_SIZE (64 << 10)
3214 #endif
3215 /* Some buffer offsets are stored in 'int' variables. */
3216 verify (READ_BUF_SIZE <= INT_MAX);
3218 /* This function is called after Lisp functions to decide a coding
3219 system are called, or when they cause an error. Before they are
3220 called, the current buffer is set unibyte and it contains only a
3221 newly inserted text (thus the buffer was empty before the
3222 insertion).
3224 The functions may set markers, overlays, text properties, or even
3225 alter the buffer contents, change the current buffer.
3227 Here, we reset all those changes by:
3228 o set back the current buffer.
3229 o move all markers and overlays to BEG.
3230 o remove all text properties.
3231 o set back the buffer multibyteness. */
3233 static void
3234 decide_coding_unwind (Lisp_Object unwind_data)
3236 Lisp_Object multibyte, undo_list, buffer;
3238 multibyte = XCAR (unwind_data);
3239 unwind_data = XCDR (unwind_data);
3240 undo_list = XCAR (unwind_data);
3241 buffer = XCDR (unwind_data);
3243 set_buffer_internal (XBUFFER (buffer));
3244 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3245 adjust_overlays_for_delete (BEG, Z - BEG);
3246 set_buffer_intervals (current_buffer, NULL);
3247 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3249 /* Now we are safe to change the buffer's multibyteness directly. */
3250 bset_enable_multibyte_characters (current_buffer, multibyte);
3251 bset_undo_list (current_buffer, undo_list);
3254 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3255 object where slot 0 is the file descriptor, slot 1 specifies
3256 an offset to put the read bytes, and slot 2 is the maximum
3257 amount of bytes to read. Value is the number of bytes read. */
3259 static Lisp_Object
3260 read_non_regular (Lisp_Object state)
3262 int nbytes;
3264 immediate_quit = 1;
3265 QUIT;
3266 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3267 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3268 + XSAVE_INTEGER (state, 1)),
3269 XSAVE_INTEGER (state, 2));
3270 immediate_quit = 0;
3271 /* Fast recycle this object for the likely next call. */
3272 free_misc (state);
3273 return make_number (nbytes);
3277 /* Condition-case handler used when reading from non-regular files
3278 in insert-file-contents. */
3280 static Lisp_Object
3281 read_non_regular_quit (Lisp_Object ignore)
3283 return Qnil;
3286 /* Return the file offset that VAL represents, checking for type
3287 errors and overflow. */
3288 static off_t
3289 file_offset (Lisp_Object val)
3291 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3292 return XINT (val);
3294 if (FLOATP (val))
3296 double v = XFLOAT_DATA (val);
3297 if (0 <= v
3298 && (sizeof (off_t) < sizeof v
3299 ? v <= TYPE_MAXIMUM (off_t)
3300 : v < TYPE_MAXIMUM (off_t)))
3301 return v;
3304 wrong_type_argument (intern ("file-offset"), val);
3307 /* Return a special time value indicating the error number ERRNUM. */
3308 static struct timespec
3309 time_error_value (int errnum)
3311 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3312 ? NONEXISTENT_MODTIME_NSECS
3313 : UNKNOWN_MODTIME_NSECS);
3314 return make_timespec (0, ns);
3317 static Lisp_Object
3318 get_window_points_and_markers (void)
3320 Lisp_Object pt_marker = Fpoint_marker ();
3321 Lisp_Object windows
3322 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3323 Lisp_Object window_markers = windows;
3324 /* Window markers (and point) are handled specially: rather than move to
3325 just before or just after the modified text, we try to keep the
3326 markers at the same distance (bug#19161).
3327 In general, this is wrong, but for window-markers, this should be harmless
3328 and is convenient for the end user when most of the file is unmodified,
3329 except for a few minor details near the beginning and near the end. */
3330 for (; CONSP (windows); windows = XCDR (windows))
3331 if (WINDOWP (XCAR (windows)))
3333 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3334 XSETCAR (windows,
3335 Fcons (window_marker, Fmarker_position (window_marker)));
3337 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3340 static void
3341 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3342 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3344 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3345 if (CONSP (XCAR (window_markers)))
3347 Lisp_Object car = XCAR (window_markers);
3348 Lisp_Object marker = XCAR (car);
3349 Lisp_Object oldpos = XCDR (car);
3350 if (MARKERP (marker) && INTEGERP (oldpos)
3351 && XINT (oldpos) > same_at_start
3352 && XINT (oldpos) < same_at_end)
3354 ptrdiff_t oldsize = same_at_end - same_at_start;
3355 ptrdiff_t newsize = inserted;
3356 double growth = newsize / (double)oldsize;
3357 ptrdiff_t newpos
3358 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3359 Fset_marker (marker, make_number (newpos), Qnil);
3364 /* FIXME: insert-file-contents should be split with the top-level moved to
3365 Elisp and only the core kept in C. */
3367 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3368 1, 5, 0,
3369 doc: /* Insert contents of file FILENAME after point.
3370 Returns list of absolute file name and number of characters inserted.
3371 If second argument VISIT is non-nil, the buffer's visited filename and
3372 last save file modtime are set, and it is marked unmodified. If
3373 visiting and the file does not exist, visiting is completed before the
3374 error is signaled.
3376 The optional third and fourth arguments BEG and END specify what portion
3377 of the file to insert. These arguments count bytes in the file, not
3378 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3380 If optional fifth argument REPLACE is non-nil, replace the current
3381 buffer contents (in the accessible portion) with the file contents.
3382 This is better than simply deleting and inserting the whole thing
3383 because (1) it preserves some marker positions and (2) it puts less data
3384 in the undo list. When REPLACE is non-nil, the second return value is
3385 the number of characters that replace previous buffer contents.
3387 This function does code conversion according to the value of
3388 `coding-system-for-read' or `file-coding-system-alist', and sets the
3389 variable `last-coding-system-used' to the coding system actually used.
3391 In addition, this function decodes the inserted text from known formats
3392 by calling `format-decode', which see. */)
3393 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3395 struct stat st;
3396 struct timespec mtime;
3397 int fd;
3398 ptrdiff_t inserted = 0;
3399 ptrdiff_t how_much;
3400 off_t beg_offset, end_offset;
3401 int unprocessed;
3402 ptrdiff_t count = SPECPDL_INDEX ();
3403 Lisp_Object handler, val, insval, orig_filename, old_undo;
3404 Lisp_Object p;
3405 ptrdiff_t total = 0;
3406 bool not_regular = 0;
3407 int save_errno = 0;
3408 char read_buf[READ_BUF_SIZE];
3409 struct coding_system coding;
3410 bool replace_handled = false;
3411 bool set_coding_system = false;
3412 Lisp_Object coding_system;
3413 bool read_quit = false;
3414 /* If the undo log only contains the insertion, there's no point
3415 keeping it. It's typically when we first fill a file-buffer. */
3416 bool empty_undo_list_p
3417 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3418 && BEG == Z);
3419 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3420 bool we_locked_file = false;
3421 ptrdiff_t fd_index;
3422 Lisp_Object window_markers = Qnil;
3423 /* same_at_start and same_at_end count bytes, because file access counts
3424 bytes and BEG and END count bytes. */
3425 ptrdiff_t same_at_start = BEGV_BYTE;
3426 ptrdiff_t same_at_end = ZV_BYTE;
3427 /* SAME_AT_END_CHARPOS counts characters, because
3428 restore_window_points needs the old character count. */
3429 ptrdiff_t same_at_end_charpos = ZV;
3431 if (current_buffer->base_buffer && ! NILP (visit))
3432 error ("Cannot do file visiting in an indirect buffer");
3434 if (!NILP (BVAR (current_buffer, read_only)))
3435 Fbarf_if_buffer_read_only (Qnil);
3437 val = Qnil;
3438 p = Qnil;
3439 orig_filename = Qnil;
3440 old_undo = Qnil;
3442 CHECK_STRING (filename);
3443 filename = Fexpand_file_name (filename, Qnil);
3445 /* The value Qnil means that the coding system is not yet
3446 decided. */
3447 coding_system = Qnil;
3449 /* If the file name has special constructs in it,
3450 call the corresponding file handler. */
3451 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3452 if (!NILP (handler))
3454 val = call6 (handler, Qinsert_file_contents, filename,
3455 visit, beg, end, replace);
3456 if (CONSP (val) && CONSP (XCDR (val))
3457 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3458 inserted = XINT (XCAR (XCDR (val)));
3459 goto handled;
3462 orig_filename = filename;
3463 filename = ENCODE_FILE (filename);
3465 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3466 if (fd < 0)
3468 save_errno = errno;
3469 if (NILP (visit))
3470 report_file_error ("Opening input file", orig_filename);
3471 mtime = time_error_value (save_errno);
3472 st.st_size = -1;
3473 if (!NILP (Vcoding_system_for_read))
3475 /* Don't let invalid values into buffer-file-coding-system. */
3476 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3477 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3479 goto notfound;
3482 fd_index = SPECPDL_INDEX ();
3483 record_unwind_protect_int (close_file_unwind, fd);
3485 /* Replacement should preserve point as it preserves markers. */
3486 if (!NILP (replace))
3488 window_markers = get_window_points_and_markers ();
3489 record_unwind_protect (restore_point_unwind,
3490 XCAR (XCAR (window_markers)));
3493 if (fstat (fd, &st) != 0)
3494 report_file_error ("Input file status", orig_filename);
3495 mtime = get_stat_mtime (&st);
3497 /* This code will need to be changed in order to work on named
3498 pipes, and it's probably just not worth it. So we should at
3499 least signal an error. */
3500 if (!S_ISREG (st.st_mode))
3502 not_regular = 1;
3504 if (! NILP (visit))
3505 goto notfound;
3507 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3508 xsignal2 (Qfile_error,
3509 build_string ("not a regular file"), orig_filename);
3512 if (!NILP (visit))
3514 if (!NILP (beg) || !NILP (end))
3515 error ("Attempt to visit less than an entire file");
3516 if (BEG < Z && NILP (replace))
3517 error ("Cannot do file visiting in a non-empty buffer");
3520 if (!NILP (beg))
3521 beg_offset = file_offset (beg);
3522 else
3523 beg_offset = 0;
3525 if (!NILP (end))
3526 end_offset = file_offset (end);
3527 else
3529 if (not_regular)
3530 end_offset = TYPE_MAXIMUM (off_t);
3531 else
3533 end_offset = st.st_size;
3535 /* A negative size can happen on a platform that allows file
3536 sizes greater than the maximum off_t value. */
3537 if (end_offset < 0)
3538 buffer_overflow ();
3540 /* The file size returned from stat may be zero, but data
3541 may be readable nonetheless, for example when this is a
3542 file in the /proc filesystem. */
3543 if (end_offset == 0)
3544 end_offset = READ_BUF_SIZE;
3548 /* Check now whether the buffer will become too large,
3549 in the likely case where the file's length is not changing.
3550 This saves a lot of needless work before a buffer overflow. */
3551 if (! not_regular)
3553 /* The likely offset where we will stop reading. We could read
3554 more (or less), if the file grows (or shrinks) as we read it. */
3555 off_t likely_end = min (end_offset, st.st_size);
3557 if (beg_offset < likely_end)
3559 ptrdiff_t buf_bytes
3560 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3561 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3562 off_t likely_growth = likely_end - beg_offset;
3563 if (buf_growth_max < likely_growth)
3564 buffer_overflow ();
3568 /* Prevent redisplay optimizations. */
3569 current_buffer->clip_changed = true;
3571 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3573 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3574 setup_coding_system (coding_system, &coding);
3575 /* Ensure we set Vlast_coding_system_used. */
3576 set_coding_system = true;
3578 else if (BEG < Z)
3580 /* Decide the coding system to use for reading the file now
3581 because we can't use an optimized method for handling
3582 `coding:' tag if the current buffer is not empty. */
3583 if (!NILP (Vcoding_system_for_read))
3584 coding_system = Vcoding_system_for_read;
3585 else
3587 /* Don't try looking inside a file for a coding system
3588 specification if it is not seekable. */
3589 if (! not_regular && ! NILP (Vset_auto_coding_function))
3591 /* Find a coding system specified in the heading two
3592 lines or in the tailing several lines of the file.
3593 We assume that the 1K-byte and 3K-byte for heading
3594 and tailing respectively are sufficient for this
3595 purpose. */
3596 int nread;
3598 if (st.st_size <= (1024 * 4))
3599 nread = emacs_read (fd, read_buf, 1024 * 4);
3600 else
3602 nread = emacs_read (fd, read_buf, 1024);
3603 if (nread == 1024)
3605 int ntail;
3606 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3607 report_file_error ("Setting file position",
3608 orig_filename);
3609 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3610 nread = ntail < 0 ? ntail : nread + ntail;
3614 if (nread < 0)
3615 report_file_error ("Read error", orig_filename);
3616 else if (nread > 0)
3618 AUTO_STRING (name, " *code-converting-work*");
3619 struct buffer *prev = current_buffer;
3620 Lisp_Object workbuf;
3621 struct buffer *buf;
3623 record_unwind_current_buffer ();
3625 workbuf = Fget_buffer_create (name);
3626 buf = XBUFFER (workbuf);
3628 delete_all_overlays (buf);
3629 bset_directory (buf, BVAR (current_buffer, directory));
3630 bset_read_only (buf, Qnil);
3631 bset_filename (buf, Qnil);
3632 bset_undo_list (buf, Qt);
3633 eassert (buf->overlays_before == NULL);
3634 eassert (buf->overlays_after == NULL);
3636 set_buffer_internal (buf);
3637 Ferase_buffer ();
3638 bset_enable_multibyte_characters (buf, Qnil);
3640 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3641 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3642 coding_system = call2 (Vset_auto_coding_function,
3643 filename, make_number (nread));
3644 set_buffer_internal (prev);
3646 /* Discard the unwind protect for recovering the
3647 current buffer. */
3648 specpdl_ptr--;
3650 /* Rewind the file for the actual read done later. */
3651 if (lseek (fd, 0, SEEK_SET) < 0)
3652 report_file_error ("Setting file position", orig_filename);
3656 if (NILP (coding_system))
3658 /* If we have not yet decided a coding system, check
3659 file-coding-system-alist. */
3660 coding_system = CALLN (Ffind_operation_coding_system,
3661 Qinsert_file_contents, orig_filename,
3662 visit, beg, end, replace);
3663 if (CONSP (coding_system))
3664 coding_system = XCAR (coding_system);
3668 if (NILP (coding_system))
3669 coding_system = Qundecided;
3670 else
3671 CHECK_CODING_SYSTEM (coding_system);
3673 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3674 /* We must suppress all character code conversion except for
3675 end-of-line conversion. */
3676 coding_system = raw_text_coding_system (coding_system);
3678 setup_coding_system (coding_system, &coding);
3679 /* Ensure we set Vlast_coding_system_used. */
3680 set_coding_system = true;
3683 /* If requested, replace the accessible part of the buffer
3684 with the file contents. Avoid replacing text at the
3685 beginning or end of the buffer that matches the file contents;
3686 that preserves markers pointing to the unchanged parts.
3688 Here we implement this feature in an optimized way
3689 for the case where code conversion is NOT needed.
3690 The following if-statement handles the case of conversion
3691 in a less optimal way.
3693 If the code conversion is "automatic" then we try using this
3694 method and hope for the best.
3695 But if we discover the need for conversion, we give up on this method
3696 and let the following if-statement handle the replace job. */
3697 if (!NILP (replace)
3698 && BEGV < ZV
3699 && (NILP (coding_system)
3700 || ! CODING_REQUIRE_DECODING (&coding)))
3702 ptrdiff_t overlap;
3703 /* There is still a possibility we will find the need to do code
3704 conversion. If that happens, set this variable to
3705 give up on handling REPLACE in the optimized way. */
3706 bool giveup_match_end = false;
3708 if (beg_offset != 0)
3710 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3711 report_file_error ("Setting file position", orig_filename);
3714 immediate_quit = 1;
3715 QUIT;
3716 /* Count how many chars at the start of the file
3717 match the text at the beginning of the buffer. */
3718 while (1)
3720 int nread, bufpos;
3722 nread = emacs_read (fd, read_buf, sizeof read_buf);
3723 if (nread < 0)
3724 report_file_error ("Read error", orig_filename);
3725 else if (nread == 0)
3726 break;
3728 if (CODING_REQUIRE_DETECTION (&coding))
3730 coding_system = detect_coding_system ((unsigned char *) read_buf,
3731 nread, nread, 1, 0,
3732 coding_system);
3733 setup_coding_system (coding_system, &coding);
3736 if (CODING_REQUIRE_DECODING (&coding))
3737 /* We found that the file should be decoded somehow.
3738 Let's give up here. */
3740 giveup_match_end = true;
3741 break;
3744 bufpos = 0;
3745 while (bufpos < nread && same_at_start < ZV_BYTE
3746 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3747 same_at_start++, bufpos++;
3748 /* If we found a discrepancy, stop the scan.
3749 Otherwise loop around and scan the next bufferful. */
3750 if (bufpos != nread)
3751 break;
3753 immediate_quit = false;
3754 /* If the file matches the buffer completely,
3755 there's no need to replace anything. */
3756 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3758 emacs_close (fd);
3759 clear_unwind_protect (fd_index);
3761 /* Truncate the buffer to the size of the file. */
3762 del_range_1 (same_at_start, same_at_end, 0, 0);
3763 goto handled;
3765 immediate_quit = true;
3766 QUIT;
3767 /* Count how many chars at the end of the file
3768 match the text at the end of the buffer. But, if we have
3769 already found that decoding is necessary, don't waste time. */
3770 while (!giveup_match_end)
3772 int total_read, nread, bufpos, trial;
3773 off_t curpos;
3775 /* At what file position are we now scanning? */
3776 curpos = end_offset - (ZV_BYTE - same_at_end);
3777 /* If the entire file matches the buffer tail, stop the scan. */
3778 if (curpos == 0)
3779 break;
3780 /* How much can we scan in the next step? */
3781 trial = min (curpos, sizeof read_buf);
3782 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3783 report_file_error ("Setting file position", orig_filename);
3785 total_read = nread = 0;
3786 while (total_read < trial)
3788 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3789 if (nread < 0)
3790 report_file_error ("Read error", orig_filename);
3791 else if (nread == 0)
3792 break;
3793 total_read += nread;
3796 /* Scan this bufferful from the end, comparing with
3797 the Emacs buffer. */
3798 bufpos = total_read;
3800 /* Compare with same_at_start to avoid counting some buffer text
3801 as matching both at the file's beginning and at the end. */
3802 while (bufpos > 0 && same_at_end > same_at_start
3803 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3804 same_at_end--, bufpos--;
3806 /* If we found a discrepancy, stop the scan.
3807 Otherwise loop around and scan the preceding bufferful. */
3808 if (bufpos != 0)
3810 /* If this discrepancy is because of code conversion,
3811 we cannot use this method; giveup and try the other. */
3812 if (same_at_end > same_at_start
3813 && FETCH_BYTE (same_at_end - 1) >= 0200
3814 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3815 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3816 giveup_match_end = true;
3817 break;
3820 if (nread == 0)
3821 break;
3823 immediate_quit = 0;
3825 if (! giveup_match_end)
3827 ptrdiff_t temp;
3829 /* We win! We can handle REPLACE the optimized way. */
3831 /* Extend the start of non-matching text area to multibyte
3832 character boundary. */
3833 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3834 while (same_at_start > BEGV_BYTE
3835 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3836 same_at_start--;
3838 /* Extend the end of non-matching text area to multibyte
3839 character boundary. */
3840 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3841 while (same_at_end < ZV_BYTE
3842 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3843 same_at_end++;
3845 /* Don't try to reuse the same piece of text twice. */
3846 overlap = (same_at_start - BEGV_BYTE
3847 - (same_at_end
3848 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3849 if (overlap > 0)
3850 same_at_end += overlap;
3851 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3853 /* Arrange to read only the nonmatching middle part of the file. */
3854 beg_offset += same_at_start - BEGV_BYTE;
3855 end_offset -= ZV_BYTE - same_at_end;
3857 invalidate_buffer_caches (current_buffer,
3858 BYTE_TO_CHAR (same_at_start),
3859 same_at_end_charpos);
3860 del_range_byte (same_at_start, same_at_end, 0);
3861 /* Insert from the file at the proper position. */
3862 temp = BYTE_TO_CHAR (same_at_start);
3863 SET_PT_BOTH (temp, same_at_start);
3865 /* If display currently starts at beginning of line,
3866 keep it that way. */
3867 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3868 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3870 replace_handled = true;
3874 /* If requested, replace the accessible part of the buffer
3875 with the file contents. Avoid replacing text at the
3876 beginning or end of the buffer that matches the file contents;
3877 that preserves markers pointing to the unchanged parts.
3879 Here we implement this feature for the case where code conversion
3880 is needed, in a simple way that needs a lot of memory.
3881 The preceding if-statement handles the case of no conversion
3882 in a more optimized way. */
3883 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3885 ptrdiff_t same_at_start_charpos;
3886 ptrdiff_t inserted_chars;
3887 ptrdiff_t overlap;
3888 ptrdiff_t bufpos;
3889 unsigned char *decoded;
3890 ptrdiff_t temp;
3891 ptrdiff_t this = 0;
3892 ptrdiff_t this_count = SPECPDL_INDEX ();
3893 bool multibyte
3894 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3895 Lisp_Object conversion_buffer;
3897 conversion_buffer = code_conversion_save (1, multibyte);
3899 /* First read the whole file, performing code conversion into
3900 CONVERSION_BUFFER. */
3902 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3903 report_file_error ("Setting file position", orig_filename);
3905 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3906 unprocessed = 0; /* Bytes not processed in previous loop. */
3908 while (1)
3910 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3911 quitting while reading a huge file. */
3913 /* Allow quitting out of the actual I/O. */
3914 immediate_quit = 1;
3915 QUIT;
3916 this = emacs_read (fd, read_buf + unprocessed,
3917 READ_BUF_SIZE - unprocessed);
3918 immediate_quit = 0;
3920 if (this <= 0)
3921 break;
3923 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3924 BUF_Z (XBUFFER (conversion_buffer)));
3925 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3926 unprocessed + this, conversion_buffer);
3927 unprocessed = coding.carryover_bytes;
3928 if (coding.carryover_bytes > 0)
3929 memcpy (read_buf, coding.carryover, unprocessed);
3932 if (this < 0)
3933 report_file_error ("Read error", orig_filename);
3934 emacs_close (fd);
3935 clear_unwind_protect (fd_index);
3937 if (unprocessed > 0)
3939 coding.mode |= CODING_MODE_LAST_BLOCK;
3940 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3941 unprocessed, conversion_buffer);
3942 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3945 coding_system = CODING_ID_NAME (coding.id);
3946 set_coding_system = true;
3947 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3948 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3949 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3951 /* Compare the beginning of the converted string with the buffer
3952 text. */
3954 bufpos = 0;
3955 while (bufpos < inserted && same_at_start < same_at_end
3956 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3957 same_at_start++, bufpos++;
3959 /* If the file matches the head of buffer completely,
3960 there's no need to replace anything. */
3962 if (bufpos == inserted)
3964 /* Truncate the buffer to the size of the file. */
3965 if (same_at_start != same_at_end)
3967 invalidate_buffer_caches (current_buffer,
3968 BYTE_TO_CHAR (same_at_start),
3969 BYTE_TO_CHAR (same_at_end));
3970 del_range_byte (same_at_start, same_at_end, 0);
3972 inserted = 0;
3974 unbind_to (this_count, Qnil);
3975 goto handled;
3978 /* Extend the start of non-matching text area to the previous
3979 multibyte character boundary. */
3980 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3981 while (same_at_start > BEGV_BYTE
3982 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3983 same_at_start--;
3985 /* Scan this bufferful from the end, comparing with
3986 the Emacs buffer. */
3987 bufpos = inserted;
3989 /* Compare with same_at_start to avoid counting some buffer text
3990 as matching both at the file's beginning and at the end. */
3991 while (bufpos > 0 && same_at_end > same_at_start
3992 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3993 same_at_end--, bufpos--;
3995 /* Extend the end of non-matching text area to the next
3996 multibyte character boundary. */
3997 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3998 while (same_at_end < ZV_BYTE
3999 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4000 same_at_end++;
4002 /* Don't try to reuse the same piece of text twice. */
4003 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4004 if (overlap > 0)
4005 same_at_end += overlap;
4006 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4008 /* If display currently starts at beginning of line,
4009 keep it that way. */
4010 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4011 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4013 /* Replace the chars that we need to replace,
4014 and update INSERTED to equal the number of bytes
4015 we are taking from the decoded string. */
4016 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4018 if (same_at_end != same_at_start)
4020 invalidate_buffer_caches (current_buffer,
4021 BYTE_TO_CHAR (same_at_start),
4022 same_at_end_charpos);
4023 del_range_byte (same_at_start, same_at_end, 0);
4024 temp = GPT;
4025 eassert (same_at_start == GPT_BYTE);
4026 same_at_start = GPT_BYTE;
4028 else
4030 temp = same_at_end_charpos;
4032 /* Insert from the file at the proper position. */
4033 SET_PT_BOTH (temp, same_at_start);
4034 same_at_start_charpos
4035 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4036 same_at_start - BEGV_BYTE
4037 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4038 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4039 inserted_chars
4040 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4041 same_at_start + inserted - BEGV_BYTE
4042 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4043 - same_at_start_charpos);
4044 /* This binding is to avoid ask-user-about-supersession-threat
4045 being called in insert_from_buffer (via in
4046 prepare_to_modify_buffer). */
4047 specbind (intern ("buffer-file-name"), Qnil);
4048 insert_from_buffer (XBUFFER (conversion_buffer),
4049 same_at_start_charpos, inserted_chars, 0);
4050 /* Set `inserted' to the number of inserted characters. */
4051 inserted = PT - temp;
4052 /* Set point before the inserted characters. */
4053 SET_PT_BOTH (temp, same_at_start);
4055 unbind_to (this_count, Qnil);
4057 goto handled;
4060 if (! not_regular)
4061 total = end_offset - beg_offset;
4062 else
4063 /* For a special file, all we can do is guess. */
4064 total = READ_BUF_SIZE;
4066 if (NILP (visit) && total > 0)
4068 if (!NILP (BVAR (current_buffer, file_truename))
4069 /* Make binding buffer-file-name to nil effective. */
4070 && !NILP (BVAR (current_buffer, filename))
4071 && SAVE_MODIFF >= MODIFF)
4072 we_locked_file = true;
4073 prepare_to_modify_buffer (PT, PT, NULL);
4076 move_gap_both (PT, PT_BYTE);
4077 if (GAP_SIZE < total)
4078 make_gap (total - GAP_SIZE);
4080 if (beg_offset != 0 || !NILP (replace))
4082 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4083 report_file_error ("Setting file position", orig_filename);
4086 /* In the following loop, HOW_MUCH contains the total bytes read so
4087 far for a regular file, and not changed for a special file. But,
4088 before exiting the loop, it is set to a negative value if I/O
4089 error occurs. */
4090 how_much = 0;
4092 /* Total bytes inserted. */
4093 inserted = 0;
4095 /* Here, we don't do code conversion in the loop. It is done by
4096 decode_coding_gap after all data are read into the buffer. */
4098 ptrdiff_t gap_size = GAP_SIZE;
4100 while (how_much < total)
4102 /* `try' is reserved in some compilers (Microsoft C). */
4103 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4104 ptrdiff_t this;
4106 if (not_regular)
4108 Lisp_Object nbytes;
4110 /* Maybe make more room. */
4111 if (gap_size < trytry)
4113 make_gap (trytry - gap_size);
4114 gap_size = GAP_SIZE - inserted;
4117 /* Read from the file, capturing `quit'. When an
4118 error occurs, end the loop, and arrange for a quit
4119 to be signaled after decoding the text we read. */
4120 nbytes = internal_condition_case_1
4121 (read_non_regular,
4122 make_save_int_int_int (fd, inserted, trytry),
4123 Qerror, read_non_regular_quit);
4125 if (NILP (nbytes))
4127 read_quit = true;
4128 break;
4131 this = XINT (nbytes);
4133 else
4135 /* Allow quitting out of the actual I/O. We don't make text
4136 part of the buffer until all the reading is done, so a C-g
4137 here doesn't do any harm. */
4138 immediate_quit = 1;
4139 QUIT;
4140 this = emacs_read (fd,
4141 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4142 + inserted),
4143 trytry);
4144 immediate_quit = 0;
4147 if (this <= 0)
4149 how_much = this;
4150 break;
4153 gap_size -= this;
4155 /* For a regular file, where TOTAL is the real size,
4156 count HOW_MUCH to compare with it.
4157 For a special file, where TOTAL is just a buffer size,
4158 so don't bother counting in HOW_MUCH.
4159 (INSERTED is where we count the number of characters inserted.) */
4160 if (! not_regular)
4161 how_much += this;
4162 inserted += this;
4166 /* Now we have either read all the file data into the gap,
4167 or stop reading on I/O error or quit. If nothing was
4168 read, undo marking the buffer modified. */
4170 if (inserted == 0)
4172 if (we_locked_file)
4173 unlock_file (BVAR (current_buffer, file_truename));
4174 Vdeactivate_mark = old_Vdeactivate_mark;
4176 else
4177 Fset (Qdeactivate_mark, Qt);
4179 emacs_close (fd);
4180 clear_unwind_protect (fd_index);
4182 if (how_much < 0)
4183 report_file_error ("Read error", orig_filename);
4185 /* Make the text read part of the buffer. */
4186 GAP_SIZE -= inserted;
4187 GPT += inserted;
4188 GPT_BYTE += inserted;
4189 ZV += inserted;
4190 ZV_BYTE += inserted;
4191 Z += inserted;
4192 Z_BYTE += inserted;
4194 if (GAP_SIZE > 0)
4195 /* Put an anchor to ensure multi-byte form ends at gap. */
4196 *GPT_ADDR = 0;
4198 notfound:
4200 if (NILP (coding_system))
4202 /* The coding system is not yet decided. Decide it by an
4203 optimized method for handling `coding:' tag.
4205 Note that we can get here only if the buffer was empty
4206 before the insertion. */
4208 if (!NILP (Vcoding_system_for_read))
4209 coding_system = Vcoding_system_for_read;
4210 else
4212 /* Since we are sure that the current buffer was empty
4213 before the insertion, we can toggle
4214 enable-multibyte-characters directly here without taking
4215 care of marker adjustment. By this way, we can run Lisp
4216 program safely before decoding the inserted text. */
4217 Lisp_Object unwind_data;
4218 ptrdiff_t count1 = SPECPDL_INDEX ();
4220 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4221 Fcons (BVAR (current_buffer, undo_list),
4222 Fcurrent_buffer ()));
4223 bset_enable_multibyte_characters (current_buffer, Qnil);
4224 bset_undo_list (current_buffer, Qt);
4225 record_unwind_protect (decide_coding_unwind, unwind_data);
4227 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4229 coding_system = call2 (Vset_auto_coding_function,
4230 filename, make_number (inserted));
4233 if (NILP (coding_system))
4235 /* If the coding system is not yet decided, check
4236 file-coding-system-alist. */
4237 coding_system = CALLN (Ffind_operation_coding_system,
4238 Qinsert_file_contents, orig_filename,
4239 visit, beg, end, Qnil);
4240 if (CONSP (coding_system))
4241 coding_system = XCAR (coding_system);
4243 unbind_to (count1, Qnil);
4244 inserted = Z_BYTE - BEG_BYTE;
4247 if (NILP (coding_system))
4248 coding_system = Qundecided;
4249 else
4250 CHECK_CODING_SYSTEM (coding_system);
4252 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4253 /* We must suppress all character code conversion except for
4254 end-of-line conversion. */
4255 coding_system = raw_text_coding_system (coding_system);
4256 setup_coding_system (coding_system, &coding);
4257 /* Ensure we set Vlast_coding_system_used. */
4258 set_coding_system = true;
4261 if (!NILP (visit))
4263 /* When we visit a file by raw-text, we change the buffer to
4264 unibyte. */
4265 if (CODING_FOR_UNIBYTE (&coding)
4266 /* Can't do this if part of the buffer might be preserved. */
4267 && NILP (replace))
4269 /* Visiting a file with these coding system makes the buffer
4270 unibyte. */
4271 if (inserted > 0)
4272 bset_enable_multibyte_characters (current_buffer, Qnil);
4273 else
4274 Fset_buffer_multibyte (Qnil);
4278 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4279 if (CODING_MAY_REQUIRE_DECODING (&coding)
4280 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4282 move_gap_both (PT, PT_BYTE);
4283 GAP_SIZE += inserted;
4284 ZV_BYTE -= inserted;
4285 Z_BYTE -= inserted;
4286 ZV -= inserted;
4287 Z -= inserted;
4288 decode_coding_gap (&coding, inserted, inserted);
4289 inserted = coding.produced_char;
4290 coding_system = CODING_ID_NAME (coding.id);
4292 else if (inserted > 0)
4294 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4295 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4296 inserted);
4299 /* Call after-change hooks for the inserted text, aside from the case
4300 of normal visiting (not with REPLACE), which is done in a new buffer
4301 "before" the buffer is changed. */
4302 if (inserted > 0 && total > 0
4303 && (NILP (visit) || !NILP (replace)))
4305 signal_after_change (PT, 0, inserted);
4306 update_compositions (PT, PT, CHECK_BORDER);
4309 /* Now INSERTED is measured in characters. */
4311 handled:
4313 if (inserted > 0)
4314 restore_window_points (window_markers, inserted,
4315 BYTE_TO_CHAR (same_at_start),
4316 same_at_end_charpos);
4318 if (!NILP (visit))
4320 if (empty_undo_list_p)
4321 bset_undo_list (current_buffer, Qnil);
4323 if (NILP (handler))
4325 current_buffer->modtime = mtime;
4326 current_buffer->modtime_size = st.st_size;
4327 bset_filename (current_buffer, orig_filename);
4330 SAVE_MODIFF = MODIFF;
4331 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4332 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4333 if (NILP (handler))
4335 if (!NILP (BVAR (current_buffer, file_truename)))
4336 unlock_file (BVAR (current_buffer, file_truename));
4337 unlock_file (filename);
4339 if (not_regular)
4340 xsignal2 (Qfile_error,
4341 build_string ("not a regular file"), orig_filename);
4344 if (set_coding_system)
4345 Vlast_coding_system_used = coding_system;
4347 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4349 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4350 visit);
4351 if (! NILP (insval))
4353 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4354 wrong_type_argument (intern ("inserted-chars"), insval);
4355 inserted = XFASTINT (insval);
4359 /* Decode file format. */
4360 if (inserted > 0)
4362 /* Don't run point motion or modification hooks when decoding. */
4363 ptrdiff_t count1 = SPECPDL_INDEX ();
4364 ptrdiff_t old_inserted = inserted;
4365 specbind (Qinhibit_point_motion_hooks, Qt);
4366 specbind (Qinhibit_modification_hooks, Qt);
4368 /* Save old undo list and don't record undo for decoding. */
4369 old_undo = BVAR (current_buffer, undo_list);
4370 bset_undo_list (current_buffer, Qt);
4372 if (NILP (replace))
4374 insval = call3 (Qformat_decode,
4375 Qnil, make_number (inserted), visit);
4376 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4377 wrong_type_argument (intern ("inserted-chars"), insval);
4378 inserted = XFASTINT (insval);
4380 else
4382 /* If REPLACE is non-nil and we succeeded in not replacing the
4383 beginning or end of the buffer text with the file's contents,
4384 call format-decode with `point' positioned at the beginning
4385 of the buffer and `inserted' equaling the number of
4386 characters in the buffer. Otherwise, format-decode might
4387 fail to correctly analyze the beginning or end of the buffer.
4388 Hence we temporarily save `point' and `inserted' here and
4389 restore `point' iff format-decode did not insert or delete
4390 any text. Otherwise we leave `point' at point-min. */
4391 ptrdiff_t opoint = PT;
4392 ptrdiff_t opoint_byte = PT_BYTE;
4393 ptrdiff_t oinserted = ZV - BEGV;
4394 EMACS_INT ochars_modiff = CHARS_MODIFF;
4396 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4397 insval = call3 (Qformat_decode,
4398 Qnil, make_number (oinserted), visit);
4399 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4400 wrong_type_argument (intern ("inserted-chars"), insval);
4401 if (ochars_modiff == CHARS_MODIFF)
4402 /* format_decode didn't modify buffer's characters => move
4403 point back to position before inserted text and leave
4404 value of inserted alone. */
4405 SET_PT_BOTH (opoint, opoint_byte);
4406 else
4407 /* format_decode modified buffer's characters => consider
4408 entire buffer changed and leave point at point-min. */
4409 inserted = XFASTINT (insval);
4412 /* For consistency with format-decode call these now iff inserted > 0
4413 (martin 2007-06-28). */
4414 p = Vafter_insert_file_functions;
4415 while (CONSP (p))
4417 if (NILP (replace))
4419 insval = call1 (XCAR (p), make_number (inserted));
4420 if (!NILP (insval))
4422 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4423 wrong_type_argument (intern ("inserted-chars"), insval);
4424 inserted = XFASTINT (insval);
4427 else
4429 /* For the rationale of this see the comment on
4430 format-decode above. */
4431 ptrdiff_t opoint = PT;
4432 ptrdiff_t opoint_byte = PT_BYTE;
4433 ptrdiff_t oinserted = ZV - BEGV;
4434 EMACS_INT ochars_modiff = CHARS_MODIFF;
4436 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4437 insval = call1 (XCAR (p), make_number (oinserted));
4438 if (!NILP (insval))
4440 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4441 wrong_type_argument (intern ("inserted-chars"), insval);
4442 if (ochars_modiff == CHARS_MODIFF)
4443 /* after_insert_file_functions didn't modify
4444 buffer's characters => move point back to
4445 position before inserted text and leave value of
4446 inserted alone. */
4447 SET_PT_BOTH (opoint, opoint_byte);
4448 else
4449 /* after_insert_file_functions did modify buffer's
4450 characters => consider entire buffer changed and
4451 leave point at point-min. */
4452 inserted = XFASTINT (insval);
4456 QUIT;
4457 p = XCDR (p);
4460 if (!empty_undo_list_p)
4462 bset_undo_list (current_buffer, old_undo);
4463 if (CONSP (old_undo) && inserted != old_inserted)
4465 /* Adjust the last undo record for the size change during
4466 the format conversion. */
4467 Lisp_Object tem = XCAR (old_undo);
4468 if (CONSP (tem) && INTEGERP (XCAR (tem))
4469 && INTEGERP (XCDR (tem))
4470 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4471 XSETCDR (tem, make_number (PT + inserted));
4474 else
4475 /* If undo_list was Qt before, keep it that way.
4476 Otherwise start with an empty undo_list. */
4477 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4479 unbind_to (count1, Qnil);
4482 if (!NILP (visit)
4483 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4485 /* If visiting nonexistent file, return nil. */
4486 report_file_errno ("Opening input file", orig_filename, save_errno);
4489 /* We made a lot of deletions and insertions above, so invalidate
4490 the newline cache for the entire region of the inserted
4491 characters. */
4492 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4493 invalidate_region_cache (current_buffer->base_buffer,
4494 current_buffer->base_buffer->newline_cache,
4495 PT - BEG, Z - PT - inserted);
4496 else if (current_buffer->newline_cache)
4497 invalidate_region_cache (current_buffer,
4498 current_buffer->newline_cache,
4499 PT - BEG, Z - PT - inserted);
4501 if (read_quit)
4502 Fsignal (Qquit, Qnil);
4504 /* Retval needs to be dealt with in all cases consistently. */
4505 if (NILP (val))
4506 val = list2 (orig_filename, make_number (inserted));
4508 return unbind_to (count, val);
4511 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4513 static void
4514 build_annotations_unwind (Lisp_Object arg)
4516 Vwrite_region_annotation_buffers = arg;
4519 /* Decide the coding-system to encode the data with. */
4521 static Lisp_Object
4522 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4523 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4524 struct coding_system *coding)
4526 Lisp_Object val;
4527 Lisp_Object eol_parent = Qnil;
4529 if (auto_saving
4530 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4531 BVAR (current_buffer, auto_save_file_name))))
4533 val = Qutf_8_emacs;
4534 eol_parent = Qunix;
4536 else if (!NILP (Vcoding_system_for_write))
4538 val = Vcoding_system_for_write;
4539 if (coding_system_require_warning
4540 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4541 /* Confirm that VAL can surely encode the current region. */
4542 val = call5 (Vselect_safe_coding_system_function,
4543 start, end, list2 (Qt, val),
4544 Qnil, filename);
4546 else
4548 /* If the variable `buffer-file-coding-system' is set locally,
4549 it means that the file was read with some kind of code
4550 conversion or the variable is explicitly set by users. We
4551 had better write it out with the same coding system even if
4552 `enable-multibyte-characters' is nil.
4554 If it is not set locally, we anyway have to convert EOL
4555 format if the default value of `buffer-file-coding-system'
4556 tells that it is not Unix-like (LF only) format. */
4557 bool using_default_coding = 0;
4558 bool force_raw_text = 0;
4560 val = BVAR (current_buffer, buffer_file_coding_system);
4561 if (NILP (val)
4562 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4564 val = Qnil;
4565 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4566 force_raw_text = 1;
4569 if (NILP (val))
4571 /* Check file-coding-system-alist. */
4572 Lisp_Object coding_systems
4573 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4574 filename, append, visit, lockname);
4575 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4576 val = XCDR (coding_systems);
4579 if (NILP (val))
4581 /* If we still have not decided a coding system, use the
4582 current buffer's value of buffer-file-coding-system. */
4583 val = BVAR (current_buffer, buffer_file_coding_system);
4584 using_default_coding = 1;
4587 if (! NILP (val) && ! force_raw_text)
4589 Lisp_Object spec, attrs;
4591 CHECK_CODING_SYSTEM (val);
4592 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4593 attrs = AREF (spec, 0);
4594 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4595 force_raw_text = 1;
4598 if (!force_raw_text
4599 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4601 /* Confirm that VAL can surely encode the current region. */
4602 val = call5 (Vselect_safe_coding_system_function,
4603 start, end, val, Qnil, filename);
4604 /* As the function specified by select-safe-coding-system-function
4605 is out of our control, make sure we are not fed by bogus
4606 values. */
4607 if (!NILP (val))
4608 CHECK_CODING_SYSTEM (val);
4611 /* If the decided coding-system doesn't specify end-of-line
4612 format, we use that of
4613 `default-buffer-file-coding-system'. */
4614 if (! using_default_coding)
4616 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4618 if (! NILP (dflt))
4619 val = coding_inherit_eol_type (val, dflt);
4622 /* If we decide not to encode text, use `raw-text' or one of its
4623 subsidiaries. */
4624 if (force_raw_text)
4625 val = raw_text_coding_system (val);
4628 val = coding_inherit_eol_type (val, eol_parent);
4629 setup_coding_system (val, coding);
4631 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4632 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4633 return val;
4636 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4637 "r\nFWrite region to file: \ni\ni\ni\np",
4638 doc: /* Write current region into specified file.
4639 When called from a program, requires three arguments:
4640 START, END and FILENAME. START and END are normally buffer positions
4641 specifying the part of the buffer to write.
4642 If START is nil, that means to use the entire buffer contents.
4643 If START is a string, then output that string to the file
4644 instead of any buffer contents; END is ignored.
4646 Optional fourth argument APPEND if non-nil means
4647 append to existing file contents (if any). If it is a number,
4648 seek to that offset in the file before writing.
4649 Optional fifth argument VISIT, if t or a string, means
4650 set the last-save-file-modtime of buffer to this file's modtime
4651 and mark buffer not modified.
4652 If VISIT is a string, it is a second file name;
4653 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4654 VISIT is also the file name to lock and unlock for clash detection.
4655 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4656 do not display the \"Wrote file\" message.
4657 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4658 use for locking and unlocking, overriding FILENAME and VISIT.
4659 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4660 for an existing file with the same name. If MUSTBENEW is `excl',
4661 that means to get an error if the file already exists; never overwrite.
4662 If MUSTBENEW is neither nil nor `excl', that means ask for
4663 confirmation before overwriting, but do go ahead and overwrite the file
4664 if the user confirms.
4666 This does code conversion according to the value of
4667 `coding-system-for-write', `buffer-file-coding-system', or
4668 `file-coding-system-alist', and sets the variable
4669 `last-coding-system-used' to the coding system actually used.
4671 This calls `write-region-annotate-functions' at the start, and
4672 `write-region-post-annotation-function' at the end. */)
4673 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4674 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4676 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4677 -1);
4680 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4681 descriptor for FILENAME, so do not open or close FILENAME. */
4683 Lisp_Object
4684 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4685 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4686 Lisp_Object mustbenew, int desc)
4688 int open_flags;
4689 int mode;
4690 off_t offset IF_LINT (= 0);
4691 bool open_and_close_file = desc < 0;
4692 bool ok;
4693 int save_errno = 0;
4694 const char *fn;
4695 struct stat st;
4696 struct timespec modtime;
4697 ptrdiff_t count = SPECPDL_INDEX ();
4698 ptrdiff_t count1 IF_LINT (= 0);
4699 Lisp_Object handler;
4700 Lisp_Object visit_file;
4701 Lisp_Object annotations;
4702 Lisp_Object encoded_filename;
4703 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4704 bool quietly = !NILP (visit);
4705 bool file_locked = 0;
4706 struct buffer *given_buffer;
4707 struct coding_system coding;
4709 if (current_buffer->base_buffer && visiting)
4710 error ("Cannot do file visiting in an indirect buffer");
4712 if (!NILP (start) && !STRINGP (start))
4713 validate_region (&start, &end);
4715 visit_file = Qnil;
4717 filename = Fexpand_file_name (filename, Qnil);
4719 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4720 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4722 if (STRINGP (visit))
4723 visit_file = Fexpand_file_name (visit, Qnil);
4724 else
4725 visit_file = filename;
4727 if (NILP (lockname))
4728 lockname = visit_file;
4730 annotations = Qnil;
4732 /* If the file name has special constructs in it,
4733 call the corresponding file handler. */
4734 handler = Ffind_file_name_handler (filename, Qwrite_region);
4735 /* If FILENAME has no handler, see if VISIT has one. */
4736 if (NILP (handler) && STRINGP (visit))
4737 handler = Ffind_file_name_handler (visit, Qwrite_region);
4739 if (!NILP (handler))
4741 Lisp_Object val;
4742 val = call6 (handler, Qwrite_region, start, end,
4743 filename, append, visit);
4745 if (visiting)
4747 SAVE_MODIFF = MODIFF;
4748 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4749 bset_filename (current_buffer, visit_file);
4752 return val;
4755 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4757 /* Special kludge to simplify auto-saving. */
4758 if (NILP (start))
4760 /* Do it later, so write-region-annotate-function can work differently
4761 if we save "the buffer" vs "a region".
4762 This is useful in tar-mode. --Stef
4763 XSETFASTINT (start, BEG);
4764 XSETFASTINT (end, Z); */
4765 Fwiden ();
4768 record_unwind_protect (build_annotations_unwind,
4769 Vwrite_region_annotation_buffers);
4770 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4772 given_buffer = current_buffer;
4774 if (!STRINGP (start))
4776 annotations = build_annotations (start, end);
4778 if (current_buffer != given_buffer)
4780 XSETFASTINT (start, BEGV);
4781 XSETFASTINT (end, ZV);
4785 if (NILP (start))
4787 XSETFASTINT (start, BEGV);
4788 XSETFASTINT (end, ZV);
4791 /* Decide the coding-system to encode the data with.
4792 We used to make this choice before calling build_annotations, but that
4793 leads to problems when a write-annotate-function takes care of
4794 unsavable chars (as was the case with X-Symbol). */
4795 Vlast_coding_system_used
4796 = choose_write_coding_system (start, end, filename,
4797 append, visit, lockname, &coding);
4799 if (open_and_close_file && !auto_saving)
4801 lock_file (lockname);
4802 file_locked = 1;
4805 encoded_filename = ENCODE_FILE (filename);
4806 fn = SSDATA (encoded_filename);
4807 open_flags = O_WRONLY | O_CREAT;
4808 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4809 if (NUMBERP (append))
4810 offset = file_offset (append);
4811 else if (!NILP (append))
4812 open_flags |= O_APPEND;
4813 #ifdef DOS_NT
4814 mode = S_IREAD | S_IWRITE;
4815 #else
4816 mode = auto_saving ? auto_save_mode_bits : 0666;
4817 #endif
4819 if (open_and_close_file)
4821 desc = emacs_open (fn, open_flags, mode);
4822 if (desc < 0)
4824 int open_errno = errno;
4825 if (file_locked)
4826 unlock_file (lockname);
4827 report_file_errno ("Opening output file", filename, open_errno);
4830 count1 = SPECPDL_INDEX ();
4831 record_unwind_protect_int (close_file_unwind, desc);
4834 if (NUMBERP (append))
4836 off_t ret = lseek (desc, offset, SEEK_SET);
4837 if (ret < 0)
4839 int lseek_errno = errno;
4840 if (file_locked)
4841 unlock_file (lockname);
4842 report_file_errno ("Lseek error", filename, lseek_errno);
4846 immediate_quit = 1;
4848 if (STRINGP (start))
4849 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4850 else if (XINT (start) != XINT (end))
4851 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4852 &annotations, &coding);
4853 else
4855 /* If file was empty, still need to write the annotations. */
4856 coding.mode |= CODING_MODE_LAST_BLOCK;
4857 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4859 save_errno = errno;
4861 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4862 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4864 /* We have to flush out a data. */
4865 coding.mode |= CODING_MODE_LAST_BLOCK;
4866 ok = e_write (desc, Qnil, 1, 1, &coding);
4867 save_errno = errno;
4870 immediate_quit = 0;
4872 /* fsync is not crucial for temporary files. Nor for auto-save
4873 files, since they might lose some work anyway. */
4874 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4876 /* Transfer data and metadata to disk, retrying if interrupted.
4877 fsync can report a write failure here, e.g., due to disk full
4878 under NFS. But ignore EINVAL, which means fsync is not
4879 supported on this file. */
4880 while (fsync (desc) != 0)
4881 if (errno != EINTR)
4883 if (errno != EINVAL)
4884 ok = 0, save_errno = errno;
4885 break;
4889 modtime = invalid_timespec ();
4890 if (visiting)
4892 if (fstat (desc, &st) == 0)
4893 modtime = get_stat_mtime (&st);
4894 else
4895 ok = 0, save_errno = errno;
4898 if (open_and_close_file)
4900 /* NFS can report a write failure now. */
4901 if (emacs_close (desc) < 0)
4902 ok = 0, save_errno = errno;
4904 /* Discard the unwind protect for close_file_unwind. */
4905 specpdl_ptr = specpdl + count1;
4908 /* Some file systems have a bug where st_mtime is not updated
4909 properly after a write. For example, CIFS might not see the
4910 st_mtime change until after the file is opened again.
4912 Attempt to detect this file system bug, and update MODTIME to the
4913 newer st_mtime if the bug appears to be present. This introduces
4914 a race condition, so to avoid most instances of the race condition
4915 on non-buggy file systems, skip this check if the most recently
4916 encountered non-buggy file system was the current file system.
4918 A race condition can occur if some other process modifies the
4919 file between the fstat above and the fstat below, but the race is
4920 unlikely and a similar race between the last write and the fstat
4921 above cannot possibly be closed anyway. */
4923 if (timespec_valid_p (modtime)
4924 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4926 int desc1 = emacs_open (fn, O_WRONLY, 0);
4927 if (desc1 >= 0)
4929 struct stat st1;
4930 if (fstat (desc1, &st1) == 0
4931 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4933 /* Use the heuristic if it appears to be valid. With neither
4934 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4935 file, the time stamp won't change. Also, some non-POSIX
4936 systems don't update an empty file's time stamp when
4937 truncating it. Finally, file systems with 100 ns or worse
4938 resolution sometimes seem to have bugs: on a system with ns
4939 resolution, checking ns % 100 incorrectly avoids the heuristic
4940 1% of the time, but the problem should be temporary as we will
4941 try again on the next time stamp. */
4942 bool use_heuristic
4943 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4944 && st.st_size != 0
4945 && modtime.tv_nsec % 100 != 0);
4947 struct timespec modtime1 = get_stat_mtime (&st1);
4948 if (use_heuristic
4949 && timespec_cmp (modtime, modtime1) == 0
4950 && st.st_size == st1.st_size)
4952 timestamp_file_system = st.st_dev;
4953 valid_timestamp_file_system = 1;
4955 else
4957 st.st_size = st1.st_size;
4958 modtime = modtime1;
4961 emacs_close (desc1);
4965 /* Call write-region-post-annotation-function. */
4966 while (CONSP (Vwrite_region_annotation_buffers))
4968 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4969 if (!NILP (Fbuffer_live_p (buf)))
4971 Fset_buffer (buf);
4972 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4973 call0 (Vwrite_region_post_annotation_function);
4975 Vwrite_region_annotation_buffers
4976 = XCDR (Vwrite_region_annotation_buffers);
4979 unbind_to (count, Qnil);
4981 if (file_locked)
4982 unlock_file (lockname);
4984 /* Do this before reporting IO error
4985 to avoid a "file has changed on disk" warning on
4986 next attempt to save. */
4987 if (timespec_valid_p (modtime))
4989 current_buffer->modtime = modtime;
4990 current_buffer->modtime_size = st.st_size;
4993 if (! ok)
4994 report_file_errno ("Write error", filename, save_errno);
4996 if (visiting)
4998 SAVE_MODIFF = MODIFF;
4999 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5000 bset_filename (current_buffer, visit_file);
5001 update_mode_lines = 14;
5003 else if (quietly)
5005 if (auto_saving
5006 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5007 BVAR (current_buffer, auto_save_file_name))))
5008 SAVE_MODIFF = MODIFF;
5010 return Qnil;
5013 if (!auto_saving && !noninteractive)
5014 message_with_string ((NUMBERP (append)
5015 ? "Updated %s"
5016 : ! NILP (append)
5017 ? "Added to %s"
5018 : "Wrote %s"),
5019 visit_file, 1);
5021 return Qnil;
5024 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5025 doc: /* Return t if (car A) is numerically less than (car B). */)
5026 (Lisp_Object a, Lisp_Object b)
5028 return CALLN (Flss, Fcar (a), Fcar (b));
5031 /* Build the complete list of annotations appropriate for writing out
5032 the text between START and END, by calling all the functions in
5033 write-region-annotate-functions and merging the lists they return.
5034 If one of these functions switches to a different buffer, we assume
5035 that buffer contains altered text. Therefore, the caller must
5036 make sure to restore the current buffer in all cases,
5037 as save-excursion would do. */
5039 static Lisp_Object
5040 build_annotations (Lisp_Object start, Lisp_Object end)
5042 Lisp_Object annotations;
5043 Lisp_Object p, res;
5044 Lisp_Object original_buffer;
5045 int i;
5046 bool used_global = false;
5048 XSETBUFFER (original_buffer, current_buffer);
5050 annotations = Qnil;
5051 p = Vwrite_region_annotate_functions;
5052 while (CONSP (p))
5054 struct buffer *given_buffer = current_buffer;
5055 if (EQ (Qt, XCAR (p)) && !used_global)
5056 { /* Use the global value of the hook. */
5057 used_global = true;
5058 p = CALLN (Fappend,
5059 Fdefault_value (Qwrite_region_annotate_functions),
5060 XCDR (p));
5061 continue;
5063 Vwrite_region_annotations_so_far = annotations;
5064 res = call2 (XCAR (p), start, end);
5065 /* If the function makes a different buffer current,
5066 assume that means this buffer contains altered text to be output.
5067 Reset START and END from the buffer bounds
5068 and discard all previous annotations because they should have
5069 been dealt with by this function. */
5070 if (current_buffer != given_buffer)
5072 Vwrite_region_annotation_buffers
5073 = Fcons (Fcurrent_buffer (),
5074 Vwrite_region_annotation_buffers);
5075 XSETFASTINT (start, BEGV);
5076 XSETFASTINT (end, ZV);
5077 annotations = Qnil;
5079 Flength (res); /* Check basic validity of return value */
5080 annotations = merge (annotations, res, Qcar_less_than_car);
5081 p = XCDR (p);
5084 /* Now do the same for annotation functions implied by the file-format */
5085 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5086 p = BVAR (current_buffer, auto_save_file_format);
5087 else
5088 p = BVAR (current_buffer, file_format);
5089 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5091 struct buffer *given_buffer = current_buffer;
5093 Vwrite_region_annotations_so_far = annotations;
5095 /* Value is either a list of annotations or nil if the function
5096 has written annotations to a temporary buffer, which is now
5097 current. */
5098 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5099 original_buffer, make_number (i));
5100 if (current_buffer != given_buffer)
5102 XSETFASTINT (start, BEGV);
5103 XSETFASTINT (end, ZV);
5104 annotations = Qnil;
5107 if (CONSP (res))
5108 annotations = merge (annotations, res, Qcar_less_than_car);
5111 return annotations;
5115 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5116 If STRING is nil, POS is the character position in the current buffer.
5117 Intersperse with them the annotations from *ANNOT
5118 which fall within the range of POS to POS + NCHARS,
5119 each at its appropriate position.
5121 We modify *ANNOT by discarding elements as we use them up.
5123 Return true if successful. */
5125 static bool
5126 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5127 ptrdiff_t nchars, Lisp_Object *annot,
5128 struct coding_system *coding)
5130 Lisp_Object tem;
5131 ptrdiff_t nextpos;
5132 ptrdiff_t lastpos = pos + nchars;
5134 while (NILP (*annot) || CONSP (*annot))
5136 tem = Fcar_safe (Fcar (*annot));
5137 nextpos = pos - 1;
5138 if (INTEGERP (tem))
5139 nextpos = XFASTINT (tem);
5141 /* If there are no more annotations in this range,
5142 output the rest of the range all at once. */
5143 if (! (nextpos >= pos && nextpos <= lastpos))
5144 return e_write (desc, string, pos, lastpos, coding);
5146 /* Output buffer text up to the next annotation's position. */
5147 if (nextpos > pos)
5149 if (!e_write (desc, string, pos, nextpos, coding))
5150 return 0;
5151 pos = nextpos;
5153 /* Output the annotation. */
5154 tem = Fcdr (Fcar (*annot));
5155 if (STRINGP (tem))
5157 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5158 return 0;
5160 *annot = Fcdr (*annot);
5162 return 1;
5165 /* Maximum number of characters that the next
5166 function encodes per one loop iteration. */
5168 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5170 /* Write text in the range START and END into descriptor DESC,
5171 encoding them with coding system CODING. If STRING is nil, START
5172 and END are character positions of the current buffer, else they
5173 are indexes to the string STRING. Return true if successful. */
5175 static bool
5176 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5177 struct coding_system *coding)
5179 if (STRINGP (string))
5181 start = 0;
5182 end = SCHARS (string);
5185 /* We used to have a code for handling selective display here. But,
5186 now it is handled within encode_coding. */
5188 while (start < end)
5190 if (STRINGP (string))
5192 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5193 if (CODING_REQUIRE_ENCODING (coding))
5195 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5197 /* Avoid creating huge Lisp string in encode_coding_object. */
5198 if (nchars == E_WRITE_MAX)
5199 coding->raw_destination = 1;
5201 encode_coding_object
5202 (coding, string, start, string_char_to_byte (string, start),
5203 start + nchars, string_char_to_byte (string, start + nchars),
5204 Qt);
5206 else
5208 coding->dst_object = string;
5209 coding->consumed_char = SCHARS (string);
5210 coding->produced = SBYTES (string);
5213 else
5215 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5216 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5218 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5219 if (CODING_REQUIRE_ENCODING (coding))
5221 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5223 /* Likewise. */
5224 if (nchars == E_WRITE_MAX)
5225 coding->raw_destination = 1;
5227 encode_coding_object
5228 (coding, Fcurrent_buffer (), start, start_byte,
5229 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5231 else
5233 coding->dst_object = Qnil;
5234 coding->dst_pos_byte = start_byte;
5235 if (start >= GPT || end <= GPT)
5237 coding->consumed_char = end - start;
5238 coding->produced = end_byte - start_byte;
5240 else
5242 coding->consumed_char = GPT - start;
5243 coding->produced = GPT_BYTE - start_byte;
5248 if (coding->produced > 0)
5250 char *buf = (coding->raw_destination ? (char *) coding->destination
5251 : (STRINGP (coding->dst_object)
5252 ? SSDATA (coding->dst_object)
5253 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5254 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5256 if (coding->raw_destination)
5258 /* We're responsible for freeing this, see
5259 encode_coding_object to check why. */
5260 xfree (coding->destination);
5261 coding->raw_destination = 0;
5263 if (coding->produced)
5264 return 0;
5266 start += coding->consumed_char;
5269 return 1;
5272 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5273 Sverify_visited_file_modtime, 0, 1, 0,
5274 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5275 This means that the file has not been changed since it was visited or saved.
5276 If BUF is omitted or nil, it defaults to the current buffer.
5277 See Info node `(elisp)Modification Time' for more details. */)
5278 (Lisp_Object buf)
5280 struct buffer *b = decode_buffer (buf);
5281 struct stat st;
5282 Lisp_Object handler;
5283 Lisp_Object filename;
5284 struct timespec mtime;
5286 if (!STRINGP (BVAR (b, filename))) return Qt;
5287 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5289 /* If the file name has special constructs in it,
5290 call the corresponding file handler. */
5291 handler = Ffind_file_name_handler (BVAR (b, filename),
5292 Qverify_visited_file_modtime);
5293 if (!NILP (handler))
5294 return call2 (handler, Qverify_visited_file_modtime, buf);
5296 filename = ENCODE_FILE (BVAR (b, filename));
5298 mtime = (stat (SSDATA (filename), &st) == 0
5299 ? get_stat_mtime (&st)
5300 : time_error_value (errno));
5301 if (timespec_cmp (mtime, b->modtime) == 0
5302 && (b->modtime_size < 0
5303 || st.st_size == b->modtime_size))
5304 return Qt;
5305 return Qnil;
5308 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5309 Svisited_file_modtime, 0, 0, 0,
5310 doc: /* Return the current buffer's recorded visited file modification time.
5311 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5312 `file-attributes' returns. If the current buffer has no recorded file
5313 modification time, this function returns 0. If the visited file
5314 doesn't exist, return -1.
5315 See Info node `(elisp)Modification Time' for more details. */)
5316 (void)
5318 int ns = current_buffer->modtime.tv_nsec;
5319 if (ns < 0)
5320 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5321 return make_lisp_time (current_buffer->modtime);
5324 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5325 Sset_visited_file_modtime, 0, 1, 0,
5326 doc: /* Update buffer's recorded modification time from the visited file's time.
5327 Useful if the buffer was not read from the file normally
5328 or if the file itself has been changed for some known benign reason.
5329 An argument specifies the modification time value to use
5330 \(instead of that of the visited file), in the form of a list
5331 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5332 `visited-file-modtime'. */)
5333 (Lisp_Object time_flag)
5335 if (!NILP (time_flag))
5337 struct timespec mtime;
5338 if (INTEGERP (time_flag))
5340 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5341 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5343 else
5344 mtime = lisp_time_argument (time_flag);
5346 current_buffer->modtime = mtime;
5347 current_buffer->modtime_size = -1;
5349 else
5351 register Lisp_Object filename;
5352 struct stat st;
5353 Lisp_Object handler;
5355 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5357 /* If the file name has special constructs in it,
5358 call the corresponding file handler. */
5359 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5360 if (!NILP (handler))
5361 /* The handler can find the file name the same way we did. */
5362 return call2 (handler, Qset_visited_file_modtime, Qnil);
5364 filename = ENCODE_FILE (filename);
5366 if (stat (SSDATA (filename), &st) >= 0)
5368 current_buffer->modtime = get_stat_mtime (&st);
5369 current_buffer->modtime_size = st.st_size;
5373 return Qnil;
5376 static Lisp_Object
5377 auto_save_error (Lisp_Object error_val)
5379 Lisp_Object msg;
5380 int i;
5382 auto_save_error_occurred = 1;
5384 ring_bell (XFRAME (selected_frame));
5386 AUTO_STRING (format, "Auto-saving %s: %s");
5387 msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5388 Ferror_message_string (error_val));
5390 for (i = 0; i < 3; ++i)
5392 if (i == 0)
5393 message3 (msg);
5394 else
5395 message3_nolog (msg);
5396 Fsleep_for (make_number (1), Qnil);
5399 return Qnil;
5402 static Lisp_Object
5403 auto_save_1 (void)
5405 struct stat st;
5406 Lisp_Object modes;
5408 auto_save_mode_bits = 0666;
5410 /* Get visited file's mode to become the auto save file's mode. */
5411 if (! NILP (BVAR (current_buffer, filename)))
5413 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5414 /* But make sure we can overwrite it later! */
5415 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5416 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5417 INTEGERP (modes))
5418 /* Remote files don't cooperate with stat. */
5419 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5422 return
5423 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5424 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5425 Qnil, Qnil);
5428 struct auto_save_unwind
5430 FILE *stream;
5431 bool auto_raise;
5434 static void
5435 do_auto_save_unwind (void *arg)
5437 struct auto_save_unwind *p = arg;
5438 FILE *stream = p->stream;
5439 minibuffer_auto_raise = p->auto_raise;
5440 auto_saving = 0;
5441 if (stream != NULL)
5443 block_input ();
5444 fclose (stream);
5445 unblock_input ();
5449 static Lisp_Object
5450 do_auto_save_make_dir (Lisp_Object dir)
5452 Lisp_Object result;
5454 auto_saving_dir_umask = 077;
5455 result = call2 (Qmake_directory, dir, Qt);
5456 auto_saving_dir_umask = 0;
5457 return result;
5460 static Lisp_Object
5461 do_auto_save_eh (Lisp_Object ignore)
5463 auto_saving_dir_umask = 0;
5464 return Qnil;
5467 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5468 doc: /* Auto-save all buffers that need it.
5469 This is all buffers that have auto-saving enabled
5470 and are changed since last auto-saved.
5471 Auto-saving writes the buffer into a file
5472 so that your editing is not lost if the system crashes.
5473 This file is not the file you visited; that changes only when you save.
5474 Normally we run the normal hook `auto-save-hook' before saving.
5476 A non-nil NO-MESSAGE argument means do not print any message if successful.
5477 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5478 (Lisp_Object no_message, Lisp_Object current_only)
5480 struct buffer *old = current_buffer, *b;
5481 Lisp_Object tail, buf, hook;
5482 bool auto_saved = 0;
5483 int do_handled_files;
5484 Lisp_Object oquit;
5485 FILE *stream = NULL;
5486 ptrdiff_t count = SPECPDL_INDEX ();
5487 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5488 bool old_message_p = 0;
5489 struct auto_save_unwind auto_save_unwind;
5491 if (max_specpdl_size < specpdl_size + 40)
5492 max_specpdl_size = specpdl_size + 40;
5494 if (minibuf_level)
5495 no_message = Qt;
5497 if (NILP (no_message))
5499 old_message_p = push_message ();
5500 record_unwind_protect_void (pop_message_unwind);
5503 /* Ordinarily don't quit within this function,
5504 but don't make it impossible to quit (in case we get hung in I/O). */
5505 oquit = Vquit_flag;
5506 Vquit_flag = Qnil;
5508 hook = intern ("auto-save-hook");
5509 safe_run_hooks (hook);
5511 if (STRINGP (Vauto_save_list_file_name))
5513 Lisp_Object listfile;
5515 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5517 /* Don't try to create the directory when shutting down Emacs,
5518 because creating the directory might signal an error, and
5519 that would leave Emacs in a strange state. */
5520 if (!NILP (Vrun_hooks))
5522 Lisp_Object dir;
5523 dir = Ffile_name_directory (listfile);
5524 if (NILP (Ffile_directory_p (dir)))
5525 internal_condition_case_1 (do_auto_save_make_dir,
5526 dir, Qt,
5527 do_auto_save_eh);
5530 stream = emacs_fopen (SSDATA (listfile), "w");
5533 auto_save_unwind.stream = stream;
5534 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5535 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5536 minibuffer_auto_raise = 0;
5537 auto_saving = 1;
5538 auto_save_error_occurred = 0;
5540 /* On first pass, save all files that don't have handlers.
5541 On second pass, save all files that do have handlers.
5543 If Emacs is crashing, the handlers may tweak what is causing
5544 Emacs to crash in the first place, and it would be a shame if
5545 Emacs failed to autosave perfectly ordinary files because it
5546 couldn't handle some ange-ftp'd file. */
5548 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5549 FOR_EACH_LIVE_BUFFER (tail, buf)
5551 b = XBUFFER (buf);
5553 /* Record all the buffers that have auto save mode
5554 in the special file that lists them. For each of these buffers,
5555 Record visited name (if any) and auto save name. */
5556 if (STRINGP (BVAR (b, auto_save_file_name))
5557 && stream != NULL && do_handled_files == 0)
5559 block_input ();
5560 if (!NILP (BVAR (b, filename)))
5562 fwrite (SDATA (BVAR (b, filename)), 1,
5563 SBYTES (BVAR (b, filename)), stream);
5565 putc ('\n', stream);
5566 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5567 SBYTES (BVAR (b, auto_save_file_name)), stream);
5568 putc ('\n', stream);
5569 unblock_input ();
5572 if (!NILP (current_only)
5573 && b != current_buffer)
5574 continue;
5576 /* Don't auto-save indirect buffers.
5577 The base buffer takes care of it. */
5578 if (b->base_buffer)
5579 continue;
5581 /* Check for auto save enabled
5582 and file changed since last auto save
5583 and file changed since last real save. */
5584 if (STRINGP (BVAR (b, auto_save_file_name))
5585 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5586 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5587 /* -1 means we've turned off autosaving for a while--see below. */
5588 && XINT (BVAR (b, save_length)) >= 0
5589 && (do_handled_files
5590 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5591 Qwrite_region))))
5593 struct timespec before_time = current_timespec ();
5594 struct timespec after_time;
5596 /* If we had a failure, don't try again for 20 minutes. */
5597 if (b->auto_save_failure_time > 0
5598 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5599 continue;
5601 set_buffer_internal (b);
5602 if (NILP (Vauto_save_include_big_deletions)
5603 && (XFASTINT (BVAR (b, save_length)) * 10
5604 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5605 /* A short file is likely to change a large fraction;
5606 spare the user annoying messages. */
5607 && XFASTINT (BVAR (b, save_length)) > 5000
5608 /* These messages are frequent and annoying for `*mail*'. */
5609 && !EQ (BVAR (b, filename), Qnil)
5610 && NILP (no_message))
5612 /* It has shrunk too much; turn off auto-saving here. */
5613 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5614 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5615 BVAR (b, name), 1);
5616 minibuffer_auto_raise = 0;
5617 /* Turn off auto-saving until there's a real save,
5618 and prevent any more warnings. */
5619 XSETINT (BVAR (b, save_length), -1);
5620 Fsleep_for (make_number (1), Qnil);
5621 continue;
5623 if (!auto_saved && NILP (no_message))
5624 message1 ("Auto-saving...");
5625 internal_condition_case (auto_save_1, Qt, auto_save_error);
5626 auto_saved = 1;
5627 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5628 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5629 set_buffer_internal (old);
5631 after_time = current_timespec ();
5633 /* If auto-save took more than 60 seconds,
5634 assume it was an NFS failure that got a timeout. */
5635 if (after_time.tv_sec - before_time.tv_sec > 60)
5636 b->auto_save_failure_time = after_time.tv_sec;
5640 /* Prevent another auto save till enough input events come in. */
5641 record_auto_save ();
5643 if (auto_saved && NILP (no_message))
5645 if (old_message_p)
5647 /* If we are going to restore an old message,
5648 give time to read ours. */
5649 sit_for (make_number (1), 0, 0);
5650 restore_message ();
5652 else if (!auto_save_error_occurred)
5653 /* Don't overwrite the error message if an error occurred.
5654 If we displayed a message and then restored a state
5655 with no message, leave a "done" message on the screen. */
5656 message1 ("Auto-saving...done");
5659 Vquit_flag = oquit;
5661 /* This restores the message-stack status. */
5662 unbind_to (count, Qnil);
5663 return Qnil;
5666 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5667 Sset_buffer_auto_saved, 0, 0, 0,
5668 doc: /* Mark current buffer as auto-saved with its current text.
5669 No auto-save file will be written until the buffer changes again. */)
5670 (void)
5672 /* FIXME: This should not be called in indirect buffers, since
5673 they're not autosaved. */
5674 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5675 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5676 current_buffer->auto_save_failure_time = 0;
5677 return Qnil;
5680 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5681 Sclear_buffer_auto_save_failure, 0, 0, 0,
5682 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5683 (void)
5685 current_buffer->auto_save_failure_time = 0;
5686 return Qnil;
5689 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5690 0, 0, 0,
5691 doc: /* Return t if current buffer has been auto-saved recently.
5692 More precisely, if it has been auto-saved since last read from or saved
5693 in the visited file. If the buffer has no visited file,
5694 then any auto-save counts as "recent". */)
5695 (void)
5697 /* FIXME: maybe we should return nil for indirect buffers since
5698 they're never autosaved. */
5699 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5702 /* Reading and completing file names. */
5704 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5705 Snext_read_file_uses_dialog_p, 0, 0, 0,
5706 doc: /* Return t if a call to `read-file-name' will use a dialog.
5707 The return value is only relevant for a call to `read-file-name' that happens
5708 before any other event (mouse or keypress) is handled. */)
5709 (void)
5711 #if (defined USE_GTK || defined USE_MOTIF \
5712 || defined HAVE_NS || defined HAVE_NTGUI)
5713 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5714 && use_dialog_box
5715 && use_file_dialog
5716 && window_system_available (SELECTED_FRAME ()))
5717 return Qt;
5718 #endif
5719 return Qnil;
5723 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5724 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5725 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5726 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5727 it to text mode.
5729 As a side effect, this function flushes any pending STREAM's data.
5731 Value is the previous value of STREAM's I/O mode, nil for text mode,
5732 non-nil for binary mode.
5734 On MS-Windows and MS-DOS, binary mode is needed to read or write
5735 arbitrary binary data, and for disabling translation between CR-LF
5736 pairs and a single newline character. Examples include generation
5737 of text files with Unix-style end-of-line format using `princ' in
5738 batch mode, with standard output redirected to a file.
5740 On Posix systems, this function always returns non-nil, and has no
5741 effect except for flushing STREAM's data. */)
5742 (Lisp_Object stream, Lisp_Object mode)
5744 FILE *fp = NULL;
5745 int binmode;
5747 CHECK_SYMBOL (stream);
5748 if (EQ (stream, Qstdin))
5749 fp = stdin;
5750 else if (EQ (stream, Qstdout))
5751 fp = stdout;
5752 else if (EQ (stream, Qstderr))
5753 fp = stderr;
5754 else
5755 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5757 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5758 if (fp != stdin)
5759 fflush (fp);
5761 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5764 void
5765 init_fileio (void)
5767 realmask = umask (0);
5768 umask (realmask);
5770 valid_timestamp_file_system = 0;
5772 /* fsync can be a significant performance hit. Often it doesn't
5773 suffice to make the file-save operation survive a crash. For
5774 batch scripts, which are typically part of larger shell commands
5775 that don't fsync other files, its effect on performance can be
5776 significant so its utility is particularly questionable.
5777 Hence, for now by default fsync is used only when interactive.
5779 For more on why fsync often fails to work on today's hardware, see:
5780 Zheng M et al. Understanding the robustness of SSDs under power fault.
5781 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5782 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5784 For more on why fsync does not suffice even if it works properly, see:
5785 Roche X. Necessary step(s) to synchronize filename operations on disk.
5786 Austin Group Defect 672, 2013-03-19
5787 http://austingroupbugs.net/view.php?id=672 */
5788 write_region_inhibit_fsync = noninteractive;
5791 void
5792 syms_of_fileio (void)
5794 /* Property name of a file name handler,
5795 which gives a list of operations it handles. */
5796 DEFSYM (Qoperations, "operations");
5798 DEFSYM (Qexpand_file_name, "expand-file-name");
5799 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5800 DEFSYM (Qdirectory_file_name, "directory-file-name");
5801 DEFSYM (Qfile_name_directory, "file-name-directory");
5802 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5803 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5804 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5805 DEFSYM (Qcopy_file, "copy-file");
5806 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5807 DEFSYM (Qmake_directory, "make-directory");
5808 DEFSYM (Qdelete_file, "delete-file");
5809 DEFSYM (Qrename_file, "rename-file");
5810 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5811 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5812 DEFSYM (Qfile_exists_p, "file-exists-p");
5813 DEFSYM (Qfile_executable_p, "file-executable-p");
5814 DEFSYM (Qfile_readable_p, "file-readable-p");
5815 DEFSYM (Qfile_writable_p, "file-writable-p");
5816 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5817 DEFSYM (Qaccess_file, "access-file");
5818 DEFSYM (Qfile_directory_p, "file-directory-p");
5819 DEFSYM (Qfile_regular_p, "file-regular-p");
5820 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5821 DEFSYM (Qfile_modes, "file-modes");
5822 DEFSYM (Qset_file_modes, "set-file-modes");
5823 DEFSYM (Qset_file_times, "set-file-times");
5824 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5825 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5826 DEFSYM (Qfile_acl, "file-acl");
5827 DEFSYM (Qset_file_acl, "set-file-acl");
5828 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5829 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5830 DEFSYM (Qwrite_region, "write-region");
5831 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5832 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5834 /* The symbol bound to coding-system-for-read when
5835 insert-file-contents is called for recovering a file. This is not
5836 an actual coding system name, but just an indicator to tell
5837 insert-file-contents to use `emacs-mule' with a special flag for
5838 auto saving and recovering a file. */
5839 DEFSYM (Qauto_save_coding, "auto-save-coding");
5841 DEFSYM (Qfile_name_history, "file-name-history");
5842 Fset (Qfile_name_history, Qnil);
5844 DEFSYM (Qfile_error, "file-error");
5845 DEFSYM (Qfile_already_exists, "file-already-exists");
5846 DEFSYM (Qfile_date_error, "file-date-error");
5847 DEFSYM (Qfile_notify_error, "file-notify-error");
5848 DEFSYM (Qexcl, "excl");
5850 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5851 doc: /* Coding system for encoding file names.
5852 If it is nil, `default-file-name-coding-system' (which see) is used.
5854 On MS-Windows, the value of this variable is largely ignored if
5855 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5856 behaves as if file names were encoded in `utf-8'. */);
5857 Vfile_name_coding_system = Qnil;
5859 DEFVAR_LISP ("default-file-name-coding-system",
5860 Vdefault_file_name_coding_system,
5861 doc: /* Default coding system for encoding file names.
5862 This variable is used only when `file-name-coding-system' is nil.
5864 This variable is set/changed by the command `set-language-environment'.
5865 User should not set this variable manually,
5866 instead use `file-name-coding-system' to get a constant encoding
5867 of file names regardless of the current language environment.
5869 On MS-Windows, the value of this variable is largely ignored if
5870 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5871 behaves as if file names were encoded in `utf-8'. */);
5872 Vdefault_file_name_coding_system = Qnil;
5874 /* Lisp functions for translating file formats. */
5875 DEFSYM (Qformat_decode, "format-decode");
5876 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5878 /* Lisp function for setting buffer-file-coding-system and the
5879 multibyteness of the current buffer after inserting a file. */
5880 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5882 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5884 Fput (Qfile_error, Qerror_conditions,
5885 Fpurecopy (list2 (Qfile_error, Qerror)));
5886 Fput (Qfile_error, Qerror_message,
5887 build_pure_c_string ("File error"));
5889 Fput (Qfile_already_exists, Qerror_conditions,
5890 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5891 Fput (Qfile_already_exists, Qerror_message,
5892 build_pure_c_string ("File already exists"));
5894 Fput (Qfile_date_error, Qerror_conditions,
5895 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5896 Fput (Qfile_date_error, Qerror_message,
5897 build_pure_c_string ("Cannot set file date"));
5899 Fput (Qfile_notify_error, Qerror_conditions,
5900 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5901 Fput (Qfile_notify_error, Qerror_message,
5902 build_pure_c_string ("File notification error"));
5904 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5905 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5906 If a file name matches REGEXP, all I/O on that file is done by calling
5907 HANDLER. If a file name matches more than one handler, the handler
5908 whose match starts last in the file name gets precedence. The
5909 function `find-file-name-handler' checks this list for a handler for
5910 its argument.
5912 HANDLER should be a function. The first argument given to it is the
5913 name of the I/O primitive to be handled; the remaining arguments are
5914 the arguments that were passed to that primitive. For example, if you
5915 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5916 HANDLER is called like this:
5918 (funcall HANDLER \\='file-exists-p FILENAME)
5920 Note that HANDLER must be able to handle all I/O primitives; if it has
5921 nothing special to do for a primitive, it should reinvoke the
5922 primitive to handle the operation \"the usual way\".
5923 See Info node `(elisp)Magic File Names' for more details. */);
5924 Vfile_name_handler_alist = Qnil;
5926 DEFVAR_LISP ("set-auto-coding-function",
5927 Vset_auto_coding_function,
5928 doc: /* If non-nil, a function to call to decide a coding system of file.
5929 Two arguments are passed to this function: the file name
5930 and the length of a file contents following the point.
5931 This function should return a coding system to decode the file contents.
5932 It should check the file name against `auto-coding-alist'.
5933 If no coding system is decided, it should check a coding system
5934 specified in the heading lines with the format:
5935 -*- ... coding: CODING-SYSTEM; ... -*-
5936 or local variable spec of the tailing lines with `coding:' tag. */);
5937 Vset_auto_coding_function = Qnil;
5939 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5940 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5941 Each is passed one argument, the number of characters inserted,
5942 with point at the start of the inserted text. Each function
5943 should leave point the same, and return the new character count.
5944 If `insert-file-contents' is intercepted by a handler from
5945 `file-name-handler-alist', that handler is responsible for calling the
5946 functions in `after-insert-file-functions' if appropriate. */);
5947 Vafter_insert_file_functions = Qnil;
5949 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5950 doc: /* A list of functions to be called at the start of `write-region'.
5951 Each is passed two arguments, START and END as for `write-region'.
5952 These are usually two numbers but not always; see the documentation
5953 for `write-region'. The function should return a list of pairs
5954 of the form (POSITION . STRING), consisting of strings to be effectively
5955 inserted at the specified positions of the file being written (1 means to
5956 insert before the first byte written). The POSITIONs must be sorted into
5957 increasing order.
5959 If there are several annotation functions, the lists returned by these
5960 functions are merged destructively. As each annotation function runs,
5961 the variable `write-region-annotations-so-far' contains a list of all
5962 annotations returned by previous annotation functions.
5964 An annotation function can return with a different buffer current.
5965 Doing so removes the annotations returned by previous functions, and
5966 resets START and END to `point-min' and `point-max' of the new buffer.
5968 After `write-region' completes, Emacs calls the function stored in
5969 `write-region-post-annotation-function', once for each buffer that was
5970 current when building the annotations (i.e., at least once), with that
5971 buffer current. */);
5972 Vwrite_region_annotate_functions = Qnil;
5973 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5975 DEFVAR_LISP ("write-region-post-annotation-function",
5976 Vwrite_region_post_annotation_function,
5977 doc: /* Function to call after `write-region' completes.
5978 The function is called with no arguments. If one or more of the
5979 annotation functions in `write-region-annotate-functions' changed the
5980 current buffer, the function stored in this variable is called for
5981 each of those additional buffers as well, in addition to the original
5982 buffer. The relevant buffer is current during each function call. */);
5983 Vwrite_region_post_annotation_function = Qnil;
5984 staticpro (&Vwrite_region_annotation_buffers);
5986 DEFVAR_LISP ("write-region-annotations-so-far",
5987 Vwrite_region_annotations_so_far,
5988 doc: /* When an annotation function is called, this holds the previous annotations.
5989 These are the annotations made by other annotation functions
5990 that were already called. See also `write-region-annotate-functions'. */);
5991 Vwrite_region_annotations_so_far = Qnil;
5993 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5994 doc: /* A list of file name handlers that temporarily should not be used.
5995 This applies only to the operation `inhibit-file-name-operation'. */);
5996 Vinhibit_file_name_handlers = Qnil;
5998 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5999 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6000 Vinhibit_file_name_operation = Qnil;
6002 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6003 doc: /* File name in which we write a list of all auto save file names.
6004 This variable is initialized automatically from `auto-save-list-file-prefix'
6005 shortly after Emacs reads your init file, if you have not yet given it
6006 a non-nil value. */);
6007 Vauto_save_list_file_name = Qnil;
6009 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6010 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6011 Normally auto-save files are written under other names. */);
6012 Vauto_save_visited_file_name = Qnil;
6014 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6015 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6016 If nil, deleting a substantial portion of the text disables auto-save
6017 in the buffer; this is the default behavior, because the auto-save
6018 file is usually more useful if it contains the deleted text. */);
6019 Vauto_save_include_big_deletions = Qnil;
6021 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6022 doc: /* Non-nil means don't call fsync in `write-region'.
6023 This variable affects calls to `write-region' as well as save commands.
6024 Setting this to nil may avoid data loss if the system loses power or
6025 the operating system crashes. By default, it is non-nil in batch mode. */);
6026 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6028 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6029 doc: /* Specifies whether to use the system's trash can.
6030 When non-nil, certain file deletion commands use the function
6031 `move-file-to-trash' instead of deleting files outright.
6032 This includes interactive calls to `delete-file' and
6033 `delete-directory' and the Dired deletion commands. */);
6034 delete_by_moving_to_trash = 0;
6035 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6037 /* Lisp function for moving files to trash. */
6038 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6040 /* Lisp function for recursively copying directories. */
6041 DEFSYM (Qcopy_directory, "copy-directory");
6043 /* Lisp function for recursively deleting directories. */
6044 DEFSYM (Qdelete_directory, "delete-directory");
6046 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6047 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6049 DEFSYM (Qstdin, "stdin");
6050 DEFSYM (Qstdout, "stdout");
6051 DEFSYM (Qstderr, "stderr");
6053 defsubr (&Sfind_file_name_handler);
6054 defsubr (&Sfile_name_directory);
6055 defsubr (&Sfile_name_nondirectory);
6056 defsubr (&Sunhandled_file_name_directory);
6057 defsubr (&Sfile_name_as_directory);
6058 defsubr (&Sdirectory_file_name);
6059 defsubr (&Smake_temp_name);
6060 defsubr (&Sexpand_file_name);
6061 defsubr (&Ssubstitute_in_file_name);
6062 defsubr (&Scopy_file);
6063 defsubr (&Smake_directory_internal);
6064 defsubr (&Sdelete_directory_internal);
6065 defsubr (&Sdelete_file);
6066 defsubr (&Srename_file);
6067 defsubr (&Sadd_name_to_file);
6068 defsubr (&Smake_symbolic_link);
6069 defsubr (&Sfile_name_absolute_p);
6070 defsubr (&Sfile_exists_p);
6071 defsubr (&Sfile_executable_p);
6072 defsubr (&Sfile_readable_p);
6073 defsubr (&Sfile_writable_p);
6074 defsubr (&Saccess_file);
6075 defsubr (&Sfile_symlink_p);
6076 defsubr (&Sfile_directory_p);
6077 defsubr (&Sfile_accessible_directory_p);
6078 defsubr (&Sfile_regular_p);
6079 defsubr (&Sfile_modes);
6080 defsubr (&Sset_file_modes);
6081 defsubr (&Sset_file_times);
6082 defsubr (&Sfile_selinux_context);
6083 defsubr (&Sfile_acl);
6084 defsubr (&Sset_file_acl);
6085 defsubr (&Sset_file_selinux_context);
6086 defsubr (&Sset_default_file_modes);
6087 defsubr (&Sdefault_file_modes);
6088 defsubr (&Sfile_newer_than_file_p);
6089 defsubr (&Sinsert_file_contents);
6090 defsubr (&Swrite_region);
6091 defsubr (&Scar_less_than_car);
6092 defsubr (&Sverify_visited_file_modtime);
6093 defsubr (&Svisited_file_modtime);
6094 defsubr (&Sset_visited_file_modtime);
6095 defsubr (&Sdo_auto_save);
6096 defsubr (&Sset_buffer_auto_saved);
6097 defsubr (&Sclear_buffer_auto_save_failure);
6098 defsubr (&Srecent_auto_save_p);
6100 defsubr (&Snext_read_file_uses_dialog_p);
6102 defsubr (&Sset_binary_mode);
6104 #ifdef HAVE_SYNC
6105 defsubr (&Sunix_sync);
6106 #endif