Fix problems caught with --enable-gcc-warnings
[emacs.git] / src / fileio.c
blob3155ef0edf18c9360c7b8da7cc6b72bc61d232bb
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include "sysstdio.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #include <errno.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
37 #endif
39 #ifdef HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "intervals.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "coding.h"
50 #include "window.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
53 #include "frame.h"
54 #include "dispextern.h"
56 #ifdef WINDOWSNT
57 #define NOMINMAX 1
58 #include <windows.h>
59 #include <sys/file.h>
60 #include "w32.h"
61 #endif /* not WINDOWSNT */
63 #ifdef MSDOS
64 #include "msdos.h"
65 #include <sys/param.h>
66 #endif
68 #ifdef DOS_NT
69 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
70 redirector allows the six letters between 'Z' and 'a' as well. */
71 #ifdef MSDOS
72 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
73 #endif
74 #ifdef WINDOWSNT
75 #define IS_DRIVE(x) c_isalpha (x)
76 #endif
77 /* Need to lower-case the drive letter, or else expanded
78 filenames will sometimes compare unequal, because
79 `expand-file-name' doesn't always down-case the drive letter. */
80 #define DRIVE_LETTER(x) c_tolower (x)
81 #endif
83 #include "systime.h"
84 #include <acl.h>
85 #include <allocator.h>
86 #include <careadlinkat.h>
87 #include <stat-time.h>
89 #include <binary-io.h>
91 #ifdef HPUX
92 #include <netio.h>
93 #endif
95 #include "commands.h"
97 /* True during writing of auto-save files. */
98 static bool auto_saving;
100 /* Emacs's real umask. */
101 static mode_t realmask;
103 /* Nonzero umask during creation of auto-save directories. */
104 static mode_t auto_saving_dir_umask;
106 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
107 a new file with the same mode as the original. */
108 static mode_t auto_save_mode_bits;
110 /* Set by auto_save_1 if an error occurred during the last auto-save. */
111 static bool auto_save_error_occurred;
113 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
114 number of a file system where time stamps were observed to to work. */
115 static bool valid_timestamp_file_system;
116 static dev_t timestamp_file_system;
118 /* Each time an annotation function changes the buffer, the new buffer
119 is added here. */
120 static Lisp_Object Vwrite_region_annotation_buffers;
122 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
123 Lisp_Object *, struct coding_system *);
124 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
125 struct coding_system *);
128 /* Return true if FILENAME exists. */
130 static bool
131 check_existing (const char *filename)
133 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
136 /* Return true if file FILENAME exists and can be executed. */
138 static bool
139 check_executable (char *filename)
141 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
144 /* Return true if file FILENAME exists and can be accessed
145 according to AMODE, which should include W_OK.
146 On failure, return false and set errno. */
148 static bool
149 check_writable (const char *filename, int amode)
151 #ifdef MSDOS
152 /* FIXME: an faccessat implementation should be added to the
153 DOS/Windows ports and this #ifdef branch should be removed. */
154 struct stat st;
155 if (stat (filename, &st) < 0)
156 return 0;
157 errno = EPERM;
158 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
159 #else /* not MSDOS */
160 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
161 #ifdef CYGWIN
162 /* faccessat may have returned failure because Cygwin couldn't
163 determine the file's UID or GID; if so, we return success. */
164 if (!res)
166 int faccessat_errno = errno;
167 struct stat st;
168 if (stat (filename, &st) < 0)
169 return 0;
170 res = (st.st_uid == -1 || st.st_gid == -1);
171 errno = faccessat_errno;
173 #endif /* CYGWIN */
174 return res;
175 #endif /* not MSDOS */
178 /* Signal a file-access failure. STRING describes the failure,
179 NAME the file involved, and ERRORNO the errno value.
181 If NAME is neither null nor a pair, package it up as a singleton
182 list before reporting it; this saves report_file_errno's caller the
183 trouble of preserving errno before calling list1. */
185 void
186 report_file_errno (char const *string, Lisp_Object name, int errorno)
188 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
189 synchronize_system_messages_locale ();
190 char *str = strerror (errorno);
191 Lisp_Object errstring
192 = code_convert_string_norecord (build_unibyte_string (str),
193 Vlocale_coding_system, 0);
194 Lisp_Object errdata = Fcons (errstring, data);
196 if (errorno == EEXIST)
197 xsignal (Qfile_already_exists, errdata);
198 else
199 xsignal (Qfile_error, Fcons (build_string (string), errdata));
202 /* Signal a file-access failure that set errno. STRING describes the
203 failure, NAME the file involved. When invoking this function, take
204 care to not use arguments such as build_string ("foo") that involve
205 side effects that may set errno. */
207 void
208 report_file_error (char const *string, Lisp_Object name)
210 report_file_errno (string, name, errno);
213 /* Like report_file_error, but reports a file-notify-error instead. */
215 void
216 report_file_notify_error (const char *string, Lisp_Object name)
218 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
219 synchronize_system_messages_locale ();
220 char *str = strerror (errno);
221 Lisp_Object errstring
222 = code_convert_string_norecord (build_unibyte_string (str),
223 Vlocale_coding_system, 0);
224 Lisp_Object errdata = Fcons (errstring, data);
226 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
229 void
230 close_file_unwind (int fd)
232 emacs_close (fd);
235 void
236 fclose_unwind (void *arg)
238 FILE *stream = arg;
239 fclose (stream);
242 /* Restore point, having saved it as a marker. */
244 void
245 restore_point_unwind (Lisp_Object location)
247 Fgoto_char (location);
248 unchain_marker (XMARKER (location));
252 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
253 Sfind_file_name_handler, 2, 2, 0,
254 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
255 Otherwise, return nil.
256 A file name is handled if one of the regular expressions in
257 `file-name-handler-alist' matches it.
259 If OPERATION equals `inhibit-file-name-operation', then we ignore
260 any handlers that are members of `inhibit-file-name-handlers',
261 but we still do run any other handlers. This lets handlers
262 use the standard functions without calling themselves recursively. */)
263 (Lisp_Object filename, Lisp_Object operation)
265 /* This function must not munge the match data. */
266 Lisp_Object chain, inhibited_handlers, result;
267 ptrdiff_t pos = -1;
269 result = Qnil;
270 CHECK_STRING (filename);
272 if (EQ (operation, Vinhibit_file_name_operation))
273 inhibited_handlers = Vinhibit_file_name_handlers;
274 else
275 inhibited_handlers = Qnil;
277 for (chain = Vfile_name_handler_alist; CONSP (chain);
278 chain = XCDR (chain))
280 Lisp_Object elt;
281 elt = XCAR (chain);
282 if (CONSP (elt))
284 Lisp_Object string = XCAR (elt);
285 ptrdiff_t match_pos;
286 Lisp_Object handler = XCDR (elt);
287 Lisp_Object operations = Qnil;
289 if (SYMBOLP (handler))
290 operations = Fget (handler, Qoperations);
292 if (STRINGP (string)
293 && (match_pos = fast_string_match (string, filename)) > pos
294 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
296 Lisp_Object tem;
298 handler = XCDR (elt);
299 tem = Fmemq (handler, inhibited_handlers);
300 if (NILP (tem))
302 result = handler;
303 pos = match_pos;
308 QUIT;
310 return result;
313 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
314 1, 1, 0,
315 doc: /* Return the directory component in file name FILENAME.
316 Return nil if FILENAME does not include a directory.
317 Otherwise return a directory name.
318 Given a Unix syntax file name, returns a string ending in slash. */)
319 (Lisp_Object filename)
321 Lisp_Object handler;
323 CHECK_STRING (filename);
325 /* If the file name has special constructs in it,
326 call the corresponding file handler. */
327 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
328 if (!NILP (handler))
330 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
331 filename);
332 return STRINGP (handled_name) ? handled_name : Qnil;
335 char *beg = SSDATA (filename);
336 char const *p = beg + SBYTES (filename);
338 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
339 #ifdef DOS_NT
340 /* only recognize drive specifier at the beginning */
341 && !(p[-1] == ':'
342 /* handle the "/:d:foo" and "/:foo" cases correctly */
343 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
344 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
345 #endif
346 ) p--;
348 if (p == beg)
349 return Qnil;
350 #ifdef DOS_NT
351 /* Expansion of "c:" to drive and default directory. */
352 Lisp_Object tem_fn;
353 USE_SAFE_ALLOCA;
354 SAFE_ALLOCA_STRING (beg, filename);
355 p = beg + (p - SSDATA (filename));
357 if (p[-1] == ':')
359 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
360 char *res = alloca (MAXPATHLEN + 1);
361 char *r = res;
363 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
365 memcpy (res, beg, 2);
366 beg += 2;
367 r += 2;
370 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
372 size_t l = strlen (res);
374 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
375 strcat (res, "/");
376 beg = res;
377 p = beg + strlen (beg);
378 dostounix_filename (beg);
379 tem_fn = make_specified_string (beg, -1, p - beg,
380 STRING_MULTIBYTE (filename));
382 else
383 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
384 STRING_MULTIBYTE (filename));
386 else if (STRING_MULTIBYTE (filename))
388 tem_fn = make_specified_string (beg, -1, p - beg, 1);
389 dostounix_filename (SSDATA (tem_fn));
390 #ifdef WINDOWSNT
391 if (!NILP (Vw32_downcase_file_names))
392 tem_fn = Fdowncase (tem_fn);
393 #endif
395 else
397 dostounix_filename (beg);
398 tem_fn = make_specified_string (beg, -1, p - beg, 0);
400 SAFE_FREE ();
401 return tem_fn;
402 #else /* DOS_NT */
403 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
404 #endif /* DOS_NT */
407 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
408 Sfile_name_nondirectory, 1, 1, 0,
409 doc: /* Return file name FILENAME sans its directory.
410 For example, in a Unix-syntax file name,
411 this is everything after the last slash,
412 or the entire name if it contains no slash. */)
413 (Lisp_Object filename)
415 register const char *beg, *p, *end;
416 Lisp_Object handler;
418 CHECK_STRING (filename);
420 /* If the file name has special constructs in it,
421 call the corresponding file handler. */
422 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
423 if (!NILP (handler))
425 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
426 filename);
427 if (STRINGP (handled_name))
428 return handled_name;
429 error ("Invalid handler in `file-name-handler-alist'");
432 beg = SSDATA (filename);
433 end = p = beg + SBYTES (filename);
435 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
436 #ifdef DOS_NT
437 /* only recognize drive specifier at beginning */
438 && !(p[-1] == ':'
439 /* handle the "/:d:foo" case correctly */
440 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
441 #endif
443 p--;
445 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
448 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
449 Sunhandled_file_name_directory, 1, 1, 0,
450 doc: /* Return a directly usable directory name somehow associated with FILENAME.
451 A `directly usable' directory name is one that may be used without the
452 intervention of any file handler.
453 If FILENAME is a directly usable file itself, return
454 (file-name-directory FILENAME).
455 If FILENAME refers to a file which is not accessible from a local process,
456 then this should return nil.
457 The `call-process' and `start-process' functions use this function to
458 get a current directory to run processes in. */)
459 (Lisp_Object filename)
461 Lisp_Object handler;
463 /* If the file name has special constructs in it,
464 call the corresponding file handler. */
465 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
466 if (!NILP (handler))
468 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
469 filename);
470 return STRINGP (handled_name) ? handled_name : Qnil;
473 return Ffile_name_directory (filename);
476 /* Maximum number of bytes that DST will be longer than SRC
477 in file_name_as_directory. This occurs when SRCLEN == 0. */
478 enum { file_name_as_directory_slop = 2 };
480 /* Convert from file name SRC of length SRCLEN to directory name in
481 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
482 string. On UNIX, just make sure there is a terminating /. Return
483 the length of DST in bytes. */
485 static ptrdiff_t
486 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
487 bool multibyte)
489 if (srclen == 0)
491 dst[0] = '.';
492 dst[1] = '/';
493 dst[2] = '\0';
494 return 2;
497 memcpy (dst, src, srclen);
498 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
499 dst[srclen++] = DIRECTORY_SEP;
500 dst[srclen] = 0;
501 #ifdef DOS_NT
502 dostounix_filename (dst);
503 #endif
504 return srclen;
507 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
508 Sfile_name_as_directory, 1, 1, 0,
509 doc: /* Return a string representing the file name FILE interpreted as a directory.
510 This operation exists because a directory is also a file, but its name as
511 a directory is different from its name as a file.
512 The result can be used as the value of `default-directory'
513 or passed as second argument to `expand-file-name'.
514 For a Unix-syntax file name, just appends a slash. */)
515 (Lisp_Object file)
517 char *buf;
518 ptrdiff_t length;
519 Lisp_Object handler, val;
520 USE_SAFE_ALLOCA;
522 CHECK_STRING (file);
524 /* If the file name has special constructs in it,
525 call the corresponding file handler. */
526 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
527 if (!NILP (handler))
529 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
530 file);
531 if (STRINGP (handled_name))
532 return handled_name;
533 error ("Invalid handler in `file-name-handler-alist'");
536 #ifdef WINDOWSNT
537 if (!NILP (Vw32_downcase_file_names))
538 file = Fdowncase (file);
539 #endif
540 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
541 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
542 STRING_MULTIBYTE (file));
543 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
544 SAFE_FREE ();
545 return val;
548 /* Convert from directory name SRC of length SRCLEN to file name in
549 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
550 string. On UNIX, just make sure there isn't a terminating /.
551 Return the length of DST in bytes. */
553 static ptrdiff_t
554 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
556 /* Process as Unix format: just remove any final slash.
557 But leave "/" and "//" unchanged. */
558 while (srclen > 1
559 #ifdef DOS_NT
560 && !IS_ANY_SEP (src[srclen - 2])
561 #endif
562 && IS_DIRECTORY_SEP (src[srclen - 1])
563 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
564 srclen--;
566 memcpy (dst, src, srclen);
567 dst[srclen] = 0;
568 #ifdef DOS_NT
569 dostounix_filename (dst);
570 #endif
571 return srclen;
574 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
575 1, 1, 0,
576 doc: /* Returns the file name of the directory named DIRECTORY.
577 This is the name of the file that holds the data for the directory DIRECTORY.
578 This operation exists because a directory is also a file, but its name as
579 a directory is different from its name as a file.
580 In Unix-syntax, this function just removes the final slash. */)
581 (Lisp_Object directory)
583 char *buf;
584 ptrdiff_t length;
585 Lisp_Object handler, val;
586 USE_SAFE_ALLOCA;
588 CHECK_STRING (directory);
590 /* If the file name has special constructs in it,
591 call the corresponding file handler. */
592 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
593 if (!NILP (handler))
595 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
596 directory);
597 if (STRINGP (handled_name))
598 return handled_name;
599 error ("Invalid handler in `file-name-handler-alist'");
602 #ifdef WINDOWSNT
603 if (!NILP (Vw32_downcase_file_names))
604 directory = Fdowncase (directory);
605 #endif
606 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
607 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
608 STRING_MULTIBYTE (directory));
609 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
610 SAFE_FREE ();
611 return val;
614 static const char make_temp_name_tbl[64] =
616 'A','B','C','D','E','F','G','H',
617 'I','J','K','L','M','N','O','P',
618 'Q','R','S','T','U','V','W','X',
619 'Y','Z','a','b','c','d','e','f',
620 'g','h','i','j','k','l','m','n',
621 'o','p','q','r','s','t','u','v',
622 'w','x','y','z','0','1','2','3',
623 '4','5','6','7','8','9','-','_'
626 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
628 /* Value is a temporary file name starting with PREFIX, a string.
630 The Emacs process number forms part of the result, so there is
631 no danger of generating a name being used by another process.
632 In addition, this function makes an attempt to choose a name
633 which has no existing file. To make this work, PREFIX should be
634 an absolute file name.
636 BASE64_P means add the pid as 3 characters in base64
637 encoding. In this case, 6 characters will be added to PREFIX to
638 form the file name. Otherwise, if Emacs is running on a system
639 with long file names, add the pid as a decimal number.
641 This function signals an error if no unique file name could be
642 generated. */
644 Lisp_Object
645 make_temp_name (Lisp_Object prefix, bool base64_p)
647 Lisp_Object val, encoded_prefix;
648 ptrdiff_t len;
649 printmax_t pid;
650 char *p, *data;
651 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
652 int pidlen;
654 CHECK_STRING (prefix);
656 /* VAL is created by adding 6 characters to PREFIX. The first
657 three are the PID of this process, in base 64, and the second
658 three are incremented if the file already exists. This ensures
659 262144 unique file names per PID per PREFIX. */
661 pid = getpid ();
663 if (base64_p)
665 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
666 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
667 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
668 pidlen = 3;
670 else
672 #ifdef HAVE_LONG_FILE_NAMES
673 pidlen = sprintf (pidbuf, "%"pMd, pid);
674 #else
675 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
676 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
677 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
678 pidlen = 3;
679 #endif
682 encoded_prefix = ENCODE_FILE (prefix);
683 len = SBYTES (encoded_prefix);
684 val = make_uninit_string (len + 3 + pidlen);
685 data = SSDATA (val);
686 memcpy (data, SSDATA (encoded_prefix), len);
687 p = data + len;
689 memcpy (p, pidbuf, pidlen);
690 p += pidlen;
692 /* Here we try to minimize useless stat'ing when this function is
693 invoked many times successively with the same PREFIX. We achieve
694 this by initializing count to a random value, and incrementing it
695 afterwards.
697 We don't want make-temp-name to be called while dumping,
698 because then make_temp_name_count_initialized_p would get set
699 and then make_temp_name_count would not be set when Emacs starts. */
701 if (!make_temp_name_count_initialized_p)
703 make_temp_name_count = time (NULL);
704 make_temp_name_count_initialized_p = 1;
707 while (1)
709 unsigned num = make_temp_name_count;
711 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
712 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
713 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
715 /* Poor man's congruential RN generator. Replace with
716 ++make_temp_name_count for debugging. */
717 make_temp_name_count += 25229;
718 make_temp_name_count %= 225307;
720 if (!check_existing (data))
722 /* We want to return only if errno is ENOENT. */
723 if (errno == ENOENT)
724 return DECODE_FILE (val);
725 else
726 /* The error here is dubious, but there is little else we
727 can do. The alternatives are to return nil, which is
728 as bad as (and in many cases worse than) throwing the
729 error, or to ignore the error, which will likely result
730 in looping through 225307 stat's, which is not only
731 dog-slow, but also useless since eventually nil would
732 have to be returned anyway. */
733 report_file_error ("Cannot create temporary name for prefix",
734 prefix);
735 /* not reached */
741 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
742 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
743 The Emacs process number forms part of the result, so there is no
744 danger of generating a name being used by another Emacs process
745 (so long as only a single host can access the containing directory...).
747 This function tries to choose a name that has no existing file.
748 For this to work, PREFIX should be an absolute file name.
750 There is a race condition between calling `make-temp-name' and creating the
751 file, which opens all kinds of security holes. For that reason, you should
752 normally use `make-temp-file' instead. */)
753 (Lisp_Object prefix)
755 return make_temp_name (prefix, 0);
758 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
759 doc: /* Convert filename NAME to absolute, and canonicalize it.
760 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
761 (does not start with slash or tilde); both the directory name and
762 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
763 missing, the current buffer's value of `default-directory' is used.
764 NAME should be a string that is a valid file name for the underlying
765 filesystem.
766 File name components that are `.' are removed, and
767 so are file name components followed by `..', along with the `..' itself;
768 note that these simplifications are done without checking the resulting
769 file names in the file system.
770 Multiple consecutive slashes are collapsed into a single slash,
771 except at the beginning of the file name when they are significant (e.g.,
772 UNC file names on MS-Windows.)
773 An initial `~/' expands to your home directory.
774 An initial `~USER/' expands to USER's home directory.
775 See also the function `substitute-in-file-name'.
777 For technical reasons, this function can return correct but
778 non-intuitive results for the root directory; for instance,
779 (expand-file-name ".." "/") returns "/..". For this reason, use
780 (directory-file-name (file-name-directory dirname)) to traverse a
781 filesystem tree, not (expand-file-name ".." dirname). */)
782 (Lisp_Object name, Lisp_Object default_directory)
784 /* These point to SDATA and need to be careful with string-relocation
785 during GC (via DECODE_FILE). */
786 char *nm;
787 char *nmlim;
788 const char *newdir;
789 const char *newdirlim;
790 /* This should only point to alloca'd data. */
791 char *target;
793 ptrdiff_t tlen;
794 struct passwd *pw;
795 #ifdef DOS_NT
796 int drive = 0;
797 bool collapse_newdir = true;
798 bool is_escaped = 0;
799 #endif /* DOS_NT */
800 ptrdiff_t length, nbytes;
801 Lisp_Object handler, result, handled_name;
802 bool multibyte;
803 Lisp_Object hdir;
804 USE_SAFE_ALLOCA;
806 CHECK_STRING (name);
808 /* If the file name has special constructs in it,
809 call the corresponding file handler. */
810 handler = Ffind_file_name_handler (name, Qexpand_file_name);
811 if (!NILP (handler))
813 handled_name = call3 (handler, Qexpand_file_name,
814 name, default_directory);
815 if (STRINGP (handled_name))
816 return handled_name;
817 error ("Invalid handler in `file-name-handler-alist'");
821 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
822 if (NILP (default_directory))
823 default_directory = BVAR (current_buffer, directory);
824 if (! STRINGP (default_directory))
826 #ifdef DOS_NT
827 /* "/" is not considered a root directory on DOS_NT, so using "/"
828 here causes an infinite recursion in, e.g., the following:
830 (let (default-directory)
831 (expand-file-name "a"))
833 To avoid this, we set default_directory to the root of the
834 current drive. */
835 default_directory = build_string (emacs_root_dir ());
836 #else
837 default_directory = build_string ("/");
838 #endif
841 if (!NILP (default_directory))
843 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
844 if (!NILP (handler))
846 handled_name = call3 (handler, Qexpand_file_name,
847 name, default_directory);
848 if (STRINGP (handled_name))
849 return handled_name;
850 error ("Invalid handler in `file-name-handler-alist'");
855 char *o = SSDATA (default_directory);
857 /* Make sure DEFAULT_DIRECTORY is properly expanded.
858 It would be better to do this down below where we actually use
859 default_directory. Unfortunately, calling Fexpand_file_name recursively
860 could invoke GC, and the strings might be relocated. This would
861 be annoying because we have pointers into strings lying around
862 that would need adjusting, and people would add new pointers to
863 the code and forget to adjust them, resulting in intermittent bugs.
864 Putting this call here avoids all that crud.
866 The EQ test avoids infinite recursion. */
867 if (! NILP (default_directory) && !EQ (default_directory, name)
868 /* Save time in some common cases - as long as default_directory
869 is not relative, it can be canonicalized with name below (if it
870 is needed at all) without requiring it to be expanded now. */
871 #ifdef DOS_NT
872 /* Detect MSDOS file names with drive specifiers. */
873 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
874 && IS_DIRECTORY_SEP (o[2]))
875 #ifdef WINDOWSNT
876 /* Detect Windows file names in UNC format. */
877 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
878 #endif
879 #else /* not DOS_NT */
880 /* Detect Unix absolute file names (/... alone is not absolute on
881 DOS or Windows). */
882 && ! (IS_DIRECTORY_SEP (o[0]))
883 #endif /* not DOS_NT */
886 default_directory = Fexpand_file_name (default_directory, Qnil);
889 multibyte = STRING_MULTIBYTE (name);
890 if (multibyte != STRING_MULTIBYTE (default_directory))
892 if (multibyte)
894 unsigned char *p = SDATA (name);
896 while (*p && ASCII_CHAR_P (*p))
897 p++;
898 if (*p == '\0')
900 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
901 unibyte. Do not convert DEFAULT_DIRECTORY to
902 multibyte; instead, convert NAME to a unibyte string,
903 so that the result of this function is also a unibyte
904 string. This is needed during bootstrapping and
905 dumping, when Emacs cannot decode file names, because
906 the locale environment is not set up. */
907 name = make_unibyte_string (SSDATA (name), SBYTES (name));
908 multibyte = 0;
910 else
911 default_directory = string_to_multibyte (default_directory);
913 else
915 name = string_to_multibyte (name);
916 multibyte = 1;
920 #ifdef WINDOWSNT
921 if (!NILP (Vw32_downcase_file_names))
922 default_directory = Fdowncase (default_directory);
923 #endif
925 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
926 SAFE_ALLOCA_STRING (nm, name);
927 nmlim = nm + SBYTES (name);
929 #ifdef DOS_NT
930 /* Note if special escape prefix is present, but remove for now. */
931 if (nm[0] == '/' && nm[1] == ':')
933 is_escaped = 1;
934 nm += 2;
937 /* Find and remove drive specifier if present; this makes nm absolute
938 even if the rest of the name appears to be relative. Only look for
939 drive specifier at the beginning. */
940 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
942 drive = (unsigned char) nm[0];
943 nm += 2;
946 #ifdef WINDOWSNT
947 /* If we see "c://somedir", we want to strip the first slash after the
948 colon when stripping the drive letter. Otherwise, this expands to
949 "//somedir". */
950 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
951 nm++;
953 /* Discard any previous drive specifier if nm is now in UNC format. */
954 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
955 && !IS_DIRECTORY_SEP (nm[2]))
956 drive = 0;
957 #endif /* WINDOWSNT */
958 #endif /* DOS_NT */
960 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
961 none are found, we can probably return right away. We will avoid
962 allocating a new string if name is already fully expanded. */
963 if (
964 IS_DIRECTORY_SEP (nm[0])
965 #ifdef MSDOS
966 && drive && !is_escaped
967 #endif
968 #ifdef WINDOWSNT
969 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
970 #endif
973 /* If it turns out that the filename we want to return is just a
974 suffix of FILENAME, we don't need to go through and edit
975 things; we just need to construct a new string using data
976 starting at the middle of FILENAME. If we set LOSE, that
977 means we've discovered that we can't do that cool trick. */
978 bool lose = 0;
979 char *p = nm;
981 while (*p)
983 /* Since we know the name is absolute, we can assume that each
984 element starts with a "/". */
986 /* "." and ".." are hairy. */
987 if (IS_DIRECTORY_SEP (p[0])
988 && p[1] == '.'
989 && (IS_DIRECTORY_SEP (p[2])
990 || p[2] == 0
991 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
992 || p[3] == 0))))
993 lose = 1;
994 /* Replace multiple slashes with a single one, except
995 leave leading "//" alone. */
996 else if (IS_DIRECTORY_SEP (p[0])
997 && IS_DIRECTORY_SEP (p[1])
998 && (p != nm || IS_DIRECTORY_SEP (p[2])))
999 lose = 1;
1000 p++;
1002 if (!lose)
1004 #ifdef DOS_NT
1005 /* Make sure directories are all separated with /, but
1006 avoid allocation of a new string when not required. */
1007 dostounix_filename (nm);
1008 #ifdef WINDOWSNT
1009 if (IS_DIRECTORY_SEP (nm[1]))
1011 if (strcmp (nm, SSDATA (name)) != 0)
1012 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1014 else
1015 #endif
1016 /* Drive must be set, so this is okay. */
1017 if (strcmp (nm - 2, SSDATA (name)) != 0)
1019 char temp[] = " :";
1021 name = make_specified_string (nm, -1, p - nm, multibyte);
1022 temp[0] = DRIVE_LETTER (drive);
1023 AUTO_STRING (drive_prefix, temp);
1024 name = concat2 (drive_prefix, name);
1026 #ifdef WINDOWSNT
1027 if (!NILP (Vw32_downcase_file_names))
1028 name = Fdowncase (name);
1029 #endif
1030 #else /* not DOS_NT */
1031 if (strcmp (nm, SSDATA (name)) != 0)
1032 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1033 #endif /* not DOS_NT */
1034 SAFE_FREE ();
1035 return name;
1039 /* At this point, nm might or might not be an absolute file name. We
1040 need to expand ~ or ~user if present, otherwise prefix nm with
1041 default_directory if nm is not absolute, and finally collapse /./
1042 and /foo/../ sequences.
1044 We set newdir to be the appropriate prefix if one is needed:
1045 - the relevant user directory if nm starts with ~ or ~user
1046 - the specified drive's working dir (DOS/NT only) if nm does not
1047 start with /
1048 - the value of default_directory.
1050 Note that these prefixes are not guaranteed to be absolute (except
1051 for the working dir of a drive). Therefore, to ensure we always
1052 return an absolute name, if the final prefix is not absolute we
1053 append it to the current working directory. */
1055 newdir = newdirlim = 0;
1057 if (nm[0] == '~') /* prefix ~ */
1059 if (IS_DIRECTORY_SEP (nm[1])
1060 || nm[1] == 0) /* ~ by itself */
1062 Lisp_Object tem;
1064 if (!(newdir = egetenv ("HOME")))
1065 newdir = newdirlim = "";
1066 nm++;
1067 /* `egetenv' may return a unibyte string, which will bite us since
1068 we expect the directory to be multibyte. */
1069 #ifdef WINDOWSNT
1070 if (newdir[0])
1072 char newdir_utf8[MAX_UTF8_PATH];
1074 filename_from_ansi (newdir, newdir_utf8);
1075 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1077 else
1078 #endif
1079 tem = build_string (newdir);
1080 newdirlim = newdir + SBYTES (tem);
1081 if (multibyte && !STRING_MULTIBYTE (tem))
1083 hdir = DECODE_FILE (tem);
1084 newdir = SSDATA (hdir);
1085 newdirlim = newdir + SBYTES (hdir);
1087 #ifdef DOS_NT
1088 collapse_newdir = false;
1089 #endif
1091 else /* ~user/filename */
1093 char *o, *p;
1094 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1095 continue;
1096 o = SAFE_ALLOCA (p - nm + 1);
1097 memcpy (o, nm, p - nm);
1098 o[p - nm] = 0;
1100 block_input ();
1101 pw = getpwnam (o + 1);
1102 unblock_input ();
1103 if (pw)
1105 Lisp_Object tem;
1107 newdir = pw->pw_dir;
1108 /* `getpwnam' may return a unibyte string, which will
1109 bite us since we expect the directory to be
1110 multibyte. */
1111 tem = make_unibyte_string (newdir, strlen (newdir));
1112 newdirlim = newdir + SBYTES (tem);
1113 if (multibyte && !STRING_MULTIBYTE (tem))
1115 hdir = DECODE_FILE (tem);
1116 newdir = SSDATA (hdir);
1117 newdirlim = newdir + SBYTES (hdir);
1119 nm = p;
1120 #ifdef DOS_NT
1121 collapse_newdir = false;
1122 #endif
1125 /* If we don't find a user of that name, leave the name
1126 unchanged; don't move nm forward to p. */
1130 #ifdef DOS_NT
1131 /* On DOS and Windows, nm is absolute if a drive name was specified;
1132 use the drive's current directory as the prefix if needed. */
1133 if (!newdir && drive)
1135 /* Get default directory if needed to make nm absolute. */
1136 char *adir = NULL;
1137 if (!IS_DIRECTORY_SEP (nm[0]))
1139 adir = alloca (MAXPATHLEN + 1);
1140 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1141 adir = NULL;
1142 else if (multibyte)
1144 Lisp_Object tem = build_string (adir);
1146 tem = DECODE_FILE (tem);
1147 newdirlim = adir + SBYTES (tem);
1148 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1150 else
1151 newdirlim = adir + strlen (adir);
1153 if (!adir)
1155 /* Either nm starts with /, or drive isn't mounted. */
1156 adir = alloca (4);
1157 adir[0] = DRIVE_LETTER (drive);
1158 adir[1] = ':';
1159 adir[2] = '/';
1160 adir[3] = 0;
1161 newdirlim = adir + 3;
1163 newdir = adir;
1165 #endif /* DOS_NT */
1167 /* Finally, if no prefix has been specified and nm is not absolute,
1168 then it must be expanded relative to default_directory. */
1170 if (1
1171 #ifndef DOS_NT
1172 /* /... alone is not absolute on DOS and Windows. */
1173 && !IS_DIRECTORY_SEP (nm[0])
1174 #endif
1175 #ifdef WINDOWSNT
1176 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1177 && !IS_DIRECTORY_SEP (nm[2]))
1178 #endif
1179 && !newdir)
1181 newdir = SSDATA (default_directory);
1182 newdirlim = newdir + SBYTES (default_directory);
1183 #ifdef DOS_NT
1184 /* Note if special escape prefix is present, but remove for now. */
1185 if (newdir[0] == '/' && newdir[1] == ':')
1187 is_escaped = 1;
1188 newdir += 2;
1190 #endif
1193 #ifdef DOS_NT
1194 if (newdir)
1196 /* First ensure newdir is an absolute name. */
1197 if (
1198 /* Detect MSDOS file names with drive specifiers. */
1199 ! (IS_DRIVE (newdir[0])
1200 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1201 #ifdef WINDOWSNT
1202 /* Detect Windows file names in UNC format. */
1203 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1204 && !IS_DIRECTORY_SEP (newdir[2]))
1205 #endif
1208 /* Effectively, let newdir be (expand-file-name newdir cwd).
1209 Because of the admonition against calling expand-file-name
1210 when we have pointers into lisp strings, we accomplish this
1211 indirectly by prepending newdir to nm if necessary, and using
1212 cwd (or the wd of newdir's drive) as the new newdir. */
1213 char *adir;
1214 #ifdef WINDOWSNT
1215 const int adir_size = MAX_UTF8_PATH;
1216 #else
1217 const int adir_size = MAXPATHLEN + 1;
1218 #endif
1220 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1222 drive = (unsigned char) newdir[0];
1223 newdir += 2;
1225 if (!IS_DIRECTORY_SEP (nm[0]))
1227 ptrdiff_t nmlen = nmlim - nm;
1228 ptrdiff_t newdirlen = newdirlim - newdir;
1229 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1230 + nmlen + 1);
1231 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1232 multibyte);
1233 memcpy (tmp + dlen, nm, nmlen + 1);
1234 nm = tmp;
1235 nmlim = nm + dlen + nmlen;
1237 adir = alloca (adir_size);
1238 if (drive)
1240 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1241 strcpy (adir, "/");
1243 else
1244 getcwd (adir, adir_size);
1245 if (multibyte)
1247 Lisp_Object tem = build_string (adir);
1249 tem = DECODE_FILE (tem);
1250 newdirlim = adir + SBYTES (tem);
1251 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1253 else
1254 newdirlim = adir + strlen (adir);
1255 newdir = adir;
1258 /* Strip off drive name from prefix, if present. */
1259 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1261 drive = newdir[0];
1262 newdir += 2;
1265 /* Keep only a prefix from newdir if nm starts with slash
1266 (//server/share for UNC, nothing otherwise). */
1267 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1269 #ifdef WINDOWSNT
1270 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1271 && !IS_DIRECTORY_SEP (newdir[2]))
1273 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1274 char *p = adir + 2;
1275 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1276 p++;
1277 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1278 *p = 0;
1279 newdir = adir;
1280 newdirlim = newdir + strlen (adir);
1282 else
1283 #endif
1284 newdir = newdirlim = "";
1287 #endif /* DOS_NT */
1289 /* Ignore any slash at the end of newdir, unless newdir is
1290 just "/" or "//". */
1291 length = newdirlim - newdir;
1292 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1293 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1294 length--;
1296 /* Now concatenate the directory and name to new space in the stack frame. */
1297 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1298 eassert (tlen > file_name_as_directory_slop + 1);
1299 #ifdef DOS_NT
1300 /* Reserve space for drive specifier and escape prefix, since either
1301 or both may need to be inserted. (The Microsoft x86 compiler
1302 produces incorrect code if the following two lines are combined.) */
1303 target = alloca (tlen + 4);
1304 target += 4;
1305 #else /* not DOS_NT */
1306 target = SAFE_ALLOCA (tlen);
1307 #endif /* not DOS_NT */
1308 *target = 0;
1309 nbytes = 0;
1311 if (newdir)
1313 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1315 #ifdef DOS_NT
1316 /* If newdir is effectively "C:/", then the drive letter will have
1317 been stripped and newdir will be "/". Concatenating with an
1318 absolute directory in nm produces "//", which will then be
1319 incorrectly treated as a network share. Ignore newdir in
1320 this case (keeping the drive letter). */
1321 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1322 && newdir[1] == '\0'))
1323 #endif
1325 memcpy (target, newdir, length);
1326 target[length] = 0;
1327 nbytes = length;
1330 else
1331 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1334 memcpy (target + nbytes, nm, nmlim - nm + 1);
1336 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1337 appear. */
1339 char *p = target;
1340 char *o = target;
1342 while (*p)
1344 if (!IS_DIRECTORY_SEP (*p))
1346 *o++ = *p++;
1348 else if (p[1] == '.'
1349 && (IS_DIRECTORY_SEP (p[2])
1350 || p[2] == 0))
1352 /* If "/." is the entire filename, keep the "/". Otherwise,
1353 just delete the whole "/.". */
1354 if (o == target && p[2] == '\0')
1355 *o++ = *p;
1356 p += 2;
1358 else if (p[1] == '.' && p[2] == '.'
1359 /* `/../' is the "superroot" on certain file systems.
1360 Turned off on DOS_NT systems because they have no
1361 "superroot" and because this causes us to produce
1362 file names like "d:/../foo" which fail file-related
1363 functions of the underlying OS. (To reproduce, try a
1364 long series of "../../" in default_directory, longer
1365 than the number of levels from the root.) */
1366 #ifndef DOS_NT
1367 && o != target
1368 #endif
1369 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1371 #ifdef WINDOWSNT
1372 char *prev_o = o;
1373 #endif
1374 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1375 continue;
1376 #ifdef WINDOWSNT
1377 /* Don't go below server level in UNC filenames. */
1378 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1379 && IS_DIRECTORY_SEP (*target))
1380 o = prev_o;
1381 else
1382 #endif
1383 /* Keep initial / only if this is the whole name. */
1384 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1385 ++o;
1386 p += 3;
1388 else if (IS_DIRECTORY_SEP (p[1])
1389 && (p != target || IS_DIRECTORY_SEP (p[2])))
1390 /* Collapse multiple "/", except leave leading "//" alone. */
1391 p++;
1392 else
1394 *o++ = *p++;
1398 #ifdef DOS_NT
1399 /* At last, set drive name. */
1400 #ifdef WINDOWSNT
1401 /* Except for network file name. */
1402 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1403 #endif /* WINDOWSNT */
1405 if (!drive) emacs_abort ();
1406 target -= 2;
1407 target[0] = DRIVE_LETTER (drive);
1408 target[1] = ':';
1410 /* Reinsert the escape prefix if required. */
1411 if (is_escaped)
1413 target -= 2;
1414 target[0] = '/';
1415 target[1] = ':';
1417 result = make_specified_string (target, -1, o - target, multibyte);
1418 dostounix_filename (SSDATA (result));
1419 #ifdef WINDOWSNT
1420 if (!NILP (Vw32_downcase_file_names))
1421 result = Fdowncase (result);
1422 #endif
1423 #else /* !DOS_NT */
1424 result = make_specified_string (target, -1, o - target, multibyte);
1425 #endif /* !DOS_NT */
1428 /* Again look to see if the file name has special constructs in it
1429 and perhaps call the corresponding file handler. This is needed
1430 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1431 the ".." component gives us "/user@host:/bar/../baz" which needs
1432 to be expanded again. */
1433 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1434 if (!NILP (handler))
1436 handled_name = call3 (handler, Qexpand_file_name,
1437 result, default_directory);
1438 if (! STRINGP (handled_name))
1439 error ("Invalid handler in `file-name-handler-alist'");
1440 result = handled_name;
1443 SAFE_FREE ();
1444 return result;
1447 #if 0
1448 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1449 This is the old version of expand-file-name, before it was thoroughly
1450 rewritten for Emacs 10.31. We leave this version here commented-out,
1451 because the code is very complex and likely to have subtle bugs. If
1452 bugs _are_ found, it might be of interest to look at the old code and
1453 see what did it do in the relevant situation.
1455 Don't remove this code: it's true that it will be accessible
1456 from the repository, but a few years from deletion, people will
1457 forget it is there. */
1459 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1460 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1461 "Convert FILENAME to absolute, and canonicalize it.\n\
1462 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1463 (does not start with slash); if DEFAULT is nil or missing,\n\
1464 the current buffer's value of default-directory is used.\n\
1465 Filenames containing `.' or `..' as components are simplified;\n\
1466 initial `~/' expands to your home directory.\n\
1467 See also the function `substitute-in-file-name'.")
1468 (name, defalt)
1469 Lisp_Object name, defalt;
1471 unsigned char *nm;
1473 register unsigned char *newdir, *p, *o;
1474 ptrdiff_t tlen;
1475 unsigned char *target;
1476 struct passwd *pw;
1478 CHECK_STRING (name);
1479 nm = SDATA (name);
1481 /* If nm is absolute, flush ...// and detect /./ and /../.
1482 If no /./ or /../ we can return right away. */
1483 if (nm[0] == '/')
1485 bool lose = 0;
1486 p = nm;
1487 while (*p)
1489 if (p[0] == '/' && p[1] == '/')
1490 nm = p + 1;
1491 if (p[0] == '/' && p[1] == '~')
1492 nm = p + 1, lose = 1;
1493 if (p[0] == '/' && p[1] == '.'
1494 && (p[2] == '/' || p[2] == 0
1495 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1496 lose = 1;
1497 p++;
1499 if (!lose)
1501 if (nm == SDATA (name))
1502 return name;
1503 return build_string (nm);
1507 /* Now determine directory to start with and put it in NEWDIR. */
1509 newdir = 0;
1511 if (nm[0] == '~') /* prefix ~ */
1512 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1514 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1515 newdir = (unsigned char *) "";
1516 nm++;
1518 else /* ~user/filename */
1520 /* Get past ~ to user. */
1521 unsigned char *user = nm + 1;
1522 /* Find end of name. */
1523 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1524 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1525 /* Copy the user name into temp storage. */
1526 o = alloca (len + 1);
1527 memcpy (o, user, len);
1528 o[len] = 0;
1530 /* Look up the user name. */
1531 block_input ();
1532 pw = (struct passwd *) getpwnam (o + 1);
1533 unblock_input ();
1534 if (!pw)
1535 error ("\"%s\" isn't a registered user", o + 1);
1537 newdir = (unsigned char *) pw->pw_dir;
1539 /* Discard the user name from NM. */
1540 nm += len;
1543 if (nm[0] != '/' && !newdir)
1545 if (NILP (defalt))
1546 defalt = current_buffer->directory;
1547 CHECK_STRING (defalt);
1548 newdir = SDATA (defalt);
1551 /* Now concatenate the directory and name to new space in the stack frame. */
1553 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1554 target = alloca (tlen);
1555 *target = 0;
1557 if (newdir)
1559 if (nm[0] == 0 || nm[0] == '/')
1560 strcpy (target, newdir);
1561 else
1562 file_name_as_directory (target, newdir);
1565 strcat (target, nm);
1567 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1569 p = target;
1570 o = target;
1572 while (*p)
1574 if (*p != '/')
1576 *o++ = *p++;
1578 else if (!strncmp (p, "//", 2)
1581 o = target;
1582 p++;
1584 else if (p[0] == '/' && p[1] == '.'
1585 && (p[2] == '/' || p[2] == 0))
1586 p += 2;
1587 else if (!strncmp (p, "/..", 3)
1588 /* `/../' is the "superroot" on certain file systems. */
1589 && o != target
1590 && (p[3] == '/' || p[3] == 0))
1592 while (o != target && *--o != '/')
1594 if (o == target && *o == '/')
1595 ++o;
1596 p += 3;
1598 else
1600 *o++ = *p++;
1604 return make_string (target, o - target);
1606 #endif
1608 /* If /~ or // appears, discard everything through first slash. */
1609 static bool
1610 file_name_absolute_p (const char *filename)
1612 return
1613 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1614 #ifdef DOS_NT
1615 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1616 && IS_DIRECTORY_SEP (filename[2]))
1617 #endif
1621 static char *
1622 search_embedded_absfilename (char *nm, char *endp)
1624 char *p, *s;
1626 for (p = nm + 1; p < endp; p++)
1628 if (IS_DIRECTORY_SEP (p[-1])
1629 && file_name_absolute_p (p)
1630 #if defined (WINDOWSNT) || defined (CYGWIN)
1631 /* // at start of file name is meaningful in Apollo,
1632 WindowsNT and Cygwin systems. */
1633 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1634 #endif /* not (WINDOWSNT || CYGWIN) */
1637 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1638 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1640 USE_SAFE_ALLOCA;
1641 char *o = SAFE_ALLOCA (s - p + 1);
1642 struct passwd *pw;
1643 memcpy (o, p, s - p);
1644 o [s - p] = 0;
1646 /* If we have ~user and `user' exists, discard
1647 everything up to ~. But if `user' does not exist, leave
1648 ~user alone, it might be a literal file name. */
1649 block_input ();
1650 pw = getpwnam (o + 1);
1651 unblock_input ();
1652 SAFE_FREE ();
1653 if (pw)
1654 return p;
1656 else
1657 return p;
1660 return NULL;
1663 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1664 Ssubstitute_in_file_name, 1, 1, 0,
1665 doc: /* Substitute environment variables referred to in FILENAME.
1666 `$FOO' where FOO is an environment variable name means to substitute
1667 the value of that variable. The variable name should be terminated
1668 with a character not a letter, digit or underscore; otherwise, enclose
1669 the entire variable name in braces.
1671 If `/~' appears, all of FILENAME through that `/' is discarded.
1672 If `//' appears, everything up to and including the first of
1673 those `/' is discarded. */)
1674 (Lisp_Object filename)
1676 char *nm, *p, *x, *endp;
1677 bool substituted = false;
1678 bool multibyte;
1679 char *xnm;
1680 Lisp_Object handler;
1682 CHECK_STRING (filename);
1684 multibyte = STRING_MULTIBYTE (filename);
1686 /* If the file name has special constructs in it,
1687 call the corresponding file handler. */
1688 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1689 if (!NILP (handler))
1691 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1692 filename);
1693 if (STRINGP (handled_name))
1694 return handled_name;
1695 error ("Invalid handler in `file-name-handler-alist'");
1698 /* Always work on a copy of the string, in case GC happens during
1699 decode of environment variables, causing the original Lisp_String
1700 data to be relocated. */
1701 USE_SAFE_ALLOCA;
1702 SAFE_ALLOCA_STRING (nm, filename);
1704 #ifdef DOS_NT
1705 dostounix_filename (nm);
1706 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1707 #endif
1708 endp = nm + SBYTES (filename);
1710 /* If /~ or // appears, discard everything through first slash. */
1711 p = search_embedded_absfilename (nm, endp);
1712 if (p)
1713 /* Start over with the new string, so we check the file-name-handler
1714 again. Important with filenames like "/home/foo//:/hello///there"
1715 which would substitute to "/:/hello///there" rather than "/there". */
1717 Lisp_Object result
1718 = (Fsubstitute_in_file_name
1719 (make_specified_string (p, -1, endp - p, multibyte)));
1720 SAFE_FREE ();
1721 return result;
1724 /* See if any variables are substituted into the string. */
1726 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1728 Lisp_Object name
1729 = (!substituted ? filename
1730 : make_specified_string (nm, -1, endp - nm, multibyte));
1731 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1732 CHECK_STRING (tmp);
1733 if (!EQ (tmp, name))
1734 substituted = true;
1735 filename = tmp;
1738 if (!substituted)
1740 #ifdef WINDOWSNT
1741 if (!NILP (Vw32_downcase_file_names))
1742 filename = Fdowncase (filename);
1743 #endif
1744 SAFE_FREE ();
1745 return filename;
1748 xnm = SSDATA (filename);
1749 x = xnm + SBYTES (filename);
1751 /* If /~ or // appears, discard everything through first slash. */
1752 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1753 /* This time we do not start over because we've already expanded envvars
1754 and replaced $$ with $. Maybe we should start over as well, but we'd
1755 need to quote some $ to $$ first. */
1756 xnm = p;
1758 #ifdef WINDOWSNT
1759 if (!NILP (Vw32_downcase_file_names))
1761 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1763 filename = Fdowncase (xname);
1765 else
1766 #endif
1767 if (xnm != SSDATA (filename))
1768 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1769 SAFE_FREE ();
1770 return filename;
1773 /* A slightly faster and more convenient way to get
1774 (directory-file-name (expand-file-name FOO)). */
1776 Lisp_Object
1777 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1779 register Lisp_Object absname;
1781 absname = Fexpand_file_name (filename, defdir);
1783 /* Remove final slash, if any (unless this is the root dir).
1784 stat behaves differently depending! */
1785 if (SCHARS (absname) > 1
1786 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1787 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1788 /* We cannot take shortcuts; they might be wrong for magic file names. */
1789 absname = Fdirectory_file_name (absname);
1790 return absname;
1793 /* Signal an error if the file ABSNAME already exists.
1794 If KNOWN_TO_EXIST, the file is known to exist.
1795 QUERYSTRING is a name for the action that is being considered
1796 to alter the file.
1797 If INTERACTIVE, ask the user whether to proceed,
1798 and bypass the error if the user says to go ahead.
1799 If QUICK, ask for y or n, not yes or no. */
1801 static void
1802 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1803 const char *querystring, bool interactive,
1804 bool quick)
1806 Lisp_Object tem, encoded_filename;
1807 struct stat statbuf;
1809 encoded_filename = ENCODE_FILE (absname);
1811 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1813 if (S_ISDIR (statbuf.st_mode))
1814 xsignal2 (Qfile_error,
1815 build_string ("File is a directory"), absname);
1816 known_to_exist = true;
1819 if (known_to_exist)
1821 if (! interactive)
1822 xsignal2 (Qfile_already_exists,
1823 build_string ("File already exists"), absname);
1824 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1825 tem = CALLN (Fformat, format, absname, build_string (querystring));
1826 if (quick)
1827 tem = call1 (intern ("y-or-n-p"), tem);
1828 else
1829 tem = do_yes_or_no_p (tem);
1830 if (NILP (tem))
1831 xsignal2 (Qfile_already_exists,
1832 build_string ("File already exists"), absname);
1836 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1837 "fCopy file: \nGCopy %s to file: \np\nP",
1838 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1839 If NEWNAME names a directory, copy FILE there.
1841 This function always sets the file modes of the output file to match
1842 the input file.
1844 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1845 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1846 signal a `file-already-exists' error without overwriting. If
1847 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1848 about overwriting; this is what happens in interactive use with M-x.
1849 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1850 existing file.
1852 Fourth arg KEEP-TIME non-nil means give the output file the same
1853 last-modified time as the old one. (This works on only some systems.)
1855 A prefix arg makes KEEP-TIME non-nil.
1857 If PRESERVE-UID-GID is non-nil, we try to transfer the
1858 uid and gid of FILE to NEWNAME.
1860 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1861 this includes the file modes, along with ACL entries and SELinux
1862 context if present. Otherwise, if NEWNAME is created its file
1863 permission bits are those of FILE, masked by the default file
1864 permissions. */)
1865 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1866 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1867 Lisp_Object preserve_permissions)
1869 Lisp_Object handler;
1870 ptrdiff_t count = SPECPDL_INDEX ();
1871 Lisp_Object encoded_file, encoded_newname;
1872 #if HAVE_LIBSELINUX
1873 security_context_t con;
1874 int conlength = 0;
1875 #endif
1876 #ifdef WINDOWSNT
1877 int result;
1878 #else
1879 bool already_exists = false;
1880 mode_t new_mask;
1881 int ifd, ofd;
1882 struct stat st;
1883 #endif
1885 encoded_file = encoded_newname = Qnil;
1886 CHECK_STRING (file);
1887 CHECK_STRING (newname);
1889 if (!NILP (Ffile_directory_p (newname)))
1890 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1891 else
1892 newname = Fexpand_file_name (newname, Qnil);
1894 file = Fexpand_file_name (file, Qnil);
1896 /* If the input file name has special constructs in it,
1897 call the corresponding file handler. */
1898 handler = Ffind_file_name_handler (file, Qcopy_file);
1899 /* Likewise for output file name. */
1900 if (NILP (handler))
1901 handler = Ffind_file_name_handler (newname, Qcopy_file);
1902 if (!NILP (handler))
1903 return call7 (handler, Qcopy_file, file, newname,
1904 ok_if_already_exists, keep_time, preserve_uid_gid,
1905 preserve_permissions);
1907 encoded_file = ENCODE_FILE (file);
1908 encoded_newname = ENCODE_FILE (newname);
1910 #ifdef WINDOWSNT
1911 if (NILP (ok_if_already_exists)
1912 || INTEGERP (ok_if_already_exists))
1913 barf_or_query_if_file_exists (newname, false, "copy to it",
1914 INTEGERP (ok_if_already_exists), false);
1916 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1917 !NILP (keep_time), !NILP (preserve_uid_gid),
1918 !NILP (preserve_permissions));
1919 switch (result)
1921 case -1:
1922 report_file_error ("Copying file", list2 (file, newname));
1923 case -2:
1924 report_file_error ("Copying permissions from", file);
1925 case -3:
1926 xsignal2 (Qfile_date_error,
1927 build_string ("Resetting file times"), newname);
1928 case -4:
1929 report_file_error ("Copying permissions to", newname);
1931 #else /* not WINDOWSNT */
1932 immediate_quit = 1;
1933 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1934 immediate_quit = 0;
1936 if (ifd < 0)
1937 report_file_error ("Opening input file", file);
1939 record_unwind_protect_int (close_file_unwind, ifd);
1941 if (fstat (ifd, &st) != 0)
1942 report_file_error ("Input file status", file);
1944 if (!NILP (preserve_permissions))
1946 #if HAVE_LIBSELINUX
1947 if (is_selinux_enabled ())
1949 conlength = fgetfilecon (ifd, &con);
1950 if (conlength == -1)
1951 report_file_error ("Doing fgetfilecon", file);
1953 #endif
1956 /* We can copy only regular files. */
1957 if (!S_ISREG (st.st_mode))
1958 report_file_errno ("Non-regular file", file,
1959 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1961 #ifndef MSDOS
1962 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1963 #else
1964 new_mask = S_IREAD | S_IWRITE;
1965 #endif
1967 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1968 new_mask);
1969 if (ofd < 0 && errno == EEXIST)
1971 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1972 barf_or_query_if_file_exists (newname, true, "copy to it",
1973 INTEGERP (ok_if_already_exists), false);
1974 already_exists = true;
1975 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1977 if (ofd < 0)
1978 report_file_error ("Opening output file", newname);
1980 record_unwind_protect_int (close_file_unwind, ofd);
1982 off_t oldsize = 0, newsize = 0;
1984 if (already_exists)
1986 struct stat out_st;
1987 if (fstat (ofd, &out_st) != 0)
1988 report_file_error ("Output file status", newname);
1989 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1990 report_file_errno ("Input and output files are the same",
1991 list2 (file, newname), 0);
1992 if (S_ISREG (out_st.st_mode))
1993 oldsize = out_st.st_size;
1996 immediate_quit = 1;
1997 QUIT;
1998 while (true)
2000 char buf[MAX_ALLOCA];
2001 ptrdiff_t n = emacs_read (ifd, buf, sizeof buf);
2002 if (n < 0)
2003 report_file_error ("Read error", file);
2004 if (n == 0)
2005 break;
2006 if (emacs_write_sig (ofd, buf, n) != n)
2007 report_file_error ("Write error", newname);
2008 newsize += n;
2011 /* Truncate any existing output file after writing the data. This
2012 is more likely to work than truncation before writing, if the
2013 file system is out of space or the user is over disk quota. */
2014 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2015 report_file_error ("Truncating output file", newname);
2017 immediate_quit = 0;
2019 #ifndef MSDOS
2020 /* Preserve the original file permissions, and if requested, also its
2021 owner and group. */
2023 mode_t preserved_permissions = st.st_mode & 07777;
2024 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2025 if (!NILP (preserve_uid_gid))
2027 /* Attempt to change owner and group. If that doesn't work
2028 attempt to change just the group, as that is sometimes allowed.
2029 Adjust the mode mask to eliminate setuid or setgid bits
2030 or group permissions bits that are inappropriate if the
2031 owner or group are wrong. */
2032 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2034 if (fchown (ofd, -1, st.st_gid) == 0)
2035 preserved_permissions &= ~04000;
2036 else
2038 preserved_permissions &= ~06000;
2040 /* Copy the other bits to the group bits, since the
2041 group is wrong. */
2042 preserved_permissions &= ~070;
2043 preserved_permissions |= (preserved_permissions & 7) << 3;
2044 default_permissions &= ~070;
2045 default_permissions |= (default_permissions & 7) << 3;
2050 switch (!NILP (preserve_permissions)
2051 ? qcopy_acl (SSDATA (encoded_file), ifd,
2052 SSDATA (encoded_newname), ofd,
2053 preserved_permissions)
2054 : (already_exists
2055 || (new_mask & ~realmask) == default_permissions)
2057 : fchmod (ofd, default_permissions))
2059 case -2: report_file_error ("Copying permissions from", file);
2060 case -1: report_file_error ("Copying permissions to", newname);
2063 #endif /* not MSDOS */
2065 #if HAVE_LIBSELINUX
2066 if (conlength > 0)
2068 /* Set the modified context back to the file. */
2069 bool fail = fsetfilecon (ofd, con) != 0;
2070 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2071 if (fail && errno != ENOTSUP)
2072 report_file_error ("Doing fsetfilecon", newname);
2074 freecon (con);
2076 #endif
2078 if (!NILP (keep_time))
2080 struct timespec atime = get_stat_atime (&st);
2081 struct timespec mtime = get_stat_mtime (&st);
2082 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2083 xsignal2 (Qfile_date_error,
2084 build_string ("Cannot set file date"), newname);
2087 if (emacs_close (ofd) < 0)
2088 report_file_error ("Write error", newname);
2090 emacs_close (ifd);
2092 #ifdef MSDOS
2093 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2094 and if it can't, it tells so. Otherwise, under MSDOS we usually
2095 get only the READ bit, which will make the copied file read-only,
2096 so it's better not to chmod at all. */
2097 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2098 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2099 #endif /* MSDOS */
2100 #endif /* not WINDOWSNT */
2102 /* Discard the unwind protects. */
2103 specpdl_ptr = specpdl + count;
2105 return Qnil;
2108 DEFUN ("make-directory-internal", Fmake_directory_internal,
2109 Smake_directory_internal, 1, 1, 0,
2110 doc: /* Create a new directory named DIRECTORY. */)
2111 (Lisp_Object directory)
2113 const char *dir;
2114 Lisp_Object handler;
2115 Lisp_Object encoded_dir;
2117 CHECK_STRING (directory);
2118 directory = Fexpand_file_name (directory, Qnil);
2120 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2121 if (!NILP (handler))
2122 return call2 (handler, Qmake_directory_internal, directory);
2124 encoded_dir = ENCODE_FILE (directory);
2126 dir = SSDATA (encoded_dir);
2128 #ifdef WINDOWSNT
2129 if (mkdir (dir) != 0)
2130 #else
2131 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2132 #endif
2133 report_file_error ("Creating directory", directory);
2135 return Qnil;
2138 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2139 Sdelete_directory_internal, 1, 1, 0,
2140 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2141 (Lisp_Object directory)
2143 const char *dir;
2144 Lisp_Object encoded_dir;
2146 CHECK_STRING (directory);
2147 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2148 encoded_dir = ENCODE_FILE (directory);
2149 dir = SSDATA (encoded_dir);
2151 if (rmdir (dir) != 0)
2152 report_file_error ("Removing directory", directory);
2154 return Qnil;
2157 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2158 "(list (read-file-name \
2159 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2160 \"Move file to trash: \" \"Delete file: \") \
2161 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2162 (null current-prefix-arg))",
2163 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2164 If file has multiple names, it continues to exist with the other names.
2165 TRASH non-nil means to trash the file instead of deleting, provided
2166 `delete-by-moving-to-trash' is non-nil.
2168 When called interactively, TRASH is t if no prefix argument is given.
2169 With a prefix argument, TRASH is nil. */)
2170 (Lisp_Object filename, Lisp_Object trash)
2172 Lisp_Object handler;
2173 Lisp_Object encoded_file;
2175 if (!NILP (Ffile_directory_p (filename))
2176 && NILP (Ffile_symlink_p (filename)))
2177 xsignal2 (Qfile_error,
2178 build_string ("Removing old name: is a directory"),
2179 filename);
2180 filename = Fexpand_file_name (filename, Qnil);
2182 handler = Ffind_file_name_handler (filename, Qdelete_file);
2183 if (!NILP (handler))
2184 return call3 (handler, Qdelete_file, filename, trash);
2186 if (delete_by_moving_to_trash && !NILP (trash))
2187 return call1 (Qmove_file_to_trash, filename);
2189 encoded_file = ENCODE_FILE (filename);
2191 if (unlink (SSDATA (encoded_file)) < 0)
2192 report_file_error ("Removing old name", filename);
2193 return Qnil;
2196 static Lisp_Object
2197 internal_delete_file_1 (Lisp_Object ignore)
2199 return Qt;
2202 /* Delete file FILENAME, returning true if successful.
2203 This ignores `delete-by-moving-to-trash'. */
2205 bool
2206 internal_delete_file (Lisp_Object filename)
2208 Lisp_Object tem;
2210 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2211 Qt, internal_delete_file_1);
2212 return NILP (tem);
2215 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2216 "fRename file: \nGRename %s to file: \np",
2217 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2218 If file has names other than FILE, it continues to have those names.
2219 Signals a `file-already-exists' error if a file NEWNAME already exists
2220 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2221 A number as third arg means request confirmation if NEWNAME already exists.
2222 This is what happens in interactive use with M-x. */)
2223 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2225 Lisp_Object handler;
2226 Lisp_Object encoded_file, encoded_newname, symlink_target;
2228 symlink_target = encoded_file = encoded_newname = Qnil;
2229 CHECK_STRING (file);
2230 CHECK_STRING (newname);
2231 file = Fexpand_file_name (file, Qnil);
2233 if ((!NILP (Ffile_directory_p (newname)))
2234 #ifdef DOS_NT
2235 /* If the file names are identical but for the case,
2236 don't attempt to move directory to itself. */
2237 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2238 #endif
2241 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2242 ? file : Fdirectory_file_name (file));
2243 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2245 else
2246 newname = Fexpand_file_name (newname, Qnil);
2248 /* If the file name has special constructs in it,
2249 call the corresponding file handler. */
2250 handler = Ffind_file_name_handler (file, Qrename_file);
2251 if (NILP (handler))
2252 handler = Ffind_file_name_handler (newname, Qrename_file);
2253 if (!NILP (handler))
2254 return call4 (handler, Qrename_file,
2255 file, newname, ok_if_already_exists);
2257 encoded_file = ENCODE_FILE (file);
2258 encoded_newname = ENCODE_FILE (newname);
2260 #ifdef DOS_NT
2261 /* If the file names are identical but for the case, don't ask for
2262 confirmation: they simply want to change the letter-case of the
2263 file name. */
2264 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2265 #endif
2266 if (NILP (ok_if_already_exists)
2267 || INTEGERP (ok_if_already_exists))
2268 barf_or_query_if_file_exists (newname, false, "rename to it",
2269 INTEGERP (ok_if_already_exists), false);
2270 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2272 int rename_errno = errno;
2273 if (rename_errno == EXDEV)
2275 ptrdiff_t count;
2276 symlink_target = Ffile_symlink_p (file);
2277 if (! NILP (symlink_target))
2278 Fmake_symbolic_link (symlink_target, newname,
2279 NILP (ok_if_already_exists) ? Qnil : Qt);
2280 else if (!NILP (Ffile_directory_p (file)))
2281 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2282 else
2283 /* We have already prompted if it was an integer, so don't
2284 have copy-file prompt again. */
2285 Fcopy_file (file, newname,
2286 NILP (ok_if_already_exists) ? Qnil : Qt,
2287 Qt, Qt, Qt);
2289 count = SPECPDL_INDEX ();
2290 specbind (Qdelete_by_moving_to_trash, Qnil);
2292 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2293 call2 (Qdelete_directory, file, Qt);
2294 else
2295 Fdelete_file (file, Qnil);
2296 unbind_to (count, Qnil);
2298 else
2299 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2302 return Qnil;
2305 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2306 "fAdd name to file: \nGName to add to %s: \np",
2307 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2308 Signals a `file-already-exists' error if a file NEWNAME already exists
2309 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2310 A number as third arg means request confirmation if NEWNAME already exists.
2311 This is what happens in interactive use with M-x. */)
2312 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2314 Lisp_Object handler;
2315 Lisp_Object encoded_file, encoded_newname;
2317 encoded_file = encoded_newname = Qnil;
2318 CHECK_STRING (file);
2319 CHECK_STRING (newname);
2320 file = Fexpand_file_name (file, Qnil);
2322 if (!NILP (Ffile_directory_p (newname)))
2323 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2324 else
2325 newname = Fexpand_file_name (newname, Qnil);
2327 /* If the file name has special constructs in it,
2328 call the corresponding file handler. */
2329 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2330 if (!NILP (handler))
2331 return call4 (handler, Qadd_name_to_file, file,
2332 newname, ok_if_already_exists);
2334 /* If the new name has special constructs in it,
2335 call the corresponding file handler. */
2336 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2337 if (!NILP (handler))
2338 return call4 (handler, Qadd_name_to_file, file,
2339 newname, ok_if_already_exists);
2341 encoded_file = ENCODE_FILE (file);
2342 encoded_newname = ENCODE_FILE (newname);
2344 if (NILP (ok_if_already_exists)
2345 || INTEGERP (ok_if_already_exists))
2346 barf_or_query_if_file_exists (newname, false, "make it a new name",
2347 INTEGERP (ok_if_already_exists), false);
2349 unlink (SSDATA (newname));
2350 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2352 int link_errno = errno;
2353 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2356 return Qnil;
2359 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2360 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2361 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2362 Both args must be strings.
2363 Signals a `file-already-exists' error if a file LINKNAME already exists
2364 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2365 A number as third arg means request confirmation if LINKNAME already exists.
2366 This happens for interactive use with M-x. */)
2367 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2369 Lisp_Object handler;
2370 Lisp_Object encoded_target, encoded_linkname;
2372 encoded_target = encoded_linkname = Qnil;
2373 CHECK_STRING (target);
2374 CHECK_STRING (linkname);
2375 /* If the link target has a ~, we must expand it to get
2376 a truly valid file name. Otherwise, do not expand;
2377 we want to permit links to relative file names. */
2378 if (SREF (target, 0) == '~')
2379 target = Fexpand_file_name (target, Qnil);
2381 if (!NILP (Ffile_directory_p (linkname)))
2382 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2383 else
2384 linkname = Fexpand_file_name (linkname, Qnil);
2386 /* If the file name has special constructs in it,
2387 call the corresponding file handler. */
2388 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2389 if (!NILP (handler))
2390 return call4 (handler, Qmake_symbolic_link, target,
2391 linkname, ok_if_already_exists);
2393 /* If the new link name has special constructs in it,
2394 call the corresponding file handler. */
2395 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2396 if (!NILP (handler))
2397 return call4 (handler, Qmake_symbolic_link, target,
2398 linkname, ok_if_already_exists);
2400 encoded_target = ENCODE_FILE (target);
2401 encoded_linkname = ENCODE_FILE (linkname);
2403 if (NILP (ok_if_already_exists)
2404 || INTEGERP (ok_if_already_exists))
2405 barf_or_query_if_file_exists (linkname, false, "make it a link",
2406 INTEGERP (ok_if_already_exists), false);
2407 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2409 /* If we didn't complain already, silently delete existing file. */
2410 int symlink_errno;
2411 if (errno == EEXIST)
2413 unlink (SSDATA (encoded_linkname));
2414 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2415 >= 0)
2416 return Qnil;
2418 if (errno == ENOSYS)
2419 xsignal1 (Qfile_error,
2420 build_string ("Symbolic links are not supported"));
2422 symlink_errno = errno;
2423 report_file_errno ("Making symbolic link", list2 (target, linkname),
2424 symlink_errno);
2427 return Qnil;
2431 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2432 1, 1, 0,
2433 doc: /* Return t if file FILENAME specifies an absolute file name.
2434 On Unix, this is a name starting with a `/' or a `~'. */)
2435 (Lisp_Object filename)
2437 CHECK_STRING (filename);
2438 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2441 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2442 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2443 See also `file-readable-p' and `file-attributes'.
2444 This returns nil for a symlink to a nonexistent file.
2445 Use `file-symlink-p' to test for such links. */)
2446 (Lisp_Object filename)
2448 Lisp_Object absname;
2449 Lisp_Object handler;
2451 CHECK_STRING (filename);
2452 absname = Fexpand_file_name (filename, Qnil);
2454 /* If the file name has special constructs in it,
2455 call the corresponding file handler. */
2456 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2457 if (!NILP (handler))
2459 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2460 errno = 0;
2461 return result;
2464 absname = ENCODE_FILE (absname);
2466 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2469 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2470 doc: /* Return t if FILENAME can be executed by you.
2471 For a directory, this means you can access files in that directory.
2472 (It is generally better to use `file-accessible-directory-p' for that
2473 purpose, though.) */)
2474 (Lisp_Object filename)
2476 Lisp_Object absname;
2477 Lisp_Object handler;
2479 CHECK_STRING (filename);
2480 absname = Fexpand_file_name (filename, Qnil);
2482 /* If the file name has special constructs in it,
2483 call the corresponding file handler. */
2484 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2485 if (!NILP (handler))
2486 return call2 (handler, Qfile_executable_p, absname);
2488 absname = ENCODE_FILE (absname);
2490 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2493 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2494 doc: /* Return t if file FILENAME exists and you can read it.
2495 See also `file-exists-p' and `file-attributes'. */)
2496 (Lisp_Object filename)
2498 Lisp_Object absname;
2499 Lisp_Object handler;
2501 CHECK_STRING (filename);
2502 absname = Fexpand_file_name (filename, Qnil);
2504 /* If the file name has special constructs in it,
2505 call the corresponding file handler. */
2506 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2507 if (!NILP (handler))
2508 return call2 (handler, Qfile_readable_p, absname);
2510 absname = ENCODE_FILE (absname);
2511 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2512 ? Qt : Qnil);
2515 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2516 doc: /* Return t if file FILENAME can be written or created by you. */)
2517 (Lisp_Object filename)
2519 Lisp_Object absname, dir, encoded;
2520 Lisp_Object handler;
2522 CHECK_STRING (filename);
2523 absname = Fexpand_file_name (filename, Qnil);
2525 /* If the file name has special constructs in it,
2526 call the corresponding file handler. */
2527 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2528 if (!NILP (handler))
2529 return call2 (handler, Qfile_writable_p, absname);
2531 encoded = ENCODE_FILE (absname);
2532 if (check_writable (SSDATA (encoded), W_OK))
2533 return Qt;
2534 if (errno != ENOENT)
2535 return Qnil;
2537 dir = Ffile_name_directory (absname);
2538 eassert (!NILP (dir));
2539 #ifdef MSDOS
2540 dir = Fdirectory_file_name (dir);
2541 #endif /* MSDOS */
2543 dir = ENCODE_FILE (dir);
2544 #ifdef WINDOWSNT
2545 /* The read-only attribute of the parent directory doesn't affect
2546 whether a file or directory can be created within it. Some day we
2547 should check ACLs though, which do affect this. */
2548 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2549 #else
2550 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2551 #endif
2554 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2555 doc: /* Access file FILENAME, and get an error if that does not work.
2556 The second argument STRING is used in the error message.
2557 If there is no error, returns nil. */)
2558 (Lisp_Object filename, Lisp_Object string)
2560 Lisp_Object handler, encoded_filename, absname;
2562 CHECK_STRING (filename);
2563 absname = Fexpand_file_name (filename, Qnil);
2565 CHECK_STRING (string);
2567 /* If the file name has special constructs in it,
2568 call the corresponding file handler. */
2569 handler = Ffind_file_name_handler (absname, Qaccess_file);
2570 if (!NILP (handler))
2571 return call3 (handler, Qaccess_file, absname, string);
2573 encoded_filename = ENCODE_FILE (absname);
2575 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2576 report_file_error (SSDATA (string), filename);
2578 return Qnil;
2581 /* Relative to directory FD, return the symbolic link value of FILENAME.
2582 On failure, return nil. */
2583 Lisp_Object
2584 emacs_readlinkat (int fd, char const *filename)
2586 static struct allocator const emacs_norealloc_allocator =
2587 { xmalloc, NULL, xfree, memory_full };
2588 Lisp_Object val;
2589 char readlink_buf[1024];
2590 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2591 &emacs_norealloc_allocator, readlinkat);
2592 if (!buf)
2593 return Qnil;
2595 val = build_unibyte_string (buf);
2596 if (buf[0] == '/' && strchr (buf, ':'))
2598 AUTO_STRING (slash_colon, "/:");
2599 val = concat2 (slash_colon, val);
2601 if (buf != readlink_buf)
2602 xfree (buf);
2603 val = DECODE_FILE (val);
2604 return val;
2607 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2608 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2609 The value is the link target, as a string.
2610 Otherwise it returns nil.
2612 This function does not check whether the link target exists. */)
2613 (Lisp_Object filename)
2615 Lisp_Object handler;
2617 CHECK_STRING (filename);
2618 filename = Fexpand_file_name (filename, Qnil);
2620 /* If the file name has special constructs in it,
2621 call the corresponding file handler. */
2622 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2623 if (!NILP (handler))
2624 return call2 (handler, Qfile_symlink_p, filename);
2626 filename = ENCODE_FILE (filename);
2628 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2631 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2632 doc: /* Return t if FILENAME names an existing directory.
2633 Symbolic links to directories count as directories.
2634 See `file-symlink-p' to distinguish symlinks. */)
2635 (Lisp_Object filename)
2637 Lisp_Object absname;
2638 Lisp_Object handler;
2640 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2642 /* If the file name has special constructs in it,
2643 call the corresponding file handler. */
2644 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2645 if (!NILP (handler))
2646 return call2 (handler, Qfile_directory_p, absname);
2648 absname = ENCODE_FILE (absname);
2650 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2653 /* Return true if FILE is a directory or a symlink to a directory. */
2654 bool
2655 file_directory_p (char const *file)
2657 #ifdef WINDOWSNT
2658 /* This is cheaper than 'stat'. */
2659 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2660 #else
2661 struct stat st;
2662 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2663 #endif
2666 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2667 Sfile_accessible_directory_p, 1, 1, 0,
2668 doc: /* Return t if file FILENAME names a directory you can open.
2669 For the value to be t, FILENAME must specify the name of a directory as a file,
2670 and the directory must allow you to open files in it. In order to use a
2671 directory as a buffer's current directory, this predicate must return true.
2672 A directory name spec may be given instead; then the value is t
2673 if the directory so specified exists and really is a readable and
2674 searchable directory. */)
2675 (Lisp_Object filename)
2677 Lisp_Object absname;
2678 Lisp_Object handler;
2680 CHECK_STRING (filename);
2681 absname = Fexpand_file_name (filename, Qnil);
2683 /* If the file name has special constructs in it,
2684 call the corresponding file handler. */
2685 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2686 if (!NILP (handler))
2688 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2689 errno = 0;
2690 return r;
2693 absname = ENCODE_FILE (absname);
2694 return file_accessible_directory_p (absname) ? Qt : Qnil;
2697 /* If FILE is a searchable directory or a symlink to a
2698 searchable directory, return true. Otherwise return
2699 false and set errno to an error number. */
2700 bool
2701 file_accessible_directory_p (Lisp_Object file)
2703 #ifdef DOS_NT
2704 # ifdef WINDOWSNT
2705 /* We need a special-purpose test because (a) NTFS security data is
2706 not reflected in Posix-style mode bits, and (b) the trick with
2707 accessing "DIR/.", used below on Posix hosts, doesn't work on
2708 Windows, because "DIR/." is normalized to just "DIR" before
2709 hitting the disk. */
2710 return (SBYTES (file) == 0
2711 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2712 # else /* MSDOS */
2713 return file_directory_p (SSDATA (file));
2714 # endif /* MSDOS */
2715 #else /* !DOS_NT */
2716 /* On POSIXish platforms, use just one system call; this avoids a
2717 race and is typically faster. */
2718 const char *data = SSDATA (file);
2719 ptrdiff_t len = SBYTES (file);
2720 char const *dir;
2721 bool ok;
2722 int saved_errno;
2723 USE_SAFE_ALLOCA;
2725 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2726 There are three exceptions: "", "/", and "//". Leave "" alone,
2727 as it's invalid. Append only "." to the other two exceptions as
2728 "/" and "//" are distinct on some platforms, whereas "/", "///",
2729 "////", etc. are all equivalent. */
2730 if (! len)
2731 dir = data;
2732 else
2734 /* Just check for trailing '/' when deciding whether to append '/'.
2735 That's simpler than testing the two special cases "/" and "//",
2736 and it's a safe optimization here. */
2737 char *buf = SAFE_ALLOCA (len + 3);
2738 memcpy (buf, data, len);
2739 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2740 dir = buf;
2743 ok = check_existing (dir);
2744 saved_errno = errno;
2745 SAFE_FREE ();
2746 errno = saved_errno;
2747 return ok;
2748 #endif /* !DOS_NT */
2751 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2752 doc: /* Return t if FILENAME names a regular file.
2753 This is the sort of file that holds an ordinary stream of data bytes.
2754 Symbolic links to regular files count as regular files.
2755 See `file-symlink-p' to distinguish symlinks. */)
2756 (Lisp_Object filename)
2758 register Lisp_Object absname;
2759 struct stat st;
2760 Lisp_Object handler;
2762 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2764 /* If the file name has special constructs in it,
2765 call the corresponding file handler. */
2766 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2767 if (!NILP (handler))
2768 return call2 (handler, Qfile_regular_p, absname);
2770 absname = ENCODE_FILE (absname);
2772 #ifdef WINDOWSNT
2774 int result;
2775 Lisp_Object tem = Vw32_get_true_file_attributes;
2777 /* Tell stat to use expensive method to get accurate info. */
2778 Vw32_get_true_file_attributes = Qt;
2779 result = stat (SDATA (absname), &st);
2780 Vw32_get_true_file_attributes = tem;
2782 if (result < 0)
2783 return Qnil;
2784 return S_ISREG (st.st_mode) ? Qt : Qnil;
2786 #else
2787 if (stat (SSDATA (absname), &st) < 0)
2788 return Qnil;
2789 return S_ISREG (st.st_mode) ? Qt : Qnil;
2790 #endif
2793 DEFUN ("file-selinux-context", Ffile_selinux_context,
2794 Sfile_selinux_context, 1, 1, 0,
2795 doc: /* Return SELinux context of file named FILENAME.
2796 The return value is a list (USER ROLE TYPE RANGE), where the list
2797 elements are strings naming the user, role, type, and range of the
2798 file's SELinux security context.
2800 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2801 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2802 (Lisp_Object filename)
2804 Lisp_Object absname;
2805 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2807 Lisp_Object handler;
2808 #if HAVE_LIBSELINUX
2809 security_context_t con;
2810 int conlength;
2811 context_t context;
2812 #endif
2814 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2816 /* If the file name has special constructs in it,
2817 call the corresponding file handler. */
2818 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2819 if (!NILP (handler))
2820 return call2 (handler, Qfile_selinux_context, absname);
2822 absname = ENCODE_FILE (absname);
2824 #if HAVE_LIBSELINUX
2825 if (is_selinux_enabled ())
2827 conlength = lgetfilecon (SSDATA (absname), &con);
2828 if (conlength > 0)
2830 context = context_new (con);
2831 if (context_user_get (context))
2832 user = build_string (context_user_get (context));
2833 if (context_role_get (context))
2834 role = build_string (context_role_get (context));
2835 if (context_type_get (context))
2836 type = build_string (context_type_get (context));
2837 if (context_range_get (context))
2838 range = build_string (context_range_get (context));
2839 context_free (context);
2840 freecon (con);
2843 #endif
2845 return list4 (user, role, type, range);
2848 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2849 Sset_file_selinux_context, 2, 2, 0,
2850 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2851 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2852 elements are strings naming the components of a SELinux context.
2854 Value is t if setting of SELinux context was successful, nil otherwise.
2856 This function does nothing and returns nil if SELinux is disabled,
2857 or if Emacs was not compiled with SELinux support. */)
2858 (Lisp_Object filename, Lisp_Object context)
2860 Lisp_Object absname;
2861 Lisp_Object handler;
2862 #if HAVE_LIBSELINUX
2863 Lisp_Object encoded_absname;
2864 Lisp_Object user = CAR_SAFE (context);
2865 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2866 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2867 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2868 security_context_t con;
2869 bool fail;
2870 int conlength;
2871 context_t parsed_con;
2872 #endif
2874 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2876 /* If the file name has special constructs in it,
2877 call the corresponding file handler. */
2878 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2879 if (!NILP (handler))
2880 return call3 (handler, Qset_file_selinux_context, absname, context);
2882 #if HAVE_LIBSELINUX
2883 if (is_selinux_enabled ())
2885 /* Get current file context. */
2886 encoded_absname = ENCODE_FILE (absname);
2887 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2888 if (conlength > 0)
2890 parsed_con = context_new (con);
2891 /* Change the parts defined in the parameter.*/
2892 if (STRINGP (user))
2894 if (context_user_set (parsed_con, SSDATA (user)))
2895 error ("Doing context_user_set");
2897 if (STRINGP (role))
2899 if (context_role_set (parsed_con, SSDATA (role)))
2900 error ("Doing context_role_set");
2902 if (STRINGP (type))
2904 if (context_type_set (parsed_con, SSDATA (type)))
2905 error ("Doing context_type_set");
2907 if (STRINGP (range))
2909 if (context_range_set (parsed_con, SSDATA (range)))
2910 error ("Doing context_range_set");
2913 /* Set the modified context back to the file. */
2914 fail = (lsetfilecon (SSDATA (encoded_absname),
2915 context_str (parsed_con))
2916 != 0);
2917 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2918 if (fail && errno != ENOTSUP)
2919 report_file_error ("Doing lsetfilecon", absname);
2921 context_free (parsed_con);
2922 freecon (con);
2923 return fail ? Qnil : Qt;
2925 else
2926 report_file_error ("Doing lgetfilecon", absname);
2928 #endif
2930 return Qnil;
2933 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2934 doc: /* Return ACL entries of file named FILENAME.
2935 The entries are returned in a format suitable for use in `set-file-acl'
2936 but is otherwise undocumented and subject to change.
2937 Return nil if file does not exist or is not accessible, or if Emacs
2938 was unable to determine the ACL entries. */)
2939 (Lisp_Object filename)
2941 Lisp_Object absname;
2942 Lisp_Object handler;
2943 #ifdef HAVE_ACL_SET_FILE
2944 acl_t acl;
2945 Lisp_Object acl_string;
2946 char *str;
2947 # ifndef HAVE_ACL_TYPE_EXTENDED
2948 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2949 # endif
2950 #endif
2952 absname = expand_and_dir_to_file (filename,
2953 BVAR (current_buffer, directory));
2955 /* If the file name has special constructs in it,
2956 call the corresponding file handler. */
2957 handler = Ffind_file_name_handler (absname, Qfile_acl);
2958 if (!NILP (handler))
2959 return call2 (handler, Qfile_acl, absname);
2961 #ifdef HAVE_ACL_SET_FILE
2962 absname = ENCODE_FILE (absname);
2964 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2965 if (acl == NULL)
2966 return Qnil;
2968 str = acl_to_text (acl, NULL);
2969 if (str == NULL)
2971 acl_free (acl);
2972 return Qnil;
2975 acl_string = build_string (str);
2976 acl_free (str);
2977 acl_free (acl);
2979 return acl_string;
2980 #endif
2982 return Qnil;
2985 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
2986 2, 2, 0,
2987 doc: /* Set ACL of file named FILENAME to ACL-STRING.
2988 ACL-STRING should contain the textual representation of the ACL
2989 entries in a format suitable for the platform.
2991 Value is t if setting of ACL was successful, nil otherwise.
2993 Setting ACL for local files requires Emacs to be built with ACL
2994 support. */)
2995 (Lisp_Object filename, Lisp_Object acl_string)
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
3036 return Qnil;
3039 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3040 doc: /* Return mode bits of file named FILENAME, as an integer.
3041 Return nil, if file does not exist or is not accessible. */)
3042 (Lisp_Object filename)
3044 Lisp_Object absname;
3045 struct stat st;
3046 Lisp_Object handler;
3048 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3050 /* If the file name has special constructs in it,
3051 call the corresponding file handler. */
3052 handler = Ffind_file_name_handler (absname, Qfile_modes);
3053 if (!NILP (handler))
3054 return call2 (handler, Qfile_modes, absname);
3056 absname = ENCODE_FILE (absname);
3058 if (stat (SSDATA (absname), &st) < 0)
3059 return Qnil;
3061 return make_number (st.st_mode & 07777);
3064 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3065 "(let ((file (read-file-name \"File: \"))) \
3066 (list file (read-file-modes nil file)))",
3067 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3068 Only the 12 low bits of MODE are used.
3070 Interactively, mode bits are read by `read-file-modes', which accepts
3071 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3072 (Lisp_Object filename, Lisp_Object mode)
3074 Lisp_Object absname, encoded_absname;
3075 Lisp_Object handler;
3077 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3078 CHECK_NUMBER (mode);
3080 /* If the file name has special constructs in it,
3081 call the corresponding file handler. */
3082 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3083 if (!NILP (handler))
3084 return call3 (handler, Qset_file_modes, absname, mode);
3086 encoded_absname = ENCODE_FILE (absname);
3088 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3089 report_file_error ("Doing chmod", absname);
3091 return Qnil;
3094 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3095 doc: /* Set the file permission bits for newly created files.
3096 The argument MODE should be an integer; only the low 9 bits are used.
3097 This setting is inherited by subprocesses. */)
3098 (Lisp_Object mode)
3100 mode_t oldrealmask, oldumask, newumask;
3101 CHECK_NUMBER (mode);
3102 oldrealmask = realmask;
3103 newumask = ~ XINT (mode) & 0777;
3105 block_input ();
3106 realmask = newumask;
3107 oldumask = umask (newumask);
3108 unblock_input ();
3110 eassert (oldumask == oldrealmask);
3111 return Qnil;
3114 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3115 doc: /* Return the default file protection for created files.
3116 The value is an integer. */)
3117 (void)
3119 Lisp_Object value;
3120 XSETINT (value, (~ realmask) & 0777);
3121 return value;
3125 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3126 doc: /* Set times of file FILENAME to TIMESTAMP.
3127 Set both access and modification times.
3128 Return t on success, else nil.
3129 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3130 `current-time'. */)
3131 (Lisp_Object filename, Lisp_Object timestamp)
3133 Lisp_Object absname, encoded_absname;
3134 Lisp_Object handler;
3135 struct timespec t = lisp_time_argument (timestamp);
3137 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3139 /* If the file name has special constructs in it,
3140 call the corresponding file handler. */
3141 handler = Ffind_file_name_handler (absname, Qset_file_times);
3142 if (!NILP (handler))
3143 return call3 (handler, Qset_file_times, absname, timestamp);
3145 encoded_absname = ENCODE_FILE (absname);
3148 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3150 #ifdef MSDOS
3151 /* Setting times on a directory always fails. */
3152 if (file_directory_p (SSDATA (encoded_absname)))
3153 return Qnil;
3154 #endif
3155 report_file_error ("Setting file times", absname);
3159 return Qt;
3162 #ifdef HAVE_SYNC
3163 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3164 doc: /* Tell Unix to finish all pending disk updates. */)
3165 (void)
3167 sync ();
3168 return Qnil;
3171 #endif /* HAVE_SYNC */
3173 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3174 doc: /* Return t if file FILE1 is newer than file FILE2.
3175 If FILE1 does not exist, the answer is nil;
3176 otherwise, if FILE2 does not exist, the answer is t. */)
3177 (Lisp_Object file1, Lisp_Object file2)
3179 Lisp_Object absname1, absname2;
3180 struct stat st1, st2;
3181 Lisp_Object handler;
3183 CHECK_STRING (file1);
3184 CHECK_STRING (file2);
3186 absname1 = Qnil;
3187 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3188 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3190 /* If the file name has special constructs in it,
3191 call the corresponding file handler. */
3192 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3193 if (NILP (handler))
3194 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3195 if (!NILP (handler))
3196 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3198 absname1 = ENCODE_FILE (absname1);
3199 absname2 = ENCODE_FILE (absname2);
3201 if (stat (SSDATA (absname1), &st1) < 0)
3202 return Qnil;
3204 if (stat (SSDATA (absname2), &st2) < 0)
3205 return Qt;
3207 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3208 ? Qt : Qnil);
3211 #ifndef READ_BUF_SIZE
3212 #define READ_BUF_SIZE (64 << 10)
3213 #endif
3214 /* Some buffer offsets are stored in 'int' variables. */
3215 verify (READ_BUF_SIZE <= INT_MAX);
3217 /* This function is called after Lisp functions to decide a coding
3218 system are called, or when they cause an error. Before they are
3219 called, the current buffer is set unibyte and it contains only a
3220 newly inserted text (thus the buffer was empty before the
3221 insertion).
3223 The functions may set markers, overlays, text properties, or even
3224 alter the buffer contents, change the current buffer.
3226 Here, we reset all those changes by:
3227 o set back the current buffer.
3228 o move all markers and overlays to BEG.
3229 o remove all text properties.
3230 o set back the buffer multibyteness. */
3232 static void
3233 decide_coding_unwind (Lisp_Object unwind_data)
3235 Lisp_Object multibyte, undo_list, buffer;
3237 multibyte = XCAR (unwind_data);
3238 unwind_data = XCDR (unwind_data);
3239 undo_list = XCAR (unwind_data);
3240 buffer = XCDR (unwind_data);
3242 set_buffer_internal (XBUFFER (buffer));
3243 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3244 adjust_overlays_for_delete (BEG, Z - BEG);
3245 set_buffer_intervals (current_buffer, NULL);
3246 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3248 /* Now we are safe to change the buffer's multibyteness directly. */
3249 bset_enable_multibyte_characters (current_buffer, multibyte);
3250 bset_undo_list (current_buffer, undo_list);
3253 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3254 object where slot 0 is the file descriptor, slot 1 specifies
3255 an offset to put the read bytes, and slot 2 is the maximum
3256 amount of bytes to read. Value is the number of bytes read. */
3258 static Lisp_Object
3259 read_non_regular (Lisp_Object state)
3261 int nbytes;
3263 immediate_quit = 1;
3264 QUIT;
3265 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3266 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3267 + XSAVE_INTEGER (state, 1)),
3268 XSAVE_INTEGER (state, 2));
3269 immediate_quit = 0;
3270 /* Fast recycle this object for the likely next call. */
3271 free_misc (state);
3272 return make_number (nbytes);
3276 /* Condition-case handler used when reading from non-regular files
3277 in insert-file-contents. */
3279 static Lisp_Object
3280 read_non_regular_quit (Lisp_Object ignore)
3282 return Qnil;
3285 /* Return the file offset that VAL represents, checking for type
3286 errors and overflow. */
3287 static off_t
3288 file_offset (Lisp_Object val)
3290 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3291 return XINT (val);
3293 if (FLOATP (val))
3295 double v = XFLOAT_DATA (val);
3296 if (0 <= v
3297 && (sizeof (off_t) < sizeof v
3298 ? v <= TYPE_MAXIMUM (off_t)
3299 : v < TYPE_MAXIMUM (off_t)))
3300 return v;
3303 wrong_type_argument (intern ("file-offset"), val);
3306 /* Return a special time value indicating the error number ERRNUM. */
3307 static struct timespec
3308 time_error_value (int errnum)
3310 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3311 ? NONEXISTENT_MODTIME_NSECS
3312 : UNKNOWN_MODTIME_NSECS);
3313 return make_timespec (0, ns);
3316 static Lisp_Object
3317 get_window_points_and_markers (void)
3319 Lisp_Object pt_marker = Fpoint_marker ();
3320 Lisp_Object windows
3321 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3322 Lisp_Object window_markers = windows;
3323 /* Window markers (and point) are handled specially: rather than move to
3324 just before or just after the modified text, we try to keep the
3325 markers at the same distance (bug#19161).
3326 In general, this is wrong, but for window-markers, this should be harmless
3327 and is convenient for the end user when most of the file is unmodified,
3328 except for a few minor details near the beginning and near the end. */
3329 for (; CONSP (windows); windows = XCDR (windows))
3330 if (WINDOWP (XCAR (windows)))
3332 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3333 XSETCAR (windows,
3334 Fcons (window_marker, Fmarker_position (window_marker)));
3336 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3339 static void
3340 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3341 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3343 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3344 if (CONSP (XCAR (window_markers)))
3346 Lisp_Object car = XCAR (window_markers);
3347 Lisp_Object marker = XCAR (car);
3348 Lisp_Object oldpos = XCDR (car);
3349 if (MARKERP (marker) && INTEGERP (oldpos)
3350 && XINT (oldpos) > same_at_start
3351 && XINT (oldpos) < same_at_end)
3353 ptrdiff_t oldsize = same_at_end - same_at_start;
3354 ptrdiff_t newsize = inserted;
3355 double growth = newsize / (double)oldsize;
3356 ptrdiff_t newpos
3357 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3358 Fset_marker (marker, make_number (newpos), Qnil);
3363 /* FIXME: insert-file-contents should be split with the top-level moved to
3364 Elisp and only the core kept in C. */
3366 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3367 1, 5, 0,
3368 doc: /* Insert contents of file FILENAME after point.
3369 Returns list of absolute file name and number of characters inserted.
3370 If second argument VISIT is non-nil, the buffer's visited filename and
3371 last save file modtime are set, and it is marked unmodified. If
3372 visiting and the file does not exist, visiting is completed before the
3373 error is signaled.
3375 The optional third and fourth arguments BEG and END specify what portion
3376 of the file to insert. These arguments count bytes in the file, not
3377 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3379 If optional fifth argument REPLACE is non-nil, replace the current
3380 buffer contents (in the accessible portion) with the file contents.
3381 This is better than simply deleting and inserting the whole thing
3382 because (1) it preserves some marker positions and (2) it puts less data
3383 in the undo list. When REPLACE is non-nil, the second return value is
3384 the number of characters that replace previous buffer contents.
3386 This function does code conversion according to the value of
3387 `coding-system-for-read' or `file-coding-system-alist', and sets the
3388 variable `last-coding-system-used' to the coding system actually used.
3390 In addition, this function decodes the inserted text from known formats
3391 by calling `format-decode', which see. */)
3392 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3394 struct stat st;
3395 struct timespec mtime;
3396 int fd;
3397 ptrdiff_t inserted = 0;
3398 ptrdiff_t how_much;
3399 off_t beg_offset, end_offset;
3400 int unprocessed;
3401 ptrdiff_t count = SPECPDL_INDEX ();
3402 Lisp_Object handler, val, insval, orig_filename, old_undo;
3403 Lisp_Object p;
3404 ptrdiff_t total = 0;
3405 bool not_regular = 0;
3406 int save_errno = 0;
3407 char read_buf[READ_BUF_SIZE];
3408 struct coding_system coding;
3409 bool replace_handled = false;
3410 bool set_coding_system = false;
3411 Lisp_Object coding_system;
3412 bool read_quit = false;
3413 /* If the undo log only contains the insertion, there's no point
3414 keeping it. It's typically when we first fill a file-buffer. */
3415 bool empty_undo_list_p
3416 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3417 && BEG == Z);
3418 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3419 bool we_locked_file = false;
3420 ptrdiff_t fd_index;
3421 Lisp_Object window_markers = Qnil;
3422 /* same_at_start and same_at_end count bytes, because file access counts
3423 bytes and BEG and END count bytes. */
3424 ptrdiff_t same_at_start = BEGV_BYTE;
3425 ptrdiff_t same_at_end = ZV_BYTE;
3426 /* SAME_AT_END_CHARPOS counts characters, because
3427 restore_window_points needs the old character count. */
3428 ptrdiff_t same_at_end_charpos = ZV;
3430 if (current_buffer->base_buffer && ! NILP (visit))
3431 error ("Cannot do file visiting in an indirect buffer");
3433 if (!NILP (BVAR (current_buffer, read_only)))
3434 Fbarf_if_buffer_read_only (Qnil);
3436 val = Qnil;
3437 p = Qnil;
3438 orig_filename = Qnil;
3439 old_undo = Qnil;
3441 CHECK_STRING (filename);
3442 filename = Fexpand_file_name (filename, Qnil);
3444 /* The value Qnil means that the coding system is not yet
3445 decided. */
3446 coding_system = Qnil;
3448 /* If the file name has special constructs in it,
3449 call the corresponding file handler. */
3450 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3451 if (!NILP (handler))
3453 val = call6 (handler, Qinsert_file_contents, filename,
3454 visit, beg, end, replace);
3455 if (CONSP (val) && CONSP (XCDR (val))
3456 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3457 inserted = XINT (XCAR (XCDR (val)));
3458 goto handled;
3461 orig_filename = filename;
3462 filename = ENCODE_FILE (filename);
3464 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3465 if (fd < 0)
3467 save_errno = errno;
3468 if (NILP (visit))
3469 report_file_error ("Opening input file", orig_filename);
3470 mtime = time_error_value (save_errno);
3471 st.st_size = -1;
3472 if (!NILP (Vcoding_system_for_read))
3474 /* Don't let invalid values into buffer-file-coding-system. */
3475 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3476 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3478 goto notfound;
3481 fd_index = SPECPDL_INDEX ();
3482 record_unwind_protect_int (close_file_unwind, fd);
3484 /* Replacement should preserve point as it preserves markers. */
3485 if (!NILP (replace))
3487 window_markers = get_window_points_and_markers ();
3488 record_unwind_protect (restore_point_unwind,
3489 XCAR (XCAR (window_markers)));
3492 if (fstat (fd, &st) != 0)
3493 report_file_error ("Input file status", orig_filename);
3494 mtime = get_stat_mtime (&st);
3496 /* This code will need to be changed in order to work on named
3497 pipes, and it's probably just not worth it. So we should at
3498 least signal an error. */
3499 if (!S_ISREG (st.st_mode))
3501 not_regular = 1;
3503 if (! NILP (visit))
3504 goto notfound;
3506 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3507 xsignal2 (Qfile_error,
3508 build_string ("not a regular file"), orig_filename);
3511 if (!NILP (visit))
3513 if (!NILP (beg) || !NILP (end))
3514 error ("Attempt to visit less than an entire file");
3515 if (BEG < Z && NILP (replace))
3516 error ("Cannot do file visiting in a non-empty buffer");
3519 if (!NILP (beg))
3520 beg_offset = file_offset (beg);
3521 else
3522 beg_offset = 0;
3524 if (!NILP (end))
3525 end_offset = file_offset (end);
3526 else
3528 if (not_regular)
3529 end_offset = TYPE_MAXIMUM (off_t);
3530 else
3532 end_offset = st.st_size;
3534 /* A negative size can happen on a platform that allows file
3535 sizes greater than the maximum off_t value. */
3536 if (end_offset < 0)
3537 buffer_overflow ();
3539 /* The file size returned from stat may be zero, but data
3540 may be readable nonetheless, for example when this is a
3541 file in the /proc filesystem. */
3542 if (end_offset == 0)
3543 end_offset = READ_BUF_SIZE;
3547 /* Check now whether the buffer will become too large,
3548 in the likely case where the file's length is not changing.
3549 This saves a lot of needless work before a buffer overflow. */
3550 if (! not_regular)
3552 /* The likely offset where we will stop reading. We could read
3553 more (or less), if the file grows (or shrinks) as we read it. */
3554 off_t likely_end = min (end_offset, st.st_size);
3556 if (beg_offset < likely_end)
3558 ptrdiff_t buf_bytes
3559 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3560 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3561 off_t likely_growth = likely_end - beg_offset;
3562 if (buf_growth_max < likely_growth)
3563 buffer_overflow ();
3567 /* Prevent redisplay optimizations. */
3568 current_buffer->clip_changed = true;
3570 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3572 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3573 setup_coding_system (coding_system, &coding);
3574 /* Ensure we set Vlast_coding_system_used. */
3575 set_coding_system = true;
3577 else if (BEG < Z)
3579 /* Decide the coding system to use for reading the file now
3580 because we can't use an optimized method for handling
3581 `coding:' tag if the current buffer is not empty. */
3582 if (!NILP (Vcoding_system_for_read))
3583 coding_system = Vcoding_system_for_read;
3584 else
3586 /* Don't try looking inside a file for a coding system
3587 specification if it is not seekable. */
3588 if (! not_regular && ! NILP (Vset_auto_coding_function))
3590 /* Find a coding system specified in the heading two
3591 lines or in the tailing several lines of the file.
3592 We assume that the 1K-byte and 3K-byte for heading
3593 and tailing respectively are sufficient for this
3594 purpose. */
3595 int nread;
3597 if (st.st_size <= (1024 * 4))
3598 nread = emacs_read (fd, read_buf, 1024 * 4);
3599 else
3601 nread = emacs_read (fd, read_buf, 1024);
3602 if (nread == 1024)
3604 int ntail;
3605 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3606 report_file_error ("Setting file position",
3607 orig_filename);
3608 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3609 nread = ntail < 0 ? ntail : nread + ntail;
3613 if (nread < 0)
3614 report_file_error ("Read error", orig_filename);
3615 else if (nread > 0)
3617 AUTO_STRING (name, " *code-converting-work*");
3618 struct buffer *prev = current_buffer;
3619 Lisp_Object workbuf;
3620 struct buffer *buf;
3622 record_unwind_current_buffer ();
3624 workbuf = Fget_buffer_create (name);
3625 buf = XBUFFER (workbuf);
3627 delete_all_overlays (buf);
3628 bset_directory (buf, BVAR (current_buffer, directory));
3629 bset_read_only (buf, Qnil);
3630 bset_filename (buf, Qnil);
3631 bset_undo_list (buf, Qt);
3632 eassert (buf->overlays_before == NULL);
3633 eassert (buf->overlays_after == NULL);
3635 set_buffer_internal (buf);
3636 Ferase_buffer ();
3637 bset_enable_multibyte_characters (buf, Qnil);
3639 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3640 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3641 coding_system = call2 (Vset_auto_coding_function,
3642 filename, make_number (nread));
3643 set_buffer_internal (prev);
3645 /* Discard the unwind protect for recovering the
3646 current buffer. */
3647 specpdl_ptr--;
3649 /* Rewind the file for the actual read done later. */
3650 if (lseek (fd, 0, SEEK_SET) < 0)
3651 report_file_error ("Setting file position", orig_filename);
3655 if (NILP (coding_system))
3657 /* If we have not yet decided a coding system, check
3658 file-coding-system-alist. */
3659 coding_system = CALLN (Ffind_operation_coding_system,
3660 Qinsert_file_contents, orig_filename,
3661 visit, beg, end, replace);
3662 if (CONSP (coding_system))
3663 coding_system = XCAR (coding_system);
3667 if (NILP (coding_system))
3668 coding_system = Qundecided;
3669 else
3670 CHECK_CODING_SYSTEM (coding_system);
3672 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3673 /* We must suppress all character code conversion except for
3674 end-of-line conversion. */
3675 coding_system = raw_text_coding_system (coding_system);
3677 setup_coding_system (coding_system, &coding);
3678 /* Ensure we set Vlast_coding_system_used. */
3679 set_coding_system = true;
3682 /* If requested, replace the accessible part of the buffer
3683 with the file contents. Avoid replacing text at the
3684 beginning or end of the buffer that matches the file contents;
3685 that preserves markers pointing to the unchanged parts.
3687 Here we implement this feature in an optimized way
3688 for the case where code conversion is NOT needed.
3689 The following if-statement handles the case of conversion
3690 in a less optimal way.
3692 If the code conversion is "automatic" then we try using this
3693 method and hope for the best.
3694 But if we discover the need for conversion, we give up on this method
3695 and let the following if-statement handle the replace job. */
3696 if (!NILP (replace)
3697 && BEGV < ZV
3698 && (NILP (coding_system)
3699 || ! CODING_REQUIRE_DECODING (&coding)))
3701 ptrdiff_t overlap;
3702 /* There is still a possibility we will find the need to do code
3703 conversion. If that happens, set this variable to
3704 give up on handling REPLACE in the optimized way. */
3705 bool giveup_match_end = false;
3707 if (beg_offset != 0)
3709 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3710 report_file_error ("Setting file position", orig_filename);
3713 immediate_quit = 1;
3714 QUIT;
3715 /* Count how many chars at the start of the file
3716 match the text at the beginning of the buffer. */
3717 while (1)
3719 int nread, bufpos;
3721 nread = emacs_read (fd, read_buf, sizeof read_buf);
3722 if (nread < 0)
3723 report_file_error ("Read error", orig_filename);
3724 else if (nread == 0)
3725 break;
3727 if (CODING_REQUIRE_DETECTION (&coding))
3729 coding_system = detect_coding_system ((unsigned char *) read_buf,
3730 nread, nread, 1, 0,
3731 coding_system);
3732 setup_coding_system (coding_system, &coding);
3735 if (CODING_REQUIRE_DECODING (&coding))
3736 /* We found that the file should be decoded somehow.
3737 Let's give up here. */
3739 giveup_match_end = true;
3740 break;
3743 bufpos = 0;
3744 while (bufpos < nread && same_at_start < ZV_BYTE
3745 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3746 same_at_start++, bufpos++;
3747 /* If we found a discrepancy, stop the scan.
3748 Otherwise loop around and scan the next bufferful. */
3749 if (bufpos != nread)
3750 break;
3752 immediate_quit = false;
3753 /* If the file matches the buffer completely,
3754 there's no need to replace anything. */
3755 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3757 emacs_close (fd);
3758 clear_unwind_protect (fd_index);
3760 /* Truncate the buffer to the size of the file. */
3761 del_range_1 (same_at_start, same_at_end, 0, 0);
3762 goto handled;
3764 immediate_quit = true;
3765 QUIT;
3766 /* Count how many chars at the end of the file
3767 match the text at the end of the buffer. But, if we have
3768 already found that decoding is necessary, don't waste time. */
3769 while (!giveup_match_end)
3771 int total_read, nread, bufpos, trial;
3772 off_t curpos;
3774 /* At what file position are we now scanning? */
3775 curpos = end_offset - (ZV_BYTE - same_at_end);
3776 /* If the entire file matches the buffer tail, stop the scan. */
3777 if (curpos == 0)
3778 break;
3779 /* How much can we scan in the next step? */
3780 trial = min (curpos, sizeof read_buf);
3781 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3782 report_file_error ("Setting file position", orig_filename);
3784 total_read = nread = 0;
3785 while (total_read < trial)
3787 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3788 if (nread < 0)
3789 report_file_error ("Read error", orig_filename);
3790 else if (nread == 0)
3791 break;
3792 total_read += nread;
3795 /* Scan this bufferful from the end, comparing with
3796 the Emacs buffer. */
3797 bufpos = total_read;
3799 /* Compare with same_at_start to avoid counting some buffer text
3800 as matching both at the file's beginning and at the end. */
3801 while (bufpos > 0 && same_at_end > same_at_start
3802 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3803 same_at_end--, bufpos--;
3805 /* If we found a discrepancy, stop the scan.
3806 Otherwise loop around and scan the preceding bufferful. */
3807 if (bufpos != 0)
3809 /* If this discrepancy is because of code conversion,
3810 we cannot use this method; giveup and try the other. */
3811 if (same_at_end > same_at_start
3812 && FETCH_BYTE (same_at_end - 1) >= 0200
3813 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3814 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3815 giveup_match_end = true;
3816 break;
3819 if (nread == 0)
3820 break;
3822 immediate_quit = 0;
3824 if (! giveup_match_end)
3826 ptrdiff_t temp;
3828 /* We win! We can handle REPLACE the optimized way. */
3830 /* Extend the start of non-matching text area to multibyte
3831 character boundary. */
3832 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3833 while (same_at_start > BEGV_BYTE
3834 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3835 same_at_start--;
3837 /* Extend the end of non-matching text area to multibyte
3838 character boundary. */
3839 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3840 while (same_at_end < ZV_BYTE
3841 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3842 same_at_end++;
3844 /* Don't try to reuse the same piece of text twice. */
3845 overlap = (same_at_start - BEGV_BYTE
3846 - (same_at_end
3847 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3848 if (overlap > 0)
3849 same_at_end += overlap;
3850 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3852 /* Arrange to read only the nonmatching middle part of the file. */
3853 beg_offset += same_at_start - BEGV_BYTE;
3854 end_offset -= ZV_BYTE - same_at_end;
3856 invalidate_buffer_caches (current_buffer,
3857 BYTE_TO_CHAR (same_at_start),
3858 same_at_end_charpos);
3859 del_range_byte (same_at_start, same_at_end, 0);
3860 /* Insert from the file at the proper position. */
3861 temp = BYTE_TO_CHAR (same_at_start);
3862 SET_PT_BOTH (temp, same_at_start);
3864 /* If display currently starts at beginning of line,
3865 keep it that way. */
3866 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3867 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3869 replace_handled = true;
3873 /* If requested, replace the accessible part of the buffer
3874 with the file contents. Avoid replacing text at the
3875 beginning or end of the buffer that matches the file contents;
3876 that preserves markers pointing to the unchanged parts.
3878 Here we implement this feature for the case where code conversion
3879 is needed, in a simple way that needs a lot of memory.
3880 The preceding if-statement handles the case of no conversion
3881 in a more optimized way. */
3882 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3884 ptrdiff_t same_at_start_charpos;
3885 ptrdiff_t inserted_chars;
3886 ptrdiff_t overlap;
3887 ptrdiff_t bufpos;
3888 unsigned char *decoded;
3889 ptrdiff_t temp;
3890 ptrdiff_t this = 0;
3891 ptrdiff_t this_count = SPECPDL_INDEX ();
3892 bool multibyte
3893 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3894 Lisp_Object conversion_buffer;
3896 conversion_buffer = code_conversion_save (1, multibyte);
3898 /* First read the whole file, performing code conversion into
3899 CONVERSION_BUFFER. */
3901 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3902 report_file_error ("Setting file position", orig_filename);
3904 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3905 unprocessed = 0; /* Bytes not processed in previous loop. */
3907 while (1)
3909 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3910 quitting while reading a huge file. */
3912 /* Allow quitting out of the actual I/O. */
3913 immediate_quit = 1;
3914 QUIT;
3915 this = emacs_read (fd, read_buf + unprocessed,
3916 READ_BUF_SIZE - unprocessed);
3917 immediate_quit = 0;
3919 if (this <= 0)
3920 break;
3922 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3923 BUF_Z (XBUFFER (conversion_buffer)));
3924 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3925 unprocessed + this, conversion_buffer);
3926 unprocessed = coding.carryover_bytes;
3927 if (coding.carryover_bytes > 0)
3928 memcpy (read_buf, coding.carryover, unprocessed);
3931 if (this < 0)
3932 report_file_error ("Read error", orig_filename);
3933 emacs_close (fd);
3934 clear_unwind_protect (fd_index);
3936 if (unprocessed > 0)
3938 coding.mode |= CODING_MODE_LAST_BLOCK;
3939 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3940 unprocessed, conversion_buffer);
3941 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3944 coding_system = CODING_ID_NAME (coding.id);
3945 set_coding_system = true;
3946 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3947 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3948 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3950 /* Compare the beginning of the converted string with the buffer
3951 text. */
3953 bufpos = 0;
3954 while (bufpos < inserted && same_at_start < same_at_end
3955 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3956 same_at_start++, bufpos++;
3958 /* If the file matches the head of buffer completely,
3959 there's no need to replace anything. */
3961 if (bufpos == inserted)
3963 /* Truncate the buffer to the size of the file. */
3964 if (same_at_start != same_at_end)
3966 invalidate_buffer_caches (current_buffer,
3967 BYTE_TO_CHAR (same_at_start),
3968 BYTE_TO_CHAR (same_at_end));
3969 del_range_byte (same_at_start, same_at_end, 0);
3971 inserted = 0;
3973 unbind_to (this_count, Qnil);
3974 goto handled;
3977 /* Extend the start of non-matching text area to the previous
3978 multibyte character boundary. */
3979 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3980 while (same_at_start > BEGV_BYTE
3981 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3982 same_at_start--;
3984 /* Scan this bufferful from the end, comparing with
3985 the Emacs buffer. */
3986 bufpos = inserted;
3988 /* Compare with same_at_start to avoid counting some buffer text
3989 as matching both at the file's beginning and at the end. */
3990 while (bufpos > 0 && same_at_end > same_at_start
3991 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3992 same_at_end--, bufpos--;
3994 /* Extend the end of non-matching text area to the next
3995 multibyte character boundary. */
3996 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3997 while (same_at_end < ZV_BYTE
3998 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3999 same_at_end++;
4001 /* Don't try to reuse the same piece of text twice. */
4002 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4003 if (overlap > 0)
4004 same_at_end += overlap;
4005 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4007 /* If display currently starts at beginning of line,
4008 keep it that way. */
4009 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4010 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4012 /* Replace the chars that we need to replace,
4013 and update INSERTED to equal the number of bytes
4014 we are taking from the decoded string. */
4015 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4017 if (same_at_end != same_at_start)
4019 invalidate_buffer_caches (current_buffer,
4020 BYTE_TO_CHAR (same_at_start),
4021 same_at_end_charpos);
4022 del_range_byte (same_at_start, same_at_end, 0);
4023 temp = GPT;
4024 eassert (same_at_start == GPT_BYTE);
4025 same_at_start = GPT_BYTE;
4027 else
4029 temp = same_at_end_charpos;
4031 /* Insert from the file at the proper position. */
4032 SET_PT_BOTH (temp, same_at_start);
4033 same_at_start_charpos
4034 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4035 same_at_start - BEGV_BYTE
4036 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4037 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4038 inserted_chars
4039 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4040 same_at_start + inserted - BEGV_BYTE
4041 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4042 - same_at_start_charpos);
4043 /* This binding is to avoid ask-user-about-supersession-threat
4044 being called in insert_from_buffer (via in
4045 prepare_to_modify_buffer). */
4046 specbind (intern ("buffer-file-name"), Qnil);
4047 insert_from_buffer (XBUFFER (conversion_buffer),
4048 same_at_start_charpos, inserted_chars, 0);
4049 /* Set `inserted' to the number of inserted characters. */
4050 inserted = PT - temp;
4051 /* Set point before the inserted characters. */
4052 SET_PT_BOTH (temp, same_at_start);
4054 unbind_to (this_count, Qnil);
4056 goto handled;
4059 if (! not_regular)
4060 total = end_offset - beg_offset;
4061 else
4062 /* For a special file, all we can do is guess. */
4063 total = READ_BUF_SIZE;
4065 if (NILP (visit) && total > 0)
4067 if (!NILP (BVAR (current_buffer, file_truename))
4068 /* Make binding buffer-file-name to nil effective. */
4069 && !NILP (BVAR (current_buffer, filename))
4070 && SAVE_MODIFF >= MODIFF)
4071 we_locked_file = true;
4072 prepare_to_modify_buffer (PT, PT, NULL);
4075 move_gap_both (PT, PT_BYTE);
4076 if (GAP_SIZE < total)
4077 make_gap (total - GAP_SIZE);
4079 if (beg_offset != 0 || !NILP (replace))
4081 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4082 report_file_error ("Setting file position", orig_filename);
4085 /* In the following loop, HOW_MUCH contains the total bytes read so
4086 far for a regular file, and not changed for a special file. But,
4087 before exiting the loop, it is set to a negative value if I/O
4088 error occurs. */
4089 how_much = 0;
4091 /* Total bytes inserted. */
4092 inserted = 0;
4094 /* Here, we don't do code conversion in the loop. It is done by
4095 decode_coding_gap after all data are read into the buffer. */
4097 ptrdiff_t gap_size = GAP_SIZE;
4099 while (how_much < total)
4101 /* `try' is reserved in some compilers (Microsoft C). */
4102 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4103 ptrdiff_t this;
4105 if (not_regular)
4107 Lisp_Object nbytes;
4109 /* Maybe make more room. */
4110 if (gap_size < trytry)
4112 make_gap (trytry - gap_size);
4113 gap_size = GAP_SIZE - inserted;
4116 /* Read from the file, capturing `quit'. When an
4117 error occurs, end the loop, and arrange for a quit
4118 to be signaled after decoding the text we read. */
4119 nbytes = internal_condition_case_1
4120 (read_non_regular,
4121 make_save_int_int_int (fd, inserted, trytry),
4122 Qerror, read_non_regular_quit);
4124 if (NILP (nbytes))
4126 read_quit = true;
4127 break;
4130 this = XINT (nbytes);
4132 else
4134 /* Allow quitting out of the actual I/O. We don't make text
4135 part of the buffer until all the reading is done, so a C-g
4136 here doesn't do any harm. */
4137 immediate_quit = 1;
4138 QUIT;
4139 this = emacs_read (fd,
4140 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4141 + inserted),
4142 trytry);
4143 immediate_quit = 0;
4146 if (this <= 0)
4148 how_much = this;
4149 break;
4152 gap_size -= this;
4154 /* For a regular file, where TOTAL is the real size,
4155 count HOW_MUCH to compare with it.
4156 For a special file, where TOTAL is just a buffer size,
4157 so don't bother counting in HOW_MUCH.
4158 (INSERTED is where we count the number of characters inserted.) */
4159 if (! not_regular)
4160 how_much += this;
4161 inserted += this;
4165 /* Now we have either read all the file data into the gap,
4166 or stop reading on I/O error or quit. If nothing was
4167 read, undo marking the buffer modified. */
4169 if (inserted == 0)
4171 if (we_locked_file)
4172 unlock_file (BVAR (current_buffer, file_truename));
4173 Vdeactivate_mark = old_Vdeactivate_mark;
4175 else
4176 Fset (Qdeactivate_mark, Qt);
4178 emacs_close (fd);
4179 clear_unwind_protect (fd_index);
4181 if (how_much < 0)
4182 report_file_error ("Read error", orig_filename);
4184 /* Make the text read part of the buffer. */
4185 GAP_SIZE -= inserted;
4186 GPT += inserted;
4187 GPT_BYTE += inserted;
4188 ZV += inserted;
4189 ZV_BYTE += inserted;
4190 Z += inserted;
4191 Z_BYTE += inserted;
4193 if (GAP_SIZE > 0)
4194 /* Put an anchor to ensure multi-byte form ends at gap. */
4195 *GPT_ADDR = 0;
4197 notfound:
4199 if (NILP (coding_system))
4201 /* The coding system is not yet decided. Decide it by an
4202 optimized method for handling `coding:' tag.
4204 Note that we can get here only if the buffer was empty
4205 before the insertion. */
4207 if (!NILP (Vcoding_system_for_read))
4208 coding_system = Vcoding_system_for_read;
4209 else
4211 /* Since we are sure that the current buffer was empty
4212 before the insertion, we can toggle
4213 enable-multibyte-characters directly here without taking
4214 care of marker adjustment. By this way, we can run Lisp
4215 program safely before decoding the inserted text. */
4216 Lisp_Object unwind_data;
4217 ptrdiff_t count1 = SPECPDL_INDEX ();
4219 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4220 Fcons (BVAR (current_buffer, undo_list),
4221 Fcurrent_buffer ()));
4222 bset_enable_multibyte_characters (current_buffer, Qnil);
4223 bset_undo_list (current_buffer, Qt);
4224 record_unwind_protect (decide_coding_unwind, unwind_data);
4226 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4228 coding_system = call2 (Vset_auto_coding_function,
4229 filename, make_number (inserted));
4232 if (NILP (coding_system))
4234 /* If the coding system is not yet decided, check
4235 file-coding-system-alist. */
4236 coding_system = CALLN (Ffind_operation_coding_system,
4237 Qinsert_file_contents, orig_filename,
4238 visit, beg, end, Qnil);
4239 if (CONSP (coding_system))
4240 coding_system = XCAR (coding_system);
4242 unbind_to (count1, Qnil);
4243 inserted = Z_BYTE - BEG_BYTE;
4246 if (NILP (coding_system))
4247 coding_system = Qundecided;
4248 else
4249 CHECK_CODING_SYSTEM (coding_system);
4251 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4252 /* We must suppress all character code conversion except for
4253 end-of-line conversion. */
4254 coding_system = raw_text_coding_system (coding_system);
4255 setup_coding_system (coding_system, &coding);
4256 /* Ensure we set Vlast_coding_system_used. */
4257 set_coding_system = true;
4260 if (!NILP (visit))
4262 /* When we visit a file by raw-text, we change the buffer to
4263 unibyte. */
4264 if (CODING_FOR_UNIBYTE (&coding)
4265 /* Can't do this if part of the buffer might be preserved. */
4266 && NILP (replace))
4267 /* Visiting a file with these coding system makes the buffer
4268 unibyte. */
4269 bset_enable_multibyte_characters (current_buffer, Qnil);
4272 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4273 if (CODING_MAY_REQUIRE_DECODING (&coding)
4274 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4276 move_gap_both (PT, PT_BYTE);
4277 GAP_SIZE += inserted;
4278 ZV_BYTE -= inserted;
4279 Z_BYTE -= inserted;
4280 ZV -= inserted;
4281 Z -= inserted;
4282 decode_coding_gap (&coding, inserted, inserted);
4283 inserted = coding.produced_char;
4284 coding_system = CODING_ID_NAME (coding.id);
4286 else if (inserted > 0)
4288 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4289 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4290 inserted);
4293 /* Call after-change hooks for the inserted text, aside from the case
4294 of normal visiting (not with REPLACE), which is done in a new buffer
4295 "before" the buffer is changed. */
4296 if (inserted > 0 && total > 0
4297 && (NILP (visit) || !NILP (replace)))
4299 signal_after_change (PT, 0, inserted);
4300 update_compositions (PT, PT, CHECK_BORDER);
4303 /* Now INSERTED is measured in characters. */
4305 handled:
4307 if (inserted > 0)
4308 restore_window_points (window_markers, inserted,
4309 BYTE_TO_CHAR (same_at_start),
4310 same_at_end_charpos);
4312 if (!NILP (visit))
4314 if (empty_undo_list_p)
4315 bset_undo_list (current_buffer, Qnil);
4317 if (NILP (handler))
4319 current_buffer->modtime = mtime;
4320 current_buffer->modtime_size = st.st_size;
4321 bset_filename (current_buffer, orig_filename);
4324 SAVE_MODIFF = MODIFF;
4325 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4326 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4327 if (NILP (handler))
4329 if (!NILP (BVAR (current_buffer, file_truename)))
4330 unlock_file (BVAR (current_buffer, file_truename));
4331 unlock_file (filename);
4333 if (not_regular)
4334 xsignal2 (Qfile_error,
4335 build_string ("not a regular file"), orig_filename);
4338 if (set_coding_system)
4339 Vlast_coding_system_used = coding_system;
4341 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4343 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4344 visit);
4345 if (! NILP (insval))
4347 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4348 wrong_type_argument (intern ("inserted-chars"), insval);
4349 inserted = XFASTINT (insval);
4353 /* Decode file format. */
4354 if (inserted > 0)
4356 /* Don't run point motion or modification hooks when decoding. */
4357 ptrdiff_t count1 = SPECPDL_INDEX ();
4358 ptrdiff_t old_inserted = inserted;
4359 specbind (Qinhibit_point_motion_hooks, Qt);
4360 specbind (Qinhibit_modification_hooks, Qt);
4362 /* Save old undo list and don't record undo for decoding. */
4363 old_undo = BVAR (current_buffer, undo_list);
4364 bset_undo_list (current_buffer, Qt);
4366 if (NILP (replace))
4368 insval = call3 (Qformat_decode,
4369 Qnil, make_number (inserted), visit);
4370 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4371 wrong_type_argument (intern ("inserted-chars"), insval);
4372 inserted = XFASTINT (insval);
4374 else
4376 /* If REPLACE is non-nil and we succeeded in not replacing the
4377 beginning or end of the buffer text with the file's contents,
4378 call format-decode with `point' positioned at the beginning
4379 of the buffer and `inserted' equaling the number of
4380 characters in the buffer. Otherwise, format-decode might
4381 fail to correctly analyze the beginning or end of the buffer.
4382 Hence we temporarily save `point' and `inserted' here and
4383 restore `point' iff format-decode did not insert or delete
4384 any text. Otherwise we leave `point' at point-min. */
4385 ptrdiff_t opoint = PT;
4386 ptrdiff_t opoint_byte = PT_BYTE;
4387 ptrdiff_t oinserted = ZV - BEGV;
4388 EMACS_INT ochars_modiff = CHARS_MODIFF;
4390 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4391 insval = call3 (Qformat_decode,
4392 Qnil, make_number (oinserted), visit);
4393 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4394 wrong_type_argument (intern ("inserted-chars"), insval);
4395 if (ochars_modiff == CHARS_MODIFF)
4396 /* format_decode didn't modify buffer's characters => move
4397 point back to position before inserted text and leave
4398 value of inserted alone. */
4399 SET_PT_BOTH (opoint, opoint_byte);
4400 else
4401 /* format_decode modified buffer's characters => consider
4402 entire buffer changed and leave point at point-min. */
4403 inserted = XFASTINT (insval);
4406 /* For consistency with format-decode call these now iff inserted > 0
4407 (martin 2007-06-28). */
4408 p = Vafter_insert_file_functions;
4409 while (CONSP (p))
4411 if (NILP (replace))
4413 insval = call1 (XCAR (p), make_number (inserted));
4414 if (!NILP (insval))
4416 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4417 wrong_type_argument (intern ("inserted-chars"), insval);
4418 inserted = XFASTINT (insval);
4421 else
4423 /* For the rationale of this see the comment on
4424 format-decode above. */
4425 ptrdiff_t opoint = PT;
4426 ptrdiff_t opoint_byte = PT_BYTE;
4427 ptrdiff_t oinserted = ZV - BEGV;
4428 EMACS_INT ochars_modiff = CHARS_MODIFF;
4430 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4431 insval = call1 (XCAR (p), make_number (oinserted));
4432 if (!NILP (insval))
4434 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4435 wrong_type_argument (intern ("inserted-chars"), insval);
4436 if (ochars_modiff == CHARS_MODIFF)
4437 /* after_insert_file_functions didn't modify
4438 buffer's characters => move point back to
4439 position before inserted text and leave value of
4440 inserted alone. */
4441 SET_PT_BOTH (opoint, opoint_byte);
4442 else
4443 /* after_insert_file_functions did modify buffer's
4444 characters => consider entire buffer changed and
4445 leave point at point-min. */
4446 inserted = XFASTINT (insval);
4450 QUIT;
4451 p = XCDR (p);
4454 if (!empty_undo_list_p)
4456 bset_undo_list (current_buffer, old_undo);
4457 if (CONSP (old_undo) && inserted != old_inserted)
4459 /* Adjust the last undo record for the size change during
4460 the format conversion. */
4461 Lisp_Object tem = XCAR (old_undo);
4462 if (CONSP (tem) && INTEGERP (XCAR (tem))
4463 && INTEGERP (XCDR (tem))
4464 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4465 XSETCDR (tem, make_number (PT + inserted));
4468 else
4469 /* If undo_list was Qt before, keep it that way.
4470 Otherwise start with an empty undo_list. */
4471 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4473 unbind_to (count1, Qnil);
4476 if (!NILP (visit)
4477 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4479 /* If visiting nonexistent file, return nil. */
4480 report_file_errno ("Opening input file", orig_filename, save_errno);
4483 /* We made a lot of deletions and insertions above, so invalidate
4484 the newline cache for the entire region of the inserted
4485 characters. */
4486 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4487 invalidate_region_cache (current_buffer->base_buffer,
4488 current_buffer->base_buffer->newline_cache,
4489 PT - BEG, Z - PT - inserted);
4490 else if (current_buffer->newline_cache)
4491 invalidate_region_cache (current_buffer,
4492 current_buffer->newline_cache,
4493 PT - BEG, Z - PT - inserted);
4495 if (read_quit)
4496 Fsignal (Qquit, Qnil);
4498 /* Retval needs to be dealt with in all cases consistently. */
4499 if (NILP (val))
4500 val = list2 (orig_filename, make_number (inserted));
4502 return unbind_to (count, val);
4505 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4507 static void
4508 build_annotations_unwind (Lisp_Object arg)
4510 Vwrite_region_annotation_buffers = arg;
4513 /* Decide the coding-system to encode the data with. */
4515 static Lisp_Object
4516 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4517 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4518 struct coding_system *coding)
4520 Lisp_Object val;
4521 Lisp_Object eol_parent = Qnil;
4523 if (auto_saving
4524 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4525 BVAR (current_buffer, auto_save_file_name))))
4527 val = Qutf_8_emacs;
4528 eol_parent = Qunix;
4530 else if (!NILP (Vcoding_system_for_write))
4532 val = Vcoding_system_for_write;
4533 if (coding_system_require_warning
4534 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4535 /* Confirm that VAL can surely encode the current region. */
4536 val = call5 (Vselect_safe_coding_system_function,
4537 start, end, list2 (Qt, val),
4538 Qnil, filename);
4540 else
4542 /* If the variable `buffer-file-coding-system' is set locally,
4543 it means that the file was read with some kind of code
4544 conversion or the variable is explicitly set by users. We
4545 had better write it out with the same coding system even if
4546 `enable-multibyte-characters' is nil.
4548 If it is not set locally, we anyway have to convert EOL
4549 format if the default value of `buffer-file-coding-system'
4550 tells that it is not Unix-like (LF only) format. */
4551 bool using_default_coding = 0;
4552 bool force_raw_text = 0;
4554 val = BVAR (current_buffer, buffer_file_coding_system);
4555 if (NILP (val)
4556 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4558 val = Qnil;
4559 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4560 force_raw_text = 1;
4563 if (NILP (val))
4565 /* Check file-coding-system-alist. */
4566 Lisp_Object coding_systems
4567 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4568 filename, append, visit, lockname);
4569 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4570 val = XCDR (coding_systems);
4573 if (NILP (val))
4575 /* If we still have not decided a coding system, use the
4576 current buffer's value of buffer-file-coding-system. */
4577 val = BVAR (current_buffer, buffer_file_coding_system);
4578 using_default_coding = 1;
4581 if (! NILP (val) && ! force_raw_text)
4583 Lisp_Object spec, attrs;
4585 CHECK_CODING_SYSTEM (val);
4586 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4587 attrs = AREF (spec, 0);
4588 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4589 force_raw_text = 1;
4592 if (!force_raw_text
4593 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4595 /* Confirm that VAL can surely encode the current region. */
4596 val = call5 (Vselect_safe_coding_system_function,
4597 start, end, val, Qnil, filename);
4598 /* As the function specified by select-safe-coding-system-function
4599 is out of our control, make sure we are not fed by bogus
4600 values. */
4601 if (!NILP (val))
4602 CHECK_CODING_SYSTEM (val);
4605 /* If the decided coding-system doesn't specify end-of-line
4606 format, we use that of
4607 `default-buffer-file-coding-system'. */
4608 if (! using_default_coding)
4610 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4612 if (! NILP (dflt))
4613 val = coding_inherit_eol_type (val, dflt);
4616 /* If we decide not to encode text, use `raw-text' or one of its
4617 subsidiaries. */
4618 if (force_raw_text)
4619 val = raw_text_coding_system (val);
4622 val = coding_inherit_eol_type (val, eol_parent);
4623 setup_coding_system (val, coding);
4625 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4626 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4627 return val;
4630 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4631 "r\nFWrite region to file: \ni\ni\ni\np",
4632 doc: /* Write current region into specified file.
4633 When called from a program, requires three arguments:
4634 START, END and FILENAME. START and END are normally buffer positions
4635 specifying the part of the buffer to write.
4636 If START is nil, that means to use the entire buffer contents.
4637 If START is a string, then output that string to the file
4638 instead of any buffer contents; END is ignored.
4640 Optional fourth argument APPEND if non-nil means
4641 append to existing file contents (if any). If it is a number,
4642 seek to that offset in the file before writing.
4643 Optional fifth argument VISIT, if t or a string, means
4644 set the last-save-file-modtime of buffer to this file's modtime
4645 and mark buffer not modified.
4646 If VISIT is a string, it is a second file name;
4647 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4648 VISIT is also the file name to lock and unlock for clash detection.
4649 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4650 do not display the \"Wrote file\" message.
4651 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4652 use for locking and unlocking, overriding FILENAME and VISIT.
4653 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4654 for an existing file with the same name. If MUSTBENEW is `excl',
4655 that means to get an error if the file already exists; never overwrite.
4656 If MUSTBENEW is neither nil nor `excl', that means ask for
4657 confirmation before overwriting, but do go ahead and overwrite the file
4658 if the user confirms.
4660 This does code conversion according to the value of
4661 `coding-system-for-write', `buffer-file-coding-system', or
4662 `file-coding-system-alist', and sets the variable
4663 `last-coding-system-used' to the coding system actually used.
4665 This calls `write-region-annotate-functions' at the start, and
4666 `write-region-post-annotation-function' at the end. */)
4667 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4668 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4670 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4671 -1);
4674 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4675 descriptor for FILENAME, so do not open or close FILENAME. */
4677 Lisp_Object
4678 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4679 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4680 Lisp_Object mustbenew, int desc)
4682 int open_flags;
4683 int mode;
4684 off_t offset IF_LINT (= 0);
4685 bool open_and_close_file = desc < 0;
4686 bool ok;
4687 int save_errno = 0;
4688 const char *fn;
4689 struct stat st;
4690 struct timespec modtime;
4691 ptrdiff_t count = SPECPDL_INDEX ();
4692 ptrdiff_t count1 IF_LINT (= 0);
4693 Lisp_Object handler;
4694 Lisp_Object visit_file;
4695 Lisp_Object annotations;
4696 Lisp_Object encoded_filename;
4697 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4698 bool quietly = !NILP (visit);
4699 bool file_locked = 0;
4700 struct buffer *given_buffer;
4701 struct coding_system coding;
4703 if (current_buffer->base_buffer && visiting)
4704 error ("Cannot do file visiting in an indirect buffer");
4706 if (!NILP (start) && !STRINGP (start))
4707 validate_region (&start, &end);
4709 visit_file = Qnil;
4711 filename = Fexpand_file_name (filename, Qnil);
4713 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4714 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4716 if (STRINGP (visit))
4717 visit_file = Fexpand_file_name (visit, Qnil);
4718 else
4719 visit_file = filename;
4721 if (NILP (lockname))
4722 lockname = visit_file;
4724 annotations = Qnil;
4726 /* If the file name has special constructs in it,
4727 call the corresponding file handler. */
4728 handler = Ffind_file_name_handler (filename, Qwrite_region);
4729 /* If FILENAME has no handler, see if VISIT has one. */
4730 if (NILP (handler) && STRINGP (visit))
4731 handler = Ffind_file_name_handler (visit, Qwrite_region);
4733 if (!NILP (handler))
4735 Lisp_Object val;
4736 val = call6 (handler, Qwrite_region, start, end,
4737 filename, append, visit);
4739 if (visiting)
4741 SAVE_MODIFF = MODIFF;
4742 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4743 bset_filename (current_buffer, visit_file);
4746 return val;
4749 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4751 /* Special kludge to simplify auto-saving. */
4752 if (NILP (start))
4754 /* Do it later, so write-region-annotate-function can work differently
4755 if we save "the buffer" vs "a region".
4756 This is useful in tar-mode. --Stef
4757 XSETFASTINT (start, BEG);
4758 XSETFASTINT (end, Z); */
4759 Fwiden ();
4762 record_unwind_protect (build_annotations_unwind,
4763 Vwrite_region_annotation_buffers);
4764 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4766 given_buffer = current_buffer;
4768 if (!STRINGP (start))
4770 annotations = build_annotations (start, end);
4772 if (current_buffer != given_buffer)
4774 XSETFASTINT (start, BEGV);
4775 XSETFASTINT (end, ZV);
4779 if (NILP (start))
4781 XSETFASTINT (start, BEGV);
4782 XSETFASTINT (end, ZV);
4785 /* Decide the coding-system to encode the data with.
4786 We used to make this choice before calling build_annotations, but that
4787 leads to problems when a write-annotate-function takes care of
4788 unsavable chars (as was the case with X-Symbol). */
4789 Vlast_coding_system_used
4790 = choose_write_coding_system (start, end, filename,
4791 append, visit, lockname, &coding);
4793 if (open_and_close_file && !auto_saving)
4795 lock_file (lockname);
4796 file_locked = 1;
4799 encoded_filename = ENCODE_FILE (filename);
4800 fn = SSDATA (encoded_filename);
4801 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4802 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4803 if (NUMBERP (append))
4804 offset = file_offset (append);
4805 else if (!NILP (append))
4806 open_flags |= O_APPEND;
4807 #ifdef DOS_NT
4808 mode = S_IREAD | S_IWRITE;
4809 #else
4810 mode = auto_saving ? auto_save_mode_bits : 0666;
4811 #endif
4813 if (open_and_close_file)
4815 desc = emacs_open (fn, open_flags, mode);
4816 if (desc < 0)
4818 int open_errno = errno;
4819 if (file_locked)
4820 unlock_file (lockname);
4821 report_file_errno ("Opening output file", filename, open_errno);
4824 count1 = SPECPDL_INDEX ();
4825 record_unwind_protect_int (close_file_unwind, desc);
4828 if (NUMBERP (append))
4830 off_t ret = lseek (desc, offset, SEEK_SET);
4831 if (ret < 0)
4833 int lseek_errno = errno;
4834 if (file_locked)
4835 unlock_file (lockname);
4836 report_file_errno ("Lseek error", filename, lseek_errno);
4840 immediate_quit = 1;
4842 if (STRINGP (start))
4843 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4844 else if (XINT (start) != XINT (end))
4845 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4846 &annotations, &coding);
4847 else
4849 /* If file was empty, still need to write the annotations. */
4850 coding.mode |= CODING_MODE_LAST_BLOCK;
4851 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4853 save_errno = errno;
4855 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4856 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4858 /* We have to flush out a data. */
4859 coding.mode |= CODING_MODE_LAST_BLOCK;
4860 ok = e_write (desc, Qnil, 1, 1, &coding);
4861 save_errno = errno;
4864 immediate_quit = 0;
4866 /* fsync is not crucial for temporary files. Nor for auto-save
4867 files, since they might lose some work anyway. */
4868 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4870 /* Transfer data and metadata to disk, retrying if interrupted.
4871 fsync can report a write failure here, e.g., due to disk full
4872 under NFS. But ignore EINVAL, which means fsync is not
4873 supported on this file. */
4874 while (fsync (desc) != 0)
4875 if (errno != EINTR)
4877 if (errno != EINVAL)
4878 ok = 0, save_errno = errno;
4879 break;
4883 modtime = invalid_timespec ();
4884 if (visiting)
4886 if (fstat (desc, &st) == 0)
4887 modtime = get_stat_mtime (&st);
4888 else
4889 ok = 0, save_errno = errno;
4892 if (open_and_close_file)
4894 /* NFS can report a write failure now. */
4895 if (emacs_close (desc) < 0)
4896 ok = 0, save_errno = errno;
4898 /* Discard the unwind protect for close_file_unwind. */
4899 specpdl_ptr = specpdl + count1;
4902 /* Some file systems have a bug where st_mtime is not updated
4903 properly after a write. For example, CIFS might not see the
4904 st_mtime change until after the file is opened again.
4906 Attempt to detect this file system bug, and update MODTIME to the
4907 newer st_mtime if the bug appears to be present. This introduces
4908 a race condition, so to avoid most instances of the race condition
4909 on non-buggy file systems, skip this check if the most recently
4910 encountered non-buggy file system was the current file system.
4912 A race condition can occur if some other process modifies the
4913 file between the fstat above and the fstat below, but the race is
4914 unlikely and a similar race between the last write and the fstat
4915 above cannot possibly be closed anyway. */
4917 if (timespec_valid_p (modtime)
4918 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4920 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4921 if (desc1 >= 0)
4923 struct stat st1;
4924 if (fstat (desc1, &st1) == 0
4925 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4927 /* Use the heuristic if it appears to be valid. With neither
4928 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4929 file, the time stamp won't change. Also, some non-POSIX
4930 systems don't update an empty file's time stamp when
4931 truncating it. Finally, file systems with 100 ns or worse
4932 resolution sometimes seem to have bugs: on a system with ns
4933 resolution, checking ns % 100 incorrectly avoids the heuristic
4934 1% of the time, but the problem should be temporary as we will
4935 try again on the next time stamp. */
4936 bool use_heuristic
4937 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4938 && st.st_size != 0
4939 && modtime.tv_nsec % 100 != 0);
4941 struct timespec modtime1 = get_stat_mtime (&st1);
4942 if (use_heuristic
4943 && timespec_cmp (modtime, modtime1) == 0
4944 && st.st_size == st1.st_size)
4946 timestamp_file_system = st.st_dev;
4947 valid_timestamp_file_system = 1;
4949 else
4951 st.st_size = st1.st_size;
4952 modtime = modtime1;
4955 emacs_close (desc1);
4959 /* Call write-region-post-annotation-function. */
4960 while (CONSP (Vwrite_region_annotation_buffers))
4962 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4963 if (!NILP (Fbuffer_live_p (buf)))
4965 Fset_buffer (buf);
4966 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4967 call0 (Vwrite_region_post_annotation_function);
4969 Vwrite_region_annotation_buffers
4970 = XCDR (Vwrite_region_annotation_buffers);
4973 unbind_to (count, Qnil);
4975 if (file_locked)
4976 unlock_file (lockname);
4978 /* Do this before reporting IO error
4979 to avoid a "file has changed on disk" warning on
4980 next attempt to save. */
4981 if (timespec_valid_p (modtime))
4983 current_buffer->modtime = modtime;
4984 current_buffer->modtime_size = st.st_size;
4987 if (! ok)
4988 report_file_errno ("Write error", filename, save_errno);
4990 if (visiting)
4992 SAVE_MODIFF = MODIFF;
4993 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4994 bset_filename (current_buffer, visit_file);
4995 update_mode_lines = 14;
4997 else if (quietly)
4999 if (auto_saving
5000 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5001 BVAR (current_buffer, auto_save_file_name))))
5002 SAVE_MODIFF = MODIFF;
5004 return Qnil;
5007 if (!auto_saving && !noninteractive)
5008 message_with_string ((NUMBERP (append)
5009 ? "Updated %s"
5010 : ! NILP (append)
5011 ? "Added to %s"
5012 : "Wrote %s"),
5013 visit_file, 1);
5015 return Qnil;
5018 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5019 doc: /* Return t if (car A) is numerically less than (car B). */)
5020 (Lisp_Object a, Lisp_Object b)
5022 return CALLN (Flss, Fcar (a), Fcar (b));
5025 /* Build the complete list of annotations appropriate for writing out
5026 the text between START and END, by calling all the functions in
5027 write-region-annotate-functions and merging the lists they return.
5028 If one of these functions switches to a different buffer, we assume
5029 that buffer contains altered text. Therefore, the caller must
5030 make sure to restore the current buffer in all cases,
5031 as save-excursion would do. */
5033 static Lisp_Object
5034 build_annotations (Lisp_Object start, Lisp_Object end)
5036 Lisp_Object annotations;
5037 Lisp_Object p, res;
5038 Lisp_Object original_buffer;
5039 int i;
5040 bool used_global = false;
5042 XSETBUFFER (original_buffer, current_buffer);
5044 annotations = Qnil;
5045 p = Vwrite_region_annotate_functions;
5046 while (CONSP (p))
5048 struct buffer *given_buffer = current_buffer;
5049 if (EQ (Qt, XCAR (p)) && !used_global)
5050 { /* Use the global value of the hook. */
5051 used_global = true;
5052 p = CALLN (Fappend,
5053 Fdefault_value (Qwrite_region_annotate_functions),
5054 XCDR (p));
5055 continue;
5057 Vwrite_region_annotations_so_far = annotations;
5058 res = call2 (XCAR (p), start, end);
5059 /* If the function makes a different buffer current,
5060 assume that means this buffer contains altered text to be output.
5061 Reset START and END from the buffer bounds
5062 and discard all previous annotations because they should have
5063 been dealt with by this function. */
5064 if (current_buffer != given_buffer)
5066 Vwrite_region_annotation_buffers
5067 = Fcons (Fcurrent_buffer (),
5068 Vwrite_region_annotation_buffers);
5069 XSETFASTINT (start, BEGV);
5070 XSETFASTINT (end, ZV);
5071 annotations = Qnil;
5073 Flength (res); /* Check basic validity of return value */
5074 annotations = merge (annotations, res, Qcar_less_than_car);
5075 p = XCDR (p);
5078 /* Now do the same for annotation functions implied by the file-format */
5079 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5080 p = BVAR (current_buffer, auto_save_file_format);
5081 else
5082 p = BVAR (current_buffer, file_format);
5083 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5085 struct buffer *given_buffer = current_buffer;
5087 Vwrite_region_annotations_so_far = annotations;
5089 /* Value is either a list of annotations or nil if the function
5090 has written annotations to a temporary buffer, which is now
5091 current. */
5092 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5093 original_buffer, make_number (i));
5094 if (current_buffer != given_buffer)
5096 XSETFASTINT (start, BEGV);
5097 XSETFASTINT (end, ZV);
5098 annotations = Qnil;
5101 if (CONSP (res))
5102 annotations = merge (annotations, res, Qcar_less_than_car);
5105 return annotations;
5109 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5110 If STRING is nil, POS is the character position in the current buffer.
5111 Intersperse with them the annotations from *ANNOT
5112 which fall within the range of POS to POS + NCHARS,
5113 each at its appropriate position.
5115 We modify *ANNOT by discarding elements as we use them up.
5117 Return true if successful. */
5119 static bool
5120 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5121 ptrdiff_t nchars, Lisp_Object *annot,
5122 struct coding_system *coding)
5124 Lisp_Object tem;
5125 ptrdiff_t nextpos;
5126 ptrdiff_t lastpos = pos + nchars;
5128 while (NILP (*annot) || CONSP (*annot))
5130 tem = Fcar_safe (Fcar (*annot));
5131 nextpos = pos - 1;
5132 if (INTEGERP (tem))
5133 nextpos = XFASTINT (tem);
5135 /* If there are no more annotations in this range,
5136 output the rest of the range all at once. */
5137 if (! (nextpos >= pos && nextpos <= lastpos))
5138 return e_write (desc, string, pos, lastpos, coding);
5140 /* Output buffer text up to the next annotation's position. */
5141 if (nextpos > pos)
5143 if (!e_write (desc, string, pos, nextpos, coding))
5144 return 0;
5145 pos = nextpos;
5147 /* Output the annotation. */
5148 tem = Fcdr (Fcar (*annot));
5149 if (STRINGP (tem))
5151 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5152 return 0;
5154 *annot = Fcdr (*annot);
5156 return 1;
5159 /* Maximum number of characters that the next
5160 function encodes per one loop iteration. */
5162 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5164 /* Write text in the range START and END into descriptor DESC,
5165 encoding them with coding system CODING. If STRING is nil, START
5166 and END are character positions of the current buffer, else they
5167 are indexes to the string STRING. Return true if successful. */
5169 static bool
5170 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5171 struct coding_system *coding)
5173 if (STRINGP (string))
5175 start = 0;
5176 end = SCHARS (string);
5179 /* We used to have a code for handling selective display here. But,
5180 now it is handled within encode_coding. */
5182 while (start < end)
5184 if (STRINGP (string))
5186 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5187 if (CODING_REQUIRE_ENCODING (coding))
5189 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5191 /* Avoid creating huge Lisp string in encode_coding_object. */
5192 if (nchars == E_WRITE_MAX)
5193 coding->raw_destination = 1;
5195 encode_coding_object
5196 (coding, string, start, string_char_to_byte (string, start),
5197 start + nchars, string_char_to_byte (string, start + nchars),
5198 Qt);
5200 else
5202 coding->dst_object = string;
5203 coding->consumed_char = SCHARS (string);
5204 coding->produced = SBYTES (string);
5207 else
5209 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5210 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5212 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5213 if (CODING_REQUIRE_ENCODING (coding))
5215 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5217 /* Likewise. */
5218 if (nchars == E_WRITE_MAX)
5219 coding->raw_destination = 1;
5221 encode_coding_object
5222 (coding, Fcurrent_buffer (), start, start_byte,
5223 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5225 else
5227 coding->dst_object = Qnil;
5228 coding->dst_pos_byte = start_byte;
5229 if (start >= GPT || end <= GPT)
5231 coding->consumed_char = end - start;
5232 coding->produced = end_byte - start_byte;
5234 else
5236 coding->consumed_char = GPT - start;
5237 coding->produced = GPT_BYTE - start_byte;
5242 if (coding->produced > 0)
5244 char *buf = (coding->raw_destination ? (char *) coding->destination
5245 : (STRINGP (coding->dst_object)
5246 ? SSDATA (coding->dst_object)
5247 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5248 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5250 if (coding->raw_destination)
5252 /* We're responsible for freeing this, see
5253 encode_coding_object to check why. */
5254 xfree (coding->destination);
5255 coding->raw_destination = 0;
5257 if (coding->produced)
5258 return 0;
5260 start += coding->consumed_char;
5263 return 1;
5266 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5267 Sverify_visited_file_modtime, 0, 1, 0,
5268 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5269 This means that the file has not been changed since it was visited or saved.
5270 If BUF is omitted or nil, it defaults to the current buffer.
5271 See Info node `(elisp)Modification Time' for more details. */)
5272 (Lisp_Object buf)
5274 struct buffer *b = decode_buffer (buf);
5275 struct stat st;
5276 Lisp_Object handler;
5277 Lisp_Object filename;
5278 struct timespec mtime;
5280 if (!STRINGP (BVAR (b, filename))) return Qt;
5281 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5283 /* If the file name has special constructs in it,
5284 call the corresponding file handler. */
5285 handler = Ffind_file_name_handler (BVAR (b, filename),
5286 Qverify_visited_file_modtime);
5287 if (!NILP (handler))
5288 return call2 (handler, Qverify_visited_file_modtime, buf);
5290 filename = ENCODE_FILE (BVAR (b, filename));
5292 mtime = (stat (SSDATA (filename), &st) == 0
5293 ? get_stat_mtime (&st)
5294 : time_error_value (errno));
5295 if (timespec_cmp (mtime, b->modtime) == 0
5296 && (b->modtime_size < 0
5297 || st.st_size == b->modtime_size))
5298 return Qt;
5299 return Qnil;
5302 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5303 Svisited_file_modtime, 0, 0, 0,
5304 doc: /* Return the current buffer's recorded visited file modification time.
5305 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5306 `file-attributes' returns. If the current buffer has no recorded file
5307 modification time, this function returns 0. If the visited file
5308 doesn't exist, return -1.
5309 See Info node `(elisp)Modification Time' for more details. */)
5310 (void)
5312 int ns = current_buffer->modtime.tv_nsec;
5313 if (ns < 0)
5314 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5315 return make_lisp_time (current_buffer->modtime);
5318 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5319 Sset_visited_file_modtime, 0, 1, 0,
5320 doc: /* Update buffer's recorded modification time from the visited file's time.
5321 Useful if the buffer was not read from the file normally
5322 or if the file itself has been changed for some known benign reason.
5323 An argument specifies the modification time value to use
5324 (instead of that of the visited file), in the form of a list
5325 (HIGH LOW USEC PSEC) or an integer flag as returned by
5326 `visited-file-modtime'. */)
5327 (Lisp_Object time_flag)
5329 if (!NILP (time_flag))
5331 struct timespec mtime;
5332 if (INTEGERP (time_flag))
5334 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5335 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5337 else
5338 mtime = lisp_time_argument (time_flag);
5340 current_buffer->modtime = mtime;
5341 current_buffer->modtime_size = -1;
5343 else
5345 register Lisp_Object filename;
5346 struct stat st;
5347 Lisp_Object handler;
5349 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5351 /* If the file name has special constructs in it,
5352 call the corresponding file handler. */
5353 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5354 if (!NILP (handler))
5355 /* The handler can find the file name the same way we did. */
5356 return call2 (handler, Qset_visited_file_modtime, Qnil);
5358 filename = ENCODE_FILE (filename);
5360 if (stat (SSDATA (filename), &st) >= 0)
5362 current_buffer->modtime = get_stat_mtime (&st);
5363 current_buffer->modtime_size = st.st_size;
5367 return Qnil;
5370 static Lisp_Object
5371 auto_save_error (Lisp_Object error_val)
5373 Lisp_Object msg;
5374 int i;
5376 auto_save_error_occurred = 1;
5378 ring_bell (XFRAME (selected_frame));
5380 AUTO_STRING (format, "Auto-saving %s: %s");
5381 msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5382 Ferror_message_string (error_val));
5384 for (i = 0; i < 3; ++i)
5386 if (i == 0)
5387 message3 (msg);
5388 else
5389 message3_nolog (msg);
5390 Fsleep_for (make_number (1), Qnil);
5393 return Qnil;
5396 static Lisp_Object
5397 auto_save_1 (void)
5399 struct stat st;
5400 Lisp_Object modes;
5402 auto_save_mode_bits = 0666;
5404 /* Get visited file's mode to become the auto save file's mode. */
5405 if (! NILP (BVAR (current_buffer, filename)))
5407 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5408 /* But make sure we can overwrite it later! */
5409 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5410 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5411 INTEGERP (modes))
5412 /* Remote files don't cooperate with stat. */
5413 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5416 return
5417 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5418 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5419 Qnil, Qnil);
5422 struct auto_save_unwind
5424 FILE *stream;
5425 bool auto_raise;
5428 static void
5429 do_auto_save_unwind (void *arg)
5431 struct auto_save_unwind *p = arg;
5432 FILE *stream = p->stream;
5433 minibuffer_auto_raise = p->auto_raise;
5434 auto_saving = 0;
5435 if (stream != NULL)
5437 block_input ();
5438 fclose (stream);
5439 unblock_input ();
5443 static Lisp_Object
5444 do_auto_save_make_dir (Lisp_Object dir)
5446 Lisp_Object result;
5448 auto_saving_dir_umask = 077;
5449 result = call2 (Qmake_directory, dir, Qt);
5450 auto_saving_dir_umask = 0;
5451 return result;
5454 static Lisp_Object
5455 do_auto_save_eh (Lisp_Object ignore)
5457 auto_saving_dir_umask = 0;
5458 return Qnil;
5461 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5462 doc: /* Auto-save all buffers that need it.
5463 This is all buffers that have auto-saving enabled
5464 and are changed since last auto-saved.
5465 Auto-saving writes the buffer into a file
5466 so that your editing is not lost if the system crashes.
5467 This file is not the file you visited; that changes only when you save.
5468 Normally we run the normal hook `auto-save-hook' before saving.
5470 A non-nil NO-MESSAGE argument means do not print any message if successful.
5471 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5472 (Lisp_Object no_message, Lisp_Object current_only)
5474 struct buffer *old = current_buffer, *b;
5475 Lisp_Object tail, buf, hook;
5476 bool auto_saved = 0;
5477 int do_handled_files;
5478 Lisp_Object oquit;
5479 FILE *stream = NULL;
5480 ptrdiff_t count = SPECPDL_INDEX ();
5481 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5482 bool old_message_p = 0;
5483 struct auto_save_unwind auto_save_unwind;
5485 if (max_specpdl_size < specpdl_size + 40)
5486 max_specpdl_size = specpdl_size + 40;
5488 if (minibuf_level)
5489 no_message = Qt;
5491 if (NILP (no_message))
5493 old_message_p = push_message ();
5494 record_unwind_protect_void (pop_message_unwind);
5497 /* Ordinarily don't quit within this function,
5498 but don't make it impossible to quit (in case we get hung in I/O). */
5499 oquit = Vquit_flag;
5500 Vquit_flag = Qnil;
5502 hook = intern ("auto-save-hook");
5503 safe_run_hooks (hook);
5505 if (STRINGP (Vauto_save_list_file_name))
5507 Lisp_Object listfile;
5509 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5511 /* Don't try to create the directory when shutting down Emacs,
5512 because creating the directory might signal an error, and
5513 that would leave Emacs in a strange state. */
5514 if (!NILP (Vrun_hooks))
5516 Lisp_Object dir;
5517 dir = Ffile_name_directory (listfile);
5518 if (NILP (Ffile_directory_p (dir)))
5519 internal_condition_case_1 (do_auto_save_make_dir,
5520 dir, Qt,
5521 do_auto_save_eh);
5524 stream = emacs_fopen (SSDATA (listfile), "w");
5527 auto_save_unwind.stream = stream;
5528 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5529 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5530 minibuffer_auto_raise = 0;
5531 auto_saving = 1;
5532 auto_save_error_occurred = 0;
5534 /* On first pass, save all files that don't have handlers.
5535 On second pass, save all files that do have handlers.
5537 If Emacs is crashing, the handlers may tweak what is causing
5538 Emacs to crash in the first place, and it would be a shame if
5539 Emacs failed to autosave perfectly ordinary files because it
5540 couldn't handle some ange-ftp'd file. */
5542 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5543 FOR_EACH_LIVE_BUFFER (tail, buf)
5545 b = XBUFFER (buf);
5547 /* Record all the buffers that have auto save mode
5548 in the special file that lists them. For each of these buffers,
5549 Record visited name (if any) and auto save name. */
5550 if (STRINGP (BVAR (b, auto_save_file_name))
5551 && stream != NULL && do_handled_files == 0)
5553 block_input ();
5554 if (!NILP (BVAR (b, filename)))
5556 fwrite (SDATA (BVAR (b, filename)), 1,
5557 SBYTES (BVAR (b, filename)), stream);
5559 putc ('\n', stream);
5560 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5561 SBYTES (BVAR (b, auto_save_file_name)), stream);
5562 putc ('\n', stream);
5563 unblock_input ();
5566 if (!NILP (current_only)
5567 && b != current_buffer)
5568 continue;
5570 /* Don't auto-save indirect buffers.
5571 The base buffer takes care of it. */
5572 if (b->base_buffer)
5573 continue;
5575 /* Check for auto save enabled
5576 and file changed since last auto save
5577 and file changed since last real save. */
5578 if (STRINGP (BVAR (b, auto_save_file_name))
5579 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5580 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5581 /* -1 means we've turned off autosaving for a while--see below. */
5582 && XINT (BVAR (b, save_length)) >= 0
5583 && (do_handled_files
5584 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5585 Qwrite_region))))
5587 struct timespec before_time = current_timespec ();
5588 struct timespec after_time;
5590 /* If we had a failure, don't try again for 20 minutes. */
5591 if (b->auto_save_failure_time > 0
5592 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5593 continue;
5595 set_buffer_internal (b);
5596 if (NILP (Vauto_save_include_big_deletions)
5597 && (XFASTINT (BVAR (b, save_length)) * 10
5598 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5599 /* A short file is likely to change a large fraction;
5600 spare the user annoying messages. */
5601 && XFASTINT (BVAR (b, save_length)) > 5000
5602 /* These messages are frequent and annoying for `*mail*'. */
5603 && !EQ (BVAR (b, filename), Qnil)
5604 && NILP (no_message))
5606 /* It has shrunk too much; turn off auto-saving here. */
5607 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5608 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5609 BVAR (b, name), 1);
5610 minibuffer_auto_raise = 0;
5611 /* Turn off auto-saving until there's a real save,
5612 and prevent any more warnings. */
5613 XSETINT (BVAR (b, save_length), -1);
5614 Fsleep_for (make_number (1), Qnil);
5615 continue;
5617 if (!auto_saved && NILP (no_message))
5618 message1 ("Auto-saving...");
5619 internal_condition_case (auto_save_1, Qt, auto_save_error);
5620 auto_saved = 1;
5621 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5622 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5623 set_buffer_internal (old);
5625 after_time = current_timespec ();
5627 /* If auto-save took more than 60 seconds,
5628 assume it was an NFS failure that got a timeout. */
5629 if (after_time.tv_sec - before_time.tv_sec > 60)
5630 b->auto_save_failure_time = after_time.tv_sec;
5634 /* Prevent another auto save till enough input events come in. */
5635 record_auto_save ();
5637 if (auto_saved && NILP (no_message))
5639 if (old_message_p)
5641 /* If we are going to restore an old message,
5642 give time to read ours. */
5643 sit_for (make_number (1), 0, 0);
5644 restore_message ();
5646 else if (!auto_save_error_occurred)
5647 /* Don't overwrite the error message if an error occurred.
5648 If we displayed a message and then restored a state
5649 with no message, leave a "done" message on the screen. */
5650 message1 ("Auto-saving...done");
5653 Vquit_flag = oquit;
5655 /* This restores the message-stack status. */
5656 unbind_to (count, Qnil);
5657 return Qnil;
5660 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5661 Sset_buffer_auto_saved, 0, 0, 0,
5662 doc: /* Mark current buffer as auto-saved with its current text.
5663 No auto-save file will be written until the buffer changes again. */)
5664 (void)
5666 /* FIXME: This should not be called in indirect buffers, since
5667 they're not autosaved. */
5668 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5669 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5670 current_buffer->auto_save_failure_time = 0;
5671 return Qnil;
5674 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5675 Sclear_buffer_auto_save_failure, 0, 0, 0,
5676 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5677 (void)
5679 current_buffer->auto_save_failure_time = 0;
5680 return Qnil;
5683 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5684 0, 0, 0,
5685 doc: /* Return t if current buffer has been auto-saved recently.
5686 More precisely, if it has been auto-saved since last read from or saved
5687 in the visited file. If the buffer has no visited file,
5688 then any auto-save counts as "recent". */)
5689 (void)
5691 /* FIXME: maybe we should return nil for indirect buffers since
5692 they're never autosaved. */
5693 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5696 /* Reading and completing file names. */
5698 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5699 Snext_read_file_uses_dialog_p, 0, 0, 0,
5700 doc: /* Return t if a call to `read-file-name' will use a dialog.
5701 The return value is only relevant for a call to `read-file-name' that happens
5702 before any other event (mouse or keypress) is handled. */)
5703 (void)
5705 #if (defined USE_GTK || defined USE_MOTIF \
5706 || defined HAVE_NS || defined HAVE_NTGUI)
5707 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5708 && use_dialog_box
5709 && use_file_dialog
5710 && window_system_available (SELECTED_FRAME ()))
5711 return Qt;
5712 #endif
5713 return Qnil;
5717 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5718 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5719 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5720 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5721 it to text mode.
5723 As a side effect, this function flushes any pending STREAM's data.
5725 Value is the previous value of STREAM's I/O mode, nil for text mode,
5726 non-nil for binary mode.
5728 On MS-Windows and MS-DOS, binary mode is needed to read or write
5729 arbitrary binary data, and for disabling translation between CR-LF
5730 pairs and a single newline character. Examples include generation
5731 of text files with Unix-style end-of-line format using `princ' in
5732 batch mode, with standard output redirected to a file.
5734 On Posix systems, this function always returns non-nil, and has no
5735 effect except for flushing STREAM's data. */)
5736 (Lisp_Object stream, Lisp_Object mode)
5738 FILE *fp = NULL;
5739 int binmode;
5741 CHECK_SYMBOL (stream);
5742 if (EQ (stream, Qstdin))
5743 fp = stdin;
5744 else if (EQ (stream, Qstdout))
5745 fp = stdout;
5746 else if (EQ (stream, Qstderr))
5747 fp = stderr;
5748 else
5749 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5751 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5752 if (fp != stdin)
5753 fflush (fp);
5755 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5758 void
5759 init_fileio (void)
5761 realmask = umask (0);
5762 umask (realmask);
5764 valid_timestamp_file_system = 0;
5766 /* fsync can be a significant performance hit. Often it doesn't
5767 suffice to make the file-save operation survive a crash. For
5768 batch scripts, which are typically part of larger shell commands
5769 that don't fsync other files, its effect on performance can be
5770 significant so its utility is particularly questionable.
5771 Hence, for now by default fsync is used only when interactive.
5773 For more on why fsync often fails to work on today's hardware, see:
5774 Zheng M et al. Understanding the robustness of SSDs under power fault.
5775 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5776 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5778 For more on why fsync does not suffice even if it works properly, see:
5779 Roche X. Necessary step(s) to synchronize filename operations on disk.
5780 Austin Group Defect 672, 2013-03-19
5781 http://austingroupbugs.net/view.php?id=672 */
5782 write_region_inhibit_fsync = noninteractive;
5785 void
5786 syms_of_fileio (void)
5788 /* Property name of a file name handler,
5789 which gives a list of operations it handles. */
5790 DEFSYM (Qoperations, "operations");
5792 DEFSYM (Qexpand_file_name, "expand-file-name");
5793 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5794 DEFSYM (Qdirectory_file_name, "directory-file-name");
5795 DEFSYM (Qfile_name_directory, "file-name-directory");
5796 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5797 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5798 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5799 DEFSYM (Qcopy_file, "copy-file");
5800 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5801 DEFSYM (Qmake_directory, "make-directory");
5802 DEFSYM (Qdelete_file, "delete-file");
5803 DEFSYM (Qrename_file, "rename-file");
5804 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5805 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5806 DEFSYM (Qfile_exists_p, "file-exists-p");
5807 DEFSYM (Qfile_executable_p, "file-executable-p");
5808 DEFSYM (Qfile_readable_p, "file-readable-p");
5809 DEFSYM (Qfile_writable_p, "file-writable-p");
5810 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5811 DEFSYM (Qaccess_file, "access-file");
5812 DEFSYM (Qfile_directory_p, "file-directory-p");
5813 DEFSYM (Qfile_regular_p, "file-regular-p");
5814 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5815 DEFSYM (Qfile_modes, "file-modes");
5816 DEFSYM (Qset_file_modes, "set-file-modes");
5817 DEFSYM (Qset_file_times, "set-file-times");
5818 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5819 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5820 DEFSYM (Qfile_acl, "file-acl");
5821 DEFSYM (Qset_file_acl, "set-file-acl");
5822 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5823 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5824 DEFSYM (Qwrite_region, "write-region");
5825 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5826 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5828 /* The symbol bound to coding-system-for-read when
5829 insert-file-contents is called for recovering a file. This is not
5830 an actual coding system name, but just an indicator to tell
5831 insert-file-contents to use `emacs-mule' with a special flag for
5832 auto saving and recovering a file. */
5833 DEFSYM (Qauto_save_coding, "auto-save-coding");
5835 DEFSYM (Qfile_name_history, "file-name-history");
5836 Fset (Qfile_name_history, Qnil);
5838 DEFSYM (Qfile_error, "file-error");
5839 DEFSYM (Qfile_already_exists, "file-already-exists");
5840 DEFSYM (Qfile_date_error, "file-date-error");
5841 DEFSYM (Qfile_notify_error, "file-notify-error");
5842 DEFSYM (Qexcl, "excl");
5844 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5845 doc: /* Coding system for encoding file names.
5846 If it is nil, `default-file-name-coding-system' (which see) is used.
5848 On MS-Windows, the value of this variable is largely ignored if
5849 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5850 behaves as if file names were encoded in `utf-8'. */);
5851 Vfile_name_coding_system = Qnil;
5853 DEFVAR_LISP ("default-file-name-coding-system",
5854 Vdefault_file_name_coding_system,
5855 doc: /* Default coding system for encoding file names.
5856 This variable is used only when `file-name-coding-system' is nil.
5858 This variable is set/changed by the command `set-language-environment'.
5859 User should not set this variable manually,
5860 instead use `file-name-coding-system' to get a constant encoding
5861 of file names regardless of the current language environment.
5863 On MS-Windows, the value of this variable is largely ignored if
5864 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5865 behaves as if file names were encoded in `utf-8'. */);
5866 Vdefault_file_name_coding_system = Qnil;
5868 /* Lisp functions for translating file formats. */
5869 DEFSYM (Qformat_decode, "format-decode");
5870 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5872 /* Lisp function for setting buffer-file-coding-system and the
5873 multibyteness of the current buffer after inserting a file. */
5874 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5876 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5878 Fput (Qfile_error, Qerror_conditions,
5879 Fpurecopy (list2 (Qfile_error, Qerror)));
5880 Fput (Qfile_error, Qerror_message,
5881 build_pure_c_string ("File error"));
5883 Fput (Qfile_already_exists, Qerror_conditions,
5884 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5885 Fput (Qfile_already_exists, Qerror_message,
5886 build_pure_c_string ("File already exists"));
5888 Fput (Qfile_date_error, Qerror_conditions,
5889 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5890 Fput (Qfile_date_error, Qerror_message,
5891 build_pure_c_string ("Cannot set file date"));
5893 Fput (Qfile_notify_error, Qerror_conditions,
5894 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5895 Fput (Qfile_notify_error, Qerror_message,
5896 build_pure_c_string ("File notification error"));
5898 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5899 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5900 If a file name matches REGEXP, all I/O on that file is done by calling
5901 HANDLER. If a file name matches more than one handler, the handler
5902 whose match starts last in the file name gets precedence. The
5903 function `find-file-name-handler' checks this list for a handler for
5904 its argument.
5906 HANDLER should be a function. The first argument given to it is the
5907 name of the I/O primitive to be handled; the remaining arguments are
5908 the arguments that were passed to that primitive. For example, if you
5909 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5910 HANDLER is called like this:
5912 (funcall HANDLER \\='file-exists-p FILENAME)
5914 Note that HANDLER must be able to handle all I/O primitives; if it has
5915 nothing special to do for a primitive, it should reinvoke the
5916 primitive to handle the operation \"the usual way\".
5917 See Info node `(elisp)Magic File Names' for more details. */);
5918 Vfile_name_handler_alist = Qnil;
5920 DEFVAR_LISP ("set-auto-coding-function",
5921 Vset_auto_coding_function,
5922 doc: /* If non-nil, a function to call to decide a coding system of file.
5923 Two arguments are passed to this function: the file name
5924 and the length of a file contents following the point.
5925 This function should return a coding system to decode the file contents.
5926 It should check the file name against `auto-coding-alist'.
5927 If no coding system is decided, it should check a coding system
5928 specified in the heading lines with the format:
5929 -*- ... coding: CODING-SYSTEM; ... -*-
5930 or local variable spec of the tailing lines with `coding:' tag. */);
5931 Vset_auto_coding_function = Qnil;
5933 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5934 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5935 Each is passed one argument, the number of characters inserted,
5936 with point at the start of the inserted text. Each function
5937 should leave point the same, and return the new character count.
5938 If `insert-file-contents' is intercepted by a handler from
5939 `file-name-handler-alist', that handler is responsible for calling the
5940 functions in `after-insert-file-functions' if appropriate. */);
5941 Vafter_insert_file_functions = Qnil;
5943 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5944 doc: /* A list of functions to be called at the start of `write-region'.
5945 Each is passed two arguments, START and END as for `write-region'.
5946 These are usually two numbers but not always; see the documentation
5947 for `write-region'. The function should return a list of pairs
5948 of the form (POSITION . STRING), consisting of strings to be effectively
5949 inserted at the specified positions of the file being written (1 means to
5950 insert before the first byte written). The POSITIONs must be sorted into
5951 increasing order.
5953 If there are several annotation functions, the lists returned by these
5954 functions are merged destructively. As each annotation function runs,
5955 the variable `write-region-annotations-so-far' contains a list of all
5956 annotations returned by previous annotation functions.
5958 An annotation function can return with a different buffer current.
5959 Doing so removes the annotations returned by previous functions, and
5960 resets START and END to `point-min' and `point-max' of the new buffer.
5962 After `write-region' completes, Emacs calls the function stored in
5963 `write-region-post-annotation-function', once for each buffer that was
5964 current when building the annotations (i.e., at least once), with that
5965 buffer current. */);
5966 Vwrite_region_annotate_functions = Qnil;
5967 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5969 DEFVAR_LISP ("write-region-post-annotation-function",
5970 Vwrite_region_post_annotation_function,
5971 doc: /* Function to call after `write-region' completes.
5972 The function is called with no arguments. If one or more of the
5973 annotation functions in `write-region-annotate-functions' changed the
5974 current buffer, the function stored in this variable is called for
5975 each of those additional buffers as well, in addition to the original
5976 buffer. The relevant buffer is current during each function call. */);
5977 Vwrite_region_post_annotation_function = Qnil;
5978 staticpro (&Vwrite_region_annotation_buffers);
5980 DEFVAR_LISP ("write-region-annotations-so-far",
5981 Vwrite_region_annotations_so_far,
5982 doc: /* When an annotation function is called, this holds the previous annotations.
5983 These are the annotations made by other annotation functions
5984 that were already called. See also `write-region-annotate-functions'. */);
5985 Vwrite_region_annotations_so_far = Qnil;
5987 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5988 doc: /* A list of file name handlers that temporarily should not be used.
5989 This applies only to the operation `inhibit-file-name-operation'. */);
5990 Vinhibit_file_name_handlers = Qnil;
5992 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5993 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5994 Vinhibit_file_name_operation = Qnil;
5996 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
5997 doc: /* File name in which we write a list of all auto save file names.
5998 This variable is initialized automatically from `auto-save-list-file-prefix'
5999 shortly after Emacs reads your init file, if you have not yet given it
6000 a non-nil value. */);
6001 Vauto_save_list_file_name = Qnil;
6003 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6004 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6005 Normally auto-save files are written under other names. */);
6006 Vauto_save_visited_file_name = Qnil;
6008 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6009 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6010 If nil, deleting a substantial portion of the text disables auto-save
6011 in the buffer; this is the default behavior, because the auto-save
6012 file is usually more useful if it contains the deleted text. */);
6013 Vauto_save_include_big_deletions = Qnil;
6015 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6016 doc: /* Non-nil means don't call fsync in `write-region'.
6017 This variable affects calls to `write-region' as well as save commands.
6018 Setting this to nil may avoid data loss if the system loses power or
6019 the operating system crashes. By default, it is non-nil in batch mode. */);
6020 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6022 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6023 doc: /* Specifies whether to use the system's trash can.
6024 When non-nil, certain file deletion commands use the function
6025 `move-file-to-trash' instead of deleting files outright.
6026 This includes interactive calls to `delete-file' and
6027 `delete-directory' and the Dired deletion commands. */);
6028 delete_by_moving_to_trash = 0;
6029 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6031 /* Lisp function for moving files to trash. */
6032 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6034 /* Lisp function for recursively copying directories. */
6035 DEFSYM (Qcopy_directory, "copy-directory");
6037 /* Lisp function for recursively deleting directories. */
6038 DEFSYM (Qdelete_directory, "delete-directory");
6040 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6041 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6043 DEFSYM (Qstdin, "stdin");
6044 DEFSYM (Qstdout, "stdout");
6045 DEFSYM (Qstderr, "stderr");
6047 defsubr (&Sfind_file_name_handler);
6048 defsubr (&Sfile_name_directory);
6049 defsubr (&Sfile_name_nondirectory);
6050 defsubr (&Sunhandled_file_name_directory);
6051 defsubr (&Sfile_name_as_directory);
6052 defsubr (&Sdirectory_file_name);
6053 defsubr (&Smake_temp_name);
6054 defsubr (&Sexpand_file_name);
6055 defsubr (&Ssubstitute_in_file_name);
6056 defsubr (&Scopy_file);
6057 defsubr (&Smake_directory_internal);
6058 defsubr (&Sdelete_directory_internal);
6059 defsubr (&Sdelete_file);
6060 defsubr (&Srename_file);
6061 defsubr (&Sadd_name_to_file);
6062 defsubr (&Smake_symbolic_link);
6063 defsubr (&Sfile_name_absolute_p);
6064 defsubr (&Sfile_exists_p);
6065 defsubr (&Sfile_executable_p);
6066 defsubr (&Sfile_readable_p);
6067 defsubr (&Sfile_writable_p);
6068 defsubr (&Saccess_file);
6069 defsubr (&Sfile_symlink_p);
6070 defsubr (&Sfile_directory_p);
6071 defsubr (&Sfile_accessible_directory_p);
6072 defsubr (&Sfile_regular_p);
6073 defsubr (&Sfile_modes);
6074 defsubr (&Sset_file_modes);
6075 defsubr (&Sset_file_times);
6076 defsubr (&Sfile_selinux_context);
6077 defsubr (&Sfile_acl);
6078 defsubr (&Sset_file_acl);
6079 defsubr (&Sset_file_selinux_context);
6080 defsubr (&Sset_default_file_modes);
6081 defsubr (&Sdefault_file_modes);
6082 defsubr (&Sfile_newer_than_file_p);
6083 defsubr (&Sinsert_file_contents);
6084 defsubr (&Swrite_region);
6085 defsubr (&Scar_less_than_car);
6086 defsubr (&Sverify_visited_file_modtime);
6087 defsubr (&Svisited_file_modtime);
6088 defsubr (&Sset_visited_file_modtime);
6089 defsubr (&Sdo_auto_save);
6090 defsubr (&Sset_buffer_auto_saved);
6091 defsubr (&Sclear_buffer_auto_save_failure);
6092 defsubr (&Srecent_auto_save_p);
6094 defsubr (&Snext_read_file_uses_dialog_p);
6096 defsubr (&Sset_binary_mode);
6098 #ifdef HAVE_SYNC
6099 defsubr (&Sunix_sync);
6100 #endif