Document return value of `display-buffer-in-side-window'
[emacs.git] / src / fileio.c
blob8f16d1e8496fa29ffaba9dbc3e498be3b6357542
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include "sysstdio.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #include <errno.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
37 #endif
39 #if USE_ACL && defined HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "composite.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "coding.h"
50 #include "window.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
53 #include "frame.h"
55 #ifdef HAVE_LINUX_FS_H
56 # include <sys/ioctl.h>
57 # include <linux/fs.h>
58 #endif
60 #ifdef WINDOWSNT
61 #define NOMINMAX 1
62 #include <windows.h>
63 #include <sys/file.h>
64 #include "w32.h"
65 #endif /* not WINDOWSNT */
67 #ifdef MSDOS
68 #include "msdos.h"
69 #include <sys/param.h>
70 #endif
72 #ifdef DOS_NT
73 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
74 redirector allows the six letters between 'Z' and 'a' as well. */
75 #ifdef MSDOS
76 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
77 #endif
78 #ifdef WINDOWSNT
79 #define IS_DRIVE(x) c_isalpha (x)
80 #endif
81 /* Need to lower-case the drive letter, or else expanded
82 filenames will sometimes compare unequal, because
83 `expand-file-name' doesn't always down-case the drive letter. */
84 #define DRIVE_LETTER(x) c_tolower (x)
85 #endif
87 #include "systime.h"
88 #include <acl.h>
89 #include <allocator.h>
90 #include <careadlinkat.h>
91 #include <stat-time.h>
93 #include <binary-io.h>
95 #ifdef HPUX
96 #include <netio.h>
97 #endif
99 #include "commands.h"
101 /* True during writing of auto-save files. */
102 static bool auto_saving;
104 /* Emacs's real umask. */
105 static mode_t realmask;
107 /* Nonzero umask during creation of auto-save directories. */
108 static mode_t auto_saving_dir_umask;
110 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
111 a new file with the same mode as the original. */
112 static mode_t auto_save_mode_bits;
114 /* Set by auto_save_1 if an error occurred during the last auto-save. */
115 static bool auto_save_error_occurred;
117 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
118 number of a file system where time stamps were observed to to work. */
119 static bool valid_timestamp_file_system;
120 static dev_t timestamp_file_system;
122 /* Each time an annotation function changes the buffer, the new buffer
123 is added here. */
124 static Lisp_Object Vwrite_region_annotation_buffers;
126 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
127 Lisp_Object *, struct coding_system *);
128 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
129 struct coding_system *);
132 /* Return true if FILENAME exists. */
134 static bool
135 check_existing (const char *filename)
137 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
140 /* Return true if file FILENAME exists and can be executed. */
142 static bool
143 check_executable (char *filename)
145 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
148 /* Return true if file FILENAME exists and can be accessed
149 according to AMODE, which should include W_OK.
150 On failure, return false and set errno. */
152 static bool
153 check_writable (const char *filename, int amode)
155 #ifdef MSDOS
156 /* FIXME: an faccessat implementation should be added to the
157 DOS/Windows ports and this #ifdef branch should be removed. */
158 struct stat st;
159 if (stat (filename, &st) < 0)
160 return 0;
161 errno = EPERM;
162 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
163 #else /* not MSDOS */
164 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
165 #ifdef CYGWIN
166 /* faccessat may have returned failure because Cygwin couldn't
167 determine the file's UID or GID; if so, we return success. */
168 if (!res)
170 int faccessat_errno = errno;
171 struct stat st;
172 if (stat (filename, &st) < 0)
173 return 0;
174 res = (st.st_uid == -1 || st.st_gid == -1);
175 errno = faccessat_errno;
177 #endif /* CYGWIN */
178 return res;
179 #endif /* not MSDOS */
182 /* Signal a file-access failure. STRING describes the failure,
183 NAME the file involved, and ERRORNO the errno value.
185 If NAME is neither null nor a pair, package it up as a singleton
186 list before reporting it; this saves report_file_errno's caller the
187 trouble of preserving errno before calling list1. */
189 void
190 report_file_errno (char const *string, Lisp_Object name, int errorno)
192 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
193 char *str = emacs_strerror (errorno);
194 AUTO_STRING (unibyte_str, str);
195 Lisp_Object errstring
196 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
197 Lisp_Object errdata = Fcons (errstring, data);
199 if (errorno == EEXIST)
200 xsignal (Qfile_already_exists, errdata);
201 else
202 xsignal (Qfile_error, Fcons (build_string (string), errdata));
205 /* Signal a file-access failure that set errno. STRING describes the
206 failure, NAME the file involved. When invoking this function, take
207 care to not use arguments such as build_string ("foo") that involve
208 side effects that may set errno. */
210 void
211 report_file_error (char const *string, Lisp_Object name)
213 report_file_errno (string, name, errno);
216 /* Like report_file_error, but reports a file-notify-error instead. */
218 void
219 report_file_notify_error (const char *string, Lisp_Object name)
221 char *str = emacs_strerror (errno);
222 AUTO_STRING (unibyte_str, str);
223 Lisp_Object errstring
224 = code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
225 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
226 Lisp_Object errdata = Fcons (errstring, data);
228 xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
231 void
232 close_file_unwind (int fd)
234 emacs_close (fd);
237 void
238 fclose_unwind (void *arg)
240 FILE *stream = arg;
241 fclose (stream);
244 /* Restore point, having saved it as a marker. */
246 void
247 restore_point_unwind (Lisp_Object location)
249 Fgoto_char (location);
250 unchain_marker (XMARKER (location));
254 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
255 Sfind_file_name_handler, 2, 2, 0,
256 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
257 Otherwise, return nil.
258 A file name is handled if one of the regular expressions in
259 `file-name-handler-alist' matches it.
261 If OPERATION equals `inhibit-file-name-operation', then we ignore
262 any handlers that are members of `inhibit-file-name-handlers',
263 but we still do run any other handlers. This lets handlers
264 use the standard functions without calling themselves recursively. */)
265 (Lisp_Object filename, Lisp_Object operation)
267 /* This function must not munge the match data. */
268 Lisp_Object chain, inhibited_handlers, result;
269 ptrdiff_t pos = -1;
271 result = Qnil;
272 CHECK_STRING (filename);
274 if (EQ (operation, Vinhibit_file_name_operation))
275 inhibited_handlers = Vinhibit_file_name_handlers;
276 else
277 inhibited_handlers = Qnil;
279 for (chain = Vfile_name_handler_alist; CONSP (chain);
280 chain = XCDR (chain))
282 Lisp_Object elt;
283 elt = XCAR (chain);
284 if (CONSP (elt))
286 Lisp_Object string = XCAR (elt);
287 ptrdiff_t match_pos;
288 Lisp_Object handler = XCDR (elt);
289 Lisp_Object operations = Qnil;
291 if (SYMBOLP (handler))
292 operations = Fget (handler, Qoperations);
294 if (STRINGP (string)
295 && (match_pos = fast_string_match (string, filename)) > pos
296 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
298 Lisp_Object tem;
300 handler = XCDR (elt);
301 tem = Fmemq (handler, inhibited_handlers);
302 if (NILP (tem))
304 result = handler;
305 pos = match_pos;
310 QUIT;
312 return result;
315 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
316 1, 1, 0,
317 doc: /* Return the directory component in file name FILENAME.
318 Return nil if FILENAME does not include a directory.
319 Otherwise return a directory name.
320 Given a Unix syntax file name, returns a string ending in slash. */)
321 (Lisp_Object filename)
323 Lisp_Object handler;
325 CHECK_STRING (filename);
327 /* If the file name has special constructs in it,
328 call the corresponding file handler. */
329 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
330 if (!NILP (handler))
332 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
333 filename);
334 return STRINGP (handled_name) ? handled_name : Qnil;
337 char *beg = SSDATA (filename);
338 char const *p = beg + SBYTES (filename);
340 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
341 #ifdef DOS_NT
342 /* only recognize drive specifier at the beginning */
343 && !(p[-1] == ':'
344 /* handle the "/:d:foo" and "/:foo" cases correctly */
345 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
346 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
347 #endif
348 ) p--;
350 if (p == beg)
351 return Qnil;
352 #ifdef DOS_NT
353 /* Expansion of "c:" to drive and default directory. */
354 Lisp_Object tem_fn;
355 USE_SAFE_ALLOCA;
356 SAFE_ALLOCA_STRING (beg, filename);
357 p = beg + (p - SSDATA (filename));
359 if (p[-1] == ':')
361 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
362 char *res = alloca (MAXPATHLEN + 1);
363 char *r = res;
365 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
367 memcpy (res, beg, 2);
368 beg += 2;
369 r += 2;
372 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
374 size_t l = strlen (res);
376 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
377 strcat (res, "/");
378 beg = res;
379 p = beg + strlen (beg);
380 dostounix_filename (beg);
381 tem_fn = make_specified_string (beg, -1, p - beg,
382 STRING_MULTIBYTE (filename));
384 else
385 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
386 STRING_MULTIBYTE (filename));
388 else if (STRING_MULTIBYTE (filename))
390 tem_fn = make_specified_string (beg, -1, p - beg, 1);
391 dostounix_filename (SSDATA (tem_fn));
392 #ifdef WINDOWSNT
393 if (!NILP (Vw32_downcase_file_names))
394 tem_fn = Fdowncase (tem_fn);
395 #endif
397 else
399 dostounix_filename (beg);
400 tem_fn = make_specified_string (beg, -1, p - beg, 0);
402 SAFE_FREE ();
403 return tem_fn;
404 #else /* DOS_NT */
405 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
406 #endif /* DOS_NT */
409 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
410 Sfile_name_nondirectory, 1, 1, 0,
411 doc: /* Return file name FILENAME sans its directory.
412 For example, in a Unix-syntax file name,
413 this is everything after the last slash,
414 or the entire name if it contains no slash. */)
415 (Lisp_Object filename)
417 register const char *beg, *p, *end;
418 Lisp_Object handler;
420 CHECK_STRING (filename);
422 /* If the file name has special constructs in it,
423 call the corresponding file handler. */
424 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
425 if (!NILP (handler))
427 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
428 filename);
429 if (STRINGP (handled_name))
430 return handled_name;
431 error ("Invalid handler in `file-name-handler-alist'");
434 beg = SSDATA (filename);
435 end = p = beg + SBYTES (filename);
437 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
438 #ifdef DOS_NT
439 /* only recognize drive specifier at beginning */
440 && !(p[-1] == ':'
441 /* handle the "/:d:foo" case correctly */
442 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
443 #endif
445 p--;
447 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
450 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
451 Sunhandled_file_name_directory, 1, 1, 0,
452 doc: /* Return a directly usable directory name somehow associated with FILENAME.
453 A `directly usable' directory name is one that may be used without the
454 intervention of any file handler.
455 If FILENAME is a directly usable file itself, return
456 \(file-name-as-directory FILENAME).
457 If FILENAME refers to a file which is not accessible from a local process,
458 then this should return nil.
459 The `call-process' and `start-process' functions use this function to
460 get a current directory to run processes in. */)
461 (Lisp_Object filename)
463 Lisp_Object handler;
465 /* If the file name has special constructs in it,
466 call the corresponding file handler. */
467 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
468 if (!NILP (handler))
470 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
471 filename);
472 return STRINGP (handled_name) ? handled_name : Qnil;
475 return Ffile_name_as_directory (filename);
478 /* Maximum number of bytes that DST will be longer than SRC
479 in file_name_as_directory. This occurs when SRCLEN == 0. */
480 enum { file_name_as_directory_slop = 2 };
482 /* Convert from file name SRC of length SRCLEN to directory name in
483 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
484 string. On UNIX, just make sure there is a terminating /. Return
485 the length of DST in bytes. */
487 static ptrdiff_t
488 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
489 bool multibyte)
491 if (srclen == 0)
493 dst[0] = '.';
494 dst[1] = '/';
495 dst[2] = '\0';
496 return 2;
499 memcpy (dst, src, srclen);
500 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
501 dst[srclen++] = DIRECTORY_SEP;
502 dst[srclen] = 0;
503 #ifdef DOS_NT
504 dostounix_filename (dst);
505 #endif
506 return srclen;
509 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
510 Sfile_name_as_directory, 1, 1, 0,
511 doc: /* Return a string representing the file name FILE interpreted as a directory.
512 This operation exists because a directory is also a file, but its name as
513 a directory is different from its name as a file.
514 The result can be used as the value of `default-directory'
515 or passed as second argument to `expand-file-name'.
516 For a Unix-syntax file name, just appends a slash unless a trailing slash
517 is already present. */)
518 (Lisp_Object file)
520 char *buf;
521 ptrdiff_t length;
522 Lisp_Object handler, val;
523 USE_SAFE_ALLOCA;
525 CHECK_STRING (file);
527 /* If the file name has special constructs in it,
528 call the corresponding file handler. */
529 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
530 if (!NILP (handler))
532 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
533 file);
534 if (STRINGP (handled_name))
535 return handled_name;
536 error ("Invalid handler in `file-name-handler-alist'");
539 #ifdef WINDOWSNT
540 if (!NILP (Vw32_downcase_file_names))
541 file = Fdowncase (file);
542 #endif
543 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
544 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
545 STRING_MULTIBYTE (file));
546 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
547 SAFE_FREE ();
548 return val;
551 /* Convert from directory name SRC of length SRCLEN to file name in
552 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
553 string. On UNIX, just make sure there isn't a terminating /.
554 Return the length of DST in bytes. */
556 static ptrdiff_t
557 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
559 /* Process as Unix format: just remove any final slash.
560 But leave "/" and "//" unchanged. */
561 while (srclen > 1
562 #ifdef DOS_NT
563 && !IS_ANY_SEP (src[srclen - 2])
564 #endif
565 && IS_DIRECTORY_SEP (src[srclen - 1])
566 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
567 srclen--;
569 memcpy (dst, src, srclen);
570 dst[srclen] = 0;
571 #ifdef DOS_NT
572 dostounix_filename (dst);
573 #endif
574 return srclen;
577 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
578 1, 1, 0,
579 doc: /* Returns the file name of the directory named DIRECTORY.
580 This is the name of the file that holds the data for the directory DIRECTORY.
581 This operation exists because a directory is also a file, but its name as
582 a directory is different from its name as a file.
583 In Unix-syntax, this function just removes the final slash. */)
584 (Lisp_Object directory)
586 char *buf;
587 ptrdiff_t length;
588 Lisp_Object handler, val;
589 USE_SAFE_ALLOCA;
591 CHECK_STRING (directory);
593 /* If the file name has special constructs in it,
594 call the corresponding file handler. */
595 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
596 if (!NILP (handler))
598 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
599 directory);
600 if (STRINGP (handled_name))
601 return handled_name;
602 error ("Invalid handler in `file-name-handler-alist'");
605 #ifdef WINDOWSNT
606 if (!NILP (Vw32_downcase_file_names))
607 directory = Fdowncase (directory);
608 #endif
609 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
610 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
611 STRING_MULTIBYTE (directory));
612 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
613 SAFE_FREE ();
614 return val;
617 static const char make_temp_name_tbl[64] =
619 'A','B','C','D','E','F','G','H',
620 'I','J','K','L','M','N','O','P',
621 'Q','R','S','T','U','V','W','X',
622 'Y','Z','a','b','c','d','e','f',
623 'g','h','i','j','k','l','m','n',
624 'o','p','q','r','s','t','u','v',
625 'w','x','y','z','0','1','2','3',
626 '4','5','6','7','8','9','-','_'
629 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
631 /* Value is a temporary file name starting with PREFIX, a string.
633 The Emacs process number forms part of the result, so there is
634 no danger of generating a name being used by another process.
635 In addition, this function makes an attempt to choose a name
636 which has no existing file. To make this work, PREFIX should be
637 an absolute file name.
639 BASE64_P means add the pid as 3 characters in base64
640 encoding. In this case, 6 characters will be added to PREFIX to
641 form the file name. Otherwise, if Emacs is running on a system
642 with long file names, add the pid as a decimal number.
644 This function signals an error if no unique file name could be
645 generated. */
647 Lisp_Object
648 make_temp_name (Lisp_Object prefix, bool base64_p)
650 Lisp_Object val, encoded_prefix;
651 ptrdiff_t len;
652 printmax_t pid;
653 char *p, *data;
654 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
655 int pidlen;
657 CHECK_STRING (prefix);
659 /* VAL is created by adding 6 characters to PREFIX. The first
660 three are the PID of this process, in base 64, and the second
661 three are incremented if the file already exists. This ensures
662 262144 unique file names per PID per PREFIX. */
664 pid = getpid ();
666 if (base64_p)
668 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
669 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
670 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
671 pidlen = 3;
673 else
675 #ifdef HAVE_LONG_FILE_NAMES
676 pidlen = sprintf (pidbuf, "%"pMd, pid);
677 #else
678 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
679 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
680 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
681 pidlen = 3;
682 #endif
685 encoded_prefix = ENCODE_FILE (prefix);
686 len = SBYTES (encoded_prefix);
687 val = make_uninit_string (len + 3 + pidlen);
688 data = SSDATA (val);
689 memcpy (data, SSDATA (encoded_prefix), len);
690 p = data + len;
692 memcpy (p, pidbuf, pidlen);
693 p += pidlen;
695 /* Here we try to minimize useless stat'ing when this function is
696 invoked many times successively with the same PREFIX. We achieve
697 this by initializing count to a random value, and incrementing it
698 afterwards.
700 We don't want make-temp-name to be called while dumping,
701 because then make_temp_name_count_initialized_p would get set
702 and then make_temp_name_count would not be set when Emacs starts. */
704 if (!make_temp_name_count_initialized_p)
706 make_temp_name_count = time (NULL);
707 make_temp_name_count_initialized_p = 1;
710 while (1)
712 unsigned num = make_temp_name_count;
714 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
715 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
716 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
718 /* Poor man's congruential RN generator. Replace with
719 ++make_temp_name_count for debugging. */
720 make_temp_name_count += 25229;
721 make_temp_name_count %= 225307;
723 if (!check_existing (data))
725 /* We want to return only if errno is ENOENT. */
726 if (errno == ENOENT)
727 return DECODE_FILE (val);
728 else
729 /* The error here is dubious, but there is little else we
730 can do. The alternatives are to return nil, which is
731 as bad as (and in many cases worse than) throwing the
732 error, or to ignore the error, which will likely result
733 in looping through 225307 stat's, which is not only
734 dog-slow, but also useless since eventually nil would
735 have to be returned anyway. */
736 report_file_error ("Cannot create temporary name for prefix",
737 prefix);
738 /* not reached */
744 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
745 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
746 The Emacs process number forms part of the result, so there is no
747 danger of generating a name being used by another Emacs process
748 \(so long as only a single host can access the containing directory...).
750 This function tries to choose a name that has no existing file.
751 For this to work, PREFIX should be an absolute file name.
753 There is a race condition between calling `make-temp-name' and creating the
754 file, which opens all kinds of security holes. For that reason, you should
755 normally use `make-temp-file' instead. */)
756 (Lisp_Object prefix)
758 return make_temp_name (prefix, 0);
761 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
762 doc: /* Convert filename NAME to absolute, and canonicalize it.
763 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
764 \(does not start with slash or tilde); both the directory name and
765 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
766 missing, the current buffer's value of `default-directory' is used.
767 NAME should be a string that is a valid file name for the underlying
768 filesystem.
769 File name components that are `.' are removed, and
770 so are file name components followed by `..', along with the `..' itself;
771 note that these simplifications are done without checking the resulting
772 file names in the file system.
773 Multiple consecutive slashes are collapsed into a single slash,
774 except at the beginning of the file name when they are significant (e.g.,
775 UNC file names on MS-Windows.)
776 An initial `~/' expands to your home directory.
777 An initial `~USER/' expands to USER's home directory.
778 See also the function `substitute-in-file-name'.
780 For technical reasons, this function can return correct but
781 non-intuitive results for the root directory; for instance,
782 \(expand-file-name ".." "/") returns "/..". For this reason, use
783 \(directory-file-name (file-name-directory dirname)) to traverse a
784 filesystem tree, not (expand-file-name ".." dirname). */)
785 (Lisp_Object name, Lisp_Object default_directory)
787 /* These point to SDATA and need to be careful with string-relocation
788 during GC (via DECODE_FILE). */
789 char *nm;
790 char *nmlim;
791 const char *newdir;
792 const char *newdirlim;
793 /* This should only point to alloca'd data. */
794 char *target;
796 ptrdiff_t tlen;
797 struct passwd *pw;
798 #ifdef DOS_NT
799 int drive = 0;
800 bool collapse_newdir = true;
801 bool is_escaped = 0;
802 #endif /* DOS_NT */
803 ptrdiff_t length, nbytes;
804 Lisp_Object handler, result, handled_name;
805 bool multibyte;
806 Lisp_Object hdir;
807 USE_SAFE_ALLOCA;
809 CHECK_STRING (name);
811 /* If the file name has special constructs in it,
812 call the corresponding file handler. */
813 handler = Ffind_file_name_handler (name, Qexpand_file_name);
814 if (!NILP (handler))
816 handled_name = call3 (handler, Qexpand_file_name,
817 name, default_directory);
818 if (STRINGP (handled_name))
819 return handled_name;
820 error ("Invalid handler in `file-name-handler-alist'");
824 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
825 if (NILP (default_directory))
826 default_directory = BVAR (current_buffer, directory);
827 if (! STRINGP (default_directory))
829 #ifdef DOS_NT
830 /* "/" is not considered a root directory on DOS_NT, so using "/"
831 here causes an infinite recursion in, e.g., the following:
833 (let (default-directory)
834 (expand-file-name "a"))
836 To avoid this, we set default_directory to the root of the
837 current drive. */
838 default_directory = build_string (emacs_root_dir ());
839 #else
840 default_directory = build_string ("/");
841 #endif
844 if (!NILP (default_directory))
846 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
847 if (!NILP (handler))
849 handled_name = call3 (handler, Qexpand_file_name,
850 name, default_directory);
851 if (STRINGP (handled_name))
852 return handled_name;
853 error ("Invalid handler in `file-name-handler-alist'");
858 char *o = SSDATA (default_directory);
860 /* Make sure DEFAULT_DIRECTORY is properly expanded.
861 It would be better to do this down below where we actually use
862 default_directory. Unfortunately, calling Fexpand_file_name recursively
863 could invoke GC, and the strings might be relocated. This would
864 be annoying because we have pointers into strings lying around
865 that would need adjusting, and people would add new pointers to
866 the code and forget to adjust them, resulting in intermittent bugs.
867 Putting this call here avoids all that crud.
869 The EQ test avoids infinite recursion. */
870 if (! NILP (default_directory) && !EQ (default_directory, name)
871 /* Save time in some common cases - as long as default_directory
872 is not relative, it can be canonicalized with name below (if it
873 is needed at all) without requiring it to be expanded now. */
874 #ifdef DOS_NT
875 /* Detect MSDOS file names with drive specifiers. */
876 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
877 && IS_DIRECTORY_SEP (o[2]))
878 #ifdef WINDOWSNT
879 /* Detect Windows file names in UNC format. */
880 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
881 #endif
882 #else /* not DOS_NT */
883 /* Detect Unix absolute file names (/... alone is not absolute on
884 DOS or Windows). */
885 && ! (IS_DIRECTORY_SEP (o[0]))
886 #endif /* not DOS_NT */
889 default_directory = Fexpand_file_name (default_directory, Qnil);
892 multibyte = STRING_MULTIBYTE (name);
893 if (multibyte != STRING_MULTIBYTE (default_directory))
895 if (multibyte)
897 unsigned char *p = SDATA (name);
899 while (*p && ASCII_CHAR_P (*p))
900 p++;
901 if (*p == '\0')
903 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
904 unibyte. Do not convert DEFAULT_DIRECTORY to
905 multibyte; instead, convert NAME to a unibyte string,
906 so that the result of this function is also a unibyte
907 string. This is needed during bootstrapping and
908 dumping, when Emacs cannot decode file names, because
909 the locale environment is not set up. */
910 name = make_unibyte_string (SSDATA (name), SBYTES (name));
911 multibyte = 0;
913 else
914 default_directory = string_to_multibyte (default_directory);
916 else
918 name = string_to_multibyte (name);
919 multibyte = 1;
923 #ifdef WINDOWSNT
924 if (!NILP (Vw32_downcase_file_names))
925 default_directory = Fdowncase (default_directory);
926 #endif
928 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
929 SAFE_ALLOCA_STRING (nm, name);
930 nmlim = nm + SBYTES (name);
932 #ifdef DOS_NT
933 /* Note if special escape prefix is present, but remove for now. */
934 if (nm[0] == '/' && nm[1] == ':')
936 is_escaped = 1;
937 nm += 2;
940 /* Find and remove drive specifier if present; this makes nm absolute
941 even if the rest of the name appears to be relative. Only look for
942 drive specifier at the beginning. */
943 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
945 drive = (unsigned char) nm[0];
946 nm += 2;
949 #ifdef WINDOWSNT
950 /* If we see "c://somedir", we want to strip the first slash after the
951 colon when stripping the drive letter. Otherwise, this expands to
952 "//somedir". */
953 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
954 nm++;
956 /* Discard any previous drive specifier if nm is now in UNC format. */
957 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
958 && !IS_DIRECTORY_SEP (nm[2]))
959 drive = 0;
960 #endif /* WINDOWSNT */
961 #endif /* DOS_NT */
963 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
964 none are found, we can probably return right away. We will avoid
965 allocating a new string if name is already fully expanded. */
966 if (
967 IS_DIRECTORY_SEP (nm[0])
968 #ifdef MSDOS
969 && drive && !is_escaped
970 #endif
971 #ifdef WINDOWSNT
972 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
973 #endif
976 /* If it turns out that the filename we want to return is just a
977 suffix of FILENAME, we don't need to go through and edit
978 things; we just need to construct a new string using data
979 starting at the middle of FILENAME. If we set LOSE, that
980 means we've discovered that we can't do that cool trick. */
981 bool lose = 0;
982 char *p = nm;
984 while (*p)
986 /* Since we know the name is absolute, we can assume that each
987 element starts with a "/". */
989 /* "." and ".." are hairy. */
990 if (IS_DIRECTORY_SEP (p[0])
991 && p[1] == '.'
992 && (IS_DIRECTORY_SEP (p[2])
993 || p[2] == 0
994 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
995 || p[3] == 0))))
996 lose = 1;
997 /* Replace multiple slashes with a single one, except
998 leave leading "//" alone. */
999 else if (IS_DIRECTORY_SEP (p[0])
1000 && IS_DIRECTORY_SEP (p[1])
1001 && (p != nm || IS_DIRECTORY_SEP (p[2])))
1002 lose = 1;
1003 p++;
1005 if (!lose)
1007 #ifdef DOS_NT
1008 /* Make sure directories are all separated with /, but
1009 avoid allocation of a new string when not required. */
1010 dostounix_filename (nm);
1011 #ifdef WINDOWSNT
1012 if (IS_DIRECTORY_SEP (nm[1]))
1014 if (strcmp (nm, SSDATA (name)) != 0)
1015 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1017 else
1018 #endif
1019 /* Drive must be set, so this is okay. */
1020 if (strcmp (nm - 2, SSDATA (name)) != 0)
1022 name = make_specified_string (nm, -1, p - nm, multibyte);
1023 char temp[] = { DRIVE_LETTER (drive), ':', 0 };
1024 AUTO_STRING_WITH_LEN (drive_prefix, temp, 2);
1025 name = concat2 (drive_prefix, name);
1027 #ifdef WINDOWSNT
1028 if (!NILP (Vw32_downcase_file_names))
1029 name = Fdowncase (name);
1030 #endif
1031 #else /* not DOS_NT */
1032 if (strcmp (nm, SSDATA (name)) != 0)
1033 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1034 #endif /* not DOS_NT */
1035 SAFE_FREE ();
1036 return name;
1040 /* At this point, nm might or might not be an absolute file name. We
1041 need to expand ~ or ~user if present, otherwise prefix nm with
1042 default_directory if nm is not absolute, and finally collapse /./
1043 and /foo/../ sequences.
1045 We set newdir to be the appropriate prefix if one is needed:
1046 - the relevant user directory if nm starts with ~ or ~user
1047 - the specified drive's working dir (DOS/NT only) if nm does not
1048 start with /
1049 - the value of default_directory.
1051 Note that these prefixes are not guaranteed to be absolute (except
1052 for the working dir of a drive). Therefore, to ensure we always
1053 return an absolute name, if the final prefix is not absolute we
1054 append it to the current working directory. */
1056 newdir = newdirlim = 0;
1058 if (nm[0] == '~') /* prefix ~ */
1060 if (IS_DIRECTORY_SEP (nm[1])
1061 || nm[1] == 0) /* ~ by itself */
1063 Lisp_Object tem;
1065 if (!(newdir = egetenv ("HOME")))
1066 newdir = newdirlim = "";
1067 nm++;
1068 /* `egetenv' may return a unibyte string, which will bite us since
1069 we expect the directory to be multibyte. */
1070 #ifdef WINDOWSNT
1071 if (newdir[0])
1073 char newdir_utf8[MAX_UTF8_PATH];
1075 filename_from_ansi (newdir, newdir_utf8);
1076 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1078 else
1079 #endif
1080 tem = build_string (newdir);
1081 newdirlim = newdir + SBYTES (tem);
1082 if (multibyte && !STRING_MULTIBYTE (tem))
1084 hdir = DECODE_FILE (tem);
1085 newdir = SSDATA (hdir);
1086 newdirlim = newdir + SBYTES (hdir);
1088 #ifdef DOS_NT
1089 collapse_newdir = false;
1090 #endif
1092 else /* ~user/filename */
1094 char *o, *p;
1095 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1096 continue;
1097 o = SAFE_ALLOCA (p - nm + 1);
1098 memcpy (o, nm, p - nm);
1099 o[p - nm] = 0;
1101 block_input ();
1102 pw = getpwnam (o + 1);
1103 unblock_input ();
1104 if (pw)
1106 Lisp_Object tem;
1108 newdir = pw->pw_dir;
1109 /* `getpwnam' may return a unibyte string, which will
1110 bite us since we expect the directory to be
1111 multibyte. */
1112 tem = make_unibyte_string (newdir, strlen (newdir));
1113 newdirlim = newdir + SBYTES (tem);
1114 if (multibyte && !STRING_MULTIBYTE (tem))
1116 hdir = DECODE_FILE (tem);
1117 newdir = SSDATA (hdir);
1118 newdirlim = newdir + SBYTES (hdir);
1120 nm = p;
1121 #ifdef DOS_NT
1122 collapse_newdir = false;
1123 #endif
1126 /* If we don't find a user of that name, leave the name
1127 unchanged; don't move nm forward to p. */
1131 #ifdef DOS_NT
1132 /* On DOS and Windows, nm is absolute if a drive name was specified;
1133 use the drive's current directory as the prefix if needed. */
1134 if (!newdir && drive)
1136 /* Get default directory if needed to make nm absolute. */
1137 char *adir = NULL;
1138 if (!IS_DIRECTORY_SEP (nm[0]))
1140 adir = alloca (MAXPATHLEN + 1);
1141 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1142 adir = NULL;
1143 else if (multibyte)
1145 Lisp_Object tem = build_string (adir);
1147 tem = DECODE_FILE (tem);
1148 newdirlim = adir + SBYTES (tem);
1149 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1151 else
1152 newdirlim = adir + strlen (adir);
1154 if (!adir)
1156 /* Either nm starts with /, or drive isn't mounted. */
1157 adir = alloca (4);
1158 adir[0] = DRIVE_LETTER (drive);
1159 adir[1] = ':';
1160 adir[2] = '/';
1161 adir[3] = 0;
1162 newdirlim = adir + 3;
1164 newdir = adir;
1166 #endif /* DOS_NT */
1168 /* Finally, if no prefix has been specified and nm is not absolute,
1169 then it must be expanded relative to default_directory. */
1171 if (1
1172 #ifndef DOS_NT
1173 /* /... alone is not absolute on DOS and Windows. */
1174 && !IS_DIRECTORY_SEP (nm[0])
1175 #endif
1176 #ifdef WINDOWSNT
1177 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1178 && !IS_DIRECTORY_SEP (nm[2]))
1179 #endif
1180 && !newdir)
1182 newdir = SSDATA (default_directory);
1183 newdirlim = newdir + SBYTES (default_directory);
1184 #ifdef DOS_NT
1185 /* Note if special escape prefix is present, but remove for now. */
1186 if (newdir[0] == '/' && newdir[1] == ':')
1188 is_escaped = 1;
1189 newdir += 2;
1191 #endif
1194 #ifdef DOS_NT
1195 if (newdir)
1197 /* First ensure newdir is an absolute name. */
1198 if (
1199 /* Detect MSDOS file names with drive specifiers. */
1200 ! (IS_DRIVE (newdir[0])
1201 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1202 #ifdef WINDOWSNT
1203 /* Detect Windows file names in UNC format. */
1204 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1205 && !IS_DIRECTORY_SEP (newdir[2]))
1206 #endif
1209 /* Effectively, let newdir be (expand-file-name newdir cwd).
1210 Because of the admonition against calling expand-file-name
1211 when we have pointers into lisp strings, we accomplish this
1212 indirectly by prepending newdir to nm if necessary, and using
1213 cwd (or the wd of newdir's drive) as the new newdir. */
1214 char *adir;
1215 #ifdef WINDOWSNT
1216 const int adir_size = MAX_UTF8_PATH;
1217 #else
1218 const int adir_size = MAXPATHLEN + 1;
1219 #endif
1221 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1223 drive = (unsigned char) newdir[0];
1224 newdir += 2;
1226 if (!IS_DIRECTORY_SEP (nm[0]))
1228 ptrdiff_t nmlen = nmlim - nm;
1229 ptrdiff_t newdirlen = newdirlim - newdir;
1230 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1231 + nmlen + 1);
1232 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1233 multibyte);
1234 memcpy (tmp + dlen, nm, nmlen + 1);
1235 nm = tmp;
1236 nmlim = nm + dlen + nmlen;
1238 adir = alloca (adir_size);
1239 if (drive)
1241 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1242 strcpy (adir, "/");
1244 else
1245 getcwd (adir, adir_size);
1246 if (multibyte)
1248 Lisp_Object tem = build_string (adir);
1250 tem = DECODE_FILE (tem);
1251 newdirlim = adir + SBYTES (tem);
1252 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1254 else
1255 newdirlim = adir + strlen (adir);
1256 newdir = adir;
1259 /* Strip off drive name from prefix, if present. */
1260 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1262 drive = newdir[0];
1263 newdir += 2;
1266 /* Keep only a prefix from newdir if nm starts with slash
1267 (//server/share for UNC, nothing otherwise). */
1268 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1270 #ifdef WINDOWSNT
1271 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1272 && !IS_DIRECTORY_SEP (newdir[2]))
1274 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1275 char *p = adir + 2;
1276 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1277 p++;
1278 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1279 *p = 0;
1280 newdir = adir;
1281 newdirlim = newdir + strlen (adir);
1283 else
1284 #endif
1285 newdir = newdirlim = "";
1288 #endif /* DOS_NT */
1290 /* Ignore any slash at the end of newdir, unless newdir is
1291 just "/" or "//". */
1292 length = newdirlim - newdir;
1293 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1294 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1295 length--;
1297 /* Now concatenate the directory and name to new space in the stack frame. */
1298 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1299 eassert (tlen > file_name_as_directory_slop + 1);
1300 #ifdef DOS_NT
1301 /* Reserve space for drive specifier and escape prefix, since either
1302 or both may need to be inserted. (The Microsoft x86 compiler
1303 produces incorrect code if the following two lines are combined.) */
1304 target = alloca (tlen + 4);
1305 target += 4;
1306 #else /* not DOS_NT */
1307 target = SAFE_ALLOCA (tlen);
1308 #endif /* not DOS_NT */
1309 *target = 0;
1310 nbytes = 0;
1312 if (newdir)
1314 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1316 #ifdef DOS_NT
1317 /* If newdir is effectively "C:/", then the drive letter will have
1318 been stripped and newdir will be "/". Concatenating with an
1319 absolute directory in nm produces "//", which will then be
1320 incorrectly treated as a network share. Ignore newdir in
1321 this case (keeping the drive letter). */
1322 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1323 && newdir[1] == '\0'))
1324 #endif
1326 memcpy (target, newdir, length);
1327 target[length] = 0;
1328 nbytes = length;
1331 else
1332 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1335 memcpy (target + nbytes, nm, nmlim - nm + 1);
1337 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1338 appear. */
1340 char *p = target;
1341 char *o = target;
1343 while (*p)
1345 if (!IS_DIRECTORY_SEP (*p))
1347 *o++ = *p++;
1349 else if (p[1] == '.'
1350 && (IS_DIRECTORY_SEP (p[2])
1351 || p[2] == 0))
1353 /* If "/." is the entire filename, keep the "/". Otherwise,
1354 just delete the whole "/.". */
1355 if (o == target && p[2] == '\0')
1356 *o++ = *p;
1357 p += 2;
1359 else if (p[1] == '.' && p[2] == '.'
1360 /* `/../' is the "superroot" on certain file systems.
1361 Turned off on DOS_NT systems because they have no
1362 "superroot" and because this causes us to produce
1363 file names like "d:/../foo" which fail file-related
1364 functions of the underlying OS. (To reproduce, try a
1365 long series of "../../" in default_directory, longer
1366 than the number of levels from the root.) */
1367 #ifndef DOS_NT
1368 && o != target
1369 #endif
1370 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1372 #ifdef WINDOWSNT
1373 char *prev_o = o;
1374 #endif
1375 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1376 continue;
1377 #ifdef WINDOWSNT
1378 /* Don't go below server level in UNC filenames. */
1379 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1380 && IS_DIRECTORY_SEP (*target))
1381 o = prev_o;
1382 else
1383 #endif
1384 /* Keep initial / only if this is the whole name. */
1385 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1386 ++o;
1387 p += 3;
1389 else if (IS_DIRECTORY_SEP (p[1])
1390 && (p != target || IS_DIRECTORY_SEP (p[2])))
1391 /* Collapse multiple "/", except leave leading "//" alone. */
1392 p++;
1393 else
1395 *o++ = *p++;
1399 #ifdef DOS_NT
1400 /* At last, set drive name. */
1401 #ifdef WINDOWSNT
1402 /* Except for network file name. */
1403 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1404 #endif /* WINDOWSNT */
1406 if (!drive) emacs_abort ();
1407 target -= 2;
1408 target[0] = DRIVE_LETTER (drive);
1409 target[1] = ':';
1411 /* Reinsert the escape prefix if required. */
1412 if (is_escaped)
1414 target -= 2;
1415 target[0] = '/';
1416 target[1] = ':';
1418 result = make_specified_string (target, -1, o - target, multibyte);
1419 dostounix_filename (SSDATA (result));
1420 #ifdef WINDOWSNT
1421 if (!NILP (Vw32_downcase_file_names))
1422 result = Fdowncase (result);
1423 #endif
1424 #else /* !DOS_NT */
1425 result = make_specified_string (target, -1, o - target, multibyte);
1426 #endif /* !DOS_NT */
1429 /* Again look to see if the file name has special constructs in it
1430 and perhaps call the corresponding file handler. This is needed
1431 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1432 the ".." component gives us "/user@host:/bar/../baz" which needs
1433 to be expanded again. */
1434 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1435 if (!NILP (handler))
1437 handled_name = call3 (handler, Qexpand_file_name,
1438 result, default_directory);
1439 if (! STRINGP (handled_name))
1440 error ("Invalid handler in `file-name-handler-alist'");
1441 result = handled_name;
1444 SAFE_FREE ();
1445 return result;
1448 #if 0
1449 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1450 This is the old version of expand-file-name, before it was thoroughly
1451 rewritten for Emacs 10.31. We leave this version here commented-out,
1452 because the code is very complex and likely to have subtle bugs. If
1453 bugs _are_ found, it might be of interest to look at the old code and
1454 see what did it do in the relevant situation.
1456 Don't remove this code: it's true that it will be accessible
1457 from the repository, but a few years from deletion, people will
1458 forget it is there. */
1460 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1461 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1462 "Convert FILENAME to absolute, and canonicalize it.\n\
1463 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1464 \(does not start with slash); if DEFAULT is nil or missing,\n\
1465 the current buffer's value of default-directory is used.\n\
1466 Filenames containing `.' or `..' as components are simplified;\n\
1467 initial `~/' expands to your home directory.\n\
1468 See also the function `substitute-in-file-name'.")
1469 (name, defalt)
1470 Lisp_Object name, defalt;
1472 unsigned char *nm;
1474 register unsigned char *newdir, *p, *o;
1475 ptrdiff_t tlen;
1476 unsigned char *target;
1477 struct passwd *pw;
1479 CHECK_STRING (name);
1480 nm = SDATA (name);
1482 /* If nm is absolute, flush ...// and detect /./ and /../.
1483 If no /./ or /../ we can return right away. */
1484 if (nm[0] == '/')
1486 bool lose = 0;
1487 p = nm;
1488 while (*p)
1490 if (p[0] == '/' && p[1] == '/')
1491 nm = p + 1;
1492 if (p[0] == '/' && p[1] == '~')
1493 nm = p + 1, lose = 1;
1494 if (p[0] == '/' && p[1] == '.'
1495 && (p[2] == '/' || p[2] == 0
1496 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1497 lose = 1;
1498 p++;
1500 if (!lose)
1502 if (nm == SDATA (name))
1503 return name;
1504 return build_string (nm);
1508 /* Now determine directory to start with and put it in NEWDIR. */
1510 newdir = 0;
1512 if (nm[0] == '~') /* prefix ~ */
1513 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1515 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1516 newdir = (unsigned char *) "";
1517 nm++;
1519 else /* ~user/filename */
1521 /* Get past ~ to user. */
1522 unsigned char *user = nm + 1;
1523 /* Find end of name. */
1524 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1525 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1526 /* Copy the user name into temp storage. */
1527 o = alloca (len + 1);
1528 memcpy (o, user, len);
1529 o[len] = 0;
1531 /* Look up the user name. */
1532 block_input ();
1533 pw = (struct passwd *) getpwnam (o + 1);
1534 unblock_input ();
1535 if (!pw)
1536 error ("\"%s\" isn't a registered user", o + 1);
1538 newdir = (unsigned char *) pw->pw_dir;
1540 /* Discard the user name from NM. */
1541 nm += len;
1544 if (nm[0] != '/' && !newdir)
1546 if (NILP (defalt))
1547 defalt = current_buffer->directory;
1548 CHECK_STRING (defalt);
1549 newdir = SDATA (defalt);
1552 /* Now concatenate the directory and name to new space in the stack frame. */
1554 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1555 target = alloca (tlen);
1556 *target = 0;
1558 if (newdir)
1560 if (nm[0] == 0 || nm[0] == '/')
1561 strcpy (target, newdir);
1562 else
1563 file_name_as_directory (target, newdir);
1566 strcat (target, nm);
1568 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1570 p = target;
1571 o = target;
1573 while (*p)
1575 if (*p != '/')
1577 *o++ = *p++;
1579 else if (!strncmp (p, "//", 2)
1582 o = target;
1583 p++;
1585 else if (p[0] == '/' && p[1] == '.'
1586 && (p[2] == '/' || p[2] == 0))
1587 p += 2;
1588 else if (!strncmp (p, "/..", 3)
1589 /* `/../' is the "superroot" on certain file systems. */
1590 && o != target
1591 && (p[3] == '/' || p[3] == 0))
1593 while (o != target && *--o != '/')
1595 if (o == target && *o == '/')
1596 ++o;
1597 p += 3;
1599 else
1601 *o++ = *p++;
1605 return make_string (target, o - target);
1607 #endif
1609 /* If /~ or // appears, discard everything through first slash. */
1610 static bool
1611 file_name_absolute_p (const char *filename)
1613 return
1614 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1615 #ifdef DOS_NT
1616 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1617 && IS_DIRECTORY_SEP (filename[2]))
1618 #endif
1622 static char *
1623 search_embedded_absfilename (char *nm, char *endp)
1625 char *p, *s;
1627 for (p = nm + 1; p < endp; p++)
1629 if (IS_DIRECTORY_SEP (p[-1])
1630 && file_name_absolute_p (p)
1631 #if defined (WINDOWSNT) || defined (CYGWIN)
1632 /* // at start of file name is meaningful in Apollo,
1633 WindowsNT and Cygwin systems. */
1634 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1635 #endif /* not (WINDOWSNT || CYGWIN) */
1638 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1639 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1641 USE_SAFE_ALLOCA;
1642 char *o = SAFE_ALLOCA (s - p + 1);
1643 struct passwd *pw;
1644 memcpy (o, p, s - p);
1645 o [s - p] = 0;
1647 /* If we have ~user and `user' exists, discard
1648 everything up to ~. But if `user' does not exist, leave
1649 ~user alone, it might be a literal file name. */
1650 block_input ();
1651 pw = getpwnam (o + 1);
1652 unblock_input ();
1653 SAFE_FREE ();
1654 if (pw)
1655 return p;
1657 else
1658 return p;
1661 return NULL;
1664 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1665 Ssubstitute_in_file_name, 1, 1, 0,
1666 doc: /* Substitute environment variables referred to in FILENAME.
1667 `$FOO' where FOO is an environment variable name means to substitute
1668 the value of that variable. The variable name should be terminated
1669 with a character not a letter, digit or underscore; otherwise, enclose
1670 the entire variable name in braces.
1672 If `/~' appears, all of FILENAME through that `/' is discarded.
1673 If `//' appears, everything up to and including the first of
1674 those `/' is discarded. */)
1675 (Lisp_Object filename)
1677 char *nm, *p, *x, *endp;
1678 bool substituted = false;
1679 bool multibyte;
1680 char *xnm;
1681 Lisp_Object handler;
1683 CHECK_STRING (filename);
1685 multibyte = STRING_MULTIBYTE (filename);
1687 /* If the file name has special constructs in it,
1688 call the corresponding file handler. */
1689 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1690 if (!NILP (handler))
1692 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1693 filename);
1694 if (STRINGP (handled_name))
1695 return handled_name;
1696 error ("Invalid handler in `file-name-handler-alist'");
1699 /* Always work on a copy of the string, in case GC happens during
1700 decode of environment variables, causing the original Lisp_String
1701 data to be relocated. */
1702 USE_SAFE_ALLOCA;
1703 SAFE_ALLOCA_STRING (nm, filename);
1705 #ifdef DOS_NT
1706 dostounix_filename (nm);
1707 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1708 #endif
1709 endp = nm + SBYTES (filename);
1711 /* If /~ or // appears, discard everything through first slash. */
1712 p = search_embedded_absfilename (nm, endp);
1713 if (p)
1714 /* Start over with the new string, so we check the file-name-handler
1715 again. Important with filenames like "/home/foo//:/hello///there"
1716 which would substitute to "/:/hello///there" rather than "/there". */
1718 Lisp_Object result
1719 = (Fsubstitute_in_file_name
1720 (make_specified_string (p, -1, endp - p, multibyte)));
1721 SAFE_FREE ();
1722 return result;
1725 /* See if any variables are substituted into the string. */
1727 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1729 Lisp_Object name
1730 = (!substituted ? filename
1731 : make_specified_string (nm, -1, endp - nm, multibyte));
1732 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1733 CHECK_STRING (tmp);
1734 if (!EQ (tmp, name))
1735 substituted = true;
1736 filename = tmp;
1739 if (!substituted)
1741 #ifdef WINDOWSNT
1742 if (!NILP (Vw32_downcase_file_names))
1743 filename = Fdowncase (filename);
1744 #endif
1745 SAFE_FREE ();
1746 return filename;
1749 xnm = SSDATA (filename);
1750 x = xnm + SBYTES (filename);
1752 /* If /~ or // appears, discard everything through first slash. */
1753 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1754 /* This time we do not start over because we've already expanded envvars
1755 and replaced $$ with $. Maybe we should start over as well, but we'd
1756 need to quote some $ to $$ first. */
1757 xnm = p;
1759 #ifdef WINDOWSNT
1760 if (!NILP (Vw32_downcase_file_names))
1762 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1764 filename = Fdowncase (xname);
1766 else
1767 #endif
1768 if (xnm != SSDATA (filename))
1769 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1770 SAFE_FREE ();
1771 return filename;
1774 /* A slightly faster and more convenient way to get
1775 (directory-file-name (expand-file-name FOO)). */
1777 Lisp_Object
1778 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1780 register Lisp_Object absname;
1782 absname = Fexpand_file_name (filename, defdir);
1784 /* Remove final slash, if any (unless this is the root dir).
1785 stat behaves differently depending! */
1786 if (SCHARS (absname) > 1
1787 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1788 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1789 /* We cannot take shortcuts; they might be wrong for magic file names. */
1790 absname = Fdirectory_file_name (absname);
1791 return absname;
1794 /* Signal an error if the file ABSNAME already exists.
1795 If KNOWN_TO_EXIST, the file is known to exist.
1796 QUERYSTRING is a name for the action that is being considered
1797 to alter the file.
1798 If INTERACTIVE, ask the user whether to proceed,
1799 and bypass the error if the user says to go ahead.
1800 If QUICK, ask for y or n, not yes or no. */
1802 static void
1803 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1804 const char *querystring, bool interactive,
1805 bool quick)
1807 Lisp_Object tem, encoded_filename;
1808 struct stat statbuf;
1810 encoded_filename = ENCODE_FILE (absname);
1812 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1814 if (S_ISDIR (statbuf.st_mode))
1815 xsignal2 (Qfile_error,
1816 build_string ("File is a directory"), absname);
1817 known_to_exist = true;
1820 if (known_to_exist)
1822 if (! interactive)
1823 xsignal2 (Qfile_already_exists,
1824 build_string ("File already exists"), absname);
1825 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1826 tem = CALLN (Fformat, format, absname, build_string (querystring));
1827 if (quick)
1828 tem = call1 (intern ("y-or-n-p"), tem);
1829 else
1830 tem = do_yes_or_no_p (tem);
1831 if (NILP (tem))
1832 xsignal2 (Qfile_already_exists,
1833 build_string ("File already exists"), absname);
1837 #ifndef WINDOWSNT
1838 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1839 static bool
1840 clone_file (int dest, int source)
1842 #ifdef FICLONE
1843 return ioctl (dest, FICLONE, source) == 0;
1844 #endif
1845 return false;
1847 #endif
1849 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1850 "fCopy file: \nGCopy %s to file: \np\nP",
1851 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1852 If NEWNAME names a directory, copy FILE there.
1854 This function always sets the file modes of the output file to match
1855 the input file.
1857 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1858 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1859 signal a `file-already-exists' error without overwriting. If
1860 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1861 about overwriting; this is what happens in interactive use with M-x.
1862 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1863 existing file.
1865 Fourth arg KEEP-TIME non-nil means give the output file the same
1866 last-modified time as the old one. (This works on only some systems.)
1868 A prefix arg makes KEEP-TIME non-nil.
1870 If PRESERVE-UID-GID is non-nil, we try to transfer the
1871 uid and gid of FILE to NEWNAME.
1873 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1874 this includes the file modes, along with ACL entries and SELinux
1875 context if present. Otherwise, if NEWNAME is created its file
1876 permission bits are those of FILE, masked by the default file
1877 permissions. */)
1878 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1879 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1880 Lisp_Object preserve_permissions)
1882 Lisp_Object handler;
1883 ptrdiff_t count = SPECPDL_INDEX ();
1884 Lisp_Object encoded_file, encoded_newname;
1885 #if HAVE_LIBSELINUX
1886 security_context_t con;
1887 int conlength = 0;
1888 #endif
1889 #ifdef WINDOWSNT
1890 int result;
1891 #else
1892 bool already_exists = false;
1893 mode_t new_mask;
1894 int ifd, ofd;
1895 struct stat st;
1896 #endif
1898 encoded_file = encoded_newname = Qnil;
1899 CHECK_STRING (file);
1900 CHECK_STRING (newname);
1902 if (!NILP (Ffile_directory_p (newname)))
1903 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1904 else
1905 newname = Fexpand_file_name (newname, Qnil);
1907 file = Fexpand_file_name (file, Qnil);
1909 /* If the input file name has special constructs in it,
1910 call the corresponding file handler. */
1911 handler = Ffind_file_name_handler (file, Qcopy_file);
1912 /* Likewise for output file name. */
1913 if (NILP (handler))
1914 handler = Ffind_file_name_handler (newname, Qcopy_file);
1915 if (!NILP (handler))
1916 return call7 (handler, Qcopy_file, file, newname,
1917 ok_if_already_exists, keep_time, preserve_uid_gid,
1918 preserve_permissions);
1920 encoded_file = ENCODE_FILE (file);
1921 encoded_newname = ENCODE_FILE (newname);
1923 #ifdef WINDOWSNT
1924 if (NILP (ok_if_already_exists)
1925 || INTEGERP (ok_if_already_exists))
1926 barf_or_query_if_file_exists (newname, false, "copy to it",
1927 INTEGERP (ok_if_already_exists), false);
1929 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1930 !NILP (keep_time), !NILP (preserve_uid_gid),
1931 !NILP (preserve_permissions));
1932 switch (result)
1934 case -1:
1935 report_file_error ("Copying file", list2 (file, newname));
1936 case -2:
1937 report_file_error ("Copying permissions from", file);
1938 case -3:
1939 xsignal2 (Qfile_date_error,
1940 build_string ("Resetting file times"), newname);
1941 case -4:
1942 report_file_error ("Copying permissions to", newname);
1944 #else /* not WINDOWSNT */
1945 immediate_quit = 1;
1946 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1947 immediate_quit = 0;
1949 if (ifd < 0)
1950 report_file_error ("Opening input file", file);
1952 record_unwind_protect_int (close_file_unwind, ifd);
1954 if (fstat (ifd, &st) != 0)
1955 report_file_error ("Input file status", file);
1957 if (!NILP (preserve_permissions))
1959 #if HAVE_LIBSELINUX
1960 if (is_selinux_enabled ())
1962 conlength = fgetfilecon (ifd, &con);
1963 if (conlength == -1)
1964 report_file_error ("Doing fgetfilecon", file);
1966 #endif
1969 /* We can copy only regular files. */
1970 if (!S_ISREG (st.st_mode))
1971 report_file_errno ("Non-regular file", file,
1972 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1974 #ifndef MSDOS
1975 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1976 #else
1977 new_mask = S_IREAD | S_IWRITE;
1978 #endif
1980 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1981 new_mask);
1982 if (ofd < 0 && errno == EEXIST)
1984 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1985 barf_or_query_if_file_exists (newname, true, "copy to it",
1986 INTEGERP (ok_if_already_exists), false);
1987 already_exists = true;
1988 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1990 if (ofd < 0)
1991 report_file_error ("Opening output file", newname);
1993 record_unwind_protect_int (close_file_unwind, ofd);
1995 off_t oldsize = 0, newsize;
1997 if (already_exists)
1999 struct stat out_st;
2000 if (fstat (ofd, &out_st) != 0)
2001 report_file_error ("Output file status", newname);
2002 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2003 report_file_errno ("Input and output files are the same",
2004 list2 (file, newname), 0);
2005 if (S_ISREG (out_st.st_mode))
2006 oldsize = out_st.st_size;
2009 immediate_quit = 1;
2010 QUIT;
2012 if (clone_file (ofd, ifd))
2013 newsize = st.st_size;
2014 else
2016 char buf[MAX_ALLOCA];
2017 ptrdiff_t n;
2018 for (newsize = 0; 0 < (n = emacs_read (ifd, buf, sizeof buf));
2019 newsize += n)
2020 if (emacs_write_sig (ofd, buf, n) != n)
2021 report_file_error ("Write error", newname);
2022 if (n < 0)
2023 report_file_error ("Read error", file);
2026 /* Truncate any existing output file after writing the data. This
2027 is more likely to work than truncation before writing, if the
2028 file system is out of space or the user is over disk quota. */
2029 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
2030 report_file_error ("Truncating output file", newname);
2032 immediate_quit = 0;
2034 #ifndef MSDOS
2035 /* Preserve the original file permissions, and if requested, also its
2036 owner and group. */
2038 mode_t preserved_permissions = st.st_mode & 07777;
2039 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2040 if (!NILP (preserve_uid_gid))
2042 /* Attempt to change owner and group. If that doesn't work
2043 attempt to change just the group, as that is sometimes allowed.
2044 Adjust the mode mask to eliminate setuid or setgid bits
2045 or group permissions bits that are inappropriate if the
2046 owner or group are wrong. */
2047 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2049 if (fchown (ofd, -1, st.st_gid) == 0)
2050 preserved_permissions &= ~04000;
2051 else
2053 preserved_permissions &= ~06000;
2055 /* Copy the other bits to the group bits, since the
2056 group is wrong. */
2057 preserved_permissions &= ~070;
2058 preserved_permissions |= (preserved_permissions & 7) << 3;
2059 default_permissions &= ~070;
2060 default_permissions |= (default_permissions & 7) << 3;
2065 switch (!NILP (preserve_permissions)
2066 ? qcopy_acl (SSDATA (encoded_file), ifd,
2067 SSDATA (encoded_newname), ofd,
2068 preserved_permissions)
2069 : (already_exists
2070 || (new_mask & ~realmask) == default_permissions)
2072 : fchmod (ofd, default_permissions))
2074 case -2: report_file_error ("Copying permissions from", file);
2075 case -1: report_file_error ("Copying permissions to", newname);
2078 #endif /* not MSDOS */
2080 #if HAVE_LIBSELINUX
2081 if (conlength > 0)
2083 /* Set the modified context back to the file. */
2084 bool fail = fsetfilecon (ofd, con) != 0;
2085 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2086 if (fail && errno != ENOTSUP)
2087 report_file_error ("Doing fsetfilecon", newname);
2089 freecon (con);
2091 #endif
2093 if (!NILP (keep_time))
2095 struct timespec atime = get_stat_atime (&st);
2096 struct timespec mtime = get_stat_mtime (&st);
2097 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2098 xsignal2 (Qfile_date_error,
2099 build_string ("Cannot set file date"), newname);
2102 if (emacs_close (ofd) < 0)
2103 report_file_error ("Write error", newname);
2105 emacs_close (ifd);
2107 #ifdef MSDOS
2108 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2109 and if it can't, it tells so. Otherwise, under MSDOS we usually
2110 get only the READ bit, which will make the copied file read-only,
2111 so it's better not to chmod at all. */
2112 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2113 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2114 #endif /* MSDOS */
2115 #endif /* not WINDOWSNT */
2117 /* Discard the unwind protects. */
2118 specpdl_ptr = specpdl + count;
2120 return Qnil;
2123 DEFUN ("make-directory-internal", Fmake_directory_internal,
2124 Smake_directory_internal, 1, 1, 0,
2125 doc: /* Create a new directory named DIRECTORY. */)
2126 (Lisp_Object directory)
2128 const char *dir;
2129 Lisp_Object handler;
2130 Lisp_Object encoded_dir;
2132 CHECK_STRING (directory);
2133 directory = Fexpand_file_name (directory, Qnil);
2135 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2136 if (!NILP (handler))
2137 return call2 (handler, Qmake_directory_internal, directory);
2139 encoded_dir = ENCODE_FILE (directory);
2141 dir = SSDATA (encoded_dir);
2143 #ifdef WINDOWSNT
2144 if (mkdir (dir) != 0)
2145 #else
2146 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2147 #endif
2148 report_file_error ("Creating directory", directory);
2150 return Qnil;
2153 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2154 Sdelete_directory_internal, 1, 1, 0,
2155 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2156 (Lisp_Object directory)
2158 const char *dir;
2159 Lisp_Object encoded_dir;
2161 CHECK_STRING (directory);
2162 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2163 encoded_dir = ENCODE_FILE (directory);
2164 dir = SSDATA (encoded_dir);
2166 if (rmdir (dir) != 0)
2167 report_file_error ("Removing directory", directory);
2169 return Qnil;
2172 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2173 "(list (read-file-name \
2174 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2175 \"Move file to trash: \" \"Delete file: \") \
2176 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2177 (null current-prefix-arg))",
2178 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2179 If file has multiple names, it continues to exist with the other names.
2180 TRASH non-nil means to trash the file instead of deleting, provided
2181 `delete-by-moving-to-trash' is non-nil.
2183 When called interactively, TRASH is t if no prefix argument is given.
2184 With a prefix argument, TRASH is nil. */)
2185 (Lisp_Object filename, Lisp_Object trash)
2187 Lisp_Object handler;
2188 Lisp_Object encoded_file;
2190 if (!NILP (Ffile_directory_p (filename))
2191 && NILP (Ffile_symlink_p (filename)))
2192 xsignal2 (Qfile_error,
2193 build_string ("Removing old name: is a directory"),
2194 filename);
2195 filename = Fexpand_file_name (filename, Qnil);
2197 handler = Ffind_file_name_handler (filename, Qdelete_file);
2198 if (!NILP (handler))
2199 return call3 (handler, Qdelete_file, filename, trash);
2201 if (delete_by_moving_to_trash && !NILP (trash))
2202 return call1 (Qmove_file_to_trash, filename);
2204 encoded_file = ENCODE_FILE (filename);
2206 if (unlink (SSDATA (encoded_file)) < 0)
2207 report_file_error ("Removing old name", filename);
2208 return Qnil;
2211 static Lisp_Object
2212 internal_delete_file_1 (Lisp_Object ignore)
2214 return Qt;
2217 /* Delete file FILENAME, returning true if successful.
2218 This ignores `delete-by-moving-to-trash'. */
2220 bool
2221 internal_delete_file (Lisp_Object filename)
2223 Lisp_Object tem;
2225 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2226 Qt, internal_delete_file_1);
2227 return NILP (tem);
2230 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2231 "fRename file: \nGRename %s to file: \np",
2232 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2233 If file has names other than FILE, it continues to have those names.
2234 Signals a `file-already-exists' error if a file NEWNAME already exists
2235 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2236 A number as third arg means request confirmation if NEWNAME already exists.
2237 This is what happens in interactive use with M-x. */)
2238 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2240 Lisp_Object handler;
2241 Lisp_Object encoded_file, encoded_newname, symlink_target;
2243 symlink_target = encoded_file = encoded_newname = Qnil;
2244 CHECK_STRING (file);
2245 CHECK_STRING (newname);
2246 file = Fexpand_file_name (file, Qnil);
2248 if ((!NILP (Ffile_directory_p (newname)))
2249 #ifdef DOS_NT
2250 /* If the file names are identical but for the case,
2251 don't attempt to move directory to itself. */
2252 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2253 #endif
2256 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2257 ? file : Fdirectory_file_name (file));
2258 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2260 else
2261 newname = Fexpand_file_name (newname, Qnil);
2263 /* If the file name has special constructs in it,
2264 call the corresponding file handler. */
2265 handler = Ffind_file_name_handler (file, Qrename_file);
2266 if (NILP (handler))
2267 handler = Ffind_file_name_handler (newname, Qrename_file);
2268 if (!NILP (handler))
2269 return call4 (handler, Qrename_file,
2270 file, newname, ok_if_already_exists);
2272 encoded_file = ENCODE_FILE (file);
2273 encoded_newname = ENCODE_FILE (newname);
2275 #ifdef DOS_NT
2276 /* If the file names are identical but for the case, don't ask for
2277 confirmation: they simply want to change the letter-case of the
2278 file name. */
2279 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2280 #endif
2281 if (NILP (ok_if_already_exists)
2282 || INTEGERP (ok_if_already_exists))
2283 barf_or_query_if_file_exists (newname, false, "rename to it",
2284 INTEGERP (ok_if_already_exists), false);
2285 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2287 int rename_errno = errno;
2288 if (rename_errno == EXDEV)
2290 ptrdiff_t count;
2291 symlink_target = Ffile_symlink_p (file);
2292 if (! NILP (symlink_target))
2293 Fmake_symbolic_link (symlink_target, newname,
2294 NILP (ok_if_already_exists) ? Qnil : Qt);
2295 else if (!NILP (Ffile_directory_p (file)))
2296 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2297 else
2298 /* We have already prompted if it was an integer, so don't
2299 have copy-file prompt again. */
2300 Fcopy_file (file, newname,
2301 NILP (ok_if_already_exists) ? Qnil : Qt,
2302 Qt, Qt, Qt);
2304 count = SPECPDL_INDEX ();
2305 specbind (Qdelete_by_moving_to_trash, Qnil);
2307 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2308 call2 (Qdelete_directory, file, Qt);
2309 else
2310 Fdelete_file (file, Qnil);
2311 unbind_to (count, Qnil);
2313 else
2314 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2317 return Qnil;
2320 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2321 "fAdd name to file: \nGName to add to %s: \np",
2322 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2323 Signals a `file-already-exists' error if a file NEWNAME already exists
2324 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2325 A number as third arg means request confirmation if NEWNAME already exists.
2326 This is what happens in interactive use with M-x. */)
2327 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2329 Lisp_Object handler;
2330 Lisp_Object encoded_file, encoded_newname;
2332 encoded_file = encoded_newname = Qnil;
2333 CHECK_STRING (file);
2334 CHECK_STRING (newname);
2335 file = Fexpand_file_name (file, Qnil);
2337 if (!NILP (Ffile_directory_p (newname)))
2338 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2339 else
2340 newname = Fexpand_file_name (newname, Qnil);
2342 /* If the file name has special constructs in it,
2343 call the corresponding file handler. */
2344 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2345 if (!NILP (handler))
2346 return call4 (handler, Qadd_name_to_file, file,
2347 newname, ok_if_already_exists);
2349 /* If the new name has special constructs in it,
2350 call the corresponding file handler. */
2351 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2352 if (!NILP (handler))
2353 return call4 (handler, Qadd_name_to_file, file,
2354 newname, ok_if_already_exists);
2356 encoded_file = ENCODE_FILE (file);
2357 encoded_newname = ENCODE_FILE (newname);
2359 if (NILP (ok_if_already_exists)
2360 || INTEGERP (ok_if_already_exists))
2361 barf_or_query_if_file_exists (newname, false, "make it a new name",
2362 INTEGERP (ok_if_already_exists), false);
2364 unlink (SSDATA (newname));
2365 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2367 int link_errno = errno;
2368 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2371 return Qnil;
2374 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2375 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2376 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2377 Both args must be strings.
2378 Signals a `file-already-exists' error if a file LINKNAME already exists
2379 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2380 A number as third arg means request confirmation if LINKNAME already exists.
2381 This happens for interactive use with M-x. */)
2382 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2384 Lisp_Object handler;
2385 Lisp_Object encoded_target, encoded_linkname;
2387 encoded_target = encoded_linkname = Qnil;
2388 CHECK_STRING (target);
2389 CHECK_STRING (linkname);
2390 /* If the link target has a ~, we must expand it to get
2391 a truly valid file name. Otherwise, do not expand;
2392 we want to permit links to relative file names. */
2393 if (SREF (target, 0) == '~')
2394 target = Fexpand_file_name (target, Qnil);
2396 if (!NILP (Ffile_directory_p (linkname)))
2397 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2398 else
2399 linkname = Fexpand_file_name (linkname, Qnil);
2401 /* If the file name has special constructs in it,
2402 call the corresponding file handler. */
2403 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2404 if (!NILP (handler))
2405 return call4 (handler, Qmake_symbolic_link, target,
2406 linkname, ok_if_already_exists);
2408 /* If the new link name has special constructs in it,
2409 call the corresponding file handler. */
2410 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2411 if (!NILP (handler))
2412 return call4 (handler, Qmake_symbolic_link, target,
2413 linkname, ok_if_already_exists);
2415 encoded_target = ENCODE_FILE (target);
2416 encoded_linkname = ENCODE_FILE (linkname);
2418 if (NILP (ok_if_already_exists)
2419 || INTEGERP (ok_if_already_exists))
2420 barf_or_query_if_file_exists (linkname, false, "make it a link",
2421 INTEGERP (ok_if_already_exists), false);
2422 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2424 /* If we didn't complain already, silently delete existing file. */
2425 int symlink_errno;
2426 if (errno == EEXIST)
2428 unlink (SSDATA (encoded_linkname));
2429 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2430 >= 0)
2431 return Qnil;
2433 if (errno == ENOSYS)
2434 xsignal1 (Qfile_error,
2435 build_string ("Symbolic links are not supported"));
2437 symlink_errno = errno;
2438 report_file_errno ("Making symbolic link", list2 (target, linkname),
2439 symlink_errno);
2442 return Qnil;
2446 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2447 1, 1, 0,
2448 doc: /* Return t if file FILENAME specifies an absolute file name.
2449 On Unix, this is a name starting with a `/' or a `~'. */)
2450 (Lisp_Object filename)
2452 CHECK_STRING (filename);
2453 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2456 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2457 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2458 See also `file-readable-p' and `file-attributes'.
2459 This returns nil for a symlink to a nonexistent file.
2460 Use `file-symlink-p' to test for such links. */)
2461 (Lisp_Object filename)
2463 Lisp_Object absname;
2464 Lisp_Object handler;
2466 CHECK_STRING (filename);
2467 absname = Fexpand_file_name (filename, Qnil);
2469 /* If the file name has special constructs in it,
2470 call the corresponding file handler. */
2471 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2472 if (!NILP (handler))
2474 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2475 errno = 0;
2476 return result;
2479 absname = ENCODE_FILE (absname);
2481 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2484 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2485 doc: /* Return t if FILENAME can be executed by you.
2486 For a directory, this means you can access files in that directory.
2487 \(It is generally better to use `file-accessible-directory-p' for that
2488 purpose, though.) */)
2489 (Lisp_Object filename)
2491 Lisp_Object absname;
2492 Lisp_Object handler;
2494 CHECK_STRING (filename);
2495 absname = Fexpand_file_name (filename, Qnil);
2497 /* If the file name has special constructs in it,
2498 call the corresponding file handler. */
2499 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2500 if (!NILP (handler))
2501 return call2 (handler, Qfile_executable_p, absname);
2503 absname = ENCODE_FILE (absname);
2505 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2508 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2509 doc: /* Return t if file FILENAME exists and you can read it.
2510 See also `file-exists-p' and `file-attributes'. */)
2511 (Lisp_Object filename)
2513 Lisp_Object absname;
2514 Lisp_Object handler;
2516 CHECK_STRING (filename);
2517 absname = Fexpand_file_name (filename, Qnil);
2519 /* If the file name has special constructs in it,
2520 call the corresponding file handler. */
2521 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2522 if (!NILP (handler))
2523 return call2 (handler, Qfile_readable_p, absname);
2525 absname = ENCODE_FILE (absname);
2526 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2527 ? Qt : Qnil);
2530 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2531 doc: /* Return t if file FILENAME can be written or created by you. */)
2532 (Lisp_Object filename)
2534 Lisp_Object absname, dir, encoded;
2535 Lisp_Object handler;
2537 CHECK_STRING (filename);
2538 absname = Fexpand_file_name (filename, Qnil);
2540 /* If the file name has special constructs in it,
2541 call the corresponding file handler. */
2542 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2543 if (!NILP (handler))
2544 return call2 (handler, Qfile_writable_p, absname);
2546 encoded = ENCODE_FILE (absname);
2547 if (check_writable (SSDATA (encoded), W_OK))
2548 return Qt;
2549 if (errno != ENOENT)
2550 return Qnil;
2552 dir = Ffile_name_directory (absname);
2553 eassert (!NILP (dir));
2554 #ifdef MSDOS
2555 dir = Fdirectory_file_name (dir);
2556 #endif /* MSDOS */
2558 dir = ENCODE_FILE (dir);
2559 #ifdef WINDOWSNT
2560 /* The read-only attribute of the parent directory doesn't affect
2561 whether a file or directory can be created within it. Some day we
2562 should check ACLs though, which do affect this. */
2563 return file_directory_p (SSDATA (dir)) ? Qt : Qnil;
2564 #else
2565 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2566 #endif
2569 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2570 doc: /* Access file FILENAME, and get an error if that does not work.
2571 The second argument STRING is used in the error message.
2572 If there is no error, returns nil. */)
2573 (Lisp_Object filename, Lisp_Object string)
2575 Lisp_Object handler, encoded_filename, absname;
2577 CHECK_STRING (filename);
2578 absname = Fexpand_file_name (filename, Qnil);
2580 CHECK_STRING (string);
2582 /* If the file name has special constructs in it,
2583 call the corresponding file handler. */
2584 handler = Ffind_file_name_handler (absname, Qaccess_file);
2585 if (!NILP (handler))
2586 return call3 (handler, Qaccess_file, absname, string);
2588 encoded_filename = ENCODE_FILE (absname);
2590 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2591 report_file_error (SSDATA (string), filename);
2593 return Qnil;
2596 /* Relative to directory FD, return the symbolic link value of FILENAME.
2597 On failure, return nil. */
2598 Lisp_Object
2599 emacs_readlinkat (int fd, char const *filename)
2601 static struct allocator const emacs_norealloc_allocator =
2602 { xmalloc, NULL, xfree, memory_full };
2603 Lisp_Object val;
2604 char readlink_buf[1024];
2605 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2606 &emacs_norealloc_allocator, readlinkat);
2607 if (!buf)
2608 return Qnil;
2610 val = build_unibyte_string (buf);
2611 if (buf[0] == '/' && strchr (buf, ':'))
2613 AUTO_STRING (slash_colon, "/:");
2614 val = concat2 (slash_colon, val);
2616 if (buf != readlink_buf)
2617 xfree (buf);
2618 val = DECODE_FILE (val);
2619 return val;
2622 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2623 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2624 The value is the link target, as a string.
2625 Otherwise it returns nil.
2627 This function does not check whether the link target exists. */)
2628 (Lisp_Object filename)
2630 Lisp_Object handler;
2632 CHECK_STRING (filename);
2633 filename = Fexpand_file_name (filename, Qnil);
2635 /* If the file name has special constructs in it,
2636 call the corresponding file handler. */
2637 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2638 if (!NILP (handler))
2639 return call2 (handler, Qfile_symlink_p, filename);
2641 filename = ENCODE_FILE (filename);
2643 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2646 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2647 doc: /* Return t if FILENAME names an existing directory.
2648 Symbolic links to directories count as directories.
2649 See `file-symlink-p' to distinguish symlinks. */)
2650 (Lisp_Object filename)
2652 Lisp_Object absname;
2653 Lisp_Object handler;
2655 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2657 /* If the file name has special constructs in it,
2658 call the corresponding file handler. */
2659 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2660 if (!NILP (handler))
2661 return call2 (handler, Qfile_directory_p, absname);
2663 absname = ENCODE_FILE (absname);
2665 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2668 /* Return true if FILE is a directory or a symlink to a directory. */
2669 bool
2670 file_directory_p (char const *file)
2672 #ifdef WINDOWSNT
2673 /* This is cheaper than 'stat'. */
2674 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2675 #else
2676 struct stat st;
2677 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2678 #endif
2681 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2682 Sfile_accessible_directory_p, 1, 1, 0,
2683 doc: /* Return t if FILENAME names a directory you can open.
2684 For the value to be t, FILENAME must specify the name of a directory
2685 as a file, and the directory must allow you to open files in it. In
2686 order to use a directory as a buffer's current directory, this
2687 predicate must return true. A directory name spec may be given
2688 instead; then the value is t if the directory so specified exists and
2689 really is a readable and searchable directory. */)
2690 (Lisp_Object filename)
2692 Lisp_Object absname;
2693 Lisp_Object handler;
2695 CHECK_STRING (filename);
2696 absname = Fexpand_file_name (filename, Qnil);
2698 /* If the file name has special constructs in it,
2699 call the corresponding file handler. */
2700 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2701 if (!NILP (handler))
2703 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2704 errno = 0;
2705 return r;
2708 absname = ENCODE_FILE (absname);
2709 return file_accessible_directory_p (absname) ? Qt : Qnil;
2712 /* If FILE is a searchable directory or a symlink to a
2713 searchable directory, return true. Otherwise return
2714 false and set errno to an error number. */
2715 bool
2716 file_accessible_directory_p (Lisp_Object file)
2718 #ifdef DOS_NT
2719 # ifdef WINDOWSNT
2720 /* We need a special-purpose test because (a) NTFS security data is
2721 not reflected in Posix-style mode bits, and (b) the trick with
2722 accessing "DIR/.", used below on Posix hosts, doesn't work on
2723 Windows, because "DIR/." is normalized to just "DIR" before
2724 hitting the disk. */
2725 return (SBYTES (file) == 0
2726 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2727 # else /* MSDOS */
2728 return file_directory_p (SSDATA (file));
2729 # endif /* MSDOS */
2730 #else /* !DOS_NT */
2731 /* On POSIXish platforms, use just one system call; this avoids a
2732 race and is typically faster. */
2733 const char *data = SSDATA (file);
2734 ptrdiff_t len = SBYTES (file);
2735 char const *dir;
2736 bool ok;
2737 int saved_errno;
2738 USE_SAFE_ALLOCA;
2740 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2741 There are three exceptions: "", "/", and "//". Leave "" alone,
2742 as it's invalid. Append only "." to the other two exceptions as
2743 "/" and "//" are distinct on some platforms, whereas "/", "///",
2744 "////", etc. are all equivalent. */
2745 if (! len)
2746 dir = data;
2747 else
2749 /* Just check for trailing '/' when deciding whether to append '/'.
2750 That's simpler than testing the two special cases "/" and "//",
2751 and it's a safe optimization here. */
2752 char *buf = SAFE_ALLOCA (len + 3);
2753 memcpy (buf, data, len);
2754 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2755 dir = buf;
2758 ok = check_existing (dir);
2759 saved_errno = errno;
2760 SAFE_FREE ();
2761 errno = saved_errno;
2762 return ok;
2763 #endif /* !DOS_NT */
2766 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2767 doc: /* Return t if FILENAME names a regular file.
2768 This is the sort of file that holds an ordinary stream of data bytes.
2769 Symbolic links to regular files count as regular files.
2770 See `file-symlink-p' to distinguish symlinks. */)
2771 (Lisp_Object filename)
2773 register Lisp_Object absname;
2774 struct stat st;
2775 Lisp_Object handler;
2777 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2779 /* If the file name has special constructs in it,
2780 call the corresponding file handler. */
2781 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2782 if (!NILP (handler))
2783 return call2 (handler, Qfile_regular_p, absname);
2785 absname = ENCODE_FILE (absname);
2787 #ifdef WINDOWSNT
2789 int result;
2790 Lisp_Object tem = Vw32_get_true_file_attributes;
2792 /* Tell stat to use expensive method to get accurate info. */
2793 Vw32_get_true_file_attributes = Qt;
2794 result = stat (SSDATA (absname), &st);
2795 Vw32_get_true_file_attributes = tem;
2797 if (result < 0)
2798 return Qnil;
2799 return S_ISREG (st.st_mode) ? Qt : Qnil;
2801 #else
2802 if (stat (SSDATA (absname), &st) < 0)
2803 return Qnil;
2804 return S_ISREG (st.st_mode) ? Qt : Qnil;
2805 #endif
2808 DEFUN ("file-selinux-context", Ffile_selinux_context,
2809 Sfile_selinux_context, 1, 1, 0,
2810 doc: /* Return SELinux context of file named FILENAME.
2811 The return value is a list (USER ROLE TYPE RANGE), where the list
2812 elements are strings naming the user, role, type, and range of the
2813 file's SELinux security context.
2815 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2816 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2817 (Lisp_Object filename)
2819 Lisp_Object absname;
2820 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2822 Lisp_Object handler;
2823 #if HAVE_LIBSELINUX
2824 security_context_t con;
2825 int conlength;
2826 context_t context;
2827 #endif
2829 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2831 /* If the file name has special constructs in it,
2832 call the corresponding file handler. */
2833 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2834 if (!NILP (handler))
2835 return call2 (handler, Qfile_selinux_context, absname);
2837 absname = ENCODE_FILE (absname);
2839 #if HAVE_LIBSELINUX
2840 if (is_selinux_enabled ())
2842 conlength = lgetfilecon (SSDATA (absname), &con);
2843 if (conlength > 0)
2845 context = context_new (con);
2846 if (context_user_get (context))
2847 user = build_string (context_user_get (context));
2848 if (context_role_get (context))
2849 role = build_string (context_role_get (context));
2850 if (context_type_get (context))
2851 type = build_string (context_type_get (context));
2852 if (context_range_get (context))
2853 range = build_string (context_range_get (context));
2854 context_free (context);
2855 freecon (con);
2858 #endif
2860 return list4 (user, role, type, range);
2863 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2864 Sset_file_selinux_context, 2, 2, 0,
2865 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2866 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2867 elements are strings naming the components of a SELinux context.
2869 Value is t if setting of SELinux context was successful, nil otherwise.
2871 This function does nothing and returns nil if SELinux is disabled,
2872 or if Emacs was not compiled with SELinux support. */)
2873 (Lisp_Object filename, Lisp_Object context)
2875 Lisp_Object absname;
2876 Lisp_Object handler;
2877 #if HAVE_LIBSELINUX
2878 Lisp_Object encoded_absname;
2879 Lisp_Object user = CAR_SAFE (context);
2880 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2881 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2882 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2883 security_context_t con;
2884 bool fail;
2885 int conlength;
2886 context_t parsed_con;
2887 #endif
2889 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2891 /* If the file name has special constructs in it,
2892 call the corresponding file handler. */
2893 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2894 if (!NILP (handler))
2895 return call3 (handler, Qset_file_selinux_context, absname, context);
2897 #if HAVE_LIBSELINUX
2898 if (is_selinux_enabled ())
2900 /* Get current file context. */
2901 encoded_absname = ENCODE_FILE (absname);
2902 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2903 if (conlength > 0)
2905 parsed_con = context_new (con);
2906 /* Change the parts defined in the parameter.*/
2907 if (STRINGP (user))
2909 if (context_user_set (parsed_con, SSDATA (user)))
2910 error ("Doing context_user_set");
2912 if (STRINGP (role))
2914 if (context_role_set (parsed_con, SSDATA (role)))
2915 error ("Doing context_role_set");
2917 if (STRINGP (type))
2919 if (context_type_set (parsed_con, SSDATA (type)))
2920 error ("Doing context_type_set");
2922 if (STRINGP (range))
2924 if (context_range_set (parsed_con, SSDATA (range)))
2925 error ("Doing context_range_set");
2928 /* Set the modified context back to the file. */
2929 fail = (lsetfilecon (SSDATA (encoded_absname),
2930 context_str (parsed_con))
2931 != 0);
2932 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2933 if (fail && errno != ENOTSUP)
2934 report_file_error ("Doing lsetfilecon", absname);
2936 context_free (parsed_con);
2937 freecon (con);
2938 return fail ? Qnil : Qt;
2940 else
2941 report_file_error ("Doing lgetfilecon", absname);
2943 #endif
2945 return Qnil;
2948 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2949 doc: /* Return ACL entries of file named FILENAME.
2950 The entries are returned in a format suitable for use in `set-file-acl'
2951 but is otherwise undocumented and subject to change.
2952 Return nil if file does not exist or is not accessible, or if Emacs
2953 was unable to determine the ACL entries. */)
2954 (Lisp_Object filename)
2956 #if USE_ACL
2957 Lisp_Object absname;
2958 Lisp_Object handler;
2959 # ifdef HAVE_ACL_SET_FILE
2960 acl_t acl;
2961 Lisp_Object acl_string;
2962 char *str;
2963 # ifndef HAVE_ACL_TYPE_EXTENDED
2964 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2965 # endif
2966 # endif
2968 absname = expand_and_dir_to_file (filename,
2969 BVAR (current_buffer, directory));
2971 /* If the file name has special constructs in it,
2972 call the corresponding file handler. */
2973 handler = Ffind_file_name_handler (absname, Qfile_acl);
2974 if (!NILP (handler))
2975 return call2 (handler, Qfile_acl, absname);
2977 # ifdef HAVE_ACL_SET_FILE
2978 absname = ENCODE_FILE (absname);
2980 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2981 if (acl == NULL)
2982 return Qnil;
2984 str = acl_to_text (acl, NULL);
2985 if (str == NULL)
2987 acl_free (acl);
2988 return Qnil;
2991 acl_string = build_string (str);
2992 acl_free (str);
2993 acl_free (acl);
2995 return acl_string;
2996 # endif
2997 #endif
2999 return Qnil;
3002 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3003 2, 2, 0,
3004 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3005 ACL-STRING should contain the textual representation of the ACL
3006 entries in a format suitable for the platform.
3008 Value is t if setting of ACL was successful, nil otherwise.
3010 Setting ACL for local files requires Emacs to be built with ACL
3011 support. */)
3012 (Lisp_Object filename, Lisp_Object acl_string)
3014 #if USE_ACL
3015 Lisp_Object absname;
3016 Lisp_Object handler;
3017 # ifdef HAVE_ACL_SET_FILE
3018 Lisp_Object encoded_absname;
3019 acl_t acl;
3020 bool fail;
3021 # endif
3023 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3025 /* If the file name has special constructs in it,
3026 call the corresponding file handler. */
3027 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3028 if (!NILP (handler))
3029 return call3 (handler, Qset_file_acl, absname, acl_string);
3031 # ifdef HAVE_ACL_SET_FILE
3032 if (STRINGP (acl_string))
3034 acl = acl_from_text (SSDATA (acl_string));
3035 if (acl == NULL)
3037 report_file_error ("Converting ACL", absname);
3038 return Qnil;
3041 encoded_absname = ENCODE_FILE (absname);
3043 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3044 acl)
3045 != 0);
3046 if (fail && acl_errno_valid (errno))
3047 report_file_error ("Setting ACL", absname);
3049 acl_free (acl);
3050 return fail ? Qnil : Qt;
3052 # endif
3053 #endif
3055 return Qnil;
3058 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3059 doc: /* Return mode bits of file named FILENAME, as an integer.
3060 Return nil, if file does not exist or is not accessible. */)
3061 (Lisp_Object filename)
3063 Lisp_Object absname;
3064 struct stat st;
3065 Lisp_Object handler;
3067 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3069 /* If the file name has special constructs in it,
3070 call the corresponding file handler. */
3071 handler = Ffind_file_name_handler (absname, Qfile_modes);
3072 if (!NILP (handler))
3073 return call2 (handler, Qfile_modes, absname);
3075 absname = ENCODE_FILE (absname);
3077 if (stat (SSDATA (absname), &st) < 0)
3078 return Qnil;
3080 return make_number (st.st_mode & 07777);
3083 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3084 "(let ((file (read-file-name \"File: \"))) \
3085 (list file (read-file-modes nil file)))",
3086 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3087 Only the 12 low bits of MODE are used.
3089 Interactively, mode bits are read by `read-file-modes', which accepts
3090 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3091 (Lisp_Object filename, Lisp_Object mode)
3093 Lisp_Object absname, encoded_absname;
3094 Lisp_Object handler;
3096 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3097 CHECK_NUMBER (mode);
3099 /* If the file name has special constructs in it,
3100 call the corresponding file handler. */
3101 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3102 if (!NILP (handler))
3103 return call3 (handler, Qset_file_modes, absname, mode);
3105 encoded_absname = ENCODE_FILE (absname);
3107 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3108 report_file_error ("Doing chmod", absname);
3110 return Qnil;
3113 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3114 doc: /* Set the file permission bits for newly created files.
3115 The argument MODE should be an integer; only the low 9 bits are used.
3116 This setting is inherited by subprocesses. */)
3117 (Lisp_Object mode)
3119 mode_t oldrealmask, oldumask, newumask;
3120 CHECK_NUMBER (mode);
3121 oldrealmask = realmask;
3122 newumask = ~ XINT (mode) & 0777;
3124 block_input ();
3125 realmask = newumask;
3126 oldumask = umask (newumask);
3127 unblock_input ();
3129 eassert (oldumask == oldrealmask);
3130 return Qnil;
3133 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3134 doc: /* Return the default file protection for created files.
3135 The value is an integer. */)
3136 (void)
3138 Lisp_Object value;
3139 XSETINT (value, (~ realmask) & 0777);
3140 return value;
3144 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3145 doc: /* Set times of file FILENAME to TIMESTAMP.
3146 Set both access and modification times.
3147 Return t on success, else nil.
3148 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3149 `current-time'. */)
3150 (Lisp_Object filename, Lisp_Object timestamp)
3152 Lisp_Object absname, encoded_absname;
3153 Lisp_Object handler;
3154 struct timespec t = lisp_time_argument (timestamp);
3156 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3158 /* If the file name has special constructs in it,
3159 call the corresponding file handler. */
3160 handler = Ffind_file_name_handler (absname, Qset_file_times);
3161 if (!NILP (handler))
3162 return call3 (handler, Qset_file_times, absname, timestamp);
3164 encoded_absname = ENCODE_FILE (absname);
3167 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3169 #ifdef MSDOS
3170 /* Setting times on a directory always fails. */
3171 if (file_directory_p (SSDATA (encoded_absname)))
3172 return Qnil;
3173 #endif
3174 report_file_error ("Setting file times", absname);
3178 return Qt;
3181 #ifdef HAVE_SYNC
3182 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3183 doc: /* Tell Unix to finish all pending disk updates. */)
3184 (void)
3186 sync ();
3187 return Qnil;
3190 #endif /* HAVE_SYNC */
3192 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3193 doc: /* Return t if file FILE1 is newer than file FILE2.
3194 If FILE1 does not exist, the answer is nil;
3195 otherwise, if FILE2 does not exist, the answer is t. */)
3196 (Lisp_Object file1, Lisp_Object file2)
3198 Lisp_Object absname1, absname2;
3199 struct stat st1, st2;
3200 Lisp_Object handler;
3202 CHECK_STRING (file1);
3203 CHECK_STRING (file2);
3205 absname1 = Qnil;
3206 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3207 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3209 /* If the file name has special constructs in it,
3210 call the corresponding file handler. */
3211 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3212 if (NILP (handler))
3213 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3214 if (!NILP (handler))
3215 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3217 absname1 = ENCODE_FILE (absname1);
3218 absname2 = ENCODE_FILE (absname2);
3220 if (stat (SSDATA (absname1), &st1) < 0)
3221 return Qnil;
3223 if (stat (SSDATA (absname2), &st2) < 0)
3224 return Qt;
3226 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3227 ? Qt : Qnil);
3230 #ifndef READ_BUF_SIZE
3231 #define READ_BUF_SIZE (64 << 10)
3232 #endif
3233 /* Some buffer offsets are stored in 'int' variables. */
3234 verify (READ_BUF_SIZE <= INT_MAX);
3236 /* This function is called after Lisp functions to decide a coding
3237 system are called, or when they cause an error. Before they are
3238 called, the current buffer is set unibyte and it contains only a
3239 newly inserted text (thus the buffer was empty before the
3240 insertion).
3242 The functions may set markers, overlays, text properties, or even
3243 alter the buffer contents, change the current buffer.
3245 Here, we reset all those changes by:
3246 o set back the current buffer.
3247 o move all markers and overlays to BEG.
3248 o remove all text properties.
3249 o set back the buffer multibyteness. */
3251 static void
3252 decide_coding_unwind (Lisp_Object unwind_data)
3254 Lisp_Object multibyte, undo_list, buffer;
3256 multibyte = XCAR (unwind_data);
3257 unwind_data = XCDR (unwind_data);
3258 undo_list = XCAR (unwind_data);
3259 buffer = XCDR (unwind_data);
3261 set_buffer_internal (XBUFFER (buffer));
3262 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3263 adjust_overlays_for_delete (BEG, Z - BEG);
3264 set_buffer_intervals (current_buffer, NULL);
3265 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3267 /* Now we are safe to change the buffer's multibyteness directly. */
3268 bset_enable_multibyte_characters (current_buffer, multibyte);
3269 bset_undo_list (current_buffer, undo_list);
3272 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3273 object where slot 0 is the file descriptor, slot 1 specifies
3274 an offset to put the read bytes, and slot 2 is the maximum
3275 amount of bytes to read. Value is the number of bytes read. */
3277 static Lisp_Object
3278 read_non_regular (Lisp_Object state)
3280 int nbytes;
3282 immediate_quit = 1;
3283 QUIT;
3284 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3285 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3286 + XSAVE_INTEGER (state, 1)),
3287 XSAVE_INTEGER (state, 2));
3288 immediate_quit = 0;
3289 /* Fast recycle this object for the likely next call. */
3290 free_misc (state);
3291 return make_number (nbytes);
3295 /* Condition-case handler used when reading from non-regular files
3296 in insert-file-contents. */
3298 static Lisp_Object
3299 read_non_regular_quit (Lisp_Object ignore)
3301 return Qnil;
3304 /* Return the file offset that VAL represents, checking for type
3305 errors and overflow. */
3306 static off_t
3307 file_offset (Lisp_Object val)
3309 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3310 return XINT (val);
3312 if (FLOATP (val))
3314 double v = XFLOAT_DATA (val);
3315 if (0 <= v
3316 && (sizeof (off_t) < sizeof v
3317 ? v <= TYPE_MAXIMUM (off_t)
3318 : v < TYPE_MAXIMUM (off_t)))
3319 return v;
3322 wrong_type_argument (intern ("file-offset"), val);
3325 /* Return a special time value indicating the error number ERRNUM. */
3326 static struct timespec
3327 time_error_value (int errnum)
3329 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3330 ? NONEXISTENT_MODTIME_NSECS
3331 : UNKNOWN_MODTIME_NSECS);
3332 return make_timespec (0, ns);
3335 static Lisp_Object
3336 get_window_points_and_markers (void)
3338 Lisp_Object pt_marker = Fpoint_marker ();
3339 Lisp_Object windows
3340 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3341 Lisp_Object window_markers = windows;
3342 /* Window markers (and point) are handled specially: rather than move to
3343 just before or just after the modified text, we try to keep the
3344 markers at the same distance (bug#19161).
3345 In general, this is wrong, but for window-markers, this should be harmless
3346 and is convenient for the end user when most of the file is unmodified,
3347 except for a few minor details near the beginning and near the end. */
3348 for (; CONSP (windows); windows = XCDR (windows))
3349 if (WINDOWP (XCAR (windows)))
3351 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3352 XSETCAR (windows,
3353 Fcons (window_marker, Fmarker_position (window_marker)));
3355 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3358 static void
3359 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3360 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3362 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3363 if (CONSP (XCAR (window_markers)))
3365 Lisp_Object car = XCAR (window_markers);
3366 Lisp_Object marker = XCAR (car);
3367 Lisp_Object oldpos = XCDR (car);
3368 if (MARKERP (marker) && INTEGERP (oldpos)
3369 && XINT (oldpos) > same_at_start
3370 && XINT (oldpos) < same_at_end)
3372 ptrdiff_t oldsize = same_at_end - same_at_start;
3373 ptrdiff_t newsize = inserted;
3374 double growth = newsize / (double)oldsize;
3375 ptrdiff_t newpos
3376 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3377 Fset_marker (marker, make_number (newpos), Qnil);
3382 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3383 text as a linear C char array. */
3384 static void
3385 maybe_move_gap (struct buffer *b)
3387 if (BUF_GPT_BYTE (b) != BUF_Z_BYTE (b))
3389 struct buffer *cb = current_buffer;
3391 set_buffer_internal (b);
3392 move_gap_both (Z, Z_BYTE);
3393 set_buffer_internal (cb);
3397 /* FIXME: insert-file-contents should be split with the top-level moved to
3398 Elisp and only the core kept in C. */
3400 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3401 1, 5, 0,
3402 doc: /* Insert contents of file FILENAME after point.
3403 Returns list of absolute file name and number of characters inserted.
3404 If second argument VISIT is non-nil, the buffer's visited filename and
3405 last save file modtime are set, and it is marked unmodified. If
3406 visiting and the file does not exist, visiting is completed before the
3407 error is signaled.
3409 The optional third and fourth arguments BEG and END specify what portion
3410 of the file to insert. These arguments count bytes in the file, not
3411 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3413 If optional fifth argument REPLACE is non-nil, replace the current
3414 buffer contents (in the accessible portion) with the file contents.
3415 This is better than simply deleting and inserting the whole thing
3416 because (1) it preserves some marker positions and (2) it puts less data
3417 in the undo list. When REPLACE is non-nil, the second return value is
3418 the number of characters that replace previous buffer contents.
3420 This function does code conversion according to the value of
3421 `coding-system-for-read' or `file-coding-system-alist', and sets the
3422 variable `last-coding-system-used' to the coding system actually used.
3424 In addition, this function decodes the inserted text from known formats
3425 by calling `format-decode', which see. */)
3426 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3428 struct stat st;
3429 struct timespec mtime;
3430 int fd;
3431 ptrdiff_t inserted = 0;
3432 ptrdiff_t how_much;
3433 off_t beg_offset, end_offset;
3434 int unprocessed;
3435 ptrdiff_t count = SPECPDL_INDEX ();
3436 Lisp_Object handler, val, insval, orig_filename, old_undo;
3437 Lisp_Object p;
3438 ptrdiff_t total = 0;
3439 bool not_regular = 0;
3440 int save_errno = 0;
3441 char read_buf[READ_BUF_SIZE];
3442 struct coding_system coding;
3443 bool replace_handled = false;
3444 bool set_coding_system = false;
3445 Lisp_Object coding_system;
3446 bool read_quit = false;
3447 /* If the undo log only contains the insertion, there's no point
3448 keeping it. It's typically when we first fill a file-buffer. */
3449 bool empty_undo_list_p
3450 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3451 && BEG == Z);
3452 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3453 bool we_locked_file = false;
3454 ptrdiff_t fd_index;
3455 Lisp_Object window_markers = Qnil;
3456 /* same_at_start and same_at_end count bytes, because file access counts
3457 bytes and BEG and END count bytes. */
3458 ptrdiff_t same_at_start = BEGV_BYTE;
3459 ptrdiff_t same_at_end = ZV_BYTE;
3460 /* SAME_AT_END_CHARPOS counts characters, because
3461 restore_window_points needs the old character count. */
3462 ptrdiff_t same_at_end_charpos = ZV;
3464 if (current_buffer->base_buffer && ! NILP (visit))
3465 error ("Cannot do file visiting in an indirect buffer");
3467 if (!NILP (BVAR (current_buffer, read_only)))
3468 Fbarf_if_buffer_read_only (Qnil);
3470 val = Qnil;
3471 p = Qnil;
3472 orig_filename = Qnil;
3473 old_undo = Qnil;
3475 CHECK_STRING (filename);
3476 filename = Fexpand_file_name (filename, Qnil);
3478 /* The value Qnil means that the coding system is not yet
3479 decided. */
3480 coding_system = Qnil;
3482 /* If the file name has special constructs in it,
3483 call the corresponding file handler. */
3484 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3485 if (!NILP (handler))
3487 val = call6 (handler, Qinsert_file_contents, filename,
3488 visit, beg, end, replace);
3489 if (CONSP (val) && CONSP (XCDR (val))
3490 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3491 inserted = XINT (XCAR (XCDR (val)));
3492 goto handled;
3495 orig_filename = filename;
3496 filename = ENCODE_FILE (filename);
3498 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3499 if (fd < 0)
3501 save_errno = errno;
3502 if (NILP (visit))
3503 report_file_error ("Opening input file", orig_filename);
3504 mtime = time_error_value (save_errno);
3505 st.st_size = -1;
3506 if (!NILP (Vcoding_system_for_read))
3508 /* Don't let invalid values into buffer-file-coding-system. */
3509 CHECK_CODING_SYSTEM (Vcoding_system_for_read);
3510 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3512 goto notfound;
3515 fd_index = SPECPDL_INDEX ();
3516 record_unwind_protect_int (close_file_unwind, fd);
3518 /* Replacement should preserve point as it preserves markers. */
3519 if (!NILP (replace))
3521 window_markers = get_window_points_and_markers ();
3522 record_unwind_protect (restore_point_unwind,
3523 XCAR (XCAR (window_markers)));
3526 if (fstat (fd, &st) != 0)
3527 report_file_error ("Input file status", orig_filename);
3528 mtime = get_stat_mtime (&st);
3530 /* This code will need to be changed in order to work on named
3531 pipes, and it's probably just not worth it. So we should at
3532 least signal an error. */
3533 if (!S_ISREG (st.st_mode))
3535 not_regular = 1;
3537 if (! NILP (visit))
3538 goto notfound;
3540 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3541 xsignal2 (Qfile_error,
3542 build_string ("not a regular file"), orig_filename);
3545 if (!NILP (visit))
3547 if (!NILP (beg) || !NILP (end))
3548 error ("Attempt to visit less than an entire file");
3549 if (BEG < Z && NILP (replace))
3550 error ("Cannot do file visiting in a non-empty buffer");
3553 if (!NILP (beg))
3554 beg_offset = file_offset (beg);
3555 else
3556 beg_offset = 0;
3558 if (!NILP (end))
3559 end_offset = file_offset (end);
3560 else
3562 if (not_regular)
3563 end_offset = TYPE_MAXIMUM (off_t);
3564 else
3566 end_offset = st.st_size;
3568 /* A negative size can happen on a platform that allows file
3569 sizes greater than the maximum off_t value. */
3570 if (end_offset < 0)
3571 buffer_overflow ();
3573 /* The file size returned from stat may be zero, but data
3574 may be readable nonetheless, for example when this is a
3575 file in the /proc filesystem. */
3576 if (end_offset == 0)
3577 end_offset = READ_BUF_SIZE;
3581 /* Check now whether the buffer will become too large,
3582 in the likely case where the file's length is not changing.
3583 This saves a lot of needless work before a buffer overflow. */
3584 if (! not_regular)
3586 /* The likely offset where we will stop reading. We could read
3587 more (or less), if the file grows (or shrinks) as we read it. */
3588 off_t likely_end = min (end_offset, st.st_size);
3590 if (beg_offset < likely_end)
3592 ptrdiff_t buf_bytes
3593 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3594 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3595 off_t likely_growth = likely_end - beg_offset;
3596 if (buf_growth_max < likely_growth)
3597 buffer_overflow ();
3601 /* Prevent redisplay optimizations. */
3602 current_buffer->clip_changed = true;
3604 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3606 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3607 setup_coding_system (coding_system, &coding);
3608 /* Ensure we set Vlast_coding_system_used. */
3609 set_coding_system = true;
3611 else if (BEG < Z)
3613 /* Decide the coding system to use for reading the file now
3614 because we can't use an optimized method for handling
3615 `coding:' tag if the current buffer is not empty. */
3616 if (!NILP (Vcoding_system_for_read))
3617 coding_system = Vcoding_system_for_read;
3618 else
3620 /* Don't try looking inside a file for a coding system
3621 specification if it is not seekable. */
3622 if (! not_regular && ! NILP (Vset_auto_coding_function))
3624 /* Find a coding system specified in the heading two
3625 lines or in the tailing several lines of the file.
3626 We assume that the 1K-byte and 3K-byte for heading
3627 and tailing respectively are sufficient for this
3628 purpose. */
3629 int nread;
3631 if (st.st_size <= (1024 * 4))
3632 nread = emacs_read (fd, read_buf, 1024 * 4);
3633 else
3635 nread = emacs_read (fd, read_buf, 1024);
3636 if (nread == 1024)
3638 int ntail;
3639 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3640 report_file_error ("Setting file position",
3641 orig_filename);
3642 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3643 nread = ntail < 0 ? ntail : nread + ntail;
3647 if (nread < 0)
3648 report_file_error ("Read error", orig_filename);
3649 else if (nread > 0)
3651 AUTO_STRING (name, " *code-converting-work*");
3652 struct buffer *prev = current_buffer;
3653 Lisp_Object workbuf;
3654 struct buffer *buf;
3656 record_unwind_current_buffer ();
3658 workbuf = Fget_buffer_create (name);
3659 buf = XBUFFER (workbuf);
3661 delete_all_overlays (buf);
3662 bset_directory (buf, BVAR (current_buffer, directory));
3663 bset_read_only (buf, Qnil);
3664 bset_filename (buf, Qnil);
3665 bset_undo_list (buf, Qt);
3666 eassert (buf->overlays_before == NULL);
3667 eassert (buf->overlays_after == NULL);
3669 set_buffer_internal (buf);
3670 Ferase_buffer ();
3671 bset_enable_multibyte_characters (buf, Qnil);
3673 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3674 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3675 coding_system = call2 (Vset_auto_coding_function,
3676 filename, make_number (nread));
3677 set_buffer_internal (prev);
3679 /* Discard the unwind protect for recovering the
3680 current buffer. */
3681 specpdl_ptr--;
3683 /* Rewind the file for the actual read done later. */
3684 if (lseek (fd, 0, SEEK_SET) < 0)
3685 report_file_error ("Setting file position", orig_filename);
3689 if (NILP (coding_system))
3691 /* If we have not yet decided a coding system, check
3692 file-coding-system-alist. */
3693 coding_system = CALLN (Ffind_operation_coding_system,
3694 Qinsert_file_contents, orig_filename,
3695 visit, beg, end, replace);
3696 if (CONSP (coding_system))
3697 coding_system = XCAR (coding_system);
3701 if (NILP (coding_system))
3702 coding_system = Qundecided;
3703 else
3704 CHECK_CODING_SYSTEM (coding_system);
3706 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3707 /* We must suppress all character code conversion except for
3708 end-of-line conversion. */
3709 coding_system = raw_text_coding_system (coding_system);
3711 setup_coding_system (coding_system, &coding);
3712 /* Ensure we set Vlast_coding_system_used. */
3713 set_coding_system = true;
3716 /* If requested, replace the accessible part of the buffer
3717 with the file contents. Avoid replacing text at the
3718 beginning or end of the buffer that matches the file contents;
3719 that preserves markers pointing to the unchanged parts.
3721 Here we implement this feature in an optimized way
3722 for the case where code conversion is NOT needed.
3723 The following if-statement handles the case of conversion
3724 in a less optimal way.
3726 If the code conversion is "automatic" then we try using this
3727 method and hope for the best.
3728 But if we discover the need for conversion, we give up on this method
3729 and let the following if-statement handle the replace job. */
3730 if (!NILP (replace)
3731 && BEGV < ZV
3732 && (NILP (coding_system)
3733 || ! CODING_REQUIRE_DECODING (&coding)))
3735 ptrdiff_t overlap;
3736 /* There is still a possibility we will find the need to do code
3737 conversion. If that happens, set this variable to
3738 give up on handling REPLACE in the optimized way. */
3739 bool giveup_match_end = false;
3741 if (beg_offset != 0)
3743 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3744 report_file_error ("Setting file position", orig_filename);
3747 immediate_quit = 1;
3748 QUIT;
3749 /* Count how many chars at the start of the file
3750 match the text at the beginning of the buffer. */
3751 while (1)
3753 int nread, bufpos;
3755 nread = emacs_read (fd, read_buf, sizeof read_buf);
3756 if (nread < 0)
3757 report_file_error ("Read error", orig_filename);
3758 else if (nread == 0)
3759 break;
3761 if (CODING_REQUIRE_DETECTION (&coding))
3763 coding_system = detect_coding_system ((unsigned char *) read_buf,
3764 nread, nread, 1, 0,
3765 coding_system);
3766 setup_coding_system (coding_system, &coding);
3769 if (CODING_REQUIRE_DECODING (&coding))
3770 /* We found that the file should be decoded somehow.
3771 Let's give up here. */
3773 giveup_match_end = true;
3774 break;
3777 bufpos = 0;
3778 while (bufpos < nread && same_at_start < ZV_BYTE
3779 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3780 same_at_start++, bufpos++;
3781 /* If we found a discrepancy, stop the scan.
3782 Otherwise loop around and scan the next bufferful. */
3783 if (bufpos != nread)
3784 break;
3786 immediate_quit = false;
3787 /* If the file matches the buffer completely,
3788 there's no need to replace anything. */
3789 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3791 emacs_close (fd);
3792 clear_unwind_protect (fd_index);
3794 /* Truncate the buffer to the size of the file. */
3795 del_range_1 (same_at_start, same_at_end, 0, 0);
3796 goto handled;
3798 immediate_quit = true;
3799 QUIT;
3800 /* Count how many chars at the end of the file
3801 match the text at the end of the buffer. But, if we have
3802 already found that decoding is necessary, don't waste time. */
3803 while (!giveup_match_end)
3805 int total_read, nread, bufpos, trial;
3806 off_t curpos;
3808 /* At what file position are we now scanning? */
3809 curpos = end_offset - (ZV_BYTE - same_at_end);
3810 /* If the entire file matches the buffer tail, stop the scan. */
3811 if (curpos == 0)
3812 break;
3813 /* How much can we scan in the next step? */
3814 trial = min (curpos, sizeof read_buf);
3815 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3816 report_file_error ("Setting file position", orig_filename);
3818 total_read = nread = 0;
3819 while (total_read < trial)
3821 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3822 if (nread < 0)
3823 report_file_error ("Read error", orig_filename);
3824 else if (nread == 0)
3825 break;
3826 total_read += nread;
3829 /* Scan this bufferful from the end, comparing with
3830 the Emacs buffer. */
3831 bufpos = total_read;
3833 /* Compare with same_at_start to avoid counting some buffer text
3834 as matching both at the file's beginning and at the end. */
3835 while (bufpos > 0 && same_at_end > same_at_start
3836 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3837 same_at_end--, bufpos--;
3839 /* If we found a discrepancy, stop the scan.
3840 Otherwise loop around and scan the preceding bufferful. */
3841 if (bufpos != 0)
3843 /* If this discrepancy is because of code conversion,
3844 we cannot use this method; giveup and try the other. */
3845 if (same_at_end > same_at_start
3846 && FETCH_BYTE (same_at_end - 1) >= 0200
3847 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3848 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3849 giveup_match_end = true;
3850 break;
3853 if (nread == 0)
3854 break;
3856 immediate_quit = 0;
3858 if (! giveup_match_end)
3860 ptrdiff_t temp;
3861 ptrdiff_t this_count = SPECPDL_INDEX ();
3863 /* We win! We can handle REPLACE the optimized way. */
3865 /* Extend the start of non-matching text area to multibyte
3866 character boundary. */
3867 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3868 while (same_at_start > BEGV_BYTE
3869 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3870 same_at_start--;
3872 /* Extend the end of non-matching text area to multibyte
3873 character boundary. */
3874 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3875 while (same_at_end < ZV_BYTE
3876 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3877 same_at_end++;
3879 /* Don't try to reuse the same piece of text twice. */
3880 overlap = (same_at_start - BEGV_BYTE
3881 - (same_at_end
3882 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3883 if (overlap > 0)
3884 same_at_end += overlap;
3885 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3887 /* Arrange to read only the nonmatching middle part of the file. */
3888 beg_offset += same_at_start - BEGV_BYTE;
3889 end_offset -= ZV_BYTE - same_at_end;
3891 /* This binding is to avoid ask-user-about-supersession-threat
3892 being called in insert_from_buffer or del_range_bytes (via
3893 prepare_to_modify_buffer).
3894 AFAICT we could avoid ask-user-about-supersession-threat by setting
3895 current_buffer->modtime earlier, but we could still end up calling
3896 ask-user-about-supersession-threat if the file is modified while
3897 we read it, so we bind buffer-file-name instead. */
3898 specbind (intern ("buffer-file-name"), Qnil);
3899 del_range_byte (same_at_start, same_at_end);
3900 /* Insert from the file at the proper position. */
3901 temp = BYTE_TO_CHAR (same_at_start);
3902 SET_PT_BOTH (temp, same_at_start);
3903 unbind_to (this_count, Qnil);
3905 /* If display currently starts at beginning of line,
3906 keep it that way. */
3907 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3908 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3910 replace_handled = true;
3914 /* If requested, replace the accessible part of the buffer
3915 with the file contents. Avoid replacing text at the
3916 beginning or end of the buffer that matches the file contents;
3917 that preserves markers pointing to the unchanged parts.
3919 Here we implement this feature for the case where code conversion
3920 is needed, in a simple way that needs a lot of memory.
3921 The preceding if-statement handles the case of no conversion
3922 in a more optimized way. */
3923 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3925 ptrdiff_t same_at_start_charpos;
3926 ptrdiff_t inserted_chars;
3927 ptrdiff_t overlap;
3928 ptrdiff_t bufpos;
3929 unsigned char *decoded;
3930 ptrdiff_t temp;
3931 ptrdiff_t this = 0;
3932 ptrdiff_t this_count = SPECPDL_INDEX ();
3933 bool multibyte
3934 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3935 Lisp_Object conversion_buffer;
3937 conversion_buffer = code_conversion_save (1, multibyte);
3939 /* First read the whole file, performing code conversion into
3940 CONVERSION_BUFFER. */
3942 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3943 report_file_error ("Setting file position", orig_filename);
3945 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3946 unprocessed = 0; /* Bytes not processed in previous loop. */
3948 while (1)
3950 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3951 quitting while reading a huge file. */
3953 /* Allow quitting out of the actual I/O. */
3954 immediate_quit = 1;
3955 QUIT;
3956 this = emacs_read (fd, read_buf + unprocessed,
3957 READ_BUF_SIZE - unprocessed);
3958 immediate_quit = 0;
3960 if (this <= 0)
3961 break;
3963 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3964 BUF_Z (XBUFFER (conversion_buffer)));
3965 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3966 unprocessed + this, conversion_buffer);
3967 unprocessed = coding.carryover_bytes;
3968 if (coding.carryover_bytes > 0)
3969 memcpy (read_buf, coding.carryover, unprocessed);
3972 if (this < 0)
3973 report_file_error ("Read error", orig_filename);
3974 emacs_close (fd);
3975 clear_unwind_protect (fd_index);
3977 if (unprocessed > 0)
3979 coding.mode |= CODING_MODE_LAST_BLOCK;
3980 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3981 unprocessed, conversion_buffer);
3982 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3985 coding_system = CODING_ID_NAME (coding.id);
3986 set_coding_system = true;
3987 maybe_move_gap (XBUFFER (conversion_buffer));
3988 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3989 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3990 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3992 /* Compare the beginning of the converted string with the buffer
3993 text. */
3995 bufpos = 0;
3996 while (bufpos < inserted && same_at_start < same_at_end
3997 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3998 same_at_start++, bufpos++;
4000 /* If the file matches the head of buffer completely,
4001 there's no need to replace anything. */
4003 if (bufpos == inserted)
4005 /* Truncate the buffer to the size of the file. */
4006 if (same_at_start != same_at_end)
4008 /* See previous specbind for the reason behind this. */
4009 specbind (intern ("buffer-file-name"), Qnil);
4010 del_range_byte (same_at_start, same_at_end);
4012 inserted = 0;
4014 unbind_to (this_count, Qnil);
4015 goto handled;
4018 /* Extend the start of non-matching text area to the previous
4019 multibyte character boundary. */
4020 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4021 while (same_at_start > BEGV_BYTE
4022 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4023 same_at_start--;
4025 /* Scan this bufferful from the end, comparing with
4026 the Emacs buffer. */
4027 bufpos = inserted;
4029 /* Compare with same_at_start to avoid counting some buffer text
4030 as matching both at the file's beginning and at the end. */
4031 while (bufpos > 0 && same_at_end > same_at_start
4032 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4033 same_at_end--, bufpos--;
4035 /* Extend the end of non-matching text area to the next
4036 multibyte character boundary. */
4037 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4038 while (same_at_end < ZV_BYTE
4039 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4040 same_at_end++;
4042 /* Don't try to reuse the same piece of text twice. */
4043 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4044 if (overlap > 0)
4045 same_at_end += overlap;
4046 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
4048 /* If display currently starts at beginning of line,
4049 keep it that way. */
4050 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4051 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4053 /* Replace the chars that we need to replace,
4054 and update INSERTED to equal the number of bytes
4055 we are taking from the decoded string. */
4056 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4058 /* See previous specbind for the reason behind this. */
4059 specbind (intern ("buffer-file-name"), Qnil);
4060 if (same_at_end != same_at_start)
4062 del_range_byte (same_at_start, same_at_end);
4063 temp = GPT;
4064 eassert (same_at_start == GPT_BYTE);
4065 same_at_start = GPT_BYTE;
4067 else
4069 temp = same_at_end_charpos;
4071 /* Insert from the file at the proper position. */
4072 SET_PT_BOTH (temp, same_at_start);
4073 same_at_start_charpos
4074 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4075 same_at_start - BEGV_BYTE
4076 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4077 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4078 inserted_chars
4079 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4080 same_at_start + inserted - BEGV_BYTE
4081 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4082 - same_at_start_charpos);
4083 insert_from_buffer (XBUFFER (conversion_buffer),
4084 same_at_start_charpos, inserted_chars, 0);
4085 /* Set `inserted' to the number of inserted characters. */
4086 inserted = PT - temp;
4087 /* Set point before the inserted characters. */
4088 SET_PT_BOTH (temp, same_at_start);
4090 unbind_to (this_count, Qnil);
4092 goto handled;
4095 if (! not_regular)
4096 total = end_offset - beg_offset;
4097 else
4098 /* For a special file, all we can do is guess. */
4099 total = READ_BUF_SIZE;
4101 if (NILP (visit) && total > 0)
4103 if (!NILP (BVAR (current_buffer, file_truename))
4104 /* Make binding buffer-file-name to nil effective. */
4105 && !NILP (BVAR (current_buffer, filename))
4106 && SAVE_MODIFF >= MODIFF)
4107 we_locked_file = true;
4108 prepare_to_modify_buffer (PT, PT, NULL);
4111 move_gap_both (PT, PT_BYTE);
4112 if (GAP_SIZE < total)
4113 make_gap (total - GAP_SIZE);
4115 if (beg_offset != 0 || !NILP (replace))
4117 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4118 report_file_error ("Setting file position", orig_filename);
4121 /* In the following loop, HOW_MUCH contains the total bytes read so
4122 far for a regular file, and not changed for a special file. But,
4123 before exiting the loop, it is set to a negative value if I/O
4124 error occurs. */
4125 how_much = 0;
4127 /* Total bytes inserted. */
4128 inserted = 0;
4130 /* Here, we don't do code conversion in the loop. It is done by
4131 decode_coding_gap after all data are read into the buffer. */
4133 ptrdiff_t gap_size = GAP_SIZE;
4135 while (how_much < total)
4137 /* `try' is reserved in some compilers (Microsoft C). */
4138 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4139 ptrdiff_t this;
4141 if (not_regular)
4143 Lisp_Object nbytes;
4145 /* Maybe make more room. */
4146 if (gap_size < trytry)
4148 make_gap (trytry - gap_size);
4149 gap_size = GAP_SIZE - inserted;
4152 /* Read from the file, capturing `quit'. When an
4153 error occurs, end the loop, and arrange for a quit
4154 to be signaled after decoding the text we read. */
4155 nbytes = internal_condition_case_1
4156 (read_non_regular,
4157 make_save_int_int_int (fd, inserted, trytry),
4158 Qerror, read_non_regular_quit);
4160 if (NILP (nbytes))
4162 read_quit = true;
4163 break;
4166 this = XINT (nbytes);
4168 else
4170 /* Allow quitting out of the actual I/O. We don't make text
4171 part of the buffer until all the reading is done, so a C-g
4172 here doesn't do any harm. */
4173 immediate_quit = 1;
4174 QUIT;
4175 this = emacs_read (fd,
4176 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4177 + inserted),
4178 trytry);
4179 immediate_quit = 0;
4182 if (this <= 0)
4184 how_much = this;
4185 break;
4188 gap_size -= this;
4190 /* For a regular file, where TOTAL is the real size,
4191 count HOW_MUCH to compare with it.
4192 For a special file, where TOTAL is just a buffer size,
4193 so don't bother counting in HOW_MUCH.
4194 (INSERTED is where we count the number of characters inserted.) */
4195 if (! not_regular)
4196 how_much += this;
4197 inserted += this;
4201 /* Now we have either read all the file data into the gap,
4202 or stop reading on I/O error or quit. If nothing was
4203 read, undo marking the buffer modified. */
4205 if (inserted == 0)
4207 if (we_locked_file)
4208 unlock_file (BVAR (current_buffer, file_truename));
4209 Vdeactivate_mark = old_Vdeactivate_mark;
4211 else
4212 Fset (Qdeactivate_mark, Qt);
4214 emacs_close (fd);
4215 clear_unwind_protect (fd_index);
4217 if (how_much < 0)
4218 report_file_error ("Read error", orig_filename);
4220 /* Make the text read part of the buffer. */
4221 GAP_SIZE -= inserted;
4222 GPT += inserted;
4223 GPT_BYTE += inserted;
4224 ZV += inserted;
4225 ZV_BYTE += inserted;
4226 Z += inserted;
4227 Z_BYTE += inserted;
4229 if (GAP_SIZE > 0)
4230 /* Put an anchor to ensure multi-byte form ends at gap. */
4231 *GPT_ADDR = 0;
4233 notfound:
4235 if (NILP (coding_system))
4237 /* The coding system is not yet decided. Decide it by an
4238 optimized method for handling `coding:' tag.
4240 Note that we can get here only if the buffer was empty
4241 before the insertion. */
4243 if (!NILP (Vcoding_system_for_read))
4244 coding_system = Vcoding_system_for_read;
4245 else
4247 /* Since we are sure that the current buffer was empty
4248 before the insertion, we can toggle
4249 enable-multibyte-characters directly here without taking
4250 care of marker adjustment. By this way, we can run Lisp
4251 program safely before decoding the inserted text. */
4252 Lisp_Object unwind_data;
4253 ptrdiff_t count1 = SPECPDL_INDEX ();
4255 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4256 Fcons (BVAR (current_buffer, undo_list),
4257 Fcurrent_buffer ()));
4258 bset_enable_multibyte_characters (current_buffer, Qnil);
4259 bset_undo_list (current_buffer, Qt);
4260 record_unwind_protect (decide_coding_unwind, unwind_data);
4262 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4264 coding_system = call2 (Vset_auto_coding_function,
4265 filename, make_number (inserted));
4268 if (NILP (coding_system))
4270 /* If the coding system is not yet decided, check
4271 file-coding-system-alist. */
4272 coding_system = CALLN (Ffind_operation_coding_system,
4273 Qinsert_file_contents, orig_filename,
4274 visit, beg, end, Qnil);
4275 if (CONSP (coding_system))
4276 coding_system = XCAR (coding_system);
4278 unbind_to (count1, Qnil);
4279 inserted = Z_BYTE - BEG_BYTE;
4282 if (NILP (coding_system))
4283 coding_system = Qundecided;
4284 else
4285 CHECK_CODING_SYSTEM (coding_system);
4287 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4288 /* We must suppress all character code conversion except for
4289 end-of-line conversion. */
4290 coding_system = raw_text_coding_system (coding_system);
4291 setup_coding_system (coding_system, &coding);
4292 /* Ensure we set Vlast_coding_system_used. */
4293 set_coding_system = true;
4296 if (!NILP (visit))
4298 /* When we visit a file by raw-text, we change the buffer to
4299 unibyte. */
4300 if (CODING_FOR_UNIBYTE (&coding)
4301 /* Can't do this if part of the buffer might be preserved. */
4302 && NILP (replace))
4304 /* Visiting a file with these coding system makes the buffer
4305 unibyte. */
4306 if (inserted > 0)
4307 bset_enable_multibyte_characters (current_buffer, Qnil);
4308 else
4309 Fset_buffer_multibyte (Qnil);
4313 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4314 if (CODING_MAY_REQUIRE_DECODING (&coding)
4315 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4317 move_gap_both (PT, PT_BYTE);
4318 GAP_SIZE += inserted;
4319 ZV_BYTE -= inserted;
4320 Z_BYTE -= inserted;
4321 ZV -= inserted;
4322 Z -= inserted;
4323 decode_coding_gap (&coding, inserted, inserted);
4324 inserted = coding.produced_char;
4325 coding_system = CODING_ID_NAME (coding.id);
4327 else if (inserted > 0)
4329 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4330 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4331 inserted);
4334 /* Call after-change hooks for the inserted text, aside from the case
4335 of normal visiting (not with REPLACE), which is done in a new buffer
4336 "before" the buffer is changed. */
4337 if (inserted > 0 && total > 0
4338 && (NILP (visit) || !NILP (replace)))
4340 signal_after_change (PT, 0, inserted);
4341 update_compositions (PT, PT, CHECK_BORDER);
4344 /* Now INSERTED is measured in characters. */
4346 handled:
4348 if (inserted > 0)
4349 restore_window_points (window_markers, inserted,
4350 BYTE_TO_CHAR (same_at_start),
4351 same_at_end_charpos);
4353 if (!NILP (visit))
4355 if (empty_undo_list_p)
4356 bset_undo_list (current_buffer, Qnil);
4358 if (NILP (handler))
4360 current_buffer->modtime = mtime;
4361 current_buffer->modtime_size = st.st_size;
4362 bset_filename (current_buffer, orig_filename);
4365 SAVE_MODIFF = MODIFF;
4366 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4367 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4368 if (NILP (handler))
4370 if (!NILP (BVAR (current_buffer, file_truename)))
4371 unlock_file (BVAR (current_buffer, file_truename));
4372 unlock_file (filename);
4374 if (not_regular)
4375 xsignal2 (Qfile_error,
4376 build_string ("not a regular file"), orig_filename);
4379 if (set_coding_system)
4380 Vlast_coding_system_used = coding_system;
4382 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4384 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4385 visit);
4386 if (! NILP (insval))
4388 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4389 wrong_type_argument (intern ("inserted-chars"), insval);
4390 inserted = XFASTINT (insval);
4394 /* Decode file format. */
4395 if (inserted > 0)
4397 /* Don't run point motion or modification hooks when decoding. */
4398 ptrdiff_t count1 = SPECPDL_INDEX ();
4399 ptrdiff_t old_inserted = inserted;
4400 specbind (Qinhibit_point_motion_hooks, Qt);
4401 specbind (Qinhibit_modification_hooks, Qt);
4403 /* Save old undo list and don't record undo for decoding. */
4404 old_undo = BVAR (current_buffer, undo_list);
4405 bset_undo_list (current_buffer, Qt);
4407 if (NILP (replace))
4409 insval = call3 (Qformat_decode,
4410 Qnil, make_number (inserted), visit);
4411 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4412 wrong_type_argument (intern ("inserted-chars"), insval);
4413 inserted = XFASTINT (insval);
4415 else
4417 /* If REPLACE is non-nil and we succeeded in not replacing the
4418 beginning or end of the buffer text with the file's contents,
4419 call format-decode with `point' positioned at the beginning
4420 of the buffer and `inserted' equaling the number of
4421 characters in the buffer. Otherwise, format-decode might
4422 fail to correctly analyze the beginning or end of the buffer.
4423 Hence we temporarily save `point' and `inserted' here and
4424 restore `point' iff format-decode did not insert or delete
4425 any text. Otherwise we leave `point' at point-min. */
4426 ptrdiff_t opoint = PT;
4427 ptrdiff_t opoint_byte = PT_BYTE;
4428 ptrdiff_t oinserted = ZV - BEGV;
4429 EMACS_INT ochars_modiff = CHARS_MODIFF;
4431 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4432 insval = call3 (Qformat_decode,
4433 Qnil, make_number (oinserted), visit);
4434 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4435 wrong_type_argument (intern ("inserted-chars"), insval);
4436 if (ochars_modiff == CHARS_MODIFF)
4437 /* format_decode didn't modify buffer's characters => move
4438 point back to position before inserted text and leave
4439 value of inserted alone. */
4440 SET_PT_BOTH (opoint, opoint_byte);
4441 else
4442 /* format_decode modified buffer's characters => consider
4443 entire buffer changed and leave point at point-min. */
4444 inserted = XFASTINT (insval);
4447 /* For consistency with format-decode call these now iff inserted > 0
4448 (martin 2007-06-28). */
4449 p = Vafter_insert_file_functions;
4450 while (CONSP (p))
4452 if (NILP (replace))
4454 insval = call1 (XCAR (p), make_number (inserted));
4455 if (!NILP (insval))
4457 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4458 wrong_type_argument (intern ("inserted-chars"), insval);
4459 inserted = XFASTINT (insval);
4462 else
4464 /* For the rationale of this see the comment on
4465 format-decode above. */
4466 ptrdiff_t opoint = PT;
4467 ptrdiff_t opoint_byte = PT_BYTE;
4468 ptrdiff_t oinserted = ZV - BEGV;
4469 EMACS_INT ochars_modiff = CHARS_MODIFF;
4471 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4472 insval = call1 (XCAR (p), make_number (oinserted));
4473 if (!NILP (insval))
4475 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4476 wrong_type_argument (intern ("inserted-chars"), insval);
4477 if (ochars_modiff == CHARS_MODIFF)
4478 /* after_insert_file_functions didn't modify
4479 buffer's characters => move point back to
4480 position before inserted text and leave value of
4481 inserted alone. */
4482 SET_PT_BOTH (opoint, opoint_byte);
4483 else
4484 /* after_insert_file_functions did modify buffer's
4485 characters => consider entire buffer changed and
4486 leave point at point-min. */
4487 inserted = XFASTINT (insval);
4491 QUIT;
4492 p = XCDR (p);
4495 if (!empty_undo_list_p)
4497 bset_undo_list (current_buffer, old_undo);
4498 if (CONSP (old_undo) && inserted != old_inserted)
4500 /* Adjust the last undo record for the size change during
4501 the format conversion. */
4502 Lisp_Object tem = XCAR (old_undo);
4503 if (CONSP (tem) && INTEGERP (XCAR (tem))
4504 && INTEGERP (XCDR (tem))
4505 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4506 XSETCDR (tem, make_number (PT + inserted));
4509 else
4510 /* If undo_list was Qt before, keep it that way.
4511 Otherwise start with an empty undo_list. */
4512 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4514 unbind_to (count1, Qnil);
4517 if (!NILP (visit)
4518 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4520 /* If visiting nonexistent file, return nil. */
4521 report_file_errno ("Opening input file", orig_filename, save_errno);
4524 /* We made a lot of deletions and insertions above, so invalidate
4525 the newline cache for the entire region of the inserted
4526 characters. */
4527 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4528 invalidate_region_cache (current_buffer->base_buffer,
4529 current_buffer->base_buffer->newline_cache,
4530 PT - BEG, Z - PT - inserted);
4531 else if (current_buffer->newline_cache)
4532 invalidate_region_cache (current_buffer,
4533 current_buffer->newline_cache,
4534 PT - BEG, Z - PT - inserted);
4536 if (read_quit)
4537 quit ();
4539 /* Retval needs to be dealt with in all cases consistently. */
4540 if (NILP (val))
4541 val = list2 (orig_filename, make_number (inserted));
4543 return unbind_to (count, val);
4546 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4548 static void
4549 build_annotations_unwind (Lisp_Object arg)
4551 Vwrite_region_annotation_buffers = arg;
4554 /* Decide the coding-system to encode the data with. */
4556 static Lisp_Object
4557 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4558 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4559 struct coding_system *coding)
4561 Lisp_Object val;
4562 Lisp_Object eol_parent = Qnil;
4564 if (auto_saving
4565 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4566 BVAR (current_buffer, auto_save_file_name))))
4568 val = Qutf_8_emacs;
4569 eol_parent = Qunix;
4571 else if (!NILP (Vcoding_system_for_write))
4573 val = Vcoding_system_for_write;
4574 if (coding_system_require_warning
4575 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4576 /* Confirm that VAL can surely encode the current region. */
4577 val = call5 (Vselect_safe_coding_system_function,
4578 start, end, list2 (Qt, val),
4579 Qnil, filename);
4581 else
4583 /* If the variable `buffer-file-coding-system' is set locally,
4584 it means that the file was read with some kind of code
4585 conversion or the variable is explicitly set by users. We
4586 had better write it out with the same coding system even if
4587 `enable-multibyte-characters' is nil.
4589 If it is not set locally, we anyway have to convert EOL
4590 format if the default value of `buffer-file-coding-system'
4591 tells that it is not Unix-like (LF only) format. */
4592 bool using_default_coding = 0;
4593 bool force_raw_text = 0;
4595 val = BVAR (current_buffer, buffer_file_coding_system);
4596 if (NILP (val)
4597 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4599 val = Qnil;
4600 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4601 force_raw_text = 1;
4604 if (NILP (val))
4606 /* Check file-coding-system-alist. */
4607 Lisp_Object coding_systems
4608 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4609 filename, append, visit, lockname);
4610 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4611 val = XCDR (coding_systems);
4614 if (NILP (val))
4616 /* If we still have not decided a coding system, use the
4617 current buffer's value of buffer-file-coding-system. */
4618 val = BVAR (current_buffer, buffer_file_coding_system);
4619 using_default_coding = 1;
4622 if (! NILP (val) && ! force_raw_text)
4624 Lisp_Object spec, attrs;
4626 CHECK_CODING_SYSTEM (val);
4627 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4628 attrs = AREF (spec, 0);
4629 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4630 force_raw_text = 1;
4633 if (!force_raw_text
4634 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4636 /* Confirm that VAL can surely encode the current region. */
4637 val = call5 (Vselect_safe_coding_system_function,
4638 start, end, val, Qnil, filename);
4639 /* As the function specified by select-safe-coding-system-function
4640 is out of our control, make sure we are not fed by bogus
4641 values. */
4642 if (!NILP (val))
4643 CHECK_CODING_SYSTEM (val);
4646 /* If the decided coding-system doesn't specify end-of-line
4647 format, we use that of
4648 `default-buffer-file-coding-system'. */
4649 if (! using_default_coding)
4651 Lisp_Object dflt = BVAR (&buffer_defaults, buffer_file_coding_system);
4653 if (! NILP (dflt))
4654 val = coding_inherit_eol_type (val, dflt);
4657 /* If we decide not to encode text, use `raw-text' or one of its
4658 subsidiaries. */
4659 if (force_raw_text)
4660 val = raw_text_coding_system (val);
4663 val = coding_inherit_eol_type (val, eol_parent);
4664 setup_coding_system (val, coding);
4666 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4667 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4668 return val;
4671 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4672 "r\nFWrite region to file: \ni\ni\ni\np",
4673 doc: /* Write current region into specified file.
4674 When called from a program, requires three arguments:
4675 START, END and FILENAME. START and END are normally buffer positions
4676 specifying the part of the buffer to write.
4677 If START is nil, that means to use the entire buffer contents; END is
4678 ignored.
4679 If START is a string, then output that string to the file
4680 instead of any buffer contents; END is ignored.
4682 Optional fourth argument APPEND if non-nil means
4683 append to existing file contents (if any). If it is a number,
4684 seek to that offset in the file before writing.
4685 Optional fifth argument VISIT, if t or a string, means
4686 set the last-save-file-modtime of buffer to this file's modtime
4687 and mark buffer not modified.
4688 If VISIT is a string, it is a second file name;
4689 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4690 VISIT is also the file name to lock and unlock for clash detection.
4691 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4692 do not display the \"Wrote file\" message.
4693 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4694 use for locking and unlocking, overriding FILENAME and VISIT.
4695 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4696 for an existing file with the same name. If MUSTBENEW is `excl',
4697 that means to get an error if the file already exists; never overwrite.
4698 If MUSTBENEW is neither nil nor `excl', that means ask for
4699 confirmation before overwriting, but do go ahead and overwrite the file
4700 if the user confirms.
4702 This does code conversion according to the value of
4703 `coding-system-for-write', `buffer-file-coding-system', or
4704 `file-coding-system-alist', and sets the variable
4705 `last-coding-system-used' to the coding system actually used.
4707 This calls `write-region-annotate-functions' at the start, and
4708 `write-region-post-annotation-function' at the end. */)
4709 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4710 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4712 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4713 -1);
4716 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4717 descriptor for FILENAME, so do not open or close FILENAME. */
4719 Lisp_Object
4720 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4721 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4722 Lisp_Object mustbenew, int desc)
4724 int open_flags;
4725 int mode;
4726 off_t offset UNINIT;
4727 bool open_and_close_file = desc < 0;
4728 bool ok;
4729 int save_errno = 0;
4730 const char *fn;
4731 struct stat st;
4732 struct timespec modtime;
4733 ptrdiff_t count = SPECPDL_INDEX ();
4734 ptrdiff_t count1 UNINIT;
4735 Lisp_Object handler;
4736 Lisp_Object visit_file;
4737 Lisp_Object annotations;
4738 Lisp_Object encoded_filename;
4739 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4740 bool quietly = !NILP (visit);
4741 bool file_locked = 0;
4742 struct buffer *given_buffer;
4743 struct coding_system coding;
4745 if (current_buffer->base_buffer && visiting)
4746 error ("Cannot do file visiting in an indirect buffer");
4748 if (!NILP (start) && !STRINGP (start))
4749 validate_region (&start, &end);
4751 visit_file = Qnil;
4753 filename = Fexpand_file_name (filename, Qnil);
4755 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4756 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4758 if (STRINGP (visit))
4759 visit_file = Fexpand_file_name (visit, Qnil);
4760 else
4761 visit_file = filename;
4763 if (NILP (lockname))
4764 lockname = visit_file;
4766 annotations = Qnil;
4768 /* If the file name has special constructs in it,
4769 call the corresponding file handler. */
4770 handler = Ffind_file_name_handler (filename, Qwrite_region);
4771 /* If FILENAME has no handler, see if VISIT has one. */
4772 if (NILP (handler) && STRINGP (visit))
4773 handler = Ffind_file_name_handler (visit, Qwrite_region);
4775 if (!NILP (handler))
4777 Lisp_Object val;
4778 val = call6 (handler, Qwrite_region, start, end,
4779 filename, append, visit);
4781 if (visiting)
4783 SAVE_MODIFF = MODIFF;
4784 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4785 bset_filename (current_buffer, visit_file);
4788 return val;
4791 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4793 /* Special kludge to simplify auto-saving. */
4794 if (NILP (start))
4796 /* Do it later, so write-region-annotate-function can work differently
4797 if we save "the buffer" vs "a region".
4798 This is useful in tar-mode. --Stef
4799 XSETFASTINT (start, BEG);
4800 XSETFASTINT (end, Z); */
4801 Fwiden ();
4804 record_unwind_protect (build_annotations_unwind,
4805 Vwrite_region_annotation_buffers);
4806 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4808 given_buffer = current_buffer;
4810 if (!STRINGP (start))
4812 annotations = build_annotations (start, end);
4814 if (current_buffer != given_buffer)
4816 XSETFASTINT (start, BEGV);
4817 XSETFASTINT (end, ZV);
4821 if (NILP (start))
4823 XSETFASTINT (start, BEGV);
4824 XSETFASTINT (end, ZV);
4827 /* Decide the coding-system to encode the data with.
4828 We used to make this choice before calling build_annotations, but that
4829 leads to problems when a write-annotate-function takes care of
4830 unsavable chars (as was the case with X-Symbol). */
4831 Vlast_coding_system_used
4832 = choose_write_coding_system (start, end, filename,
4833 append, visit, lockname, &coding);
4835 if (open_and_close_file && !auto_saving)
4837 lock_file (lockname);
4838 file_locked = 1;
4841 encoded_filename = ENCODE_FILE (filename);
4842 fn = SSDATA (encoded_filename);
4843 open_flags = O_WRONLY | O_CREAT;
4844 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4845 if (NUMBERP (append))
4846 offset = file_offset (append);
4847 else if (!NILP (append))
4848 open_flags |= O_APPEND;
4849 #ifdef DOS_NT
4850 mode = S_IREAD | S_IWRITE;
4851 #else
4852 mode = auto_saving ? auto_save_mode_bits : 0666;
4853 #endif
4855 if (open_and_close_file)
4857 desc = emacs_open (fn, open_flags, mode);
4858 if (desc < 0)
4860 int open_errno = errno;
4861 if (file_locked)
4862 unlock_file (lockname);
4863 report_file_errno ("Opening output file", filename, open_errno);
4866 count1 = SPECPDL_INDEX ();
4867 record_unwind_protect_int (close_file_unwind, desc);
4870 if (NUMBERP (append))
4872 off_t ret = lseek (desc, offset, SEEK_SET);
4873 if (ret < 0)
4875 int lseek_errno = errno;
4876 if (file_locked)
4877 unlock_file (lockname);
4878 report_file_errno ("Lseek error", filename, lseek_errno);
4882 immediate_quit = 1;
4884 if (STRINGP (start))
4885 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4886 else if (XINT (start) != XINT (end))
4887 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4888 &annotations, &coding);
4889 else
4891 /* If file was empty, still need to write the annotations. */
4892 coding.mode |= CODING_MODE_LAST_BLOCK;
4893 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4895 save_errno = errno;
4897 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4898 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4900 /* We have to flush out a data. */
4901 coding.mode |= CODING_MODE_LAST_BLOCK;
4902 ok = e_write (desc, Qnil, 1, 1, &coding);
4903 save_errno = errno;
4906 immediate_quit = 0;
4908 /* fsync is not crucial for temporary files. Nor for auto-save
4909 files, since they might lose some work anyway. */
4910 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4912 /* Transfer data and metadata to disk, retrying if interrupted.
4913 fsync can report a write failure here, e.g., due to disk full
4914 under NFS. But ignore EINVAL, which means fsync is not
4915 supported on this file. */
4916 while (fsync (desc) != 0)
4917 if (errno != EINTR)
4919 if (errno != EINVAL)
4920 ok = 0, save_errno = errno;
4921 break;
4925 modtime = invalid_timespec ();
4926 if (visiting)
4928 if (fstat (desc, &st) == 0)
4929 modtime = get_stat_mtime (&st);
4930 else
4931 ok = 0, save_errno = errno;
4934 if (open_and_close_file)
4936 /* NFS can report a write failure now. */
4937 if (emacs_close (desc) < 0)
4938 ok = 0, save_errno = errno;
4940 /* Discard the unwind protect for close_file_unwind. */
4941 specpdl_ptr = specpdl + count1;
4944 /* Some file systems have a bug where st_mtime is not updated
4945 properly after a write. For example, CIFS might not see the
4946 st_mtime change until after the file is opened again.
4948 Attempt to detect this file system bug, and update MODTIME to the
4949 newer st_mtime if the bug appears to be present. This introduces
4950 a race condition, so to avoid most instances of the race condition
4951 on non-buggy file systems, skip this check if the most recently
4952 encountered non-buggy file system was the current file system.
4954 A race condition can occur if some other process modifies the
4955 file between the fstat above and the fstat below, but the race is
4956 unlikely and a similar race between the last write and the fstat
4957 above cannot possibly be closed anyway. */
4959 if (timespec_valid_p (modtime)
4960 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4962 int desc1 = emacs_open (fn, O_WRONLY, 0);
4963 if (desc1 >= 0)
4965 struct stat st1;
4966 if (fstat (desc1, &st1) == 0
4967 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4969 /* Use the heuristic if it appears to be valid. With neither
4970 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4971 file, the time stamp won't change. Also, some non-POSIX
4972 systems don't update an empty file's time stamp when
4973 truncating it. Finally, file systems with 100 ns or worse
4974 resolution sometimes seem to have bugs: on a system with ns
4975 resolution, checking ns % 100 incorrectly avoids the heuristic
4976 1% of the time, but the problem should be temporary as we will
4977 try again on the next time stamp. */
4978 bool use_heuristic
4979 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4980 && st.st_size != 0
4981 && modtime.tv_nsec % 100 != 0);
4983 struct timespec modtime1 = get_stat_mtime (&st1);
4984 if (use_heuristic
4985 && timespec_cmp (modtime, modtime1) == 0
4986 && st.st_size == st1.st_size)
4988 timestamp_file_system = st.st_dev;
4989 valid_timestamp_file_system = 1;
4991 else
4993 st.st_size = st1.st_size;
4994 modtime = modtime1;
4997 emacs_close (desc1);
5001 /* Call write-region-post-annotation-function. */
5002 while (CONSP (Vwrite_region_annotation_buffers))
5004 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5005 if (!NILP (Fbuffer_live_p (buf)))
5007 Fset_buffer (buf);
5008 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5009 call0 (Vwrite_region_post_annotation_function);
5011 Vwrite_region_annotation_buffers
5012 = XCDR (Vwrite_region_annotation_buffers);
5015 unbind_to (count, Qnil);
5017 if (file_locked)
5018 unlock_file (lockname);
5020 /* Do this before reporting IO error
5021 to avoid a "file has changed on disk" warning on
5022 next attempt to save. */
5023 if (timespec_valid_p (modtime))
5025 current_buffer->modtime = modtime;
5026 current_buffer->modtime_size = st.st_size;
5029 if (! ok)
5030 report_file_errno ("Write error", filename, save_errno);
5032 if (visiting)
5034 SAVE_MODIFF = MODIFF;
5035 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5036 bset_filename (current_buffer, visit_file);
5037 update_mode_lines = 14;
5039 else if (quietly)
5041 if (auto_saving
5042 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5043 BVAR (current_buffer, auto_save_file_name))))
5044 SAVE_MODIFF = MODIFF;
5046 return Qnil;
5049 if (!auto_saving && !noninteractive)
5050 message_with_string ((NUMBERP (append)
5051 ? "Updated %s"
5052 : ! NILP (append)
5053 ? "Added to %s"
5054 : "Wrote %s"),
5055 visit_file, 1);
5057 return Qnil;
5060 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5061 doc: /* Return t if (car A) is numerically less than (car B). */)
5062 (Lisp_Object a, Lisp_Object b)
5064 return CALLN (Flss, Fcar (a), Fcar (b));
5067 /* Build the complete list of annotations appropriate for writing out
5068 the text between START and END, by calling all the functions in
5069 write-region-annotate-functions and merging the lists they return.
5070 If one of these functions switches to a different buffer, we assume
5071 that buffer contains altered text. Therefore, the caller must
5072 make sure to restore the current buffer in all cases,
5073 as save-excursion would do. */
5075 static Lisp_Object
5076 build_annotations (Lisp_Object start, Lisp_Object end)
5078 Lisp_Object annotations;
5079 Lisp_Object p, res;
5080 Lisp_Object original_buffer;
5081 int i;
5082 bool used_global = false;
5084 XSETBUFFER (original_buffer, current_buffer);
5086 annotations = Qnil;
5087 p = Vwrite_region_annotate_functions;
5088 while (CONSP (p))
5090 struct buffer *given_buffer = current_buffer;
5091 if (EQ (Qt, XCAR (p)) && !used_global)
5092 { /* Use the global value of the hook. */
5093 used_global = true;
5094 p = CALLN (Fappend,
5095 Fdefault_value (Qwrite_region_annotate_functions),
5096 XCDR (p));
5097 continue;
5099 Vwrite_region_annotations_so_far = annotations;
5100 res = call2 (XCAR (p), start, end);
5101 /* If the function makes a different buffer current,
5102 assume that means this buffer contains altered text to be output.
5103 Reset START and END from the buffer bounds
5104 and discard all previous annotations because they should have
5105 been dealt with by this function. */
5106 if (current_buffer != given_buffer)
5108 Vwrite_region_annotation_buffers
5109 = Fcons (Fcurrent_buffer (),
5110 Vwrite_region_annotation_buffers);
5111 XSETFASTINT (start, BEGV);
5112 XSETFASTINT (end, ZV);
5113 annotations = Qnil;
5115 Flength (res); /* Check basic validity of return value */
5116 annotations = merge (annotations, res, Qcar_less_than_car);
5117 p = XCDR (p);
5120 /* Now do the same for annotation functions implied by the file-format */
5121 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5122 p = BVAR (current_buffer, auto_save_file_format);
5123 else
5124 p = BVAR (current_buffer, file_format);
5125 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5127 struct buffer *given_buffer = current_buffer;
5129 Vwrite_region_annotations_so_far = annotations;
5131 /* Value is either a list of annotations or nil if the function
5132 has written annotations to a temporary buffer, which is now
5133 current. */
5134 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5135 original_buffer, make_number (i));
5136 if (current_buffer != given_buffer)
5138 XSETFASTINT (start, BEGV);
5139 XSETFASTINT (end, ZV);
5140 annotations = Qnil;
5143 if (CONSP (res))
5144 annotations = merge (annotations, res, Qcar_less_than_car);
5147 return annotations;
5151 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5152 If STRING is nil, POS is the character position in the current buffer.
5153 Intersperse with them the annotations from *ANNOT
5154 which fall within the range of POS to POS + NCHARS,
5155 each at its appropriate position.
5157 We modify *ANNOT by discarding elements as we use them up.
5159 Return true if successful. */
5161 static bool
5162 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5163 ptrdiff_t nchars, Lisp_Object *annot,
5164 struct coding_system *coding)
5166 Lisp_Object tem;
5167 ptrdiff_t nextpos;
5168 ptrdiff_t lastpos = pos + nchars;
5170 while (NILP (*annot) || CONSP (*annot))
5172 tem = Fcar_safe (Fcar (*annot));
5173 nextpos = pos - 1;
5174 if (INTEGERP (tem))
5175 nextpos = XFASTINT (tem);
5177 /* If there are no more annotations in this range,
5178 output the rest of the range all at once. */
5179 if (! (nextpos >= pos && nextpos <= lastpos))
5180 return e_write (desc, string, pos, lastpos, coding);
5182 /* Output buffer text up to the next annotation's position. */
5183 if (nextpos > pos)
5185 if (!e_write (desc, string, pos, nextpos, coding))
5186 return 0;
5187 pos = nextpos;
5189 /* Output the annotation. */
5190 tem = Fcdr (Fcar (*annot));
5191 if (STRINGP (tem))
5193 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5194 return 0;
5196 *annot = Fcdr (*annot);
5198 return 1;
5201 /* Maximum number of characters that the next
5202 function encodes per one loop iteration. */
5204 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5206 /* Write text in the range START and END into descriptor DESC,
5207 encoding them with coding system CODING. If STRING is nil, START
5208 and END are character positions of the current buffer, else they
5209 are indexes to the string STRING. Return true if successful. */
5211 static bool
5212 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5213 struct coding_system *coding)
5215 if (STRINGP (string))
5217 start = 0;
5218 end = SCHARS (string);
5221 /* We used to have a code for handling selective display here. But,
5222 now it is handled within encode_coding. */
5224 while (start < end)
5226 if (STRINGP (string))
5228 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5229 if (CODING_REQUIRE_ENCODING (coding))
5231 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5233 /* Avoid creating huge Lisp string in encode_coding_object. */
5234 if (nchars == E_WRITE_MAX)
5235 coding->raw_destination = 1;
5237 encode_coding_object
5238 (coding, string, start, string_char_to_byte (string, start),
5239 start + nchars, string_char_to_byte (string, start + nchars),
5240 Qt);
5242 else
5244 coding->dst_object = string;
5245 coding->consumed_char = SCHARS (string);
5246 coding->produced = SBYTES (string);
5249 else
5251 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5252 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5254 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5255 if (CODING_REQUIRE_ENCODING (coding))
5257 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5259 /* Likewise. */
5260 if (nchars == E_WRITE_MAX)
5261 coding->raw_destination = 1;
5263 encode_coding_object
5264 (coding, Fcurrent_buffer (), start, start_byte,
5265 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5267 else
5269 coding->dst_object = Qnil;
5270 coding->dst_pos_byte = start_byte;
5271 if (start >= GPT || end <= GPT)
5273 coding->consumed_char = end - start;
5274 coding->produced = end_byte - start_byte;
5276 else
5278 coding->consumed_char = GPT - start;
5279 coding->produced = GPT_BYTE - start_byte;
5284 if (coding->produced > 0)
5286 char *buf = (coding->raw_destination ? (char *) coding->destination
5287 : (STRINGP (coding->dst_object)
5288 ? SSDATA (coding->dst_object)
5289 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5290 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5292 if (coding->raw_destination)
5294 /* We're responsible for freeing this, see
5295 encode_coding_object to check why. */
5296 xfree (coding->destination);
5297 coding->raw_destination = 0;
5299 if (coding->produced)
5300 return 0;
5302 start += coding->consumed_char;
5305 return 1;
5308 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5309 Sverify_visited_file_modtime, 0, 1, 0,
5310 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5311 This means that the file has not been changed since it was visited or saved.
5312 If BUF is omitted or nil, it defaults to the current buffer.
5313 See Info node `(elisp)Modification Time' for more details. */)
5314 (Lisp_Object buf)
5316 struct buffer *b = decode_buffer (buf);
5317 struct stat st;
5318 Lisp_Object handler;
5319 Lisp_Object filename;
5320 struct timespec mtime;
5322 if (!STRINGP (BVAR (b, filename))) return Qt;
5323 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5325 /* If the file name has special constructs in it,
5326 call the corresponding file handler. */
5327 handler = Ffind_file_name_handler (BVAR (b, filename),
5328 Qverify_visited_file_modtime);
5329 if (!NILP (handler))
5330 return call2 (handler, Qverify_visited_file_modtime, buf);
5332 filename = ENCODE_FILE (BVAR (b, filename));
5334 mtime = (stat (SSDATA (filename), &st) == 0
5335 ? get_stat_mtime (&st)
5336 : time_error_value (errno));
5337 if (timespec_cmp (mtime, b->modtime) == 0
5338 && (b->modtime_size < 0
5339 || st.st_size == b->modtime_size))
5340 return Qt;
5341 return Qnil;
5344 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5345 Svisited_file_modtime, 0, 0, 0,
5346 doc: /* Return the current buffer's recorded visited file modification time.
5347 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5348 `file-attributes' returns. If the current buffer has no recorded file
5349 modification time, this function returns 0. If the visited file
5350 doesn't exist, return -1.
5351 See Info node `(elisp)Modification Time' for more details. */)
5352 (void)
5354 int ns = current_buffer->modtime.tv_nsec;
5355 if (ns < 0)
5356 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5357 return make_lisp_time (current_buffer->modtime);
5360 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5361 Sset_visited_file_modtime, 0, 1, 0,
5362 doc: /* Update buffer's recorded modification time from the visited file's time.
5363 Useful if the buffer was not read from the file normally
5364 or if the file itself has been changed for some known benign reason.
5365 An argument specifies the modification time value to use
5366 \(instead of that of the visited file), in the form of a list
5367 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5368 `visited-file-modtime'. */)
5369 (Lisp_Object time_flag)
5371 if (!NILP (time_flag))
5373 struct timespec mtime;
5374 if (INTEGERP (time_flag))
5376 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5377 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5379 else
5380 mtime = lisp_time_argument (time_flag);
5382 current_buffer->modtime = mtime;
5383 current_buffer->modtime_size = -1;
5385 else
5387 register Lisp_Object filename;
5388 struct stat st;
5389 Lisp_Object handler;
5391 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5393 /* If the file name has special constructs in it,
5394 call the corresponding file handler. */
5395 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5396 if (!NILP (handler))
5397 /* The handler can find the file name the same way we did. */
5398 return call2 (handler, Qset_visited_file_modtime, Qnil);
5400 filename = ENCODE_FILE (filename);
5402 if (stat (SSDATA (filename), &st) >= 0)
5404 current_buffer->modtime = get_stat_mtime (&st);
5405 current_buffer->modtime_size = st.st_size;
5409 return Qnil;
5412 static Lisp_Object
5413 auto_save_error (Lisp_Object error_val)
5415 auto_save_error_occurred = 1;
5417 ring_bell (XFRAME (selected_frame));
5419 AUTO_STRING (format, "Auto-saving %s: %s");
5420 Lisp_Object msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5421 Ferror_message_string (error_val));
5422 call3 (intern ("display-warning"),
5423 intern ("auto-save"), msg, intern ("error"));
5425 return Qnil;
5428 static Lisp_Object
5429 auto_save_1 (void)
5431 struct stat st;
5432 Lisp_Object modes;
5434 auto_save_mode_bits = 0666;
5436 /* Get visited file's mode to become the auto save file's mode. */
5437 if (! NILP (BVAR (current_buffer, filename)))
5439 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5440 /* But make sure we can overwrite it later! */
5441 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5442 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5443 INTEGERP (modes))
5444 /* Remote files don't cooperate with stat. */
5445 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5448 return
5449 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5450 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5451 Qnil, Qnil);
5454 struct auto_save_unwind
5456 FILE *stream;
5457 bool auto_raise;
5460 static void
5461 do_auto_save_unwind (void *arg)
5463 struct auto_save_unwind *p = arg;
5464 FILE *stream = p->stream;
5465 minibuffer_auto_raise = p->auto_raise;
5466 auto_saving = 0;
5467 if (stream != NULL)
5469 block_input ();
5470 fclose (stream);
5471 unblock_input ();
5475 static Lisp_Object
5476 do_auto_save_make_dir (Lisp_Object dir)
5478 Lisp_Object result;
5480 auto_saving_dir_umask = 077;
5481 result = call2 (Qmake_directory, dir, Qt);
5482 auto_saving_dir_umask = 0;
5483 return result;
5486 static Lisp_Object
5487 do_auto_save_eh (Lisp_Object ignore)
5489 auto_saving_dir_umask = 0;
5490 return Qnil;
5493 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5494 doc: /* Auto-save all buffers that need it.
5495 This is all buffers that have auto-saving enabled
5496 and are changed since last auto-saved.
5497 Auto-saving writes the buffer into a file
5498 so that your editing is not lost if the system crashes.
5499 This file is not the file you visited; that changes only when you save.
5500 Normally we run the normal hook `auto-save-hook' before saving.
5502 A non-nil NO-MESSAGE argument means do not print any message if successful.
5503 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5504 (Lisp_Object no_message, Lisp_Object current_only)
5506 struct buffer *old = current_buffer, *b;
5507 Lisp_Object tail, buf, hook;
5508 bool auto_saved = 0;
5509 int do_handled_files;
5510 Lisp_Object oquit;
5511 FILE *stream = NULL;
5512 ptrdiff_t count = SPECPDL_INDEX ();
5513 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5514 bool old_message_p = 0;
5515 struct auto_save_unwind auto_save_unwind;
5517 if (max_specpdl_size < specpdl_size + 40)
5518 max_specpdl_size = specpdl_size + 40;
5520 if (minibuf_level)
5521 no_message = Qt;
5523 if (NILP (no_message))
5525 old_message_p = push_message ();
5526 record_unwind_protect_void (pop_message_unwind);
5529 /* Ordinarily don't quit within this function,
5530 but don't make it impossible to quit (in case we get hung in I/O). */
5531 oquit = Vquit_flag;
5532 Vquit_flag = Qnil;
5534 hook = intern ("auto-save-hook");
5535 safe_run_hooks (hook);
5537 if (STRINGP (Vauto_save_list_file_name))
5539 Lisp_Object listfile;
5541 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5543 /* Don't try to create the directory when shutting down Emacs,
5544 because creating the directory might signal an error, and
5545 that would leave Emacs in a strange state. */
5546 if (!NILP (Vrun_hooks))
5548 Lisp_Object dir;
5549 dir = Ffile_name_directory (listfile);
5550 if (NILP (Ffile_directory_p (dir)))
5551 internal_condition_case_1 (do_auto_save_make_dir,
5552 dir, Qt,
5553 do_auto_save_eh);
5556 stream = emacs_fopen (SSDATA (listfile), "w");
5559 auto_save_unwind.stream = stream;
5560 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5561 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5562 minibuffer_auto_raise = 0;
5563 auto_saving = 1;
5564 auto_save_error_occurred = 0;
5566 /* On first pass, save all files that don't have handlers.
5567 On second pass, save all files that do have handlers.
5569 If Emacs is crashing, the handlers may tweak what is causing
5570 Emacs to crash in the first place, and it would be a shame if
5571 Emacs failed to autosave perfectly ordinary files because it
5572 couldn't handle some ange-ftp'd file. */
5574 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5575 FOR_EACH_LIVE_BUFFER (tail, buf)
5577 b = XBUFFER (buf);
5579 /* Record all the buffers that have auto save mode
5580 in the special file that lists them. For each of these buffers,
5581 Record visited name (if any) and auto save name. */
5582 if (STRINGP (BVAR (b, auto_save_file_name))
5583 && stream != NULL && do_handled_files == 0)
5585 block_input ();
5586 if (!NILP (BVAR (b, filename)))
5588 fwrite (SDATA (BVAR (b, filename)), 1,
5589 SBYTES (BVAR (b, filename)), stream);
5591 putc ('\n', stream);
5592 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5593 SBYTES (BVAR (b, auto_save_file_name)), stream);
5594 putc ('\n', stream);
5595 unblock_input ();
5598 if (!NILP (current_only)
5599 && b != current_buffer)
5600 continue;
5602 /* Don't auto-save indirect buffers.
5603 The base buffer takes care of it. */
5604 if (b->base_buffer)
5605 continue;
5607 /* Check for auto save enabled
5608 and file changed since last auto save
5609 and file changed since last real save. */
5610 if (STRINGP (BVAR (b, auto_save_file_name))
5611 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5612 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5613 /* -1 means we've turned off autosaving for a while--see below. */
5614 && XINT (BVAR (b, save_length)) >= 0
5615 && (do_handled_files
5616 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5617 Qwrite_region))))
5619 struct timespec before_time = current_timespec ();
5620 struct timespec after_time;
5622 /* If we had a failure, don't try again for 20 minutes. */
5623 if (b->auto_save_failure_time > 0
5624 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5625 continue;
5627 set_buffer_internal (b);
5628 if (NILP (Vauto_save_include_big_deletions)
5629 && (XFASTINT (BVAR (b, save_length)) * 10
5630 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5631 /* A short file is likely to change a large fraction;
5632 spare the user annoying messages. */
5633 && XFASTINT (BVAR (b, save_length)) > 5000
5634 /* These messages are frequent and annoying for `*mail*'. */
5635 && !EQ (BVAR (b, filename), Qnil)
5636 && NILP (no_message))
5638 /* It has shrunk too much; turn off auto-saving here. */
5639 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5640 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5641 BVAR (b, name), 1);
5642 minibuffer_auto_raise = 0;
5643 /* Turn off auto-saving until there's a real save,
5644 and prevent any more warnings. */
5645 XSETINT (BVAR (b, save_length), -1);
5646 Fsleep_for (make_number (1), Qnil);
5647 continue;
5649 if (!auto_saved && NILP (no_message))
5650 message1 ("Auto-saving...");
5651 internal_condition_case (auto_save_1, Qt, auto_save_error);
5652 auto_saved = 1;
5653 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5654 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5655 set_buffer_internal (old);
5657 after_time = current_timespec ();
5659 /* If auto-save took more than 60 seconds,
5660 assume it was an NFS failure that got a timeout. */
5661 if (after_time.tv_sec - before_time.tv_sec > 60)
5662 b->auto_save_failure_time = after_time.tv_sec;
5666 /* Prevent another auto save till enough input events come in. */
5667 record_auto_save ();
5669 if (auto_saved && NILP (no_message))
5671 if (old_message_p)
5673 /* If we are going to restore an old message,
5674 give time to read ours. */
5675 sit_for (make_number (1), 0, 0);
5676 restore_message ();
5678 else if (!auto_save_error_occurred)
5679 /* Don't overwrite the error message if an error occurred.
5680 If we displayed a message and then restored a state
5681 with no message, leave a "done" message on the screen. */
5682 message1 ("Auto-saving...done");
5685 Vquit_flag = oquit;
5687 /* This restores the message-stack status. */
5688 unbind_to (count, Qnil);
5689 return Qnil;
5692 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5693 Sset_buffer_auto_saved, 0, 0, 0,
5694 doc: /* Mark current buffer as auto-saved with its current text.
5695 No auto-save file will be written until the buffer changes again. */)
5696 (void)
5698 /* FIXME: This should not be called in indirect buffers, since
5699 they're not autosaved. */
5700 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5701 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5702 current_buffer->auto_save_failure_time = 0;
5703 return Qnil;
5706 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5707 Sclear_buffer_auto_save_failure, 0, 0, 0,
5708 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5709 (void)
5711 current_buffer->auto_save_failure_time = 0;
5712 return Qnil;
5715 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5716 0, 0, 0,
5717 doc: /* Return t if current buffer has been auto-saved recently.
5718 More precisely, if it has been auto-saved since last read from or saved
5719 in the visited file. If the buffer has no visited file,
5720 then any auto-save counts as "recent". */)
5721 (void)
5723 /* FIXME: maybe we should return nil for indirect buffers since
5724 they're never autosaved. */
5725 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5728 /* Reading and completing file names. */
5730 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5731 Snext_read_file_uses_dialog_p, 0, 0, 0,
5732 doc: /* Return t if a call to `read-file-name' will use a dialog.
5733 The return value is only relevant for a call to `read-file-name' that happens
5734 before any other event (mouse or keypress) is handled. */)
5735 (void)
5737 #if (defined USE_GTK || defined USE_MOTIF \
5738 || defined HAVE_NS || defined HAVE_NTGUI)
5739 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5740 && use_dialog_box
5741 && use_file_dialog
5742 && window_system_available (SELECTED_FRAME ()))
5743 return Qt;
5744 #endif
5745 return Qnil;
5749 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5750 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5751 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5752 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5753 it to text mode.
5755 As a side effect, this function flushes any pending STREAM's data.
5757 Value is the previous value of STREAM's I/O mode, nil for text mode,
5758 non-nil for binary mode.
5760 On MS-Windows and MS-DOS, binary mode is needed to read or write
5761 arbitrary binary data, and for disabling translation between CR-LF
5762 pairs and a single newline character. Examples include generation
5763 of text files with Unix-style end-of-line format using `princ' in
5764 batch mode, with standard output redirected to a file.
5766 On Posix systems, this function always returns non-nil, and has no
5767 effect except for flushing STREAM's data. */)
5768 (Lisp_Object stream, Lisp_Object mode)
5770 FILE *fp = NULL;
5771 int binmode;
5773 CHECK_SYMBOL (stream);
5774 if (EQ (stream, Qstdin))
5775 fp = stdin;
5776 else if (EQ (stream, Qstdout))
5777 fp = stdout;
5778 else if (EQ (stream, Qstderr))
5779 fp = stderr;
5780 else
5781 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5783 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5784 if (fp != stdin)
5785 fflush (fp);
5787 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5790 void
5791 init_fileio (void)
5793 realmask = umask (0);
5794 umask (realmask);
5796 valid_timestamp_file_system = 0;
5798 /* fsync can be a significant performance hit. Often it doesn't
5799 suffice to make the file-save operation survive a crash. For
5800 batch scripts, which are typically part of larger shell commands
5801 that don't fsync other files, its effect on performance can be
5802 significant so its utility is particularly questionable.
5803 Hence, for now by default fsync is used only when interactive.
5805 For more on why fsync often fails to work on today's hardware, see:
5806 Zheng M et al. Understanding the robustness of SSDs under power fault.
5807 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5808 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5810 For more on why fsync does not suffice even if it works properly, see:
5811 Roche X. Necessary step(s) to synchronize filename operations on disk.
5812 Austin Group Defect 672, 2013-03-19
5813 http://austingroupbugs.net/view.php?id=672 */
5814 write_region_inhibit_fsync = noninteractive;
5817 void
5818 syms_of_fileio (void)
5820 /* Property name of a file name handler,
5821 which gives a list of operations it handles. */
5822 DEFSYM (Qoperations, "operations");
5824 DEFSYM (Qexpand_file_name, "expand-file-name");
5825 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5826 DEFSYM (Qdirectory_file_name, "directory-file-name");
5827 DEFSYM (Qfile_name_directory, "file-name-directory");
5828 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5829 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5830 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5831 DEFSYM (Qcopy_file, "copy-file");
5832 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5833 DEFSYM (Qmake_directory, "make-directory");
5834 DEFSYM (Qdelete_file, "delete-file");
5835 DEFSYM (Qrename_file, "rename-file");
5836 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5837 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5838 DEFSYM (Qfile_exists_p, "file-exists-p");
5839 DEFSYM (Qfile_executable_p, "file-executable-p");
5840 DEFSYM (Qfile_readable_p, "file-readable-p");
5841 DEFSYM (Qfile_writable_p, "file-writable-p");
5842 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5843 DEFSYM (Qaccess_file, "access-file");
5844 DEFSYM (Qfile_directory_p, "file-directory-p");
5845 DEFSYM (Qfile_regular_p, "file-regular-p");
5846 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5847 DEFSYM (Qfile_modes, "file-modes");
5848 DEFSYM (Qset_file_modes, "set-file-modes");
5849 DEFSYM (Qset_file_times, "set-file-times");
5850 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5851 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5852 DEFSYM (Qfile_acl, "file-acl");
5853 DEFSYM (Qset_file_acl, "set-file-acl");
5854 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5855 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5856 DEFSYM (Qwrite_region, "write-region");
5857 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5858 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5860 /* The symbol bound to coding-system-for-read when
5861 insert-file-contents is called for recovering a file. This is not
5862 an actual coding system name, but just an indicator to tell
5863 insert-file-contents to use `emacs-mule' with a special flag for
5864 auto saving and recovering a file. */
5865 DEFSYM (Qauto_save_coding, "auto-save-coding");
5867 DEFSYM (Qfile_name_history, "file-name-history");
5868 Fset (Qfile_name_history, Qnil);
5870 DEFSYM (Qfile_error, "file-error");
5871 DEFSYM (Qfile_already_exists, "file-already-exists");
5872 DEFSYM (Qfile_date_error, "file-date-error");
5873 DEFSYM (Qfile_notify_error, "file-notify-error");
5874 DEFSYM (Qexcl, "excl");
5876 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5877 doc: /* Coding system for encoding file names.
5878 If it is nil, `default-file-name-coding-system' (which see) is used.
5880 On MS-Windows, the value of this variable is largely ignored if
5881 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5882 behaves as if file names were encoded in `utf-8'. */);
5883 Vfile_name_coding_system = Qnil;
5885 DEFVAR_LISP ("default-file-name-coding-system",
5886 Vdefault_file_name_coding_system,
5887 doc: /* Default coding system for encoding file names.
5888 This variable is used only when `file-name-coding-system' is nil.
5890 This variable is set/changed by the command `set-language-environment'.
5891 User should not set this variable manually,
5892 instead use `file-name-coding-system' to get a constant encoding
5893 of file names regardless of the current language environment.
5895 On MS-Windows, the value of this variable is largely ignored if
5896 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5897 behaves as if file names were encoded in `utf-8'. */);
5898 Vdefault_file_name_coding_system = Qnil;
5900 /* Lisp functions for translating file formats. */
5901 DEFSYM (Qformat_decode, "format-decode");
5902 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5904 /* Lisp function for setting buffer-file-coding-system and the
5905 multibyteness of the current buffer after inserting a file. */
5906 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5908 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5910 Fput (Qfile_error, Qerror_conditions,
5911 Fpurecopy (list2 (Qfile_error, Qerror)));
5912 Fput (Qfile_error, Qerror_message,
5913 build_pure_c_string ("File error"));
5915 Fput (Qfile_already_exists, Qerror_conditions,
5916 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5917 Fput (Qfile_already_exists, Qerror_message,
5918 build_pure_c_string ("File already exists"));
5920 Fput (Qfile_date_error, Qerror_conditions,
5921 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5922 Fput (Qfile_date_error, Qerror_message,
5923 build_pure_c_string ("Cannot set file date"));
5925 Fput (Qfile_notify_error, Qerror_conditions,
5926 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5927 Fput (Qfile_notify_error, Qerror_message,
5928 build_pure_c_string ("File notification error"));
5930 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5931 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5932 If a file name matches REGEXP, all I/O on that file is done by calling
5933 HANDLER. If a file name matches more than one handler, the handler
5934 whose match starts last in the file name gets precedence. The
5935 function `find-file-name-handler' checks this list for a handler for
5936 its argument.
5938 HANDLER should be a function. The first argument given to it is the
5939 name of the I/O primitive to be handled; the remaining arguments are
5940 the arguments that were passed to that primitive. For example, if you
5941 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5942 HANDLER is called like this:
5944 (funcall HANDLER \\='file-exists-p FILENAME)
5946 Note that HANDLER must be able to handle all I/O primitives; if it has
5947 nothing special to do for a primitive, it should reinvoke the
5948 primitive to handle the operation \"the usual way\".
5949 See Info node `(elisp)Magic File Names' for more details. */);
5950 Vfile_name_handler_alist = Qnil;
5952 DEFVAR_LISP ("set-auto-coding-function",
5953 Vset_auto_coding_function,
5954 doc: /* If non-nil, a function to call to decide a coding system of file.
5955 Two arguments are passed to this function: the file name
5956 and the length of a file contents following the point.
5957 This function should return a coding system to decode the file contents.
5958 It should check the file name against `auto-coding-alist'.
5959 If no coding system is decided, it should check a coding system
5960 specified in the heading lines with the format:
5961 -*- ... coding: CODING-SYSTEM; ... -*-
5962 or local variable spec of the tailing lines with `coding:' tag. */);
5963 Vset_auto_coding_function = Qnil;
5965 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5966 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5967 Each is passed one argument, the number of characters inserted,
5968 with point at the start of the inserted text. Each function
5969 should leave point the same, and return the new character count.
5970 If `insert-file-contents' is intercepted by a handler from
5971 `file-name-handler-alist', that handler is responsible for calling the
5972 functions in `after-insert-file-functions' if appropriate. */);
5973 Vafter_insert_file_functions = Qnil;
5975 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5976 doc: /* A list of functions to be called at the start of `write-region'.
5977 Each is passed two arguments, START and END as for `write-region'.
5978 These are usually two numbers but not always; see the documentation
5979 for `write-region'. The function should return a list of pairs
5980 of the form (POSITION . STRING), consisting of strings to be effectively
5981 inserted at the specified positions of the file being written (1 means to
5982 insert before the first byte written). The POSITIONs must be sorted into
5983 increasing order.
5985 If there are several annotation functions, the lists returned by these
5986 functions are merged destructively. As each annotation function runs,
5987 the variable `write-region-annotations-so-far' contains a list of all
5988 annotations returned by previous annotation functions.
5990 An annotation function can return with a different buffer current.
5991 Doing so removes the annotations returned by previous functions, and
5992 resets START and END to `point-min' and `point-max' of the new buffer.
5994 After `write-region' completes, Emacs calls the function stored in
5995 `write-region-post-annotation-function', once for each buffer that was
5996 current when building the annotations (i.e., at least once), with that
5997 buffer current. */);
5998 Vwrite_region_annotate_functions = Qnil;
5999 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
6001 DEFVAR_LISP ("write-region-post-annotation-function",
6002 Vwrite_region_post_annotation_function,
6003 doc: /* Function to call after `write-region' completes.
6004 The function is called with no arguments. If one or more of the
6005 annotation functions in `write-region-annotate-functions' changed the
6006 current buffer, the function stored in this variable is called for
6007 each of those additional buffers as well, in addition to the original
6008 buffer. The relevant buffer is current during each function call. */);
6009 Vwrite_region_post_annotation_function = Qnil;
6010 staticpro (&Vwrite_region_annotation_buffers);
6012 DEFVAR_LISP ("write-region-annotations-so-far",
6013 Vwrite_region_annotations_so_far,
6014 doc: /* When an annotation function is called, this holds the previous annotations.
6015 These are the annotations made by other annotation functions
6016 that were already called. See also `write-region-annotate-functions'. */);
6017 Vwrite_region_annotations_so_far = Qnil;
6019 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
6020 doc: /* A list of file name handlers that temporarily should not be used.
6021 This applies only to the operation `inhibit-file-name-operation'. */);
6022 Vinhibit_file_name_handlers = Qnil;
6024 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6025 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6026 Vinhibit_file_name_operation = Qnil;
6028 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6029 doc: /* File name in which we write a list of all auto save file names.
6030 This variable is initialized automatically from `auto-save-list-file-prefix'
6031 shortly after Emacs reads your init file, if you have not yet given it
6032 a non-nil value. */);
6033 Vauto_save_list_file_name = Qnil;
6035 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6036 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6037 Normally auto-save files are written under other names. */);
6038 Vauto_save_visited_file_name = Qnil;
6040 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6041 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6042 If nil, deleting a substantial portion of the text disables auto-save
6043 in the buffer; this is the default behavior, because the auto-save
6044 file is usually more useful if it contains the deleted text. */);
6045 Vauto_save_include_big_deletions = Qnil;
6047 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6048 doc: /* Non-nil means don't call fsync in `write-region'.
6049 This variable affects calls to `write-region' as well as save commands.
6050 Setting this to nil may avoid data loss if the system loses power or
6051 the operating system crashes. By default, it is non-nil in batch mode. */);
6052 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
6054 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6055 doc: /* Specifies whether to use the system's trash can.
6056 When non-nil, certain file deletion commands use the function
6057 `move-file-to-trash' instead of deleting files outright.
6058 This includes interactive calls to `delete-file' and
6059 `delete-directory' and the Dired deletion commands. */);
6060 delete_by_moving_to_trash = 0;
6061 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6063 /* Lisp function for moving files to trash. */
6064 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6066 /* Lisp function for recursively copying directories. */
6067 DEFSYM (Qcopy_directory, "copy-directory");
6069 /* Lisp function for recursively deleting directories. */
6070 DEFSYM (Qdelete_directory, "delete-directory");
6072 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6073 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6075 DEFSYM (Qstdin, "stdin");
6076 DEFSYM (Qstdout, "stdout");
6077 DEFSYM (Qstderr, "stderr");
6079 defsubr (&Sfind_file_name_handler);
6080 defsubr (&Sfile_name_directory);
6081 defsubr (&Sfile_name_nondirectory);
6082 defsubr (&Sunhandled_file_name_directory);
6083 defsubr (&Sfile_name_as_directory);
6084 defsubr (&Sdirectory_file_name);
6085 defsubr (&Smake_temp_name);
6086 defsubr (&Sexpand_file_name);
6087 defsubr (&Ssubstitute_in_file_name);
6088 defsubr (&Scopy_file);
6089 defsubr (&Smake_directory_internal);
6090 defsubr (&Sdelete_directory_internal);
6091 defsubr (&Sdelete_file);
6092 defsubr (&Srename_file);
6093 defsubr (&Sadd_name_to_file);
6094 defsubr (&Smake_symbolic_link);
6095 defsubr (&Sfile_name_absolute_p);
6096 defsubr (&Sfile_exists_p);
6097 defsubr (&Sfile_executable_p);
6098 defsubr (&Sfile_readable_p);
6099 defsubr (&Sfile_writable_p);
6100 defsubr (&Saccess_file);
6101 defsubr (&Sfile_symlink_p);
6102 defsubr (&Sfile_directory_p);
6103 defsubr (&Sfile_accessible_directory_p);
6104 defsubr (&Sfile_regular_p);
6105 defsubr (&Sfile_modes);
6106 defsubr (&Sset_file_modes);
6107 defsubr (&Sset_file_times);
6108 defsubr (&Sfile_selinux_context);
6109 defsubr (&Sfile_acl);
6110 defsubr (&Sset_file_acl);
6111 defsubr (&Sset_file_selinux_context);
6112 defsubr (&Sset_default_file_modes);
6113 defsubr (&Sdefault_file_modes);
6114 defsubr (&Sfile_newer_than_file_p);
6115 defsubr (&Sinsert_file_contents);
6116 defsubr (&Swrite_region);
6117 defsubr (&Scar_less_than_car);
6118 defsubr (&Sverify_visited_file_modtime);
6119 defsubr (&Svisited_file_modtime);
6120 defsubr (&Sset_visited_file_modtime);
6121 defsubr (&Sdo_auto_save);
6122 defsubr (&Sset_buffer_auto_saved);
6123 defsubr (&Sclear_buffer_auto_save_failure);
6124 defsubr (&Srecent_auto_save_p);
6126 defsubr (&Snext_read_file_uses_dialog_p);
6128 defsubr (&Sset_binary_mode);
6130 #ifdef HAVE_SYNC
6131 defsubr (&Sunix_sync);
6132 #endif