Make file-accessible-directory-p reliable on MS-Windows
[emacs.git] / src / fileio.c
bloba36dfbcfa364b78a0546b04ec823bbc8bad3669d
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <limits.h>
22 #include <fcntl.h>
23 #include "sysstdio.h"
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #ifdef HAVE_PWD_H
29 #include <pwd.h>
30 #endif
32 #include <errno.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
37 #endif
39 #ifdef HAVE_ACL_SET_FILE
40 #include <sys/acl.h>
41 #endif
43 #include <c-ctype.h>
45 #include "lisp.h"
46 #include "intervals.h"
47 #include "character.h"
48 #include "buffer.h"
49 #include "coding.h"
50 #include "window.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
53 #include "frame.h"
54 #include "dispextern.h"
56 #ifdef WINDOWSNT
57 #define NOMINMAX 1
58 #include <windows.h>
59 #include <sys/file.h>
60 #include "w32.h"
61 #endif /* not WINDOWSNT */
63 #ifdef MSDOS
64 #include "msdos.h"
65 #include <sys/param.h>
66 #endif
68 #ifdef DOS_NT
69 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
70 redirector allows the six letters between 'Z' and 'a' as well. */
71 #ifdef MSDOS
72 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
73 #endif
74 #ifdef WINDOWSNT
75 #define IS_DRIVE(x) c_isalpha (x)
76 #endif
77 /* Need to lower-case the drive letter, or else expanded
78 filenames will sometimes compare unequal, because
79 `expand-file-name' doesn't always down-case the drive letter. */
80 #define DRIVE_LETTER(x) c_tolower (x)
81 #endif
83 #include "systime.h"
84 #include <acl.h>
85 #include <allocator.h>
86 #include <careadlinkat.h>
87 #include <stat-time.h>
89 #include <binary-io.h>
91 #ifdef HPUX
92 #include <netio.h>
93 #endif
95 #include "commands.h"
97 /* True during writing of auto-save files. */
98 static bool auto_saving;
100 /* Emacs's real umask. */
101 static mode_t realmask;
103 /* Nonzero umask during creation of auto-save directories. */
104 static mode_t auto_saving_dir_umask;
106 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
107 a new file with the same mode as the original. */
108 static mode_t auto_save_mode_bits;
110 /* Set by auto_save_1 if an error occurred during the last auto-save. */
111 static bool auto_save_error_occurred;
113 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
114 number of a file system where time stamps were observed to to work. */
115 static bool valid_timestamp_file_system;
116 static dev_t timestamp_file_system;
118 /* Each time an annotation function changes the buffer, the new buffer
119 is added here. */
120 static Lisp_Object Vwrite_region_annotation_buffers;
122 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
123 Lisp_Object *, struct coding_system *);
124 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
125 struct coding_system *);
128 /* Return true if FILENAME exists. */
130 static bool
131 check_existing (const char *filename)
133 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
136 /* Return true if file FILENAME exists and can be executed. */
138 static bool
139 check_executable (char *filename)
141 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
144 /* Return true if file FILENAME exists and can be accessed
145 according to AMODE, which should include W_OK.
146 On failure, return false and set errno. */
148 static bool
149 check_writable (const char *filename, int amode)
151 #ifdef MSDOS
152 /* FIXME: an faccessat implementation should be added to the
153 DOS/Windows ports and this #ifdef branch should be removed. */
154 struct stat st;
155 if (stat (filename, &st) < 0)
156 return 0;
157 errno = EPERM;
158 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
159 #else /* not MSDOS */
160 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
161 #ifdef CYGWIN
162 /* faccessat may have returned failure because Cygwin couldn't
163 determine the file's UID or GID; if so, we return success. */
164 if (!res)
166 int faccessat_errno = errno;
167 struct stat st;
168 if (stat (filename, &st) < 0)
169 return 0;
170 res = (st.st_uid == -1 || st.st_gid == -1);
171 errno = faccessat_errno;
173 #endif /* CYGWIN */
174 return res;
175 #endif /* not MSDOS */
178 /* Signal a file-access failure. STRING describes the failure,
179 NAME the file involved, and ERRORNO the errno value.
181 If NAME is neither null nor a pair, package it up as a singleton
182 list before reporting it; this saves report_file_errno's caller the
183 trouble of preserving errno before calling list1. */
185 void
186 report_file_errno (char const *string, Lisp_Object name, int errorno)
188 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
189 synchronize_system_messages_locale ();
190 char *str = strerror (errorno);
191 Lisp_Object errstring
192 = code_convert_string_norecord (build_unibyte_string (str),
193 Vlocale_coding_system, 0);
194 Lisp_Object errdata = Fcons (errstring, data);
196 if (errorno == EEXIST)
197 xsignal (Qfile_already_exists, errdata);
198 else
199 xsignal (Qfile_error, Fcons (build_string (string), errdata));
202 /* Signal a file-access failure that set errno. STRING describes the
203 failure, NAME the file involved. When invoking this function, take
204 care to not use arguments such as build_string ("foo") that involve
205 side effects that may set errno. */
207 void
208 report_file_error (char const *string, Lisp_Object name)
210 report_file_errno (string, name, errno);
213 void
214 close_file_unwind (int fd)
216 emacs_close (fd);
219 void
220 fclose_unwind (void *arg)
222 FILE *stream = arg;
223 fclose (stream);
226 /* Restore point, having saved it as a marker. */
228 void
229 restore_point_unwind (Lisp_Object location)
231 Fgoto_char (location);
232 unchain_marker (XMARKER (location));
236 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
237 Sfind_file_name_handler, 2, 2, 0,
238 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
239 Otherwise, return nil.
240 A file name is handled if one of the regular expressions in
241 `file-name-handler-alist' matches it.
243 If OPERATION equals `inhibit-file-name-operation', then we ignore
244 any handlers that are members of `inhibit-file-name-handlers',
245 but we still do run any other handlers. This lets handlers
246 use the standard functions without calling themselves recursively. */)
247 (Lisp_Object filename, Lisp_Object operation)
249 /* This function must not munge the match data. */
250 Lisp_Object chain, inhibited_handlers, result;
251 ptrdiff_t pos = -1;
253 result = Qnil;
254 CHECK_STRING (filename);
256 if (EQ (operation, Vinhibit_file_name_operation))
257 inhibited_handlers = Vinhibit_file_name_handlers;
258 else
259 inhibited_handlers = Qnil;
261 for (chain = Vfile_name_handler_alist; CONSP (chain);
262 chain = XCDR (chain))
264 Lisp_Object elt;
265 elt = XCAR (chain);
266 if (CONSP (elt))
268 Lisp_Object string = XCAR (elt);
269 ptrdiff_t match_pos;
270 Lisp_Object handler = XCDR (elt);
271 Lisp_Object operations = Qnil;
273 if (SYMBOLP (handler))
274 operations = Fget (handler, Qoperations);
276 if (STRINGP (string)
277 && (match_pos = fast_string_match (string, filename)) > pos
278 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
280 Lisp_Object tem;
282 handler = XCDR (elt);
283 tem = Fmemq (handler, inhibited_handlers);
284 if (NILP (tem))
286 result = handler;
287 pos = match_pos;
292 QUIT;
294 return result;
297 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
298 1, 1, 0,
299 doc: /* Return the directory component in file name FILENAME.
300 Return nil if FILENAME does not include a directory.
301 Otherwise return a directory name.
302 Given a Unix syntax file name, returns a string ending in slash. */)
303 (Lisp_Object filename)
305 Lisp_Object handler;
307 CHECK_STRING (filename);
309 /* If the file name has special constructs in it,
310 call the corresponding file handler. */
311 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
312 if (!NILP (handler))
314 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
315 filename);
316 return STRINGP (handled_name) ? handled_name : Qnil;
319 char *beg = SSDATA (filename);
320 char const *p = beg + SBYTES (filename);
322 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
323 #ifdef DOS_NT
324 /* only recognize drive specifier at the beginning */
325 && !(p[-1] == ':'
326 /* handle the "/:d:foo" and "/:foo" cases correctly */
327 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
328 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
329 #endif
330 ) p--;
332 if (p == beg)
333 return Qnil;
334 #ifdef DOS_NT
335 /* Expansion of "c:" to drive and default directory. */
336 Lisp_Object tem_fn;
337 USE_SAFE_ALLOCA;
338 SAFE_ALLOCA_STRING (beg, filename);
339 p = beg + (p - SSDATA (filename));
341 if (p[-1] == ':')
343 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
344 char *res = alloca (MAXPATHLEN + 1);
345 char *r = res;
347 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
349 memcpy (res, beg, 2);
350 beg += 2;
351 r += 2;
354 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
356 size_t l = strlen (res);
358 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
359 strcat (res, "/");
360 beg = res;
361 p = beg + strlen (beg);
362 dostounix_filename (beg);
363 tem_fn = make_specified_string (beg, -1, p - beg,
364 STRING_MULTIBYTE (filename));
366 else
367 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
368 STRING_MULTIBYTE (filename));
370 else if (STRING_MULTIBYTE (filename))
372 tem_fn = make_specified_string (beg, -1, p - beg, 1);
373 dostounix_filename (SSDATA (tem_fn));
374 #ifdef WINDOWSNT
375 if (!NILP (Vw32_downcase_file_names))
376 tem_fn = Fdowncase (tem_fn);
377 #endif
379 else
381 dostounix_filename (beg);
382 tem_fn = make_specified_string (beg, -1, p - beg, 0);
384 SAFE_FREE ();
385 return tem_fn;
386 #else /* DOS_NT */
387 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
388 #endif /* DOS_NT */
391 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
392 Sfile_name_nondirectory, 1, 1, 0,
393 doc: /* Return file name FILENAME sans its directory.
394 For example, in a Unix-syntax file name,
395 this is everything after the last slash,
396 or the entire name if it contains no slash. */)
397 (Lisp_Object filename)
399 register const char *beg, *p, *end;
400 Lisp_Object handler;
402 CHECK_STRING (filename);
404 /* If the file name has special constructs in it,
405 call the corresponding file handler. */
406 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
407 if (!NILP (handler))
409 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
410 filename);
411 if (STRINGP (handled_name))
412 return handled_name;
413 error ("Invalid handler in `file-name-handler-alist'");
416 beg = SSDATA (filename);
417 end = p = beg + SBYTES (filename);
419 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
420 #ifdef DOS_NT
421 /* only recognize drive specifier at beginning */
422 && !(p[-1] == ':'
423 /* handle the "/:d:foo" case correctly */
424 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
425 #endif
427 p--;
429 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
432 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
433 Sunhandled_file_name_directory, 1, 1, 0,
434 doc: /* Return a directly usable directory name somehow associated with FILENAME.
435 A `directly usable' directory name is one that may be used without the
436 intervention of any file handler.
437 If FILENAME is a directly usable file itself, return
438 \(file-name-directory FILENAME).
439 If FILENAME refers to a file which is not accessible from a local process,
440 then this should return nil.
441 The `call-process' and `start-process' functions use this function to
442 get a current directory to run processes in. */)
443 (Lisp_Object filename)
445 Lisp_Object handler;
447 /* If the file name has special constructs in it,
448 call the corresponding file handler. */
449 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
450 if (!NILP (handler))
452 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
453 filename);
454 return STRINGP (handled_name) ? handled_name : Qnil;
457 return Ffile_name_directory (filename);
460 /* Maximum number of bytes that DST will be longer than SRC
461 in file_name_as_directory. This occurs when SRCLEN == 0. */
462 enum { file_name_as_directory_slop = 2 };
464 /* Convert from file name SRC of length SRCLEN to directory name in
465 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
466 string. On UNIX, just make sure there is a terminating /. Return
467 the length of DST in bytes. */
469 static ptrdiff_t
470 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
471 bool multibyte)
473 if (srclen == 0)
475 dst[0] = '.';
476 dst[1] = '/';
477 dst[2] = '\0';
478 return 2;
481 memcpy (dst, src, srclen);
482 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
483 dst[srclen++] = DIRECTORY_SEP;
484 dst[srclen] = 0;
485 #ifdef DOS_NT
486 dostounix_filename (dst);
487 #endif
488 return srclen;
491 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
492 Sfile_name_as_directory, 1, 1, 0,
493 doc: /* Return a string representing the file name FILE interpreted as a directory.
494 This operation exists because a directory is also a file, but its name as
495 a directory is different from its name as a file.
496 The result can be used as the value of `default-directory'
497 or passed as second argument to `expand-file-name'.
498 For a Unix-syntax file name, just appends a slash. */)
499 (Lisp_Object file)
501 char *buf;
502 ptrdiff_t length;
503 Lisp_Object handler, val;
504 USE_SAFE_ALLOCA;
506 CHECK_STRING (file);
508 /* If the file name has special constructs in it,
509 call the corresponding file handler. */
510 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
511 if (!NILP (handler))
513 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
514 file);
515 if (STRINGP (handled_name))
516 return handled_name;
517 error ("Invalid handler in `file-name-handler-alist'");
520 #ifdef WINDOWSNT
521 if (!NILP (Vw32_downcase_file_names))
522 file = Fdowncase (file);
523 #endif
524 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
525 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
526 STRING_MULTIBYTE (file));
527 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
528 SAFE_FREE ();
529 return val;
532 /* Convert from directory name SRC of length SRCLEN to file name in
533 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
534 string. On UNIX, just make sure there isn't a terminating /.
535 Return the length of DST in bytes. */
537 static ptrdiff_t
538 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
540 /* Process as Unix format: just remove any final slash.
541 But leave "/" and "//" unchanged. */
542 while (srclen > 1
543 #ifdef DOS_NT
544 && !IS_ANY_SEP (src[srclen - 2])
545 #endif
546 && IS_DIRECTORY_SEP (src[srclen - 1])
547 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
548 srclen--;
550 memcpy (dst, src, srclen);
551 dst[srclen] = 0;
552 #ifdef DOS_NT
553 dostounix_filename (dst);
554 #endif
555 return srclen;
558 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
559 1, 1, 0,
560 doc: /* Returns the file name of the directory named DIRECTORY.
561 This is the name of the file that holds the data for the directory DIRECTORY.
562 This operation exists because a directory is also a file, but its name as
563 a directory is different from its name as a file.
564 In Unix-syntax, this function just removes the final slash. */)
565 (Lisp_Object directory)
567 char *buf;
568 ptrdiff_t length;
569 Lisp_Object handler, val;
570 USE_SAFE_ALLOCA;
572 CHECK_STRING (directory);
574 /* If the file name has special constructs in it,
575 call the corresponding file handler. */
576 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
577 if (!NILP (handler))
579 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
580 directory);
581 if (STRINGP (handled_name))
582 return handled_name;
583 error ("Invalid handler in `file-name-handler-alist'");
586 #ifdef WINDOWSNT
587 if (!NILP (Vw32_downcase_file_names))
588 directory = Fdowncase (directory);
589 #endif
590 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
591 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
592 STRING_MULTIBYTE (directory));
593 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
594 SAFE_FREE ();
595 return val;
598 static const char make_temp_name_tbl[64] =
600 'A','B','C','D','E','F','G','H',
601 'I','J','K','L','M','N','O','P',
602 'Q','R','S','T','U','V','W','X',
603 'Y','Z','a','b','c','d','e','f',
604 'g','h','i','j','k','l','m','n',
605 'o','p','q','r','s','t','u','v',
606 'w','x','y','z','0','1','2','3',
607 '4','5','6','7','8','9','-','_'
610 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
612 /* Value is a temporary file name starting with PREFIX, a string.
614 The Emacs process number forms part of the result, so there is
615 no danger of generating a name being used by another process.
616 In addition, this function makes an attempt to choose a name
617 which has no existing file. To make this work, PREFIX should be
618 an absolute file name.
620 BASE64_P means add the pid as 3 characters in base64
621 encoding. In this case, 6 characters will be added to PREFIX to
622 form the file name. Otherwise, if Emacs is running on a system
623 with long file names, add the pid as a decimal number.
625 This function signals an error if no unique file name could be
626 generated. */
628 Lisp_Object
629 make_temp_name (Lisp_Object prefix, bool base64_p)
631 Lisp_Object val, encoded_prefix;
632 ptrdiff_t len;
633 printmax_t pid;
634 char *p, *data;
635 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
636 int pidlen;
638 CHECK_STRING (prefix);
640 /* VAL is created by adding 6 characters to PREFIX. The first
641 three are the PID of this process, in base 64, and the second
642 three are incremented if the file already exists. This ensures
643 262144 unique file names per PID per PREFIX. */
645 pid = getpid ();
647 if (base64_p)
649 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
650 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
651 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
652 pidlen = 3;
654 else
656 #ifdef HAVE_LONG_FILE_NAMES
657 pidlen = sprintf (pidbuf, "%"pMd, pid);
658 #else
659 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
660 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
661 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
662 pidlen = 3;
663 #endif
666 encoded_prefix = ENCODE_FILE (prefix);
667 len = SBYTES (encoded_prefix);
668 val = make_uninit_string (len + 3 + pidlen);
669 data = SSDATA (val);
670 memcpy (data, SSDATA (encoded_prefix), len);
671 p = data + len;
673 memcpy (p, pidbuf, pidlen);
674 p += pidlen;
676 /* Here we try to minimize useless stat'ing when this function is
677 invoked many times successively with the same PREFIX. We achieve
678 this by initializing count to a random value, and incrementing it
679 afterwards.
681 We don't want make-temp-name to be called while dumping,
682 because then make_temp_name_count_initialized_p would get set
683 and then make_temp_name_count would not be set when Emacs starts. */
685 if (!make_temp_name_count_initialized_p)
687 make_temp_name_count = time (NULL);
688 make_temp_name_count_initialized_p = 1;
691 while (1)
693 unsigned num = make_temp_name_count;
695 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
696 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
697 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
699 /* Poor man's congruential RN generator. Replace with
700 ++make_temp_name_count for debugging. */
701 make_temp_name_count += 25229;
702 make_temp_name_count %= 225307;
704 if (!check_existing (data))
706 /* We want to return only if errno is ENOENT. */
707 if (errno == ENOENT)
708 return DECODE_FILE (val);
709 else
710 /* The error here is dubious, but there is little else we
711 can do. The alternatives are to return nil, which is
712 as bad as (and in many cases worse than) throwing the
713 error, or to ignore the error, which will likely result
714 in looping through 225307 stat's, which is not only
715 dog-slow, but also useless since eventually nil would
716 have to be returned anyway. */
717 report_file_error ("Cannot create temporary name for prefix",
718 prefix);
719 /* not reached */
725 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
726 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
727 The Emacs process number forms part of the result, so there is no
728 danger of generating a name being used by another Emacs process
729 \(so long as only a single host can access the containing directory...).
731 This function tries to choose a name that has no existing file.
732 For this to work, PREFIX should be an absolute file name.
734 There is a race condition between calling `make-temp-name' and creating the
735 file, which opens all kinds of security holes. For that reason, you should
736 normally use `make-temp-file' instead. */)
737 (Lisp_Object prefix)
739 return make_temp_name (prefix, 0);
742 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
743 doc: /* Convert filename NAME to absolute, and canonicalize it.
744 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
745 \(does not start with slash or tilde); both the directory name and
746 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
747 missing, the current buffer's value of `default-directory' is used.
748 NAME should be a string that is a valid file name for the underlying
749 filesystem.
750 File name components that are `.' are removed, and
751 so are file name components followed by `..', along with the `..' itself;
752 note that these simplifications are done without checking the resulting
753 file names in the file system.
754 Multiple consecutive slashes are collapsed into a single slash,
755 except at the beginning of the file name when they are significant (e.g.,
756 UNC file names on MS-Windows.)
757 An initial `~/' expands to your home directory.
758 An initial `~USER/' expands to USER's home directory.
759 See also the function `substitute-in-file-name'.
761 For technical reasons, this function can return correct but
762 non-intuitive results for the root directory; for instance,
763 \(expand-file-name ".." "/") returns "/..". For this reason, use
764 \(directory-file-name (file-name-directory dirname)) to traverse a
765 filesystem tree, not (expand-file-name ".." dirname). */)
766 (Lisp_Object name, Lisp_Object default_directory)
768 /* These point to SDATA and need to be careful with string-relocation
769 during GC (via DECODE_FILE). */
770 char *nm;
771 char *nmlim;
772 const char *newdir;
773 const char *newdirlim;
774 /* This should only point to alloca'd data. */
775 char *target;
777 ptrdiff_t tlen;
778 struct passwd *pw;
779 #ifdef DOS_NT
780 int drive = 0;
781 bool collapse_newdir = true;
782 bool is_escaped = 0;
783 #endif /* DOS_NT */
784 ptrdiff_t length, nbytes;
785 Lisp_Object handler, result, handled_name;
786 bool multibyte;
787 Lisp_Object hdir;
788 USE_SAFE_ALLOCA;
790 CHECK_STRING (name);
792 /* If the file name has special constructs in it,
793 call the corresponding file handler. */
794 handler = Ffind_file_name_handler (name, Qexpand_file_name);
795 if (!NILP (handler))
797 handled_name = call3 (handler, Qexpand_file_name,
798 name, default_directory);
799 if (STRINGP (handled_name))
800 return handled_name;
801 error ("Invalid handler in `file-name-handler-alist'");
805 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
806 if (NILP (default_directory))
807 default_directory = BVAR (current_buffer, directory);
808 if (! STRINGP (default_directory))
810 #ifdef DOS_NT
811 /* "/" is not considered a root directory on DOS_NT, so using "/"
812 here causes an infinite recursion in, e.g., the following:
814 (let (default-directory)
815 (expand-file-name "a"))
817 To avoid this, we set default_directory to the root of the
818 current drive. */
819 default_directory = build_string (emacs_root_dir ());
820 #else
821 default_directory = build_string ("/");
822 #endif
825 if (!NILP (default_directory))
827 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
828 if (!NILP (handler))
830 handled_name = call3 (handler, Qexpand_file_name,
831 name, default_directory);
832 if (STRINGP (handled_name))
833 return handled_name;
834 error ("Invalid handler in `file-name-handler-alist'");
839 char *o = SSDATA (default_directory);
841 /* Make sure DEFAULT_DIRECTORY is properly expanded.
842 It would be better to do this down below where we actually use
843 default_directory. Unfortunately, calling Fexpand_file_name recursively
844 could invoke GC, and the strings might be relocated. This would
845 be annoying because we have pointers into strings lying around
846 that would need adjusting, and people would add new pointers to
847 the code and forget to adjust them, resulting in intermittent bugs.
848 Putting this call here avoids all that crud.
850 The EQ test avoids infinite recursion. */
851 if (! NILP (default_directory) && !EQ (default_directory, name)
852 /* Save time in some common cases - as long as default_directory
853 is not relative, it can be canonicalized with name below (if it
854 is needed at all) without requiring it to be expanded now. */
855 #ifdef DOS_NT
856 /* Detect MSDOS file names with drive specifiers. */
857 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
858 && IS_DIRECTORY_SEP (o[2]))
859 #ifdef WINDOWSNT
860 /* Detect Windows file names in UNC format. */
861 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
862 #endif
863 #else /* not DOS_NT */
864 /* Detect Unix absolute file names (/... alone is not absolute on
865 DOS or Windows). */
866 && ! (IS_DIRECTORY_SEP (o[0]))
867 #endif /* not DOS_NT */
870 default_directory = Fexpand_file_name (default_directory, Qnil);
873 multibyte = STRING_MULTIBYTE (name);
874 if (multibyte != STRING_MULTIBYTE (default_directory))
876 if (multibyte)
878 unsigned char *p = SDATA (name);
880 while (*p && ASCII_CHAR_P (*p))
881 p++;
882 if (*p == '\0')
884 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
885 unibyte. Do not convert DEFAULT_DIRECTORY to
886 multibyte; instead, convert NAME to a unibyte string,
887 so that the result of this function is also a unibyte
888 string. This is needed during bootstrapping and
889 dumping, when Emacs cannot decode file names, because
890 the locale environment is not set up. */
891 name = make_unibyte_string (SSDATA (name), SBYTES (name));
892 multibyte = 0;
894 else
895 default_directory = string_to_multibyte (default_directory);
897 else
899 name = string_to_multibyte (name);
900 multibyte = 1;
904 #ifdef WINDOWSNT
905 if (!NILP (Vw32_downcase_file_names))
906 default_directory = Fdowncase (default_directory);
907 #endif
909 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
910 SAFE_ALLOCA_STRING (nm, name);
911 nmlim = nm + SBYTES (name);
913 #ifdef DOS_NT
914 /* Note if special escape prefix is present, but remove for now. */
915 if (nm[0] == '/' && nm[1] == ':')
917 is_escaped = 1;
918 nm += 2;
921 /* Find and remove drive specifier if present; this makes nm absolute
922 even if the rest of the name appears to be relative. Only look for
923 drive specifier at the beginning. */
924 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
926 drive = (unsigned char) nm[0];
927 nm += 2;
930 #ifdef WINDOWSNT
931 /* If we see "c://somedir", we want to strip the first slash after the
932 colon when stripping the drive letter. Otherwise, this expands to
933 "//somedir". */
934 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
935 nm++;
937 /* Discard any previous drive specifier if nm is now in UNC format. */
938 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
939 && !IS_DIRECTORY_SEP (nm[2]))
940 drive = 0;
941 #endif /* WINDOWSNT */
942 #endif /* DOS_NT */
944 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
945 none are found, we can probably return right away. We will avoid
946 allocating a new string if name is already fully expanded. */
947 if (
948 IS_DIRECTORY_SEP (nm[0])
949 #ifdef MSDOS
950 && drive && !is_escaped
951 #endif
952 #ifdef WINDOWSNT
953 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
954 #endif
957 /* If it turns out that the filename we want to return is just a
958 suffix of FILENAME, we don't need to go through and edit
959 things; we just need to construct a new string using data
960 starting at the middle of FILENAME. If we set LOSE, that
961 means we've discovered that we can't do that cool trick. */
962 bool lose = 0;
963 char *p = nm;
965 while (*p)
967 /* Since we know the name is absolute, we can assume that each
968 element starts with a "/". */
970 /* "." and ".." are hairy. */
971 if (IS_DIRECTORY_SEP (p[0])
972 && p[1] == '.'
973 && (IS_DIRECTORY_SEP (p[2])
974 || p[2] == 0
975 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
976 || p[3] == 0))))
977 lose = 1;
978 /* Replace multiple slashes with a single one, except
979 leave leading "//" alone. */
980 else if (IS_DIRECTORY_SEP (p[0])
981 && IS_DIRECTORY_SEP (p[1])
982 && (p != nm || IS_DIRECTORY_SEP (p[2])))
983 lose = 1;
984 p++;
986 if (!lose)
988 #ifdef DOS_NT
989 /* Make sure directories are all separated with /, but
990 avoid allocation of a new string when not required. */
991 dostounix_filename (nm);
992 #ifdef WINDOWSNT
993 if (IS_DIRECTORY_SEP (nm[1]))
995 if (strcmp (nm, SSDATA (name)) != 0)
996 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
998 else
999 #endif
1000 /* Drive must be set, so this is okay. */
1001 if (strcmp (nm - 2, SSDATA (name)) != 0)
1003 char temp[] = " :";
1005 name = make_specified_string (nm, -1, p - nm, multibyte);
1006 temp[0] = DRIVE_LETTER (drive);
1007 AUTO_STRING (drive_prefix, temp);
1008 name = concat2 (drive_prefix, name);
1010 #ifdef WINDOWSNT
1011 if (!NILP (Vw32_downcase_file_names))
1012 name = Fdowncase (name);
1013 #endif
1014 #else /* not DOS_NT */
1015 if (strcmp (nm, SSDATA (name)) != 0)
1016 name = make_specified_string (nm, -1, nmlim - nm, multibyte);
1017 #endif /* not DOS_NT */
1018 SAFE_FREE ();
1019 return name;
1023 /* At this point, nm might or might not be an absolute file name. We
1024 need to expand ~ or ~user if present, otherwise prefix nm with
1025 default_directory if nm is not absolute, and finally collapse /./
1026 and /foo/../ sequences.
1028 We set newdir to be the appropriate prefix if one is needed:
1029 - the relevant user directory if nm starts with ~ or ~user
1030 - the specified drive's working dir (DOS/NT only) if nm does not
1031 start with /
1032 - the value of default_directory.
1034 Note that these prefixes are not guaranteed to be absolute (except
1035 for the working dir of a drive). Therefore, to ensure we always
1036 return an absolute name, if the final prefix is not absolute we
1037 append it to the current working directory. */
1039 newdir = newdirlim = 0;
1041 if (nm[0] == '~') /* prefix ~ */
1043 if (IS_DIRECTORY_SEP (nm[1])
1044 || nm[1] == 0) /* ~ by itself */
1046 Lisp_Object tem;
1048 if (!(newdir = egetenv ("HOME")))
1049 newdir = newdirlim = "";
1050 nm++;
1051 /* `egetenv' may return a unibyte string, which will bite us since
1052 we expect the directory to be multibyte. */
1053 #ifdef WINDOWSNT
1054 if (newdir[0])
1056 char newdir_utf8[MAX_UTF8_PATH];
1058 filename_from_ansi (newdir, newdir_utf8);
1059 tem = make_unibyte_string (newdir_utf8, strlen (newdir_utf8));
1061 else
1062 #endif
1063 tem = build_string (newdir);
1064 newdirlim = newdir + SBYTES (tem);
1065 if (multibyte && !STRING_MULTIBYTE (tem))
1067 hdir = DECODE_FILE (tem);
1068 newdir = SSDATA (hdir);
1069 newdirlim = newdir + SBYTES (hdir);
1071 #ifdef DOS_NT
1072 collapse_newdir = false;
1073 #endif
1075 else /* ~user/filename */
1077 char *o, *p;
1078 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1079 continue;
1080 o = SAFE_ALLOCA (p - nm + 1);
1081 memcpy (o, nm, p - nm);
1082 o[p - nm] = 0;
1084 block_input ();
1085 pw = getpwnam (o + 1);
1086 unblock_input ();
1087 if (pw)
1089 Lisp_Object tem;
1091 newdir = pw->pw_dir;
1092 /* `getpwnam' may return a unibyte string, which will
1093 bite us since we expect the directory to be
1094 multibyte. */
1095 tem = make_unibyte_string (newdir, strlen (newdir));
1096 newdirlim = newdir + SBYTES (tem);
1097 if (multibyte && !STRING_MULTIBYTE (tem))
1099 hdir = DECODE_FILE (tem);
1100 newdir = SSDATA (hdir);
1101 newdirlim = newdir + SBYTES (hdir);
1103 nm = p;
1104 #ifdef DOS_NT
1105 collapse_newdir = false;
1106 #endif
1109 /* If we don't find a user of that name, leave the name
1110 unchanged; don't move nm forward to p. */
1114 #ifdef DOS_NT
1115 /* On DOS and Windows, nm is absolute if a drive name was specified;
1116 use the drive's current directory as the prefix if needed. */
1117 if (!newdir && drive)
1119 /* Get default directory if needed to make nm absolute. */
1120 char *adir = NULL;
1121 if (!IS_DIRECTORY_SEP (nm[0]))
1123 adir = alloca (MAXPATHLEN + 1);
1124 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1125 adir = NULL;
1126 else if (multibyte)
1128 Lisp_Object tem = build_string (adir);
1130 tem = DECODE_FILE (tem);
1131 newdirlim = adir + SBYTES (tem);
1132 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1134 else
1135 newdirlim = adir + strlen (adir);
1137 if (!adir)
1139 /* Either nm starts with /, or drive isn't mounted. */
1140 adir = alloca (4);
1141 adir[0] = DRIVE_LETTER (drive);
1142 adir[1] = ':';
1143 adir[2] = '/';
1144 adir[3] = 0;
1145 newdirlim = adir + 3;
1147 newdir = adir;
1149 #endif /* DOS_NT */
1151 /* Finally, if no prefix has been specified and nm is not absolute,
1152 then it must be expanded relative to default_directory. */
1154 if (1
1155 #ifndef DOS_NT
1156 /* /... alone is not absolute on DOS and Windows. */
1157 && !IS_DIRECTORY_SEP (nm[0])
1158 #endif
1159 #ifdef WINDOWSNT
1160 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1])
1161 && !IS_DIRECTORY_SEP (nm[2]))
1162 #endif
1163 && !newdir)
1165 newdir = SSDATA (default_directory);
1166 newdirlim = newdir + SBYTES (default_directory);
1167 #ifdef DOS_NT
1168 /* Note if special escape prefix is present, but remove for now. */
1169 if (newdir[0] == '/' && newdir[1] == ':')
1171 is_escaped = 1;
1172 newdir += 2;
1174 #endif
1177 #ifdef DOS_NT
1178 if (newdir)
1180 /* First ensure newdir is an absolute name. */
1181 if (
1182 /* Detect MSDOS file names with drive specifiers. */
1183 ! (IS_DRIVE (newdir[0])
1184 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1185 #ifdef WINDOWSNT
1186 /* Detect Windows file names in UNC format. */
1187 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1188 && !IS_DIRECTORY_SEP (newdir[2]))
1189 #endif
1192 /* Effectively, let newdir be (expand-file-name newdir cwd).
1193 Because of the admonition against calling expand-file-name
1194 when we have pointers into lisp strings, we accomplish this
1195 indirectly by prepending newdir to nm if necessary, and using
1196 cwd (or the wd of newdir's drive) as the new newdir. */
1197 char *adir;
1198 #ifdef WINDOWSNT
1199 const int adir_size = MAX_UTF8_PATH;
1200 #else
1201 const int adir_size = MAXPATHLEN + 1;
1202 #endif
1204 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1206 drive = (unsigned char) newdir[0];
1207 newdir += 2;
1209 if (!IS_DIRECTORY_SEP (nm[0]))
1211 ptrdiff_t nmlen = nmlim - nm;
1212 ptrdiff_t newdirlen = newdirlim - newdir;
1213 char *tmp = alloca (newdirlen + file_name_as_directory_slop
1214 + nmlen + 1);
1215 ptrdiff_t dlen = file_name_as_directory (tmp, newdir, newdirlen,
1216 multibyte);
1217 memcpy (tmp + dlen, nm, nmlen + 1);
1218 nm = tmp;
1219 nmlim = nm + dlen + nmlen;
1221 adir = alloca (adir_size);
1222 if (drive)
1224 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1225 strcpy (adir, "/");
1227 else
1228 getcwd (adir, adir_size);
1229 if (multibyte)
1231 Lisp_Object tem = build_string (adir);
1233 tem = DECODE_FILE (tem);
1234 newdirlim = adir + SBYTES (tem);
1235 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1237 else
1238 newdirlim = adir + strlen (adir);
1239 newdir = adir;
1242 /* Strip off drive name from prefix, if present. */
1243 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1245 drive = newdir[0];
1246 newdir += 2;
1249 /* Keep only a prefix from newdir if nm starts with slash
1250 (//server/share for UNC, nothing otherwise). */
1251 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1253 #ifdef WINDOWSNT
1254 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1])
1255 && !IS_DIRECTORY_SEP (newdir[2]))
1257 char *adir = strcpy (alloca (newdirlim - newdir + 1), newdir);
1258 char *p = adir + 2;
1259 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1260 p++;
1261 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1262 *p = 0;
1263 newdir = adir;
1264 newdirlim = newdir + strlen (adir);
1266 else
1267 #endif
1268 newdir = newdirlim = "";
1271 #endif /* DOS_NT */
1273 /* Ignore any slash at the end of newdir, unless newdir is
1274 just "/" or "//". */
1275 length = newdirlim - newdir;
1276 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1277 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1278 length--;
1280 /* Now concatenate the directory and name to new space in the stack frame. */
1281 tlen = length + file_name_as_directory_slop + (nmlim - nm) + 1;
1282 eassert (tlen > file_name_as_directory_slop + 1);
1283 #ifdef DOS_NT
1284 /* Reserve space for drive specifier and escape prefix, since either
1285 or both may need to be inserted. (The Microsoft x86 compiler
1286 produces incorrect code if the following two lines are combined.) */
1287 target = alloca (tlen + 4);
1288 target += 4;
1289 #else /* not DOS_NT */
1290 target = SAFE_ALLOCA (tlen);
1291 #endif /* not DOS_NT */
1292 *target = 0;
1293 nbytes = 0;
1295 if (newdir)
1297 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1299 #ifdef DOS_NT
1300 /* If newdir is effectively "C:/", then the drive letter will have
1301 been stripped and newdir will be "/". Concatenating with an
1302 absolute directory in nm produces "//", which will then be
1303 incorrectly treated as a network share. Ignore newdir in
1304 this case (keeping the drive letter). */
1305 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1306 && newdir[1] == '\0'))
1307 #endif
1309 memcpy (target, newdir, length);
1310 target[length] = 0;
1311 nbytes = length;
1314 else
1315 nbytes = file_name_as_directory (target, newdir, length, multibyte);
1318 memcpy (target + nbytes, nm, nmlim - nm + 1);
1320 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1321 appear. */
1323 char *p = target;
1324 char *o = target;
1326 while (*p)
1328 if (!IS_DIRECTORY_SEP (*p))
1330 *o++ = *p++;
1332 else if (p[1] == '.'
1333 && (IS_DIRECTORY_SEP (p[2])
1334 || p[2] == 0))
1336 /* If "/." is the entire filename, keep the "/". Otherwise,
1337 just delete the whole "/.". */
1338 if (o == target && p[2] == '\0')
1339 *o++ = *p;
1340 p += 2;
1342 else if (p[1] == '.' && p[2] == '.'
1343 /* `/../' is the "superroot" on certain file systems.
1344 Turned off on DOS_NT systems because they have no
1345 "superroot" and because this causes us to produce
1346 file names like "d:/../foo" which fail file-related
1347 functions of the underlying OS. (To reproduce, try a
1348 long series of "../../" in default_directory, longer
1349 than the number of levels from the root.) */
1350 #ifndef DOS_NT
1351 && o != target
1352 #endif
1353 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1355 #ifdef WINDOWSNT
1356 char *prev_o = o;
1357 #endif
1358 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1359 continue;
1360 #ifdef WINDOWSNT
1361 /* Don't go below server level in UNC filenames. */
1362 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1363 && IS_DIRECTORY_SEP (*target))
1364 o = prev_o;
1365 else
1366 #endif
1367 /* Keep initial / only if this is the whole name. */
1368 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1369 ++o;
1370 p += 3;
1372 else if (IS_DIRECTORY_SEP (p[1])
1373 && (p != target || IS_DIRECTORY_SEP (p[2])))
1374 /* Collapse multiple "/", except leave leading "//" alone. */
1375 p++;
1376 else
1378 *o++ = *p++;
1382 #ifdef DOS_NT
1383 /* At last, set drive name. */
1384 #ifdef WINDOWSNT
1385 /* Except for network file name. */
1386 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1387 #endif /* WINDOWSNT */
1389 if (!drive) emacs_abort ();
1390 target -= 2;
1391 target[0] = DRIVE_LETTER (drive);
1392 target[1] = ':';
1394 /* Reinsert the escape prefix if required. */
1395 if (is_escaped)
1397 target -= 2;
1398 target[0] = '/';
1399 target[1] = ':';
1401 result = make_specified_string (target, -1, o - target, multibyte);
1402 dostounix_filename (SSDATA (result));
1403 #ifdef WINDOWSNT
1404 if (!NILP (Vw32_downcase_file_names))
1405 result = Fdowncase (result);
1406 #endif
1407 #else /* !DOS_NT */
1408 result = make_specified_string (target, -1, o - target, multibyte);
1409 #endif /* !DOS_NT */
1412 /* Again look to see if the file name has special constructs in it
1413 and perhaps call the corresponding file handler. This is needed
1414 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1415 the ".." component gives us "/user@host:/bar/../baz" which needs
1416 to be expanded again. */
1417 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1418 if (!NILP (handler))
1420 handled_name = call3 (handler, Qexpand_file_name,
1421 result, default_directory);
1422 if (! STRINGP (handled_name))
1423 error ("Invalid handler in `file-name-handler-alist'");
1424 result = handled_name;
1427 SAFE_FREE ();
1428 return result;
1431 #if 0
1432 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1433 This is the old version of expand-file-name, before it was thoroughly
1434 rewritten for Emacs 10.31. We leave this version here commented-out,
1435 because the code is very complex and likely to have subtle bugs. If
1436 bugs _are_ found, it might be of interest to look at the old code and
1437 see what did it do in the relevant situation.
1439 Don't remove this code: it's true that it will be accessible
1440 from the repository, but a few years from deletion, people will
1441 forget it is there. */
1443 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1444 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1445 "Convert FILENAME to absolute, and canonicalize it.\n\
1446 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1447 \(does not start with slash); if DEFAULT is nil or missing,\n\
1448 the current buffer's value of default-directory is used.\n\
1449 Filenames containing `.' or `..' as components are simplified;\n\
1450 initial `~/' expands to your home directory.\n\
1451 See also the function `substitute-in-file-name'.")
1452 (name, defalt)
1453 Lisp_Object name, defalt;
1455 unsigned char *nm;
1457 register unsigned char *newdir, *p, *o;
1458 ptrdiff_t tlen;
1459 unsigned char *target;
1460 struct passwd *pw;
1462 CHECK_STRING (name);
1463 nm = SDATA (name);
1465 /* If nm is absolute, flush ...// and detect /./ and /../.
1466 If no /./ or /../ we can return right away. */
1467 if (nm[0] == '/')
1469 bool lose = 0;
1470 p = nm;
1471 while (*p)
1473 if (p[0] == '/' && p[1] == '/')
1474 nm = p + 1;
1475 if (p[0] == '/' && p[1] == '~')
1476 nm = p + 1, lose = 1;
1477 if (p[0] == '/' && p[1] == '.'
1478 && (p[2] == '/' || p[2] == 0
1479 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1480 lose = 1;
1481 p++;
1483 if (!lose)
1485 if (nm == SDATA (name))
1486 return name;
1487 return build_string (nm);
1491 /* Now determine directory to start with and put it in NEWDIR. */
1493 newdir = 0;
1495 if (nm[0] == '~') /* prefix ~ */
1496 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1498 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1499 newdir = (unsigned char *) "";
1500 nm++;
1502 else /* ~user/filename */
1504 /* Get past ~ to user. */
1505 unsigned char *user = nm + 1;
1506 /* Find end of name. */
1507 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1508 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1509 /* Copy the user name into temp storage. */
1510 o = alloca (len + 1);
1511 memcpy (o, user, len);
1512 o[len] = 0;
1514 /* Look up the user name. */
1515 block_input ();
1516 pw = (struct passwd *) getpwnam (o + 1);
1517 unblock_input ();
1518 if (!pw)
1519 error ("\"%s\" isn't a registered user", o + 1);
1521 newdir = (unsigned char *) pw->pw_dir;
1523 /* Discard the user name from NM. */
1524 nm += len;
1527 if (nm[0] != '/' && !newdir)
1529 if (NILP (defalt))
1530 defalt = current_buffer->directory;
1531 CHECK_STRING (defalt);
1532 newdir = SDATA (defalt);
1535 /* Now concatenate the directory and name to new space in the stack frame. */
1537 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1538 target = alloca (tlen);
1539 *target = 0;
1541 if (newdir)
1543 if (nm[0] == 0 || nm[0] == '/')
1544 strcpy (target, newdir);
1545 else
1546 file_name_as_directory (target, newdir);
1549 strcat (target, nm);
1551 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1553 p = target;
1554 o = target;
1556 while (*p)
1558 if (*p != '/')
1560 *o++ = *p++;
1562 else if (!strncmp (p, "//", 2)
1565 o = target;
1566 p++;
1568 else if (p[0] == '/' && p[1] == '.'
1569 && (p[2] == '/' || p[2] == 0))
1570 p += 2;
1571 else if (!strncmp (p, "/..", 3)
1572 /* `/../' is the "superroot" on certain file systems. */
1573 && o != target
1574 && (p[3] == '/' || p[3] == 0))
1576 while (o != target && *--o != '/')
1578 if (o == target && *o == '/')
1579 ++o;
1580 p += 3;
1582 else
1584 *o++ = *p++;
1588 return make_string (target, o - target);
1590 #endif
1592 /* If /~ or // appears, discard everything through first slash. */
1593 static bool
1594 file_name_absolute_p (const char *filename)
1596 return
1597 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1598 #ifdef DOS_NT
1599 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1600 && IS_DIRECTORY_SEP (filename[2]))
1601 #endif
1605 static char *
1606 search_embedded_absfilename (char *nm, char *endp)
1608 char *p, *s;
1610 for (p = nm + 1; p < endp; p++)
1612 if (IS_DIRECTORY_SEP (p[-1])
1613 && file_name_absolute_p (p)
1614 #if defined (WINDOWSNT) || defined (CYGWIN)
1615 /* // at start of file name is meaningful in Apollo,
1616 WindowsNT and Cygwin systems. */
1617 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1618 #endif /* not (WINDOWSNT || CYGWIN) */
1621 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1622 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1624 USE_SAFE_ALLOCA;
1625 char *o = SAFE_ALLOCA (s - p + 1);
1626 struct passwd *pw;
1627 memcpy (o, p, s - p);
1628 o [s - p] = 0;
1630 /* If we have ~user and `user' exists, discard
1631 everything up to ~. But if `user' does not exist, leave
1632 ~user alone, it might be a literal file name. */
1633 block_input ();
1634 pw = getpwnam (o + 1);
1635 unblock_input ();
1636 SAFE_FREE ();
1637 if (pw)
1638 return p;
1640 else
1641 return p;
1644 return NULL;
1647 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1648 Ssubstitute_in_file_name, 1, 1, 0,
1649 doc: /* Substitute environment variables referred to in FILENAME.
1650 `$FOO' where FOO is an environment variable name means to substitute
1651 the value of that variable. The variable name should be terminated
1652 with a character not a letter, digit or underscore; otherwise, enclose
1653 the entire variable name in braces.
1655 If `/~' appears, all of FILENAME through that `/' is discarded.
1656 If `//' appears, everything up to and including the first of
1657 those `/' is discarded. */)
1658 (Lisp_Object filename)
1660 char *nm, *p, *x, *endp;
1661 bool substituted = false;
1662 bool multibyte;
1663 char *xnm;
1664 Lisp_Object handler;
1666 CHECK_STRING (filename);
1668 multibyte = STRING_MULTIBYTE (filename);
1670 /* If the file name has special constructs in it,
1671 call the corresponding file handler. */
1672 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1673 if (!NILP (handler))
1675 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1676 filename);
1677 if (STRINGP (handled_name))
1678 return handled_name;
1679 error ("Invalid handler in `file-name-handler-alist'");
1682 /* Always work on a copy of the string, in case GC happens during
1683 decode of environment variables, causing the original Lisp_String
1684 data to be relocated. */
1685 USE_SAFE_ALLOCA;
1686 SAFE_ALLOCA_STRING (nm, filename);
1688 #ifdef DOS_NT
1689 dostounix_filename (nm);
1690 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1691 #endif
1692 endp = nm + SBYTES (filename);
1694 /* If /~ or // appears, discard everything through first slash. */
1695 p = search_embedded_absfilename (nm, endp);
1696 if (p)
1697 /* Start over with the new string, so we check the file-name-handler
1698 again. Important with filenames like "/home/foo//:/hello///there"
1699 which would substitute to "/:/hello///there" rather than "/there". */
1701 Lisp_Object result
1702 = (Fsubstitute_in_file_name
1703 (make_specified_string (p, -1, endp - p, multibyte)));
1704 SAFE_FREE ();
1705 return result;
1708 /* See if any variables are substituted into the string. */
1710 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1712 Lisp_Object name
1713 = (!substituted ? filename
1714 : make_specified_string (nm, -1, endp - nm, multibyte));
1715 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1716 CHECK_STRING (tmp);
1717 if (!EQ (tmp, name))
1718 substituted = true;
1719 filename = tmp;
1722 if (!substituted)
1724 #ifdef WINDOWSNT
1725 if (!NILP (Vw32_downcase_file_names))
1726 filename = Fdowncase (filename);
1727 #endif
1728 SAFE_FREE ();
1729 return filename;
1732 xnm = SSDATA (filename);
1733 x = xnm + SBYTES (filename);
1735 /* If /~ or // appears, discard everything through first slash. */
1736 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1737 /* This time we do not start over because we've already expanded envvars
1738 and replaced $$ with $. Maybe we should start over as well, but we'd
1739 need to quote some $ to $$ first. */
1740 xnm = p;
1742 #ifdef WINDOWSNT
1743 if (!NILP (Vw32_downcase_file_names))
1745 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1747 filename = Fdowncase (xname);
1749 else
1750 #endif
1751 if (xnm != SSDATA (filename))
1752 filename = make_specified_string (xnm, -1, x - xnm, multibyte);
1753 SAFE_FREE ();
1754 return filename;
1757 /* A slightly faster and more convenient way to get
1758 (directory-file-name (expand-file-name FOO)). */
1760 Lisp_Object
1761 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1763 register Lisp_Object absname;
1765 absname = Fexpand_file_name (filename, defdir);
1767 /* Remove final slash, if any (unless this is the root dir).
1768 stat behaves differently depending! */
1769 if (SCHARS (absname) > 1
1770 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1771 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1772 /* We cannot take shortcuts; they might be wrong for magic file names. */
1773 absname = Fdirectory_file_name (absname);
1774 return absname;
1777 /* Signal an error if the file ABSNAME already exists.
1778 If KNOWN_TO_EXIST, the file is known to exist.
1779 QUERYSTRING is a name for the action that is being considered
1780 to alter the file.
1781 If INTERACTIVE, ask the user whether to proceed,
1782 and bypass the error if the user says to go ahead.
1783 If QUICK, ask for y or n, not yes or no. */
1785 static void
1786 barf_or_query_if_file_exists (Lisp_Object absname, bool known_to_exist,
1787 const char *querystring, bool interactive,
1788 bool quick)
1790 Lisp_Object tem, encoded_filename;
1791 struct stat statbuf;
1793 encoded_filename = ENCODE_FILE (absname);
1795 if (! known_to_exist && lstat (SSDATA (encoded_filename), &statbuf) == 0)
1797 if (S_ISDIR (statbuf.st_mode))
1798 xsignal2 (Qfile_error,
1799 build_string ("File is a directory"), absname);
1800 known_to_exist = true;
1803 if (known_to_exist)
1805 if (! interactive)
1806 xsignal2 (Qfile_already_exists,
1807 build_string ("File already exists"), absname);
1808 AUTO_STRING (format, "File %s already exists; %s anyway? ");
1809 tem = CALLN (Fformat, format, absname, build_string (querystring));
1810 if (quick)
1811 tem = call1 (intern ("y-or-n-p"), tem);
1812 else
1813 tem = do_yes_or_no_p (tem);
1814 if (NILP (tem))
1815 xsignal2 (Qfile_already_exists,
1816 build_string ("File already exists"), absname);
1820 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1821 "fCopy file: \nGCopy %s to file: \np\nP",
1822 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1823 If NEWNAME names a directory, copy FILE there.
1825 This function always sets the file modes of the output file to match
1826 the input file.
1828 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1829 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1830 signal a `file-already-exists' error without overwriting. If
1831 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1832 about overwriting; this is what happens in interactive use with M-x.
1833 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1834 existing file.
1836 Fourth arg KEEP-TIME non-nil means give the output file the same
1837 last-modified time as the old one. (This works on only some systems.)
1839 A prefix arg makes KEEP-TIME non-nil.
1841 If PRESERVE-UID-GID is non-nil, we try to transfer the
1842 uid and gid of FILE to NEWNAME.
1844 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1845 this includes the file modes, along with ACL entries and SELinux
1846 context if present. Otherwise, if NEWNAME is created its file
1847 permission bits are those of FILE, masked by the default file
1848 permissions. */)
1849 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists,
1850 Lisp_Object keep_time, Lisp_Object preserve_uid_gid,
1851 Lisp_Object preserve_permissions)
1853 Lisp_Object handler;
1854 ptrdiff_t count = SPECPDL_INDEX ();
1855 Lisp_Object encoded_file, encoded_newname;
1856 #if HAVE_LIBSELINUX
1857 security_context_t con;
1858 int conlength = 0;
1859 #endif
1860 #ifdef WINDOWSNT
1861 int result;
1862 #else
1863 bool already_exists = false;
1864 mode_t new_mask;
1865 int ifd, ofd;
1866 struct stat st;
1867 #endif
1869 encoded_file = encoded_newname = Qnil;
1870 CHECK_STRING (file);
1871 CHECK_STRING (newname);
1873 if (!NILP (Ffile_directory_p (newname)))
1874 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1875 else
1876 newname = Fexpand_file_name (newname, Qnil);
1878 file = Fexpand_file_name (file, Qnil);
1880 /* If the input file name has special constructs in it,
1881 call the corresponding file handler. */
1882 handler = Ffind_file_name_handler (file, Qcopy_file);
1883 /* Likewise for output file name. */
1884 if (NILP (handler))
1885 handler = Ffind_file_name_handler (newname, Qcopy_file);
1886 if (!NILP (handler))
1887 return call7 (handler, Qcopy_file, file, newname,
1888 ok_if_already_exists, keep_time, preserve_uid_gid,
1889 preserve_permissions);
1891 encoded_file = ENCODE_FILE (file);
1892 encoded_newname = ENCODE_FILE (newname);
1894 #ifdef WINDOWSNT
1895 if (NILP (ok_if_already_exists)
1896 || INTEGERP (ok_if_already_exists))
1897 barf_or_query_if_file_exists (newname, false, "copy to it",
1898 INTEGERP (ok_if_already_exists), false);
1900 result = w32_copy_file (SSDATA (encoded_file), SSDATA (encoded_newname),
1901 !NILP (keep_time), !NILP (preserve_uid_gid),
1902 !NILP (preserve_permissions));
1903 switch (result)
1905 case -1:
1906 report_file_error ("Copying file", list2 (file, newname));
1907 case -2:
1908 report_file_error ("Copying permissions from", file);
1909 case -3:
1910 xsignal2 (Qfile_date_error,
1911 build_string ("Resetting file times"), newname);
1912 case -4:
1913 report_file_error ("Copying permissions to", newname);
1915 #else /* not WINDOWSNT */
1916 immediate_quit = 1;
1917 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
1918 immediate_quit = 0;
1920 if (ifd < 0)
1921 report_file_error ("Opening input file", file);
1923 record_unwind_protect_int (close_file_unwind, ifd);
1925 if (fstat (ifd, &st) != 0)
1926 report_file_error ("Input file status", file);
1928 if (!NILP (preserve_permissions))
1930 #if HAVE_LIBSELINUX
1931 if (is_selinux_enabled ())
1933 conlength = fgetfilecon (ifd, &con);
1934 if (conlength == -1)
1935 report_file_error ("Doing fgetfilecon", file);
1937 #endif
1940 /* We can copy only regular files. */
1941 if (!S_ISREG (st.st_mode))
1942 report_file_errno ("Non-regular file", file,
1943 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
1945 #ifndef MSDOS
1946 new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0700 : 0777);
1947 #else
1948 new_mask = S_IREAD | S_IWRITE;
1949 #endif
1951 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY | O_CREAT | O_EXCL,
1952 new_mask);
1953 if (ofd < 0 && errno == EEXIST)
1955 if (NILP (ok_if_already_exists) || INTEGERP (ok_if_already_exists))
1956 barf_or_query_if_file_exists (newname, true, "copy to it",
1957 INTEGERP (ok_if_already_exists), false);
1958 already_exists = true;
1959 ofd = emacs_open (SSDATA (encoded_newname), O_WRONLY, 0);
1961 if (ofd < 0)
1962 report_file_error ("Opening output file", newname);
1964 record_unwind_protect_int (close_file_unwind, ofd);
1966 off_t oldsize = 0, newsize = 0;
1968 if (already_exists)
1970 struct stat out_st;
1971 if (fstat (ofd, &out_st) != 0)
1972 report_file_error ("Output file status", newname);
1973 if (st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
1974 report_file_errno ("Input and output files are the same",
1975 list2 (file, newname), 0);
1976 if (S_ISREG (out_st.st_mode))
1977 oldsize = out_st.st_size;
1980 immediate_quit = 1;
1981 QUIT;
1982 while (true)
1984 char buf[MAX_ALLOCA];
1985 ptrdiff_t n = emacs_read (ifd, buf, sizeof buf);
1986 if (n < 0)
1987 report_file_error ("Read error", file);
1988 if (n == 0)
1989 break;
1990 if (emacs_write_sig (ofd, buf, n) != n)
1991 report_file_error ("Write error", newname);
1992 newsize += n;
1995 /* Truncate any existing output file after writing the data. This
1996 is more likely to work than truncation before writing, if the
1997 file system is out of space or the user is over disk quota. */
1998 if (newsize < oldsize && ftruncate (ofd, newsize) != 0)
1999 report_file_error ("Truncating output file", newname);
2001 immediate_quit = 0;
2003 #ifndef MSDOS
2004 /* Preserve the original file permissions, and if requested, also its
2005 owner and group. */
2007 mode_t preserved_permissions = st.st_mode & 07777;
2008 mode_t default_permissions = st.st_mode & 0777 & ~realmask;
2009 if (!NILP (preserve_uid_gid))
2011 /* Attempt to change owner and group. If that doesn't work
2012 attempt to change just the group, as that is sometimes allowed.
2013 Adjust the mode mask to eliminate setuid or setgid bits
2014 or group permissions bits that are inappropriate if the
2015 owner or group are wrong. */
2016 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2018 if (fchown (ofd, -1, st.st_gid) == 0)
2019 preserved_permissions &= ~04000;
2020 else
2022 preserved_permissions &= ~06000;
2024 /* Copy the other bits to the group bits, since the
2025 group is wrong. */
2026 preserved_permissions &= ~070;
2027 preserved_permissions |= (preserved_permissions & 7) << 3;
2028 default_permissions &= ~070;
2029 default_permissions |= (default_permissions & 7) << 3;
2034 switch (!NILP (preserve_permissions)
2035 ? qcopy_acl (SSDATA (encoded_file), ifd,
2036 SSDATA (encoded_newname), ofd,
2037 preserved_permissions)
2038 : (already_exists
2039 || (new_mask & ~realmask) == default_permissions)
2041 : fchmod (ofd, default_permissions))
2043 case -2: report_file_error ("Copying permissions from", file);
2044 case -1: report_file_error ("Copying permissions to", newname);
2047 #endif /* not MSDOS */
2049 #if HAVE_LIBSELINUX
2050 if (conlength > 0)
2052 /* Set the modified context back to the file. */
2053 bool fail = fsetfilecon (ofd, con) != 0;
2054 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2055 if (fail && errno != ENOTSUP)
2056 report_file_error ("Doing fsetfilecon", newname);
2058 freecon (con);
2060 #endif
2062 if (!NILP (keep_time))
2064 struct timespec atime = get_stat_atime (&st);
2065 struct timespec mtime = get_stat_mtime (&st);
2066 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime) != 0)
2067 xsignal2 (Qfile_date_error,
2068 build_string ("Cannot set file date"), newname);
2071 if (emacs_close (ofd) < 0)
2072 report_file_error ("Write error", newname);
2074 emacs_close (ifd);
2076 #ifdef MSDOS
2077 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2078 and if it can't, it tells so. Otherwise, under MSDOS we usually
2079 get only the READ bit, which will make the copied file read-only,
2080 so it's better not to chmod at all. */
2081 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2082 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2083 #endif /* MSDOS */
2084 #endif /* not WINDOWSNT */
2086 /* Discard the unwind protects. */
2087 specpdl_ptr = specpdl + count;
2089 return Qnil;
2092 DEFUN ("make-directory-internal", Fmake_directory_internal,
2093 Smake_directory_internal, 1, 1, 0,
2094 doc: /* Create a new directory named DIRECTORY. */)
2095 (Lisp_Object directory)
2097 const char *dir;
2098 Lisp_Object handler;
2099 Lisp_Object encoded_dir;
2101 CHECK_STRING (directory);
2102 directory = Fexpand_file_name (directory, Qnil);
2104 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2105 if (!NILP (handler))
2106 return call2 (handler, Qmake_directory_internal, directory);
2108 encoded_dir = ENCODE_FILE (directory);
2110 dir = SSDATA (encoded_dir);
2112 #ifdef WINDOWSNT
2113 if (mkdir (dir) != 0)
2114 #else
2115 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2116 #endif
2117 report_file_error ("Creating directory", directory);
2119 return Qnil;
2122 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2123 Sdelete_directory_internal, 1, 1, 0,
2124 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2125 (Lisp_Object directory)
2127 const char *dir;
2128 Lisp_Object encoded_dir;
2130 CHECK_STRING (directory);
2131 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2132 encoded_dir = ENCODE_FILE (directory);
2133 dir = SSDATA (encoded_dir);
2135 if (rmdir (dir) != 0)
2136 report_file_error ("Removing directory", directory);
2138 return Qnil;
2141 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2142 "(list (read-file-name \
2143 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2144 \"Move file to trash: \" \"Delete file: \") \
2145 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2146 (null current-prefix-arg))",
2147 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2148 If file has multiple names, it continues to exist with the other names.
2149 TRASH non-nil means to trash the file instead of deleting, provided
2150 `delete-by-moving-to-trash' is non-nil.
2152 When called interactively, TRASH is t if no prefix argument is given.
2153 With a prefix argument, TRASH is nil. */)
2154 (Lisp_Object filename, Lisp_Object trash)
2156 Lisp_Object handler;
2157 Lisp_Object encoded_file;
2159 if (!NILP (Ffile_directory_p (filename))
2160 && NILP (Ffile_symlink_p (filename)))
2161 xsignal2 (Qfile_error,
2162 build_string ("Removing old name: is a directory"),
2163 filename);
2164 filename = Fexpand_file_name (filename, Qnil);
2166 handler = Ffind_file_name_handler (filename, Qdelete_file);
2167 if (!NILP (handler))
2168 return call3 (handler, Qdelete_file, filename, trash);
2170 if (delete_by_moving_to_trash && !NILP (trash))
2171 return call1 (Qmove_file_to_trash, filename);
2173 encoded_file = ENCODE_FILE (filename);
2175 if (unlink (SSDATA (encoded_file)) < 0)
2176 report_file_error ("Removing old name", filename);
2177 return Qnil;
2180 static Lisp_Object
2181 internal_delete_file_1 (Lisp_Object ignore)
2183 return Qt;
2186 /* Delete file FILENAME, returning true if successful.
2187 This ignores `delete-by-moving-to-trash'. */
2189 bool
2190 internal_delete_file (Lisp_Object filename)
2192 Lisp_Object tem;
2194 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2195 Qt, internal_delete_file_1);
2196 return NILP (tem);
2199 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2200 "fRename file: \nGRename %s to file: \np",
2201 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2202 If file has names other than FILE, it continues to have those names.
2203 Signals a `file-already-exists' error if a file NEWNAME already exists
2204 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2205 A number as third arg means request confirmation if NEWNAME already exists.
2206 This is what happens in interactive use with M-x. */)
2207 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2209 Lisp_Object handler;
2210 Lisp_Object encoded_file, encoded_newname, symlink_target;
2212 symlink_target = encoded_file = encoded_newname = Qnil;
2213 CHECK_STRING (file);
2214 CHECK_STRING (newname);
2215 file = Fexpand_file_name (file, Qnil);
2217 if ((!NILP (Ffile_directory_p (newname)))
2218 #ifdef DOS_NT
2219 /* If the file names are identical but for the case,
2220 don't attempt to move directory to itself. */
2221 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2222 #endif
2225 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2226 ? file : Fdirectory_file_name (file));
2227 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2229 else
2230 newname = Fexpand_file_name (newname, Qnil);
2232 /* If the file name has special constructs in it,
2233 call the corresponding file handler. */
2234 handler = Ffind_file_name_handler (file, Qrename_file);
2235 if (NILP (handler))
2236 handler = Ffind_file_name_handler (newname, Qrename_file);
2237 if (!NILP (handler))
2238 return call4 (handler, Qrename_file,
2239 file, newname, ok_if_already_exists);
2241 encoded_file = ENCODE_FILE (file);
2242 encoded_newname = ENCODE_FILE (newname);
2244 #ifdef DOS_NT
2245 /* If the file names are identical but for the case, don't ask for
2246 confirmation: they simply want to change the letter-case of the
2247 file name. */
2248 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2249 #endif
2250 if (NILP (ok_if_already_exists)
2251 || INTEGERP (ok_if_already_exists))
2252 barf_or_query_if_file_exists (newname, false, "rename to it",
2253 INTEGERP (ok_if_already_exists), false);
2254 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2256 int rename_errno = errno;
2257 if (rename_errno == EXDEV)
2259 ptrdiff_t count;
2260 symlink_target = Ffile_symlink_p (file);
2261 if (! NILP (symlink_target))
2262 Fmake_symbolic_link (symlink_target, newname,
2263 NILP (ok_if_already_exists) ? Qnil : Qt);
2264 else if (!NILP (Ffile_directory_p (file)))
2265 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2266 else
2267 /* We have already prompted if it was an integer, so don't
2268 have copy-file prompt again. */
2269 Fcopy_file (file, newname,
2270 NILP (ok_if_already_exists) ? Qnil : Qt,
2271 Qt, Qt, Qt);
2273 count = SPECPDL_INDEX ();
2274 specbind (Qdelete_by_moving_to_trash, Qnil);
2276 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2277 call2 (Qdelete_directory, file, Qt);
2278 else
2279 Fdelete_file (file, Qnil);
2280 unbind_to (count, Qnil);
2282 else
2283 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2286 return Qnil;
2289 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2290 "fAdd name to file: \nGName to add to %s: \np",
2291 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2292 Signals a `file-already-exists' error if a file NEWNAME already exists
2293 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2294 A number as third arg means request confirmation if NEWNAME already exists.
2295 This is what happens in interactive use with M-x. */)
2296 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2298 Lisp_Object handler;
2299 Lisp_Object encoded_file, encoded_newname;
2301 encoded_file = encoded_newname = Qnil;
2302 CHECK_STRING (file);
2303 CHECK_STRING (newname);
2304 file = Fexpand_file_name (file, Qnil);
2306 if (!NILP (Ffile_directory_p (newname)))
2307 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2308 else
2309 newname = Fexpand_file_name (newname, Qnil);
2311 /* If the file name has special constructs in it,
2312 call the corresponding file handler. */
2313 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2314 if (!NILP (handler))
2315 return call4 (handler, Qadd_name_to_file, file,
2316 newname, ok_if_already_exists);
2318 /* If the new name has special constructs in it,
2319 call the corresponding file handler. */
2320 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2321 if (!NILP (handler))
2322 return call4 (handler, Qadd_name_to_file, file,
2323 newname, ok_if_already_exists);
2325 encoded_file = ENCODE_FILE (file);
2326 encoded_newname = ENCODE_FILE (newname);
2328 if (NILP (ok_if_already_exists)
2329 || INTEGERP (ok_if_already_exists))
2330 barf_or_query_if_file_exists (newname, false, "make it a new name",
2331 INTEGERP (ok_if_already_exists), false);
2333 unlink (SSDATA (newname));
2334 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2336 int link_errno = errno;
2337 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2340 return Qnil;
2343 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2344 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2345 doc: /* Make a symbolic link to TARGET, named LINKNAME.
2346 Both args must be strings.
2347 Signals a `file-already-exists' error if a file LINKNAME already exists
2348 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2349 A number as third arg means request confirmation if LINKNAME already exists.
2350 This happens for interactive use with M-x. */)
2351 (Lisp_Object target, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2353 Lisp_Object handler;
2354 Lisp_Object encoded_target, encoded_linkname;
2356 encoded_target = encoded_linkname = Qnil;
2357 CHECK_STRING (target);
2358 CHECK_STRING (linkname);
2359 /* If the link target has a ~, we must expand it to get
2360 a truly valid file name. Otherwise, do not expand;
2361 we want to permit links to relative file names. */
2362 if (SREF (target, 0) == '~')
2363 target = Fexpand_file_name (target, Qnil);
2365 if (!NILP (Ffile_directory_p (linkname)))
2366 linkname = Fexpand_file_name (Ffile_name_nondirectory (target), linkname);
2367 else
2368 linkname = Fexpand_file_name (linkname, Qnil);
2370 /* If the file name has special constructs in it,
2371 call the corresponding file handler. */
2372 handler = Ffind_file_name_handler (target, Qmake_symbolic_link);
2373 if (!NILP (handler))
2374 return call4 (handler, Qmake_symbolic_link, target,
2375 linkname, ok_if_already_exists);
2377 /* If the new link name has special constructs in it,
2378 call the corresponding file handler. */
2379 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2380 if (!NILP (handler))
2381 return call4 (handler, Qmake_symbolic_link, target,
2382 linkname, ok_if_already_exists);
2384 encoded_target = ENCODE_FILE (target);
2385 encoded_linkname = ENCODE_FILE (linkname);
2387 if (NILP (ok_if_already_exists)
2388 || INTEGERP (ok_if_already_exists))
2389 barf_or_query_if_file_exists (linkname, false, "make it a link",
2390 INTEGERP (ok_if_already_exists), false);
2391 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname)) < 0)
2393 /* If we didn't complain already, silently delete existing file. */
2394 int symlink_errno;
2395 if (errno == EEXIST)
2397 unlink (SSDATA (encoded_linkname));
2398 if (symlink (SSDATA (encoded_target), SSDATA (encoded_linkname))
2399 >= 0)
2400 return Qnil;
2402 if (errno == ENOSYS)
2403 xsignal1 (Qfile_error,
2404 build_string ("Symbolic links are not supported"));
2406 symlink_errno = errno;
2407 report_file_errno ("Making symbolic link", list2 (target, linkname),
2408 symlink_errno);
2411 return Qnil;
2415 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2416 1, 1, 0,
2417 doc: /* Return t if file FILENAME specifies an absolute file name.
2418 On Unix, this is a name starting with a `/' or a `~'. */)
2419 (Lisp_Object filename)
2421 CHECK_STRING (filename);
2422 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2425 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2426 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2427 See also `file-readable-p' and `file-attributes'.
2428 This returns nil for a symlink to a nonexistent file.
2429 Use `file-symlink-p' to test for such links. */)
2430 (Lisp_Object filename)
2432 Lisp_Object absname;
2433 Lisp_Object handler;
2435 CHECK_STRING (filename);
2436 absname = Fexpand_file_name (filename, Qnil);
2438 /* If the file name has special constructs in it,
2439 call the corresponding file handler. */
2440 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2441 if (!NILP (handler))
2443 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2444 errno = 0;
2445 return result;
2448 absname = ENCODE_FILE (absname);
2450 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2453 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2454 doc: /* Return t if FILENAME can be executed by you.
2455 For a directory, this means you can access files in that directory.
2456 \(It is generally better to use `file-accessible-directory-p' for that
2457 purpose, though.) */)
2458 (Lisp_Object filename)
2460 Lisp_Object absname;
2461 Lisp_Object handler;
2463 CHECK_STRING (filename);
2464 absname = Fexpand_file_name (filename, Qnil);
2466 /* If the file name has special constructs in it,
2467 call the corresponding file handler. */
2468 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2469 if (!NILP (handler))
2470 return call2 (handler, Qfile_executable_p, absname);
2472 absname = ENCODE_FILE (absname);
2474 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2477 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2478 doc: /* Return t if file FILENAME exists and you can read it.
2479 See also `file-exists-p' and `file-attributes'. */)
2480 (Lisp_Object filename)
2482 Lisp_Object absname;
2483 Lisp_Object handler;
2485 CHECK_STRING (filename);
2486 absname = Fexpand_file_name (filename, Qnil);
2488 /* If the file name has special constructs in it,
2489 call the corresponding file handler. */
2490 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2491 if (!NILP (handler))
2492 return call2 (handler, Qfile_readable_p, absname);
2494 absname = ENCODE_FILE (absname);
2495 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2496 ? Qt : Qnil);
2499 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2500 doc: /* Return t if file FILENAME can be written or created by you. */)
2501 (Lisp_Object filename)
2503 Lisp_Object absname, dir, encoded;
2504 Lisp_Object handler;
2506 CHECK_STRING (filename);
2507 absname = Fexpand_file_name (filename, Qnil);
2509 /* If the file name has special constructs in it,
2510 call the corresponding file handler. */
2511 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2512 if (!NILP (handler))
2513 return call2 (handler, Qfile_writable_p, absname);
2515 encoded = ENCODE_FILE (absname);
2516 if (check_writable (SSDATA (encoded), W_OK))
2517 return Qt;
2518 if (errno != ENOENT)
2519 return Qnil;
2521 dir = Ffile_name_directory (absname);
2522 eassert (!NILP (dir));
2523 #ifdef MSDOS
2524 dir = Fdirectory_file_name (dir);
2525 #endif /* MSDOS */
2527 dir = ENCODE_FILE (dir);
2528 #ifdef WINDOWSNT
2529 /* The read-only attribute of the parent directory doesn't affect
2530 whether a file or directory can be created within it. Some day we
2531 should check ACLs though, which do affect this. */
2532 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2533 #else
2534 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2535 #endif
2538 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2539 doc: /* Access file FILENAME, and get an error if that does not work.
2540 The second argument STRING is used in the error message.
2541 If there is no error, returns nil. */)
2542 (Lisp_Object filename, Lisp_Object string)
2544 Lisp_Object handler, encoded_filename, absname;
2546 CHECK_STRING (filename);
2547 absname = Fexpand_file_name (filename, Qnil);
2549 CHECK_STRING (string);
2551 /* If the file name has special constructs in it,
2552 call the corresponding file handler. */
2553 handler = Ffind_file_name_handler (absname, Qaccess_file);
2554 if (!NILP (handler))
2555 return call3 (handler, Qaccess_file, absname, string);
2557 encoded_filename = ENCODE_FILE (absname);
2559 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2560 report_file_error (SSDATA (string), filename);
2562 return Qnil;
2565 /* Relative to directory FD, return the symbolic link value of FILENAME.
2566 On failure, return nil. */
2567 Lisp_Object
2568 emacs_readlinkat (int fd, char const *filename)
2570 static struct allocator const emacs_norealloc_allocator =
2571 { xmalloc, NULL, xfree, memory_full };
2572 Lisp_Object val;
2573 char readlink_buf[1024];
2574 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2575 &emacs_norealloc_allocator, readlinkat);
2576 if (!buf)
2577 return Qnil;
2579 val = build_unibyte_string (buf);
2580 if (buf[0] == '/' && strchr (buf, ':'))
2582 AUTO_STRING (slash_colon, "/:");
2583 val = concat2 (slash_colon, val);
2585 if (buf != readlink_buf)
2586 xfree (buf);
2587 val = DECODE_FILE (val);
2588 return val;
2591 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2592 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2593 The value is the link target, as a string.
2594 Otherwise it returns nil.
2596 This function does not check whether the link target exists. */)
2597 (Lisp_Object filename)
2599 Lisp_Object handler;
2601 CHECK_STRING (filename);
2602 filename = Fexpand_file_name (filename, Qnil);
2604 /* If the file name has special constructs in it,
2605 call the corresponding file handler. */
2606 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2607 if (!NILP (handler))
2608 return call2 (handler, Qfile_symlink_p, filename);
2610 filename = ENCODE_FILE (filename);
2612 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2615 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2616 doc: /* Return t if FILENAME names an existing directory.
2617 Symbolic links to directories count as directories.
2618 See `file-symlink-p' to distinguish symlinks. */)
2619 (Lisp_Object filename)
2621 Lisp_Object absname;
2622 Lisp_Object handler;
2624 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2626 /* If the file name has special constructs in it,
2627 call the corresponding file handler. */
2628 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2629 if (!NILP (handler))
2630 return call2 (handler, Qfile_directory_p, absname);
2632 absname = ENCODE_FILE (absname);
2634 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2637 /* Return true if FILE is a directory or a symlink to a directory. */
2638 bool
2639 file_directory_p (char const *file)
2641 #ifdef WINDOWSNT
2642 /* This is cheaper than 'stat'. */
2643 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2644 #else
2645 struct stat st;
2646 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2647 #endif
2650 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2651 Sfile_accessible_directory_p, 1, 1, 0,
2652 doc: /* Return t if file FILENAME names a directory you can open.
2653 For the value to be t, FILENAME must specify the name of a directory as a file,
2654 and the directory must allow you to open files in it. In order to use a
2655 directory as a buffer's current directory, this predicate must return true.
2656 A directory name spec may be given instead; then the value is t
2657 if the directory so specified exists and really is a readable and
2658 searchable directory. */)
2659 (Lisp_Object filename)
2661 Lisp_Object absname;
2662 Lisp_Object handler;
2664 CHECK_STRING (filename);
2665 absname = Fexpand_file_name (filename, Qnil);
2667 /* If the file name has special constructs in it,
2668 call the corresponding file handler. */
2669 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2670 if (!NILP (handler))
2672 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2673 errno = 0;
2674 return r;
2677 absname = ENCODE_FILE (absname);
2678 return file_accessible_directory_p (absname) ? Qt : Qnil;
2681 /* If FILE is a searchable directory or a symlink to a
2682 searchable directory, return true. Otherwise return
2683 false and set errno to an error number. */
2684 bool
2685 file_accessible_directory_p (Lisp_Object file)
2687 #ifdef DOS_NT
2688 # ifdef WINDOWSNT
2689 /* We need a special-purpose test because (a) NTFS security data is
2690 not reflected in Posix-style mode bits, and (b) the trick with
2691 accessing "DIR/.", used below on Posix hosts, doesn't work on
2692 Windows, because "DIR/." is normalized to just "DIR" before
2693 hitting the disk. */
2694 return (SBYTES (file) == 0
2695 || w32_accessible_directory_p (SSDATA (file), SBYTES (file)));
2696 # else /* MSDOS */
2697 return file_directory_p (SSDATA (file));
2698 # endif /* MSDOS */
2699 #else /* !DOS_NT */
2700 /* On POSIXish platforms, use just one system call; this avoids a
2701 race and is typically faster. */
2702 const char *data = SSDATA (file);
2703 ptrdiff_t len = SBYTES (file);
2704 char const *dir;
2705 bool ok;
2706 int saved_errno;
2707 USE_SAFE_ALLOCA;
2709 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2710 There are three exceptions: "", "/", and "//". Leave "" alone,
2711 as it's invalid. Append only "." to the other two exceptions as
2712 "/" and "//" are distinct on some platforms, whereas "/", "///",
2713 "////", etc. are all equivalent. */
2714 if (! len)
2715 dir = data;
2716 else
2718 /* Just check for trailing '/' when deciding whether to append '/'.
2719 That's simpler than testing the two special cases "/" and "//",
2720 and it's a safe optimization here. */
2721 char *buf = SAFE_ALLOCA (len + 3);
2722 memcpy (buf, data, len);
2723 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2724 dir = buf;
2727 ok = check_existing (dir);
2728 saved_errno = errno;
2729 SAFE_FREE ();
2730 errno = saved_errno;
2731 return ok;
2732 #endif /* !DOS_NT */
2735 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2736 doc: /* Return t if FILENAME names a regular file.
2737 This is the sort of file that holds an ordinary stream of data bytes.
2738 Symbolic links to regular files count as regular files.
2739 See `file-symlink-p' to distinguish symlinks. */)
2740 (Lisp_Object filename)
2742 register Lisp_Object absname;
2743 struct stat st;
2744 Lisp_Object handler;
2746 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2748 /* If the file name has special constructs in it,
2749 call the corresponding file handler. */
2750 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2751 if (!NILP (handler))
2752 return call2 (handler, Qfile_regular_p, absname);
2754 absname = ENCODE_FILE (absname);
2756 #ifdef WINDOWSNT
2758 int result;
2759 Lisp_Object tem = Vw32_get_true_file_attributes;
2761 /* Tell stat to use expensive method to get accurate info. */
2762 Vw32_get_true_file_attributes = Qt;
2763 result = stat (SDATA (absname), &st);
2764 Vw32_get_true_file_attributes = tem;
2766 if (result < 0)
2767 return Qnil;
2768 return S_ISREG (st.st_mode) ? Qt : Qnil;
2770 #else
2771 if (stat (SSDATA (absname), &st) < 0)
2772 return Qnil;
2773 return S_ISREG (st.st_mode) ? Qt : Qnil;
2774 #endif
2777 DEFUN ("file-selinux-context", Ffile_selinux_context,
2778 Sfile_selinux_context, 1, 1, 0,
2779 doc: /* Return SELinux context of file named FILENAME.
2780 The return value is a list (USER ROLE TYPE RANGE), where the list
2781 elements are strings naming the user, role, type, and range of the
2782 file's SELinux security context.
2784 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2785 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2786 (Lisp_Object filename)
2788 Lisp_Object absname;
2789 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2791 Lisp_Object handler;
2792 #if HAVE_LIBSELINUX
2793 security_context_t con;
2794 int conlength;
2795 context_t context;
2796 #endif
2798 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2800 /* If the file name has special constructs in it,
2801 call the corresponding file handler. */
2802 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2803 if (!NILP (handler))
2804 return call2 (handler, Qfile_selinux_context, absname);
2806 absname = ENCODE_FILE (absname);
2808 #if HAVE_LIBSELINUX
2809 if (is_selinux_enabled ())
2811 conlength = lgetfilecon (SSDATA (absname), &con);
2812 if (conlength > 0)
2814 context = context_new (con);
2815 if (context_user_get (context))
2816 user = build_string (context_user_get (context));
2817 if (context_role_get (context))
2818 role = build_string (context_role_get (context));
2819 if (context_type_get (context))
2820 type = build_string (context_type_get (context));
2821 if (context_range_get (context))
2822 range = build_string (context_range_get (context));
2823 context_free (context);
2824 freecon (con);
2827 #endif
2829 return list4 (user, role, type, range);
2832 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2833 Sset_file_selinux_context, 2, 2, 0,
2834 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2835 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2836 elements are strings naming the components of a SELinux context.
2838 Value is t if setting of SELinux context was successful, nil otherwise.
2840 This function does nothing and returns nil if SELinux is disabled,
2841 or if Emacs was not compiled with SELinux support. */)
2842 (Lisp_Object filename, Lisp_Object context)
2844 Lisp_Object absname;
2845 Lisp_Object handler;
2846 #if HAVE_LIBSELINUX
2847 Lisp_Object encoded_absname;
2848 Lisp_Object user = CAR_SAFE (context);
2849 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2850 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2851 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2852 security_context_t con;
2853 bool fail;
2854 int conlength;
2855 context_t parsed_con;
2856 #endif
2858 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2860 /* If the file name has special constructs in it,
2861 call the corresponding file handler. */
2862 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2863 if (!NILP (handler))
2864 return call3 (handler, Qset_file_selinux_context, absname, context);
2866 #if HAVE_LIBSELINUX
2867 if (is_selinux_enabled ())
2869 /* Get current file context. */
2870 encoded_absname = ENCODE_FILE (absname);
2871 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2872 if (conlength > 0)
2874 parsed_con = context_new (con);
2875 /* Change the parts defined in the parameter.*/
2876 if (STRINGP (user))
2878 if (context_user_set (parsed_con, SSDATA (user)))
2879 error ("Doing context_user_set");
2881 if (STRINGP (role))
2883 if (context_role_set (parsed_con, SSDATA (role)))
2884 error ("Doing context_role_set");
2886 if (STRINGP (type))
2888 if (context_type_set (parsed_con, SSDATA (type)))
2889 error ("Doing context_type_set");
2891 if (STRINGP (range))
2893 if (context_range_set (parsed_con, SSDATA (range)))
2894 error ("Doing context_range_set");
2897 /* Set the modified context back to the file. */
2898 fail = (lsetfilecon (SSDATA (encoded_absname),
2899 context_str (parsed_con))
2900 != 0);
2901 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2902 if (fail && errno != ENOTSUP)
2903 report_file_error ("Doing lsetfilecon", absname);
2905 context_free (parsed_con);
2906 freecon (con);
2907 return fail ? Qnil : Qt;
2909 else
2910 report_file_error ("Doing lgetfilecon", absname);
2912 #endif
2914 return Qnil;
2917 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2918 doc: /* Return ACL entries of file named FILENAME.
2919 The entries are returned in a format suitable for use in `set-file-acl'
2920 but is otherwise undocumented and subject to change.
2921 Return nil if file does not exist or is not accessible, or if Emacs
2922 was unable to determine the ACL entries. */)
2923 (Lisp_Object filename)
2925 Lisp_Object absname;
2926 Lisp_Object handler;
2927 #ifdef HAVE_ACL_SET_FILE
2928 acl_t acl;
2929 Lisp_Object acl_string;
2930 char *str;
2931 # ifndef HAVE_ACL_TYPE_EXTENDED
2932 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2933 # endif
2934 #endif
2936 absname = expand_and_dir_to_file (filename,
2937 BVAR (current_buffer, directory));
2939 /* If the file name has special constructs in it,
2940 call the corresponding file handler. */
2941 handler = Ffind_file_name_handler (absname, Qfile_acl);
2942 if (!NILP (handler))
2943 return call2 (handler, Qfile_acl, absname);
2945 #ifdef HAVE_ACL_SET_FILE
2946 absname = ENCODE_FILE (absname);
2948 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2949 if (acl == NULL)
2950 return Qnil;
2952 str = acl_to_text (acl, NULL);
2953 if (str == NULL)
2955 acl_free (acl);
2956 return Qnil;
2959 acl_string = build_string (str);
2960 acl_free (str);
2961 acl_free (acl);
2963 return acl_string;
2964 #endif
2966 return Qnil;
2969 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
2970 2, 2, 0,
2971 doc: /* Set ACL of file named FILENAME to ACL-STRING.
2972 ACL-STRING should contain the textual representation of the ACL
2973 entries in a format suitable for the platform.
2975 Value is t if setting of ACL was successful, nil otherwise.
2977 Setting ACL for local files requires Emacs to be built with ACL
2978 support. */)
2979 (Lisp_Object filename, Lisp_Object acl_string)
2981 Lisp_Object absname;
2982 Lisp_Object handler;
2983 #ifdef HAVE_ACL_SET_FILE
2984 Lisp_Object encoded_absname;
2985 acl_t acl;
2986 bool fail;
2987 #endif
2989 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2991 /* If the file name has special constructs in it,
2992 call the corresponding file handler. */
2993 handler = Ffind_file_name_handler (absname, Qset_file_acl);
2994 if (!NILP (handler))
2995 return call3 (handler, Qset_file_acl, absname, acl_string);
2997 #ifdef HAVE_ACL_SET_FILE
2998 if (STRINGP (acl_string))
3000 acl = acl_from_text (SSDATA (acl_string));
3001 if (acl == NULL)
3003 report_file_error ("Converting ACL", absname);
3004 return Qnil;
3007 encoded_absname = ENCODE_FILE (absname);
3009 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3010 acl)
3011 != 0);
3012 if (fail && acl_errno_valid (errno))
3013 report_file_error ("Setting ACL", absname);
3015 acl_free (acl);
3016 return fail ? Qnil : Qt;
3018 #endif
3020 return Qnil;
3023 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3024 doc: /* Return mode bits of file named FILENAME, as an integer.
3025 Return nil, if file does not exist or is not accessible. */)
3026 (Lisp_Object filename)
3028 Lisp_Object absname;
3029 struct stat st;
3030 Lisp_Object handler;
3032 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3034 /* If the file name has special constructs in it,
3035 call the corresponding file handler. */
3036 handler = Ffind_file_name_handler (absname, Qfile_modes);
3037 if (!NILP (handler))
3038 return call2 (handler, Qfile_modes, absname);
3040 absname = ENCODE_FILE (absname);
3042 if (stat (SSDATA (absname), &st) < 0)
3043 return Qnil;
3045 return make_number (st.st_mode & 07777);
3048 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3049 "(let ((file (read-file-name \"File: \"))) \
3050 (list file (read-file-modes nil file)))",
3051 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3052 Only the 12 low bits of MODE are used.
3054 Interactively, mode bits are read by `read-file-modes', which accepts
3055 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3056 (Lisp_Object filename, Lisp_Object mode)
3058 Lisp_Object absname, encoded_absname;
3059 Lisp_Object handler;
3061 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3062 CHECK_NUMBER (mode);
3064 /* If the file name has special constructs in it,
3065 call the corresponding file handler. */
3066 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3067 if (!NILP (handler))
3068 return call3 (handler, Qset_file_modes, absname, mode);
3070 encoded_absname = ENCODE_FILE (absname);
3072 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3073 report_file_error ("Doing chmod", absname);
3075 return Qnil;
3078 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3079 doc: /* Set the file permission bits for newly created files.
3080 The argument MODE should be an integer; only the low 9 bits are used.
3081 This setting is inherited by subprocesses. */)
3082 (Lisp_Object mode)
3084 mode_t oldrealmask, oldumask, newumask;
3085 CHECK_NUMBER (mode);
3086 oldrealmask = realmask;
3087 newumask = ~ XINT (mode) & 0777;
3089 block_input ();
3090 realmask = newumask;
3091 oldumask = umask (newumask);
3092 unblock_input ();
3094 eassert (oldumask == oldrealmask);
3095 return Qnil;
3098 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3099 doc: /* Return the default file protection for created files.
3100 The value is an integer. */)
3101 (void)
3103 Lisp_Object value;
3104 XSETINT (value, (~ realmask) & 0777);
3105 return value;
3109 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3110 doc: /* Set times of file FILENAME to TIMESTAMP.
3111 Set both access and modification times.
3112 Return t on success, else nil.
3113 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3114 `current-time'. */)
3115 (Lisp_Object filename, Lisp_Object timestamp)
3117 Lisp_Object absname, encoded_absname;
3118 Lisp_Object handler;
3119 struct timespec t = lisp_time_argument (timestamp);
3121 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3123 /* If the file name has special constructs in it,
3124 call the corresponding file handler. */
3125 handler = Ffind_file_name_handler (absname, Qset_file_times);
3126 if (!NILP (handler))
3127 return call3 (handler, Qset_file_times, absname, timestamp);
3129 encoded_absname = ENCODE_FILE (absname);
3132 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3134 #ifdef MSDOS
3135 /* Setting times on a directory always fails. */
3136 if (file_directory_p (SSDATA (encoded_absname)))
3137 return Qnil;
3138 #endif
3139 report_file_error ("Setting file times", absname);
3143 return Qt;
3146 #ifdef HAVE_SYNC
3147 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3148 doc: /* Tell Unix to finish all pending disk updates. */)
3149 (void)
3151 sync ();
3152 return Qnil;
3155 #endif /* HAVE_SYNC */
3157 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3158 doc: /* Return t if file FILE1 is newer than file FILE2.
3159 If FILE1 does not exist, the answer is nil;
3160 otherwise, if FILE2 does not exist, the answer is t. */)
3161 (Lisp_Object file1, Lisp_Object file2)
3163 Lisp_Object absname1, absname2;
3164 struct stat st1, st2;
3165 Lisp_Object handler;
3167 CHECK_STRING (file1);
3168 CHECK_STRING (file2);
3170 absname1 = Qnil;
3171 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3172 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3174 /* If the file name has special constructs in it,
3175 call the corresponding file handler. */
3176 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3177 if (NILP (handler))
3178 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3179 if (!NILP (handler))
3180 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3182 absname1 = ENCODE_FILE (absname1);
3183 absname2 = ENCODE_FILE (absname2);
3185 if (stat (SSDATA (absname1), &st1) < 0)
3186 return Qnil;
3188 if (stat (SSDATA (absname2), &st2) < 0)
3189 return Qt;
3191 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3192 ? Qt : Qnil);
3195 #ifndef READ_BUF_SIZE
3196 #define READ_BUF_SIZE (64 << 10)
3197 #endif
3198 /* Some buffer offsets are stored in 'int' variables. */
3199 verify (READ_BUF_SIZE <= INT_MAX);
3201 /* This function is called after Lisp functions to decide a coding
3202 system are called, or when they cause an error. Before they are
3203 called, the current buffer is set unibyte and it contains only a
3204 newly inserted text (thus the buffer was empty before the
3205 insertion).
3207 The functions may set markers, overlays, text properties, or even
3208 alter the buffer contents, change the current buffer.
3210 Here, we reset all those changes by:
3211 o set back the current buffer.
3212 o move all markers and overlays to BEG.
3213 o remove all text properties.
3214 o set back the buffer multibyteness. */
3216 static void
3217 decide_coding_unwind (Lisp_Object unwind_data)
3219 Lisp_Object multibyte, undo_list, buffer;
3221 multibyte = XCAR (unwind_data);
3222 unwind_data = XCDR (unwind_data);
3223 undo_list = XCAR (unwind_data);
3224 buffer = XCDR (unwind_data);
3226 set_buffer_internal (XBUFFER (buffer));
3227 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3228 adjust_overlays_for_delete (BEG, Z - BEG);
3229 set_buffer_intervals (current_buffer, NULL);
3230 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3232 /* Now we are safe to change the buffer's multibyteness directly. */
3233 bset_enable_multibyte_characters (current_buffer, multibyte);
3234 bset_undo_list (current_buffer, undo_list);
3237 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3238 object where slot 0 is the file descriptor, slot 1 specifies
3239 an offset to put the read bytes, and slot 2 is the maximum
3240 amount of bytes to read. Value is the number of bytes read. */
3242 static Lisp_Object
3243 read_non_regular (Lisp_Object state)
3245 int nbytes;
3247 immediate_quit = 1;
3248 QUIT;
3249 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3250 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3251 + XSAVE_INTEGER (state, 1)),
3252 XSAVE_INTEGER (state, 2));
3253 immediate_quit = 0;
3254 /* Fast recycle this object for the likely next call. */
3255 free_misc (state);
3256 return make_number (nbytes);
3260 /* Condition-case handler used when reading from non-regular files
3261 in insert-file-contents. */
3263 static Lisp_Object
3264 read_non_regular_quit (Lisp_Object ignore)
3266 return Qnil;
3269 /* Return the file offset that VAL represents, checking for type
3270 errors and overflow. */
3271 static off_t
3272 file_offset (Lisp_Object val)
3274 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3275 return XINT (val);
3277 if (FLOATP (val))
3279 double v = XFLOAT_DATA (val);
3280 if (0 <= v
3281 && (sizeof (off_t) < sizeof v
3282 ? v <= TYPE_MAXIMUM (off_t)
3283 : v < TYPE_MAXIMUM (off_t)))
3284 return v;
3287 wrong_type_argument (intern ("file-offset"), val);
3290 /* Return a special time value indicating the error number ERRNUM. */
3291 static struct timespec
3292 time_error_value (int errnum)
3294 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3295 ? NONEXISTENT_MODTIME_NSECS
3296 : UNKNOWN_MODTIME_NSECS);
3297 return make_timespec (0, ns);
3300 static Lisp_Object
3301 get_window_points_and_markers (void)
3303 Lisp_Object pt_marker = Fpoint_marker ();
3304 Lisp_Object windows
3305 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3306 Lisp_Object window_markers = windows;
3307 /* Window markers (and point) are handled specially: rather than move to
3308 just before or just after the modified text, we try to keep the
3309 markers at the same distance (bug#19161).
3310 In general, this is wrong, but for window-markers, this should be harmless
3311 and is convenient for the end user when most of the file is unmodified,
3312 except for a few minor details near the beginning and near the end. */
3313 for (; CONSP (windows); windows = XCDR (windows))
3314 if (WINDOWP (XCAR (windows)))
3316 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3317 XSETCAR (windows,
3318 Fcons (window_marker, Fmarker_position (window_marker)));
3320 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3323 static void
3324 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3325 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3327 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3328 if (CONSP (XCAR (window_markers)))
3330 Lisp_Object car = XCAR (window_markers);
3331 Lisp_Object marker = XCAR (car);
3332 Lisp_Object oldpos = XCDR (car);
3333 if (MARKERP (marker) && INTEGERP (oldpos)
3334 && XINT (oldpos) > same_at_start
3335 && XINT (oldpos) < same_at_end)
3337 ptrdiff_t oldsize = same_at_end - same_at_start;
3338 ptrdiff_t newsize = inserted;
3339 double growth = newsize / (double)oldsize;
3340 ptrdiff_t newpos
3341 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3342 Fset_marker (marker, make_number (newpos), Qnil);
3347 /* FIXME: insert-file-contents should be split with the top-level moved to
3348 Elisp and only the core kept in C. */
3350 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3351 1, 5, 0,
3352 doc: /* Insert contents of file FILENAME after point.
3353 Returns list of absolute file name and number of characters inserted.
3354 If second argument VISIT is non-nil, the buffer's visited filename and
3355 last save file modtime are set, and it is marked unmodified. If
3356 visiting and the file does not exist, visiting is completed before the
3357 error is signaled.
3359 The optional third and fourth arguments BEG and END specify what portion
3360 of the file to insert. These arguments count bytes in the file, not
3361 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3363 If optional fifth argument REPLACE is non-nil, replace the current
3364 buffer contents (in the accessible portion) with the file contents.
3365 This is better than simply deleting and inserting the whole thing
3366 because (1) it preserves some marker positions and (2) it puts less data
3367 in the undo list. When REPLACE is non-nil, the second return value is
3368 the number of characters that replace previous buffer contents.
3370 This function does code conversion according to the value of
3371 `coding-system-for-read' or `file-coding-system-alist', and sets the
3372 variable `last-coding-system-used' to the coding system actually used.
3374 In addition, this function decodes the inserted text from known formats
3375 by calling `format-decode', which see. */)
3376 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3378 struct stat st;
3379 struct timespec mtime;
3380 int fd;
3381 ptrdiff_t inserted = 0;
3382 ptrdiff_t how_much;
3383 off_t beg_offset, end_offset;
3384 int unprocessed;
3385 ptrdiff_t count = SPECPDL_INDEX ();
3386 Lisp_Object handler, val, insval, orig_filename, old_undo;
3387 Lisp_Object p;
3388 ptrdiff_t total = 0;
3389 bool not_regular = 0;
3390 int save_errno = 0;
3391 char read_buf[READ_BUF_SIZE];
3392 struct coding_system coding;
3393 bool replace_handled = false;
3394 bool set_coding_system = false;
3395 Lisp_Object coding_system;
3396 bool read_quit = false;
3397 /* If the undo log only contains the insertion, there's no point
3398 keeping it. It's typically when we first fill a file-buffer. */
3399 bool empty_undo_list_p
3400 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3401 && BEG == Z);
3402 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3403 bool we_locked_file = false;
3404 ptrdiff_t fd_index;
3405 Lisp_Object window_markers = Qnil;
3406 /* same_at_start and same_at_end count bytes, because file access counts
3407 bytes and BEG and END count bytes. */
3408 ptrdiff_t same_at_start = BEGV_BYTE;
3409 ptrdiff_t same_at_end = ZV_BYTE;
3410 /* SAME_AT_END_CHARPOS counts characters, because
3411 restore_window_points needs the old character count. */
3412 ptrdiff_t same_at_end_charpos = ZV;
3414 if (current_buffer->base_buffer && ! NILP (visit))
3415 error ("Cannot do file visiting in an indirect buffer");
3417 if (!NILP (BVAR (current_buffer, read_only)))
3418 Fbarf_if_buffer_read_only (Qnil);
3420 val = Qnil;
3421 p = Qnil;
3422 orig_filename = Qnil;
3423 old_undo = Qnil;
3425 CHECK_STRING (filename);
3426 filename = Fexpand_file_name (filename, Qnil);
3428 /* The value Qnil means that the coding system is not yet
3429 decided. */
3430 coding_system = Qnil;
3432 /* If the file name has special constructs in it,
3433 call the corresponding file handler. */
3434 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3435 if (!NILP (handler))
3437 val = call6 (handler, Qinsert_file_contents, filename,
3438 visit, beg, end, replace);
3439 if (CONSP (val) && CONSP (XCDR (val))
3440 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3441 inserted = XINT (XCAR (XCDR (val)));
3442 goto handled;
3445 orig_filename = filename;
3446 filename = ENCODE_FILE (filename);
3448 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3449 if (fd < 0)
3451 save_errno = errno;
3452 if (NILP (visit))
3453 report_file_error ("Opening input file", orig_filename);
3454 mtime = time_error_value (save_errno);
3455 st.st_size = -1;
3456 if (!NILP (Vcoding_system_for_read))
3457 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3458 goto notfound;
3461 fd_index = SPECPDL_INDEX ();
3462 record_unwind_protect_int (close_file_unwind, fd);
3464 /* Replacement should preserve point as it preserves markers. */
3465 if (!NILP (replace))
3467 window_markers = get_window_points_and_markers ();
3468 record_unwind_protect (restore_point_unwind,
3469 XCAR (XCAR (window_markers)));
3472 if (fstat (fd, &st) != 0)
3473 report_file_error ("Input file status", orig_filename);
3474 mtime = get_stat_mtime (&st);
3476 /* This code will need to be changed in order to work on named
3477 pipes, and it's probably just not worth it. So we should at
3478 least signal an error. */
3479 if (!S_ISREG (st.st_mode))
3481 not_regular = 1;
3483 if (! NILP (visit))
3484 goto notfound;
3486 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3487 xsignal2 (Qfile_error,
3488 build_string ("not a regular file"), orig_filename);
3491 if (!NILP (visit))
3493 if (!NILP (beg) || !NILP (end))
3494 error ("Attempt to visit less than an entire file");
3495 if (BEG < Z && NILP (replace))
3496 error ("Cannot do file visiting in a non-empty buffer");
3499 if (!NILP (beg))
3500 beg_offset = file_offset (beg);
3501 else
3502 beg_offset = 0;
3504 if (!NILP (end))
3505 end_offset = file_offset (end);
3506 else
3508 if (not_regular)
3509 end_offset = TYPE_MAXIMUM (off_t);
3510 else
3512 end_offset = st.st_size;
3514 /* A negative size can happen on a platform that allows file
3515 sizes greater than the maximum off_t value. */
3516 if (end_offset < 0)
3517 buffer_overflow ();
3519 /* The file size returned from stat may be zero, but data
3520 may be readable nonetheless, for example when this is a
3521 file in the /proc filesystem. */
3522 if (end_offset == 0)
3523 end_offset = READ_BUF_SIZE;
3527 /* Check now whether the buffer will become too large,
3528 in the likely case where the file's length is not changing.
3529 This saves a lot of needless work before a buffer overflow. */
3530 if (! not_regular)
3532 /* The likely offset where we will stop reading. We could read
3533 more (or less), if the file grows (or shrinks) as we read it. */
3534 off_t likely_end = min (end_offset, st.st_size);
3536 if (beg_offset < likely_end)
3538 ptrdiff_t buf_bytes
3539 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3540 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3541 off_t likely_growth = likely_end - beg_offset;
3542 if (buf_growth_max < likely_growth)
3543 buffer_overflow ();
3547 /* Prevent redisplay optimizations. */
3548 current_buffer->clip_changed = true;
3550 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3552 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3553 setup_coding_system (coding_system, &coding);
3554 /* Ensure we set Vlast_coding_system_used. */
3555 set_coding_system = true;
3557 else if (BEG < Z)
3559 /* Decide the coding system to use for reading the file now
3560 because we can't use an optimized method for handling
3561 `coding:' tag if the current buffer is not empty. */
3562 if (!NILP (Vcoding_system_for_read))
3563 coding_system = Vcoding_system_for_read;
3564 else
3566 /* Don't try looking inside a file for a coding system
3567 specification if it is not seekable. */
3568 if (! not_regular && ! NILP (Vset_auto_coding_function))
3570 /* Find a coding system specified in the heading two
3571 lines or in the tailing several lines of the file.
3572 We assume that the 1K-byte and 3K-byte for heading
3573 and tailing respectively are sufficient for this
3574 purpose. */
3575 int nread;
3577 if (st.st_size <= (1024 * 4))
3578 nread = emacs_read (fd, read_buf, 1024 * 4);
3579 else
3581 nread = emacs_read (fd, read_buf, 1024);
3582 if (nread == 1024)
3584 int ntail;
3585 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3586 report_file_error ("Setting file position",
3587 orig_filename);
3588 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3589 nread = ntail < 0 ? ntail : nread + ntail;
3593 if (nread < 0)
3594 report_file_error ("Read error", orig_filename);
3595 else if (nread > 0)
3597 AUTO_STRING (name, " *code-converting-work*");
3598 struct buffer *prev = current_buffer;
3599 Lisp_Object workbuf;
3600 struct buffer *buf;
3602 record_unwind_current_buffer ();
3604 workbuf = Fget_buffer_create (name);
3605 buf = XBUFFER (workbuf);
3607 delete_all_overlays (buf);
3608 bset_directory (buf, BVAR (current_buffer, directory));
3609 bset_read_only (buf, Qnil);
3610 bset_filename (buf, Qnil);
3611 bset_undo_list (buf, Qt);
3612 eassert (buf->overlays_before == NULL);
3613 eassert (buf->overlays_after == NULL);
3615 set_buffer_internal (buf);
3616 Ferase_buffer ();
3617 bset_enable_multibyte_characters (buf, Qnil);
3619 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3620 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3621 coding_system = call2 (Vset_auto_coding_function,
3622 filename, make_number (nread));
3623 set_buffer_internal (prev);
3625 /* Discard the unwind protect for recovering the
3626 current buffer. */
3627 specpdl_ptr--;
3629 /* Rewind the file for the actual read done later. */
3630 if (lseek (fd, 0, SEEK_SET) < 0)
3631 report_file_error ("Setting file position", orig_filename);
3635 if (NILP (coding_system))
3637 /* If we have not yet decided a coding system, check
3638 file-coding-system-alist. */
3639 coding_system = CALLN (Ffind_operation_coding_system,
3640 Qinsert_file_contents, orig_filename,
3641 visit, beg, end, replace);
3642 if (CONSP (coding_system))
3643 coding_system = XCAR (coding_system);
3647 if (NILP (coding_system))
3648 coding_system = Qundecided;
3649 else
3650 CHECK_CODING_SYSTEM (coding_system);
3652 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3653 /* We must suppress all character code conversion except for
3654 end-of-line conversion. */
3655 coding_system = raw_text_coding_system (coding_system);
3657 setup_coding_system (coding_system, &coding);
3658 /* Ensure we set Vlast_coding_system_used. */
3659 set_coding_system = true;
3662 /* If requested, replace the accessible part of the buffer
3663 with the file contents. Avoid replacing text at the
3664 beginning or end of the buffer that matches the file contents;
3665 that preserves markers pointing to the unchanged parts.
3667 Here we implement this feature in an optimized way
3668 for the case where code conversion is NOT needed.
3669 The following if-statement handles the case of conversion
3670 in a less optimal way.
3672 If the code conversion is "automatic" then we try using this
3673 method and hope for the best.
3674 But if we discover the need for conversion, we give up on this method
3675 and let the following if-statement handle the replace job. */
3676 if (!NILP (replace)
3677 && BEGV < ZV
3678 && (NILP (coding_system)
3679 || ! CODING_REQUIRE_DECODING (&coding)))
3681 ptrdiff_t overlap;
3682 /* There is still a possibility we will find the need to do code
3683 conversion. If that happens, set this variable to
3684 give up on handling REPLACE in the optimized way. */
3685 bool giveup_match_end = false;
3687 if (beg_offset != 0)
3689 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3690 report_file_error ("Setting file position", orig_filename);
3693 immediate_quit = 1;
3694 QUIT;
3695 /* Count how many chars at the start of the file
3696 match the text at the beginning of the buffer. */
3697 while (1)
3699 int nread, bufpos;
3701 nread = emacs_read (fd, read_buf, sizeof read_buf);
3702 if (nread < 0)
3703 report_file_error ("Read error", orig_filename);
3704 else if (nread == 0)
3705 break;
3707 if (CODING_REQUIRE_DETECTION (&coding))
3709 coding_system = detect_coding_system ((unsigned char *) read_buf,
3710 nread, nread, 1, 0,
3711 coding_system);
3712 setup_coding_system (coding_system, &coding);
3715 if (CODING_REQUIRE_DECODING (&coding))
3716 /* We found that the file should be decoded somehow.
3717 Let's give up here. */
3719 giveup_match_end = true;
3720 break;
3723 bufpos = 0;
3724 while (bufpos < nread && same_at_start < ZV_BYTE
3725 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3726 same_at_start++, bufpos++;
3727 /* If we found a discrepancy, stop the scan.
3728 Otherwise loop around and scan the next bufferful. */
3729 if (bufpos != nread)
3730 break;
3732 immediate_quit = false;
3733 /* If the file matches the buffer completely,
3734 there's no need to replace anything. */
3735 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3737 emacs_close (fd);
3738 clear_unwind_protect (fd_index);
3740 /* Truncate the buffer to the size of the file. */
3741 del_range_1 (same_at_start, same_at_end, 0, 0);
3742 goto handled;
3744 immediate_quit = true;
3745 QUIT;
3746 /* Count how many chars at the end of the file
3747 match the text at the end of the buffer. But, if we have
3748 already found that decoding is necessary, don't waste time. */
3749 while (!giveup_match_end)
3751 int total_read, nread, bufpos, trial;
3752 off_t curpos;
3754 /* At what file position are we now scanning? */
3755 curpos = end_offset - (ZV_BYTE - same_at_end);
3756 /* If the entire file matches the buffer tail, stop the scan. */
3757 if (curpos == 0)
3758 break;
3759 /* How much can we scan in the next step? */
3760 trial = min (curpos, sizeof read_buf);
3761 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3762 report_file_error ("Setting file position", orig_filename);
3764 total_read = nread = 0;
3765 while (total_read < trial)
3767 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3768 if (nread < 0)
3769 report_file_error ("Read error", orig_filename);
3770 else if (nread == 0)
3771 break;
3772 total_read += nread;
3775 /* Scan this bufferful from the end, comparing with
3776 the Emacs buffer. */
3777 bufpos = total_read;
3779 /* Compare with same_at_start to avoid counting some buffer text
3780 as matching both at the file's beginning and at the end. */
3781 while (bufpos > 0 && same_at_end > same_at_start
3782 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3783 same_at_end--, bufpos--;
3785 /* If we found a discrepancy, stop the scan.
3786 Otherwise loop around and scan the preceding bufferful. */
3787 if (bufpos != 0)
3789 /* If this discrepancy is because of code conversion,
3790 we cannot use this method; giveup and try the other. */
3791 if (same_at_end > same_at_start
3792 && FETCH_BYTE (same_at_end - 1) >= 0200
3793 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3794 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3795 giveup_match_end = true;
3796 break;
3799 if (nread == 0)
3800 break;
3802 immediate_quit = 0;
3804 if (! giveup_match_end)
3806 ptrdiff_t temp;
3808 /* We win! We can handle REPLACE the optimized way. */
3810 /* Extend the start of non-matching text area to multibyte
3811 character boundary. */
3812 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3813 while (same_at_start > BEGV_BYTE
3814 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3815 same_at_start--;
3817 /* Extend the end of non-matching text area to multibyte
3818 character boundary. */
3819 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3820 while (same_at_end < ZV_BYTE
3821 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3822 same_at_end++;
3824 /* Don't try to reuse the same piece of text twice. */
3825 overlap = (same_at_start - BEGV_BYTE
3826 - (same_at_end
3827 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3828 if (overlap > 0)
3829 same_at_end += overlap;
3830 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3832 /* Arrange to read only the nonmatching middle part of the file. */
3833 beg_offset += same_at_start - BEGV_BYTE;
3834 end_offset -= ZV_BYTE - same_at_end;
3836 invalidate_buffer_caches (current_buffer,
3837 BYTE_TO_CHAR (same_at_start),
3838 same_at_end_charpos);
3839 del_range_byte (same_at_start, same_at_end, 0);
3840 /* Insert from the file at the proper position. */
3841 temp = BYTE_TO_CHAR (same_at_start);
3842 SET_PT_BOTH (temp, same_at_start);
3844 /* If display currently starts at beginning of line,
3845 keep it that way. */
3846 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3847 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3849 replace_handled = true;
3853 /* If requested, replace the accessible part of the buffer
3854 with the file contents. Avoid replacing text at the
3855 beginning or end of the buffer that matches the file contents;
3856 that preserves markers pointing to the unchanged parts.
3858 Here we implement this feature for the case where code conversion
3859 is needed, in a simple way that needs a lot of memory.
3860 The preceding if-statement handles the case of no conversion
3861 in a more optimized way. */
3862 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3864 ptrdiff_t same_at_start_charpos;
3865 ptrdiff_t inserted_chars;
3866 ptrdiff_t overlap;
3867 ptrdiff_t bufpos;
3868 unsigned char *decoded;
3869 ptrdiff_t temp;
3870 ptrdiff_t this = 0;
3871 ptrdiff_t this_count = SPECPDL_INDEX ();
3872 bool multibyte
3873 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3874 Lisp_Object conversion_buffer;
3876 conversion_buffer = code_conversion_save (1, multibyte);
3878 /* First read the whole file, performing code conversion into
3879 CONVERSION_BUFFER. */
3881 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3882 report_file_error ("Setting file position", orig_filename);
3884 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3885 unprocessed = 0; /* Bytes not processed in previous loop. */
3887 while (1)
3889 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3890 quitting while reading a huge file. */
3892 /* Allow quitting out of the actual I/O. */
3893 immediate_quit = 1;
3894 QUIT;
3895 this = emacs_read (fd, read_buf + unprocessed,
3896 READ_BUF_SIZE - unprocessed);
3897 immediate_quit = 0;
3899 if (this <= 0)
3900 break;
3902 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3903 BUF_Z (XBUFFER (conversion_buffer)));
3904 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3905 unprocessed + this, conversion_buffer);
3906 unprocessed = coding.carryover_bytes;
3907 if (coding.carryover_bytes > 0)
3908 memcpy (read_buf, coding.carryover, unprocessed);
3911 if (this < 0)
3912 report_file_error ("Read error", orig_filename);
3913 emacs_close (fd);
3914 clear_unwind_protect (fd_index);
3916 if (unprocessed > 0)
3918 coding.mode |= CODING_MODE_LAST_BLOCK;
3919 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3920 unprocessed, conversion_buffer);
3921 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3924 coding_system = CODING_ID_NAME (coding.id);
3925 set_coding_system = true;
3926 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3927 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3928 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3930 /* Compare the beginning of the converted string with the buffer
3931 text. */
3933 bufpos = 0;
3934 while (bufpos < inserted && same_at_start < same_at_end
3935 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3936 same_at_start++, bufpos++;
3938 /* If the file matches the head of buffer completely,
3939 there's no need to replace anything. */
3941 if (bufpos == inserted)
3943 /* Truncate the buffer to the size of the file. */
3944 if (same_at_start != same_at_end)
3946 invalidate_buffer_caches (current_buffer,
3947 BYTE_TO_CHAR (same_at_start),
3948 BYTE_TO_CHAR (same_at_end));
3949 del_range_byte (same_at_start, same_at_end, 0);
3951 inserted = 0;
3953 unbind_to (this_count, Qnil);
3954 goto handled;
3957 /* Extend the start of non-matching text area to the previous
3958 multibyte character boundary. */
3959 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3960 while (same_at_start > BEGV_BYTE
3961 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3962 same_at_start--;
3964 /* Scan this bufferful from the end, comparing with
3965 the Emacs buffer. */
3966 bufpos = inserted;
3968 /* Compare with same_at_start to avoid counting some buffer text
3969 as matching both at the file's beginning and at the end. */
3970 while (bufpos > 0 && same_at_end > same_at_start
3971 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3972 same_at_end--, bufpos--;
3974 /* Extend the end of non-matching text area to the next
3975 multibyte character boundary. */
3976 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3977 while (same_at_end < ZV_BYTE
3978 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3979 same_at_end++;
3981 /* Don't try to reuse the same piece of text twice. */
3982 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3983 if (overlap > 0)
3984 same_at_end += overlap;
3985 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3987 /* If display currently starts at beginning of line,
3988 keep it that way. */
3989 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3990 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3992 /* Replace the chars that we need to replace,
3993 and update INSERTED to equal the number of bytes
3994 we are taking from the decoded string. */
3995 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3997 if (same_at_end != same_at_start)
3999 invalidate_buffer_caches (current_buffer,
4000 BYTE_TO_CHAR (same_at_start),
4001 same_at_end_charpos);
4002 del_range_byte (same_at_start, same_at_end, 0);
4003 temp = GPT;
4004 eassert (same_at_start == GPT_BYTE);
4005 same_at_start = GPT_BYTE;
4007 else
4009 temp = same_at_end_charpos;
4011 /* Insert from the file at the proper position. */
4012 SET_PT_BOTH (temp, same_at_start);
4013 same_at_start_charpos
4014 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4015 same_at_start - BEGV_BYTE
4016 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4017 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4018 inserted_chars
4019 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4020 same_at_start + inserted - BEGV_BYTE
4021 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4022 - same_at_start_charpos);
4023 /* This binding is to avoid ask-user-about-supersession-threat
4024 being called in insert_from_buffer (via in
4025 prepare_to_modify_buffer). */
4026 specbind (intern ("buffer-file-name"), Qnil);
4027 insert_from_buffer (XBUFFER (conversion_buffer),
4028 same_at_start_charpos, inserted_chars, 0);
4029 /* Set `inserted' to the number of inserted characters. */
4030 inserted = PT - temp;
4031 /* Set point before the inserted characters. */
4032 SET_PT_BOTH (temp, same_at_start);
4034 unbind_to (this_count, Qnil);
4036 goto handled;
4039 if (! not_regular)
4040 total = end_offset - beg_offset;
4041 else
4042 /* For a special file, all we can do is guess. */
4043 total = READ_BUF_SIZE;
4045 if (NILP (visit) && total > 0)
4047 if (!NILP (BVAR (current_buffer, file_truename))
4048 /* Make binding buffer-file-name to nil effective. */
4049 && !NILP (BVAR (current_buffer, filename))
4050 && SAVE_MODIFF >= MODIFF)
4051 we_locked_file = true;
4052 prepare_to_modify_buffer (PT, PT, NULL);
4055 move_gap_both (PT, PT_BYTE);
4056 if (GAP_SIZE < total)
4057 make_gap (total - GAP_SIZE);
4059 if (beg_offset != 0 || !NILP (replace))
4061 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4062 report_file_error ("Setting file position", orig_filename);
4065 /* In the following loop, HOW_MUCH contains the total bytes read so
4066 far for a regular file, and not changed for a special file. But,
4067 before exiting the loop, it is set to a negative value if I/O
4068 error occurs. */
4069 how_much = 0;
4071 /* Total bytes inserted. */
4072 inserted = 0;
4074 /* Here, we don't do code conversion in the loop. It is done by
4075 decode_coding_gap after all data are read into the buffer. */
4077 ptrdiff_t gap_size = GAP_SIZE;
4079 while (how_much < total)
4081 /* `try' is reserved in some compilers (Microsoft C). */
4082 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4083 ptrdiff_t this;
4085 if (not_regular)
4087 Lisp_Object nbytes;
4089 /* Maybe make more room. */
4090 if (gap_size < trytry)
4092 make_gap (trytry - gap_size);
4093 gap_size = GAP_SIZE - inserted;
4096 /* Read from the file, capturing `quit'. When an
4097 error occurs, end the loop, and arrange for a quit
4098 to be signaled after decoding the text we read. */
4099 nbytes = internal_condition_case_1
4100 (read_non_regular,
4101 make_save_int_int_int (fd, inserted, trytry),
4102 Qerror, read_non_regular_quit);
4104 if (NILP (nbytes))
4106 read_quit = true;
4107 break;
4110 this = XINT (nbytes);
4112 else
4114 /* Allow quitting out of the actual I/O. We don't make text
4115 part of the buffer until all the reading is done, so a C-g
4116 here doesn't do any harm. */
4117 immediate_quit = 1;
4118 QUIT;
4119 this = emacs_read (fd,
4120 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4121 + inserted),
4122 trytry);
4123 immediate_quit = 0;
4126 if (this <= 0)
4128 how_much = this;
4129 break;
4132 gap_size -= this;
4134 /* For a regular file, where TOTAL is the real size,
4135 count HOW_MUCH to compare with it.
4136 For a special file, where TOTAL is just a buffer size,
4137 so don't bother counting in HOW_MUCH.
4138 (INSERTED is where we count the number of characters inserted.) */
4139 if (! not_regular)
4140 how_much += this;
4141 inserted += this;
4145 /* Now we have either read all the file data into the gap,
4146 or stop reading on I/O error or quit. If nothing was
4147 read, undo marking the buffer modified. */
4149 if (inserted == 0)
4151 if (we_locked_file)
4152 unlock_file (BVAR (current_buffer, file_truename));
4153 Vdeactivate_mark = old_Vdeactivate_mark;
4155 else
4156 Fset (Qdeactivate_mark, Qt);
4158 emacs_close (fd);
4159 clear_unwind_protect (fd_index);
4161 if (how_much < 0)
4162 report_file_error ("Read error", orig_filename);
4164 /* Make the text read part of the buffer. */
4165 GAP_SIZE -= inserted;
4166 GPT += inserted;
4167 GPT_BYTE += inserted;
4168 ZV += inserted;
4169 ZV_BYTE += inserted;
4170 Z += inserted;
4171 Z_BYTE += inserted;
4173 if (GAP_SIZE > 0)
4174 /* Put an anchor to ensure multi-byte form ends at gap. */
4175 *GPT_ADDR = 0;
4177 notfound:
4179 if (NILP (coding_system))
4181 /* The coding system is not yet decided. Decide it by an
4182 optimized method for handling `coding:' tag.
4184 Note that we can get here only if the buffer was empty
4185 before the insertion. */
4187 if (!NILP (Vcoding_system_for_read))
4188 coding_system = Vcoding_system_for_read;
4189 else
4191 /* Since we are sure that the current buffer was empty
4192 before the insertion, we can toggle
4193 enable-multibyte-characters directly here without taking
4194 care of marker adjustment. By this way, we can run Lisp
4195 program safely before decoding the inserted text. */
4196 Lisp_Object unwind_data;
4197 ptrdiff_t count1 = SPECPDL_INDEX ();
4199 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4200 Fcons (BVAR (current_buffer, undo_list),
4201 Fcurrent_buffer ()));
4202 bset_enable_multibyte_characters (current_buffer, Qnil);
4203 bset_undo_list (current_buffer, Qt);
4204 record_unwind_protect (decide_coding_unwind, unwind_data);
4206 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4208 coding_system = call2 (Vset_auto_coding_function,
4209 filename, make_number (inserted));
4212 if (NILP (coding_system))
4214 /* If the coding system is not yet decided, check
4215 file-coding-system-alist. */
4216 coding_system = CALLN (Ffind_operation_coding_system,
4217 Qinsert_file_contents, orig_filename,
4218 visit, beg, end, Qnil);
4219 if (CONSP (coding_system))
4220 coding_system = XCAR (coding_system);
4222 unbind_to (count1, Qnil);
4223 inserted = Z_BYTE - BEG_BYTE;
4226 if (NILP (coding_system))
4227 coding_system = Qundecided;
4228 else
4229 CHECK_CODING_SYSTEM (coding_system);
4231 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4232 /* We must suppress all character code conversion except for
4233 end-of-line conversion. */
4234 coding_system = raw_text_coding_system (coding_system);
4235 setup_coding_system (coding_system, &coding);
4236 /* Ensure we set Vlast_coding_system_used. */
4237 set_coding_system = true;
4240 if (!NILP (visit))
4242 /* When we visit a file by raw-text, we change the buffer to
4243 unibyte. */
4244 if (CODING_FOR_UNIBYTE (&coding)
4245 /* Can't do this if part of the buffer might be preserved. */
4246 && NILP (replace))
4247 /* Visiting a file with these coding system makes the buffer
4248 unibyte. */
4249 bset_enable_multibyte_characters (current_buffer, Qnil);
4252 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4253 if (CODING_MAY_REQUIRE_DECODING (&coding)
4254 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4256 move_gap_both (PT, PT_BYTE);
4257 GAP_SIZE += inserted;
4258 ZV_BYTE -= inserted;
4259 Z_BYTE -= inserted;
4260 ZV -= inserted;
4261 Z -= inserted;
4262 decode_coding_gap (&coding, inserted, inserted);
4263 inserted = coding.produced_char;
4264 coding_system = CODING_ID_NAME (coding.id);
4266 else if (inserted > 0)
4268 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4269 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4270 inserted);
4273 /* Call after-change hooks for the inserted text, aside from the case
4274 of normal visiting (not with REPLACE), which is done in a new buffer
4275 "before" the buffer is changed. */
4276 if (inserted > 0 && total > 0
4277 && (NILP (visit) || !NILP (replace)))
4279 signal_after_change (PT, 0, inserted);
4280 update_compositions (PT, PT, CHECK_BORDER);
4283 /* Now INSERTED is measured in characters. */
4285 handled:
4287 if (inserted > 0)
4288 restore_window_points (window_markers, inserted,
4289 BYTE_TO_CHAR (same_at_start),
4290 same_at_end_charpos);
4292 if (!NILP (visit))
4294 if (empty_undo_list_p)
4295 bset_undo_list (current_buffer, Qnil);
4297 if (NILP (handler))
4299 current_buffer->modtime = mtime;
4300 current_buffer->modtime_size = st.st_size;
4301 bset_filename (current_buffer, orig_filename);
4304 SAVE_MODIFF = MODIFF;
4305 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4306 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4307 if (NILP (handler))
4309 if (!NILP (BVAR (current_buffer, file_truename)))
4310 unlock_file (BVAR (current_buffer, file_truename));
4311 unlock_file (filename);
4313 if (not_regular)
4314 xsignal2 (Qfile_error,
4315 build_string ("not a regular file"), orig_filename);
4318 if (set_coding_system)
4319 Vlast_coding_system_used = coding_system;
4321 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4323 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4324 visit);
4325 if (! NILP (insval))
4327 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4328 wrong_type_argument (intern ("inserted-chars"), insval);
4329 inserted = XFASTINT (insval);
4333 /* Decode file format. */
4334 if (inserted > 0)
4336 /* Don't run point motion or modification hooks when decoding. */
4337 ptrdiff_t count1 = SPECPDL_INDEX ();
4338 ptrdiff_t old_inserted = inserted;
4339 specbind (Qinhibit_point_motion_hooks, Qt);
4340 specbind (Qinhibit_modification_hooks, Qt);
4342 /* Save old undo list and don't record undo for decoding. */
4343 old_undo = BVAR (current_buffer, undo_list);
4344 bset_undo_list (current_buffer, Qt);
4346 if (NILP (replace))
4348 insval = call3 (Qformat_decode,
4349 Qnil, make_number (inserted), visit);
4350 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4351 wrong_type_argument (intern ("inserted-chars"), insval);
4352 inserted = XFASTINT (insval);
4354 else
4356 /* If REPLACE is non-nil and we succeeded in not replacing the
4357 beginning or end of the buffer text with the file's contents,
4358 call format-decode with `point' positioned at the beginning
4359 of the buffer and `inserted' equaling the number of
4360 characters in the buffer. Otherwise, format-decode might
4361 fail to correctly analyze the beginning or end of the buffer.
4362 Hence we temporarily save `point' and `inserted' here and
4363 restore `point' iff format-decode did not insert or delete
4364 any text. Otherwise we leave `point' at point-min. */
4365 ptrdiff_t opoint = PT;
4366 ptrdiff_t opoint_byte = PT_BYTE;
4367 ptrdiff_t oinserted = ZV - BEGV;
4368 EMACS_INT ochars_modiff = CHARS_MODIFF;
4370 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4371 insval = call3 (Qformat_decode,
4372 Qnil, make_number (oinserted), visit);
4373 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4374 wrong_type_argument (intern ("inserted-chars"), insval);
4375 if (ochars_modiff == CHARS_MODIFF)
4376 /* format_decode didn't modify buffer's characters => move
4377 point back to position before inserted text and leave
4378 value of inserted alone. */
4379 SET_PT_BOTH (opoint, opoint_byte);
4380 else
4381 /* format_decode modified buffer's characters => consider
4382 entire buffer changed and leave point at point-min. */
4383 inserted = XFASTINT (insval);
4386 /* For consistency with format-decode call these now iff inserted > 0
4387 (martin 2007-06-28). */
4388 p = Vafter_insert_file_functions;
4389 while (CONSP (p))
4391 if (NILP (replace))
4393 insval = call1 (XCAR (p), make_number (inserted));
4394 if (!NILP (insval))
4396 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4397 wrong_type_argument (intern ("inserted-chars"), insval);
4398 inserted = XFASTINT (insval);
4401 else
4403 /* For the rationale of this see the comment on
4404 format-decode above. */
4405 ptrdiff_t opoint = PT;
4406 ptrdiff_t opoint_byte = PT_BYTE;
4407 ptrdiff_t oinserted = ZV - BEGV;
4408 EMACS_INT ochars_modiff = CHARS_MODIFF;
4410 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4411 insval = call1 (XCAR (p), make_number (oinserted));
4412 if (!NILP (insval))
4414 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4415 wrong_type_argument (intern ("inserted-chars"), insval);
4416 if (ochars_modiff == CHARS_MODIFF)
4417 /* after_insert_file_functions didn't modify
4418 buffer's characters => move point back to
4419 position before inserted text and leave value of
4420 inserted alone. */
4421 SET_PT_BOTH (opoint, opoint_byte);
4422 else
4423 /* after_insert_file_functions did modify buffer's
4424 characters => consider entire buffer changed and
4425 leave point at point-min. */
4426 inserted = XFASTINT (insval);
4430 QUIT;
4431 p = XCDR (p);
4434 if (!empty_undo_list_p)
4436 bset_undo_list (current_buffer, old_undo);
4437 if (CONSP (old_undo) && inserted != old_inserted)
4439 /* Adjust the last undo record for the size change during
4440 the format conversion. */
4441 Lisp_Object tem = XCAR (old_undo);
4442 if (CONSP (tem) && INTEGERP (XCAR (tem))
4443 && INTEGERP (XCDR (tem))
4444 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4445 XSETCDR (tem, make_number (PT + inserted));
4448 else
4449 /* If undo_list was Qt before, keep it that way.
4450 Otherwise start with an empty undo_list. */
4451 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4453 unbind_to (count1, Qnil);
4456 if (!NILP (visit)
4457 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4459 /* If visiting nonexistent file, return nil. */
4460 report_file_errno ("Opening input file", orig_filename, save_errno);
4463 /* We made a lot of deletions and insertions above, so invalidate
4464 the newline cache for the entire region of the inserted
4465 characters. */
4466 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4467 invalidate_region_cache (current_buffer->base_buffer,
4468 current_buffer->base_buffer->newline_cache,
4469 PT - BEG, Z - PT - inserted);
4470 else if (current_buffer->newline_cache)
4471 invalidate_region_cache (current_buffer,
4472 current_buffer->newline_cache,
4473 PT - BEG, Z - PT - inserted);
4475 if (read_quit)
4476 Fsignal (Qquit, Qnil);
4478 /* Retval needs to be dealt with in all cases consistently. */
4479 if (NILP (val))
4480 val = list2 (orig_filename, make_number (inserted));
4482 return unbind_to (count, val);
4485 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4487 static void
4488 build_annotations_unwind (Lisp_Object arg)
4490 Vwrite_region_annotation_buffers = arg;
4493 /* Decide the coding-system to encode the data with. */
4495 static Lisp_Object
4496 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4497 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4498 struct coding_system *coding)
4500 Lisp_Object val;
4501 Lisp_Object eol_parent = Qnil;
4503 if (auto_saving
4504 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4505 BVAR (current_buffer, auto_save_file_name))))
4507 val = Qutf_8_emacs;
4508 eol_parent = Qunix;
4510 else if (!NILP (Vcoding_system_for_write))
4512 val = Vcoding_system_for_write;
4513 if (coding_system_require_warning
4514 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4515 /* Confirm that VAL can surely encode the current region. */
4516 val = call5 (Vselect_safe_coding_system_function,
4517 start, end, list2 (Qt, val),
4518 Qnil, filename);
4520 else
4522 /* If the variable `buffer-file-coding-system' is set locally,
4523 it means that the file was read with some kind of code
4524 conversion or the variable is explicitly set by users. We
4525 had better write it out with the same coding system even if
4526 `enable-multibyte-characters' is nil.
4528 If it is not set locally, we anyway have to convert EOL
4529 format if the default value of `buffer-file-coding-system'
4530 tells that it is not Unix-like (LF only) format. */
4531 bool using_default_coding = 0;
4532 bool force_raw_text = 0;
4534 val = BVAR (current_buffer, buffer_file_coding_system);
4535 if (NILP (val)
4536 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4538 val = Qnil;
4539 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4540 force_raw_text = 1;
4543 if (NILP (val))
4545 /* Check file-coding-system-alist. */
4546 Lisp_Object coding_systems
4547 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4548 filename, append, visit, lockname);
4549 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4550 val = XCDR (coding_systems);
4553 if (NILP (val))
4555 /* If we still have not decided a coding system, use the
4556 default value of buffer-file-coding-system. */
4557 val = BVAR (current_buffer, buffer_file_coding_system);
4558 using_default_coding = 1;
4561 if (! NILP (val) && ! force_raw_text)
4563 Lisp_Object spec, attrs;
4565 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4566 attrs = AREF (spec, 0);
4567 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4568 force_raw_text = 1;
4571 if (!force_raw_text
4572 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4573 /* Confirm that VAL can surely encode the current region. */
4574 val = call5 (Vselect_safe_coding_system_function,
4575 start, end, val, Qnil, filename);
4577 /* If the decided coding-system doesn't specify end-of-line
4578 format, we use that of
4579 `default-buffer-file-coding-system'. */
4580 if (! using_default_coding
4581 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4582 val = (coding_inherit_eol_type
4583 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4585 /* If we decide not to encode text, use `raw-text' or one of its
4586 subsidiaries. */
4587 if (force_raw_text)
4588 val = raw_text_coding_system (val);
4591 val = coding_inherit_eol_type (val, eol_parent);
4592 setup_coding_system (val, coding);
4594 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4595 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4596 return val;
4599 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4600 "r\nFWrite region to file: \ni\ni\ni\np",
4601 doc: /* Write current region into specified file.
4602 When called from a program, requires three arguments:
4603 START, END and FILENAME. START and END are normally buffer positions
4604 specifying the part of the buffer to write.
4605 If START is nil, that means to use the entire buffer contents.
4606 If START is a string, then output that string to the file
4607 instead of any buffer contents; END is ignored.
4609 Optional fourth argument APPEND if non-nil means
4610 append to existing file contents (if any). If it is a number,
4611 seek to that offset in the file before writing.
4612 Optional fifth argument VISIT, if t or a string, means
4613 set the last-save-file-modtime of buffer to this file's modtime
4614 and mark buffer not modified.
4615 If VISIT is a string, it is a second file name;
4616 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4617 VISIT is also the file name to lock and unlock for clash detection.
4618 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4619 do not display the \"Wrote file\" message.
4620 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4621 use for locking and unlocking, overriding FILENAME and VISIT.
4622 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4623 for an existing file with the same name. If MUSTBENEW is `excl',
4624 that means to get an error if the file already exists; never overwrite.
4625 If MUSTBENEW is neither nil nor `excl', that means ask for
4626 confirmation before overwriting, but do go ahead and overwrite the file
4627 if the user confirms.
4629 This does code conversion according to the value of
4630 `coding-system-for-write', `buffer-file-coding-system', or
4631 `file-coding-system-alist', and sets the variable
4632 `last-coding-system-used' to the coding system actually used.
4634 This calls `write-region-annotate-functions' at the start, and
4635 `write-region-post-annotation-function' at the end. */)
4636 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4637 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4639 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4640 -1);
4643 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4644 descriptor for FILENAME, so do not open or close FILENAME. */
4646 Lisp_Object
4647 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4648 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4649 Lisp_Object mustbenew, int desc)
4651 int open_flags;
4652 int mode;
4653 off_t offset IF_LINT (= 0);
4654 bool open_and_close_file = desc < 0;
4655 bool ok;
4656 int save_errno = 0;
4657 const char *fn;
4658 struct stat st;
4659 struct timespec modtime;
4660 ptrdiff_t count = SPECPDL_INDEX ();
4661 ptrdiff_t count1 IF_LINT (= 0);
4662 Lisp_Object handler;
4663 Lisp_Object visit_file;
4664 Lisp_Object annotations;
4665 Lisp_Object encoded_filename;
4666 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4667 bool quietly = !NILP (visit);
4668 bool file_locked = 0;
4669 struct buffer *given_buffer;
4670 struct coding_system coding;
4672 if (current_buffer->base_buffer && visiting)
4673 error ("Cannot do file visiting in an indirect buffer");
4675 if (!NILP (start) && !STRINGP (start))
4676 validate_region (&start, &end);
4678 visit_file = Qnil;
4680 filename = Fexpand_file_name (filename, Qnil);
4682 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4683 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4685 if (STRINGP (visit))
4686 visit_file = Fexpand_file_name (visit, Qnil);
4687 else
4688 visit_file = filename;
4690 if (NILP (lockname))
4691 lockname = visit_file;
4693 annotations = Qnil;
4695 /* If the file name has special constructs in it,
4696 call the corresponding file handler. */
4697 handler = Ffind_file_name_handler (filename, Qwrite_region);
4698 /* If FILENAME has no handler, see if VISIT has one. */
4699 if (NILP (handler) && STRINGP (visit))
4700 handler = Ffind_file_name_handler (visit, Qwrite_region);
4702 if (!NILP (handler))
4704 Lisp_Object val;
4705 val = call6 (handler, Qwrite_region, start, end,
4706 filename, append, visit);
4708 if (visiting)
4710 SAVE_MODIFF = MODIFF;
4711 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4712 bset_filename (current_buffer, visit_file);
4715 return val;
4718 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4720 /* Special kludge to simplify auto-saving. */
4721 if (NILP (start))
4723 /* Do it later, so write-region-annotate-function can work differently
4724 if we save "the buffer" vs "a region".
4725 This is useful in tar-mode. --Stef
4726 XSETFASTINT (start, BEG);
4727 XSETFASTINT (end, Z); */
4728 Fwiden ();
4731 record_unwind_protect (build_annotations_unwind,
4732 Vwrite_region_annotation_buffers);
4733 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4735 given_buffer = current_buffer;
4737 if (!STRINGP (start))
4739 annotations = build_annotations (start, end);
4741 if (current_buffer != given_buffer)
4743 XSETFASTINT (start, BEGV);
4744 XSETFASTINT (end, ZV);
4748 if (NILP (start))
4750 XSETFASTINT (start, BEGV);
4751 XSETFASTINT (end, ZV);
4754 /* Decide the coding-system to encode the data with.
4755 We used to make this choice before calling build_annotations, but that
4756 leads to problems when a write-annotate-function takes care of
4757 unsavable chars (as was the case with X-Symbol). */
4758 Vlast_coding_system_used
4759 = choose_write_coding_system (start, end, filename,
4760 append, visit, lockname, &coding);
4762 if (open_and_close_file && !auto_saving)
4764 lock_file (lockname);
4765 file_locked = 1;
4768 encoded_filename = ENCODE_FILE (filename);
4769 fn = SSDATA (encoded_filename);
4770 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4771 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4772 if (NUMBERP (append))
4773 offset = file_offset (append);
4774 else if (!NILP (append))
4775 open_flags |= O_APPEND;
4776 #ifdef DOS_NT
4777 mode = S_IREAD | S_IWRITE;
4778 #else
4779 mode = auto_saving ? auto_save_mode_bits : 0666;
4780 #endif
4782 if (open_and_close_file)
4784 desc = emacs_open (fn, open_flags, mode);
4785 if (desc < 0)
4787 int open_errno = errno;
4788 if (file_locked)
4789 unlock_file (lockname);
4790 report_file_errno ("Opening output file", filename, open_errno);
4793 count1 = SPECPDL_INDEX ();
4794 record_unwind_protect_int (close_file_unwind, desc);
4797 if (NUMBERP (append))
4799 off_t ret = lseek (desc, offset, SEEK_SET);
4800 if (ret < 0)
4802 int lseek_errno = errno;
4803 if (file_locked)
4804 unlock_file (lockname);
4805 report_file_errno ("Lseek error", filename, lseek_errno);
4809 immediate_quit = 1;
4811 if (STRINGP (start))
4812 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4813 else if (XINT (start) != XINT (end))
4814 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4815 &annotations, &coding);
4816 else
4818 /* If file was empty, still need to write the annotations. */
4819 coding.mode |= CODING_MODE_LAST_BLOCK;
4820 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4822 save_errno = errno;
4824 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4825 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4827 /* We have to flush out a data. */
4828 coding.mode |= CODING_MODE_LAST_BLOCK;
4829 ok = e_write (desc, Qnil, 1, 1, &coding);
4830 save_errno = errno;
4833 immediate_quit = 0;
4835 /* fsync is not crucial for temporary files. Nor for auto-save
4836 files, since they might lose some work anyway. */
4837 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4839 /* Transfer data and metadata to disk, retrying if interrupted.
4840 fsync can report a write failure here, e.g., due to disk full
4841 under NFS. But ignore EINVAL, which means fsync is not
4842 supported on this file. */
4843 while (fsync (desc) != 0)
4844 if (errno != EINTR)
4846 if (errno != EINVAL)
4847 ok = 0, save_errno = errno;
4848 break;
4852 modtime = invalid_timespec ();
4853 if (visiting)
4855 if (fstat (desc, &st) == 0)
4856 modtime = get_stat_mtime (&st);
4857 else
4858 ok = 0, save_errno = errno;
4861 if (open_and_close_file)
4863 /* NFS can report a write failure now. */
4864 if (emacs_close (desc) < 0)
4865 ok = 0, save_errno = errno;
4867 /* Discard the unwind protect for close_file_unwind. */
4868 specpdl_ptr = specpdl + count1;
4871 /* Some file systems have a bug where st_mtime is not updated
4872 properly after a write. For example, CIFS might not see the
4873 st_mtime change until after the file is opened again.
4875 Attempt to detect this file system bug, and update MODTIME to the
4876 newer st_mtime if the bug appears to be present. This introduces
4877 a race condition, so to avoid most instances of the race condition
4878 on non-buggy file systems, skip this check if the most recently
4879 encountered non-buggy file system was the current file system.
4881 A race condition can occur if some other process modifies the
4882 file between the fstat above and the fstat below, but the race is
4883 unlikely and a similar race between the last write and the fstat
4884 above cannot possibly be closed anyway. */
4886 if (timespec_valid_p (modtime)
4887 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4889 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4890 if (desc1 >= 0)
4892 struct stat st1;
4893 if (fstat (desc1, &st1) == 0
4894 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4896 /* Use the heuristic if it appears to be valid. With neither
4897 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4898 file, the time stamp won't change. Also, some non-POSIX
4899 systems don't update an empty file's time stamp when
4900 truncating it. Finally, file systems with 100 ns or worse
4901 resolution sometimes seem to have bugs: on a system with ns
4902 resolution, checking ns % 100 incorrectly avoids the heuristic
4903 1% of the time, but the problem should be temporary as we will
4904 try again on the next time stamp. */
4905 bool use_heuristic
4906 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4907 && st.st_size != 0
4908 && modtime.tv_nsec % 100 != 0);
4910 struct timespec modtime1 = get_stat_mtime (&st1);
4911 if (use_heuristic
4912 && timespec_cmp (modtime, modtime1) == 0
4913 && st.st_size == st1.st_size)
4915 timestamp_file_system = st.st_dev;
4916 valid_timestamp_file_system = 1;
4918 else
4920 st.st_size = st1.st_size;
4921 modtime = modtime1;
4924 emacs_close (desc1);
4928 /* Call write-region-post-annotation-function. */
4929 while (CONSP (Vwrite_region_annotation_buffers))
4931 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4932 if (!NILP (Fbuffer_live_p (buf)))
4934 Fset_buffer (buf);
4935 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4936 call0 (Vwrite_region_post_annotation_function);
4938 Vwrite_region_annotation_buffers
4939 = XCDR (Vwrite_region_annotation_buffers);
4942 unbind_to (count, Qnil);
4944 if (file_locked)
4945 unlock_file (lockname);
4947 /* Do this before reporting IO error
4948 to avoid a "file has changed on disk" warning on
4949 next attempt to save. */
4950 if (timespec_valid_p (modtime))
4952 current_buffer->modtime = modtime;
4953 current_buffer->modtime_size = st.st_size;
4956 if (! ok)
4957 report_file_errno ("Write error", filename, save_errno);
4959 if (visiting)
4961 SAVE_MODIFF = MODIFF;
4962 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4963 bset_filename (current_buffer, visit_file);
4964 update_mode_lines = 14;
4966 else if (quietly)
4968 if (auto_saving
4969 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
4970 BVAR (current_buffer, auto_save_file_name))))
4971 SAVE_MODIFF = MODIFF;
4973 return Qnil;
4976 if (!auto_saving && !noninteractive)
4977 message_with_string ((NUMBERP (append)
4978 ? "Updated %s"
4979 : ! NILP (append)
4980 ? "Added to %s"
4981 : "Wrote %s"),
4982 visit_file, 1);
4984 return Qnil;
4987 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4988 doc: /* Return t if (car A) is numerically less than (car B). */)
4989 (Lisp_Object a, Lisp_Object b)
4991 return CALLN (Flss, Fcar (a), Fcar (b));
4994 /* Build the complete list of annotations appropriate for writing out
4995 the text between START and END, by calling all the functions in
4996 write-region-annotate-functions and merging the lists they return.
4997 If one of these functions switches to a different buffer, we assume
4998 that buffer contains altered text. Therefore, the caller must
4999 make sure to restore the current buffer in all cases,
5000 as save-excursion would do. */
5002 static Lisp_Object
5003 build_annotations (Lisp_Object start, Lisp_Object end)
5005 Lisp_Object annotations;
5006 Lisp_Object p, res;
5007 Lisp_Object original_buffer;
5008 int i;
5009 bool used_global = false;
5011 XSETBUFFER (original_buffer, current_buffer);
5013 annotations = Qnil;
5014 p = Vwrite_region_annotate_functions;
5015 while (CONSP (p))
5017 struct buffer *given_buffer = current_buffer;
5018 if (EQ (Qt, XCAR (p)) && !used_global)
5019 { /* Use the global value of the hook. */
5020 used_global = true;
5021 p = CALLN (Fappend,
5022 Fdefault_value (Qwrite_region_annotate_functions),
5023 XCDR (p));
5024 continue;
5026 Vwrite_region_annotations_so_far = annotations;
5027 res = call2 (XCAR (p), start, end);
5028 /* If the function makes a different buffer current,
5029 assume that means this buffer contains altered text to be output.
5030 Reset START and END from the buffer bounds
5031 and discard all previous annotations because they should have
5032 been dealt with by this function. */
5033 if (current_buffer != given_buffer)
5035 Vwrite_region_annotation_buffers
5036 = Fcons (Fcurrent_buffer (),
5037 Vwrite_region_annotation_buffers);
5038 XSETFASTINT (start, BEGV);
5039 XSETFASTINT (end, ZV);
5040 annotations = Qnil;
5042 Flength (res); /* Check basic validity of return value */
5043 annotations = merge (annotations, res, Qcar_less_than_car);
5044 p = XCDR (p);
5047 /* Now do the same for annotation functions implied by the file-format */
5048 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5049 p = BVAR (current_buffer, auto_save_file_format);
5050 else
5051 p = BVAR (current_buffer, file_format);
5052 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5054 struct buffer *given_buffer = current_buffer;
5056 Vwrite_region_annotations_so_far = annotations;
5058 /* Value is either a list of annotations or nil if the function
5059 has written annotations to a temporary buffer, which is now
5060 current. */
5061 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5062 original_buffer, make_number (i));
5063 if (current_buffer != given_buffer)
5065 XSETFASTINT (start, BEGV);
5066 XSETFASTINT (end, ZV);
5067 annotations = Qnil;
5070 if (CONSP (res))
5071 annotations = merge (annotations, res, Qcar_less_than_car);
5074 return annotations;
5078 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5079 If STRING is nil, POS is the character position in the current buffer.
5080 Intersperse with them the annotations from *ANNOT
5081 which fall within the range of POS to POS + NCHARS,
5082 each at its appropriate position.
5084 We modify *ANNOT by discarding elements as we use them up.
5086 Return true if successful. */
5088 static bool
5089 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5090 ptrdiff_t nchars, Lisp_Object *annot,
5091 struct coding_system *coding)
5093 Lisp_Object tem;
5094 ptrdiff_t nextpos;
5095 ptrdiff_t lastpos = pos + nchars;
5097 while (NILP (*annot) || CONSP (*annot))
5099 tem = Fcar_safe (Fcar (*annot));
5100 nextpos = pos - 1;
5101 if (INTEGERP (tem))
5102 nextpos = XFASTINT (tem);
5104 /* If there are no more annotations in this range,
5105 output the rest of the range all at once. */
5106 if (! (nextpos >= pos && nextpos <= lastpos))
5107 return e_write (desc, string, pos, lastpos, coding);
5109 /* Output buffer text up to the next annotation's position. */
5110 if (nextpos > pos)
5112 if (!e_write (desc, string, pos, nextpos, coding))
5113 return 0;
5114 pos = nextpos;
5116 /* Output the annotation. */
5117 tem = Fcdr (Fcar (*annot));
5118 if (STRINGP (tem))
5120 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5121 return 0;
5123 *annot = Fcdr (*annot);
5125 return 1;
5128 /* Maximum number of characters that the next
5129 function encodes per one loop iteration. */
5131 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5133 /* Write text in the range START and END into descriptor DESC,
5134 encoding them with coding system CODING. If STRING is nil, START
5135 and END are character positions of the current buffer, else they
5136 are indexes to the string STRING. Return true if successful. */
5138 static bool
5139 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5140 struct coding_system *coding)
5142 if (STRINGP (string))
5144 start = 0;
5145 end = SCHARS (string);
5148 /* We used to have a code for handling selective display here. But,
5149 now it is handled within encode_coding. */
5151 while (start < end)
5153 if (STRINGP (string))
5155 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5156 if (CODING_REQUIRE_ENCODING (coding))
5158 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5160 /* Avoid creating huge Lisp string in encode_coding_object. */
5161 if (nchars == E_WRITE_MAX)
5162 coding->raw_destination = 1;
5164 encode_coding_object
5165 (coding, string, start, string_char_to_byte (string, start),
5166 start + nchars, string_char_to_byte (string, start + nchars),
5167 Qt);
5169 else
5171 coding->dst_object = string;
5172 coding->consumed_char = SCHARS (string);
5173 coding->produced = SBYTES (string);
5176 else
5178 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5179 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5181 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5182 if (CODING_REQUIRE_ENCODING (coding))
5184 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5186 /* Likewise. */
5187 if (nchars == E_WRITE_MAX)
5188 coding->raw_destination = 1;
5190 encode_coding_object
5191 (coding, Fcurrent_buffer (), start, start_byte,
5192 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5194 else
5196 coding->dst_object = Qnil;
5197 coding->dst_pos_byte = start_byte;
5198 if (start >= GPT || end <= GPT)
5200 coding->consumed_char = end - start;
5201 coding->produced = end_byte - start_byte;
5203 else
5205 coding->consumed_char = GPT - start;
5206 coding->produced = GPT_BYTE - start_byte;
5211 if (coding->produced > 0)
5213 char *buf = (coding->raw_destination ? (char *) coding->destination
5214 : (STRINGP (coding->dst_object)
5215 ? SSDATA (coding->dst_object)
5216 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5217 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5219 if (coding->raw_destination)
5221 /* We're responsible for freeing this, see
5222 encode_coding_object to check why. */
5223 xfree (coding->destination);
5224 coding->raw_destination = 0;
5226 if (coding->produced)
5227 return 0;
5229 start += coding->consumed_char;
5232 return 1;
5235 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5236 Sverify_visited_file_modtime, 0, 1, 0,
5237 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5238 This means that the file has not been changed since it was visited or saved.
5239 If BUF is omitted or nil, it defaults to the current buffer.
5240 See Info node `(elisp)Modification Time' for more details. */)
5241 (Lisp_Object buf)
5243 struct buffer *b = decode_buffer (buf);
5244 struct stat st;
5245 Lisp_Object handler;
5246 Lisp_Object filename;
5247 struct timespec mtime;
5249 if (!STRINGP (BVAR (b, filename))) return Qt;
5250 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5252 /* If the file name has special constructs in it,
5253 call the corresponding file handler. */
5254 handler = Ffind_file_name_handler (BVAR (b, filename),
5255 Qverify_visited_file_modtime);
5256 if (!NILP (handler))
5257 return call2 (handler, Qverify_visited_file_modtime, buf);
5259 filename = ENCODE_FILE (BVAR (b, filename));
5261 mtime = (stat (SSDATA (filename), &st) == 0
5262 ? get_stat_mtime (&st)
5263 : time_error_value (errno));
5264 if (timespec_cmp (mtime, b->modtime) == 0
5265 && (b->modtime_size < 0
5266 || st.st_size == b->modtime_size))
5267 return Qt;
5268 return Qnil;
5271 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5272 Svisited_file_modtime, 0, 0, 0,
5273 doc: /* Return the current buffer's recorded visited file modification time.
5274 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5275 `file-attributes' returns. If the current buffer has no recorded file
5276 modification time, this function returns 0. If the visited file
5277 doesn't exist, return -1.
5278 See Info node `(elisp)Modification Time' for more details. */)
5279 (void)
5281 int ns = current_buffer->modtime.tv_nsec;
5282 if (ns < 0)
5283 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5284 return make_lisp_time (current_buffer->modtime);
5287 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5288 Sset_visited_file_modtime, 0, 1, 0,
5289 doc: /* Update buffer's recorded modification time from the visited file's time.
5290 Useful if the buffer was not read from the file normally
5291 or if the file itself has been changed for some known benign reason.
5292 An argument specifies the modification time value to use
5293 \(instead of that of the visited file), in the form of a list
5294 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5295 `visited-file-modtime'. */)
5296 (Lisp_Object time_flag)
5298 if (!NILP (time_flag))
5300 struct timespec mtime;
5301 if (INTEGERP (time_flag))
5303 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5304 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5306 else
5307 mtime = lisp_time_argument (time_flag);
5309 current_buffer->modtime = mtime;
5310 current_buffer->modtime_size = -1;
5312 else
5314 register Lisp_Object filename;
5315 struct stat st;
5316 Lisp_Object handler;
5318 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5320 /* If the file name has special constructs in it,
5321 call the corresponding file handler. */
5322 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5323 if (!NILP (handler))
5324 /* The handler can find the file name the same way we did. */
5325 return call2 (handler, Qset_visited_file_modtime, Qnil);
5327 filename = ENCODE_FILE (filename);
5329 if (stat (SSDATA (filename), &st) >= 0)
5331 current_buffer->modtime = get_stat_mtime (&st);
5332 current_buffer->modtime_size = st.st_size;
5336 return Qnil;
5339 static Lisp_Object
5340 auto_save_error (Lisp_Object error_val)
5342 Lisp_Object msg;
5343 int i;
5345 auto_save_error_occurred = 1;
5347 ring_bell (XFRAME (selected_frame));
5349 AUTO_STRING (format, "Auto-saving %s: %s");
5350 msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5351 Ferror_message_string (error_val));
5353 for (i = 0; i < 3; ++i)
5355 if (i == 0)
5356 message3 (msg);
5357 else
5358 message3_nolog (msg);
5359 Fsleep_for (make_number (1), Qnil);
5362 return Qnil;
5365 static Lisp_Object
5366 auto_save_1 (void)
5368 struct stat st;
5369 Lisp_Object modes;
5371 auto_save_mode_bits = 0666;
5373 /* Get visited file's mode to become the auto save file's mode. */
5374 if (! NILP (BVAR (current_buffer, filename)))
5376 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5377 /* But make sure we can overwrite it later! */
5378 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5379 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5380 INTEGERP (modes))
5381 /* Remote files don't cooperate with stat. */
5382 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5385 return
5386 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5387 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5388 Qnil, Qnil);
5391 struct auto_save_unwind
5393 FILE *stream;
5394 bool auto_raise;
5397 static void
5398 do_auto_save_unwind (void *arg)
5400 struct auto_save_unwind *p = arg;
5401 FILE *stream = p->stream;
5402 minibuffer_auto_raise = p->auto_raise;
5403 auto_saving = 0;
5404 if (stream != NULL)
5406 block_input ();
5407 fclose (stream);
5408 unblock_input ();
5412 static Lisp_Object
5413 do_auto_save_make_dir (Lisp_Object dir)
5415 Lisp_Object result;
5417 auto_saving_dir_umask = 077;
5418 result = call2 (Qmake_directory, dir, Qt);
5419 auto_saving_dir_umask = 0;
5420 return result;
5423 static Lisp_Object
5424 do_auto_save_eh (Lisp_Object ignore)
5426 auto_saving_dir_umask = 0;
5427 return Qnil;
5430 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5431 doc: /* Auto-save all buffers that need it.
5432 This is all buffers that have auto-saving enabled
5433 and are changed since last auto-saved.
5434 Auto-saving writes the buffer into a file
5435 so that your editing is not lost if the system crashes.
5436 This file is not the file you visited; that changes only when you save.
5437 Normally we run the normal hook `auto-save-hook' before saving.
5439 A non-nil NO-MESSAGE argument means do not print any message if successful.
5440 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5441 (Lisp_Object no_message, Lisp_Object current_only)
5443 struct buffer *old = current_buffer, *b;
5444 Lisp_Object tail, buf, hook;
5445 bool auto_saved = 0;
5446 int do_handled_files;
5447 Lisp_Object oquit;
5448 FILE *stream = NULL;
5449 ptrdiff_t count = SPECPDL_INDEX ();
5450 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5451 bool old_message_p = 0;
5452 struct auto_save_unwind auto_save_unwind;
5454 if (max_specpdl_size < specpdl_size + 40)
5455 max_specpdl_size = specpdl_size + 40;
5457 if (minibuf_level)
5458 no_message = Qt;
5460 if (NILP (no_message))
5462 old_message_p = push_message ();
5463 record_unwind_protect_void (pop_message_unwind);
5466 /* Ordinarily don't quit within this function,
5467 but don't make it impossible to quit (in case we get hung in I/O). */
5468 oquit = Vquit_flag;
5469 Vquit_flag = Qnil;
5471 hook = intern ("auto-save-hook");
5472 safe_run_hooks (hook);
5474 if (STRINGP (Vauto_save_list_file_name))
5476 Lisp_Object listfile;
5478 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5480 /* Don't try to create the directory when shutting down Emacs,
5481 because creating the directory might signal an error, and
5482 that would leave Emacs in a strange state. */
5483 if (!NILP (Vrun_hooks))
5485 Lisp_Object dir;
5486 dir = Ffile_name_directory (listfile);
5487 if (NILP (Ffile_directory_p (dir)))
5488 internal_condition_case_1 (do_auto_save_make_dir,
5489 dir, Qt,
5490 do_auto_save_eh);
5493 stream = emacs_fopen (SSDATA (listfile), "w");
5496 auto_save_unwind.stream = stream;
5497 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5498 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5499 minibuffer_auto_raise = 0;
5500 auto_saving = 1;
5501 auto_save_error_occurred = 0;
5503 /* On first pass, save all files that don't have handlers.
5504 On second pass, save all files that do have handlers.
5506 If Emacs is crashing, the handlers may tweak what is causing
5507 Emacs to crash in the first place, and it would be a shame if
5508 Emacs failed to autosave perfectly ordinary files because it
5509 couldn't handle some ange-ftp'd file. */
5511 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5512 FOR_EACH_LIVE_BUFFER (tail, buf)
5514 b = XBUFFER (buf);
5516 /* Record all the buffers that have auto save mode
5517 in the special file that lists them. For each of these buffers,
5518 Record visited name (if any) and auto save name. */
5519 if (STRINGP (BVAR (b, auto_save_file_name))
5520 && stream != NULL && do_handled_files == 0)
5522 block_input ();
5523 if (!NILP (BVAR (b, filename)))
5525 fwrite (SDATA (BVAR (b, filename)), 1,
5526 SBYTES (BVAR (b, filename)), stream);
5528 putc ('\n', stream);
5529 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5530 SBYTES (BVAR (b, auto_save_file_name)), stream);
5531 putc ('\n', stream);
5532 unblock_input ();
5535 if (!NILP (current_only)
5536 && b != current_buffer)
5537 continue;
5539 /* Don't auto-save indirect buffers.
5540 The base buffer takes care of it. */
5541 if (b->base_buffer)
5542 continue;
5544 /* Check for auto save enabled
5545 and file changed since last auto save
5546 and file changed since last real save. */
5547 if (STRINGP (BVAR (b, auto_save_file_name))
5548 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5549 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5550 /* -1 means we've turned off autosaving for a while--see below. */
5551 && XINT (BVAR (b, save_length)) >= 0
5552 && (do_handled_files
5553 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5554 Qwrite_region))))
5556 struct timespec before_time = current_timespec ();
5557 struct timespec after_time;
5559 /* If we had a failure, don't try again for 20 minutes. */
5560 if (b->auto_save_failure_time > 0
5561 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5562 continue;
5564 set_buffer_internal (b);
5565 if (NILP (Vauto_save_include_big_deletions)
5566 && (XFASTINT (BVAR (b, save_length)) * 10
5567 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5568 /* A short file is likely to change a large fraction;
5569 spare the user annoying messages. */
5570 && XFASTINT (BVAR (b, save_length)) > 5000
5571 /* These messages are frequent and annoying for `*mail*'. */
5572 && !EQ (BVAR (b, filename), Qnil)
5573 && NILP (no_message))
5575 /* It has shrunk too much; turn off auto-saving here. */
5576 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5577 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5578 BVAR (b, name), 1);
5579 minibuffer_auto_raise = 0;
5580 /* Turn off auto-saving until there's a real save,
5581 and prevent any more warnings. */
5582 XSETINT (BVAR (b, save_length), -1);
5583 Fsleep_for (make_number (1), Qnil);
5584 continue;
5586 if (!auto_saved && NILP (no_message))
5587 message1 ("Auto-saving...");
5588 internal_condition_case (auto_save_1, Qt, auto_save_error);
5589 auto_saved = 1;
5590 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5591 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5592 set_buffer_internal (old);
5594 after_time = current_timespec ();
5596 /* If auto-save took more than 60 seconds,
5597 assume it was an NFS failure that got a timeout. */
5598 if (after_time.tv_sec - before_time.tv_sec > 60)
5599 b->auto_save_failure_time = after_time.tv_sec;
5603 /* Prevent another auto save till enough input events come in. */
5604 record_auto_save ();
5606 if (auto_saved && NILP (no_message))
5608 if (old_message_p)
5610 /* If we are going to restore an old message,
5611 give time to read ours. */
5612 sit_for (make_number (1), 0, 0);
5613 restore_message ();
5615 else if (!auto_save_error_occurred)
5616 /* Don't overwrite the error message if an error occurred.
5617 If we displayed a message and then restored a state
5618 with no message, leave a "done" message on the screen. */
5619 message1 ("Auto-saving...done");
5622 Vquit_flag = oquit;
5624 /* This restores the message-stack status. */
5625 unbind_to (count, Qnil);
5626 return Qnil;
5629 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5630 Sset_buffer_auto_saved, 0, 0, 0,
5631 doc: /* Mark current buffer as auto-saved with its current text.
5632 No auto-save file will be written until the buffer changes again. */)
5633 (void)
5635 /* FIXME: This should not be called in indirect buffers, since
5636 they're not autosaved. */
5637 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5638 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5639 current_buffer->auto_save_failure_time = 0;
5640 return Qnil;
5643 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5644 Sclear_buffer_auto_save_failure, 0, 0, 0,
5645 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5646 (void)
5648 current_buffer->auto_save_failure_time = 0;
5649 return Qnil;
5652 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5653 0, 0, 0,
5654 doc: /* Return t if current buffer has been auto-saved recently.
5655 More precisely, if it has been auto-saved since last read from or saved
5656 in the visited file. If the buffer has no visited file,
5657 then any auto-save counts as "recent". */)
5658 (void)
5660 /* FIXME: maybe we should return nil for indirect buffers since
5661 they're never autosaved. */
5662 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5665 /* Reading and completing file names. */
5667 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5668 Snext_read_file_uses_dialog_p, 0, 0, 0,
5669 doc: /* Return t if a call to `read-file-name' will use a dialog.
5670 The return value is only relevant for a call to `read-file-name' that happens
5671 before any other event (mouse or keypress) is handled. */)
5672 (void)
5674 #if (defined USE_GTK || defined USE_MOTIF \
5675 || defined HAVE_NS || defined HAVE_NTGUI)
5676 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5677 && use_dialog_box
5678 && use_file_dialog
5679 && window_system_available (SELECTED_FRAME ()))
5680 return Qt;
5681 #endif
5682 return Qnil;
5686 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5687 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5688 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5689 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5690 it to text mode.
5692 As a side effect, this function flushes any pending STREAM's data.
5694 Value is the previous value of STREAM's I/O mode, nil for text mode,
5695 non-nil for binary mode.
5697 On MS-Windows and MS-DOS, binary mode is needed to read or write
5698 arbitrary binary data, and for disabling translation between CR-LF
5699 pairs and a single newline character. Examples include generation
5700 of text files with Unix-style end-of-line format using `princ' in
5701 batch mode, with standard output redirected to a file.
5703 On Posix systems, this function always returns non-nil, and has no
5704 effect except for flushing STREAM's data. */)
5705 (Lisp_Object stream, Lisp_Object mode)
5707 FILE *fp = NULL;
5708 int binmode;
5710 CHECK_SYMBOL (stream);
5711 if (EQ (stream, Qstdin))
5712 fp = stdin;
5713 else if (EQ (stream, Qstdout))
5714 fp = stdout;
5715 else if (EQ (stream, Qstderr))
5716 fp = stderr;
5717 else
5718 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5720 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5721 if (fp != stdin)
5722 fflush (fp);
5724 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5727 void
5728 init_fileio (void)
5730 realmask = umask (0);
5731 umask (realmask);
5733 valid_timestamp_file_system = 0;
5735 /* fsync can be a significant performance hit. Often it doesn't
5736 suffice to make the file-save operation survive a crash. For
5737 batch scripts, which are typically part of larger shell commands
5738 that don't fsync other files, its effect on performance can be
5739 significant so its utility is particularly questionable.
5740 Hence, for now by default fsync is used only when interactive.
5742 For more on why fsync often fails to work on today's hardware, see:
5743 Zheng M et al. Understanding the robustness of SSDs under power fault.
5744 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5745 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5747 For more on why fsync does not suffice even if it works properly, see:
5748 Roche X. Necessary step(s) to synchronize filename operations on disk.
5749 Austin Group Defect 672, 2013-03-19
5750 http://austingroupbugs.net/view.php?id=672 */
5751 write_region_inhibit_fsync = noninteractive;
5754 void
5755 syms_of_fileio (void)
5757 /* Property name of a file name handler,
5758 which gives a list of operations it handles. */
5759 DEFSYM (Qoperations, "operations");
5761 DEFSYM (Qexpand_file_name, "expand-file-name");
5762 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5763 DEFSYM (Qdirectory_file_name, "directory-file-name");
5764 DEFSYM (Qfile_name_directory, "file-name-directory");
5765 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5766 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5767 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5768 DEFSYM (Qcopy_file, "copy-file");
5769 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5770 DEFSYM (Qmake_directory, "make-directory");
5771 DEFSYM (Qdelete_file, "delete-file");
5772 DEFSYM (Qrename_file, "rename-file");
5773 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5774 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5775 DEFSYM (Qfile_exists_p, "file-exists-p");
5776 DEFSYM (Qfile_executable_p, "file-executable-p");
5777 DEFSYM (Qfile_readable_p, "file-readable-p");
5778 DEFSYM (Qfile_writable_p, "file-writable-p");
5779 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5780 DEFSYM (Qaccess_file, "access-file");
5781 DEFSYM (Qfile_directory_p, "file-directory-p");
5782 DEFSYM (Qfile_regular_p, "file-regular-p");
5783 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5784 DEFSYM (Qfile_modes, "file-modes");
5785 DEFSYM (Qset_file_modes, "set-file-modes");
5786 DEFSYM (Qset_file_times, "set-file-times");
5787 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5788 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5789 DEFSYM (Qfile_acl, "file-acl");
5790 DEFSYM (Qset_file_acl, "set-file-acl");
5791 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5792 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5793 DEFSYM (Qwrite_region, "write-region");
5794 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5795 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5797 /* The symbol bound to coding-system-for-read when
5798 insert-file-contents is called for recovering a file. This is not
5799 an actual coding system name, but just an indicator to tell
5800 insert-file-contents to use `emacs-mule' with a special flag for
5801 auto saving and recovering a file. */
5802 DEFSYM (Qauto_save_coding, "auto-save-coding");
5804 DEFSYM (Qfile_name_history, "file-name-history");
5805 Fset (Qfile_name_history, Qnil);
5807 DEFSYM (Qfile_error, "file-error");
5808 DEFSYM (Qfile_already_exists, "file-already-exists");
5809 DEFSYM (Qfile_date_error, "file-date-error");
5810 DEFSYM (Qfile_notify_error, "file-notify-error");
5811 DEFSYM (Qexcl, "excl");
5813 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5814 doc: /* Coding system for encoding file names.
5815 If it is nil, `default-file-name-coding-system' (which see) is used.
5817 On MS-Windows, the value of this variable is largely ignored if
5818 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5819 behaves as if file names were encoded in `utf-8'. */);
5820 Vfile_name_coding_system = Qnil;
5822 DEFVAR_LISP ("default-file-name-coding-system",
5823 Vdefault_file_name_coding_system,
5824 doc: /* Default coding system for encoding file names.
5825 This variable is used only when `file-name-coding-system' is nil.
5827 This variable is set/changed by the command `set-language-environment'.
5828 User should not set this variable manually,
5829 instead use `file-name-coding-system' to get a constant encoding
5830 of file names regardless of the current language environment.
5832 On MS-Windows, the value of this variable is largely ignored if
5833 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5834 behaves as if file names were encoded in `utf-8'. */);
5835 Vdefault_file_name_coding_system = Qnil;
5837 /* Lisp functions for translating file formats. */
5838 DEFSYM (Qformat_decode, "format-decode");
5839 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5841 /* Lisp function for setting buffer-file-coding-system and the
5842 multibyteness of the current buffer after inserting a file. */
5843 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5845 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5847 Fput (Qfile_error, Qerror_conditions,
5848 Fpurecopy (list2 (Qfile_error, Qerror)));
5849 Fput (Qfile_error, Qerror_message,
5850 build_pure_c_string ("File error"));
5852 Fput (Qfile_already_exists, Qerror_conditions,
5853 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5854 Fput (Qfile_already_exists, Qerror_message,
5855 build_pure_c_string ("File already exists"));
5857 Fput (Qfile_date_error, Qerror_conditions,
5858 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5859 Fput (Qfile_date_error, Qerror_message,
5860 build_pure_c_string ("Cannot set file date"));
5862 Fput (Qfile_notify_error, Qerror_conditions,
5863 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5864 Fput (Qfile_notify_error, Qerror_message,
5865 build_pure_c_string ("File notification error"));
5867 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5868 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5869 If a file name matches REGEXP, all I/O on that file is done by calling
5870 HANDLER. If a file name matches more than one handler, the handler
5871 whose match starts last in the file name gets precedence. The
5872 function `find-file-name-handler' checks this list for a handler for
5873 its argument.
5875 HANDLER should be a function. The first argument given to it is the
5876 name of the I/O primitive to be handled; the remaining arguments are
5877 the arguments that were passed to that primitive. For example, if you
5878 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5879 HANDLER is called like this:
5881 (funcall HANDLER 'file-exists-p FILENAME)
5883 Note that HANDLER must be able to handle all I/O primitives; if it has
5884 nothing special to do for a primitive, it should reinvoke the
5885 primitive to handle the operation \"the usual way\".
5886 See Info node `(elisp)Magic File Names' for more details. */);
5887 Vfile_name_handler_alist = Qnil;
5889 DEFVAR_LISP ("set-auto-coding-function",
5890 Vset_auto_coding_function,
5891 doc: /* If non-nil, a function to call to decide a coding system of file.
5892 Two arguments are passed to this function: the file name
5893 and the length of a file contents following the point.
5894 This function should return a coding system to decode the file contents.
5895 It should check the file name against `auto-coding-alist'.
5896 If no coding system is decided, it should check a coding system
5897 specified in the heading lines with the format:
5898 -*- ... coding: CODING-SYSTEM; ... -*-
5899 or local variable spec of the tailing lines with `coding:' tag. */);
5900 Vset_auto_coding_function = Qnil;
5902 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5903 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5904 Each is passed one argument, the number of characters inserted,
5905 with point at the start of the inserted text. Each function
5906 should leave point the same, and return the new character count.
5907 If `insert-file-contents' is intercepted by a handler from
5908 `file-name-handler-alist', that handler is responsible for calling the
5909 functions in `after-insert-file-functions' if appropriate. */);
5910 Vafter_insert_file_functions = Qnil;
5912 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5913 doc: /* A list of functions to be called at the start of `write-region'.
5914 Each is passed two arguments, START and END as for `write-region'.
5915 These are usually two numbers but not always; see the documentation
5916 for `write-region'. The function should return a list of pairs
5917 of the form (POSITION . STRING), consisting of strings to be effectively
5918 inserted at the specified positions of the file being written (1 means to
5919 insert before the first byte written). The POSITIONs must be sorted into
5920 increasing order.
5922 If there are several annotation functions, the lists returned by these
5923 functions are merged destructively. As each annotation function runs,
5924 the variable `write-region-annotations-so-far' contains a list of all
5925 annotations returned by previous annotation functions.
5927 An annotation function can return with a different buffer current.
5928 Doing so removes the annotations returned by previous functions, and
5929 resets START and END to `point-min' and `point-max' of the new buffer.
5931 After `write-region' completes, Emacs calls the function stored in
5932 `write-region-post-annotation-function', once for each buffer that was
5933 current when building the annotations (i.e., at least once), with that
5934 buffer current. */);
5935 Vwrite_region_annotate_functions = Qnil;
5936 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5938 DEFVAR_LISP ("write-region-post-annotation-function",
5939 Vwrite_region_post_annotation_function,
5940 doc: /* Function to call after `write-region' completes.
5941 The function is called with no arguments. If one or more of the
5942 annotation functions in `write-region-annotate-functions' changed the
5943 current buffer, the function stored in this variable is called for
5944 each of those additional buffers as well, in addition to the original
5945 buffer. The relevant buffer is current during each function call. */);
5946 Vwrite_region_post_annotation_function = Qnil;
5947 staticpro (&Vwrite_region_annotation_buffers);
5949 DEFVAR_LISP ("write-region-annotations-so-far",
5950 Vwrite_region_annotations_so_far,
5951 doc: /* When an annotation function is called, this holds the previous annotations.
5952 These are the annotations made by other annotation functions
5953 that were already called. See also `write-region-annotate-functions'. */);
5954 Vwrite_region_annotations_so_far = Qnil;
5956 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5957 doc: /* A list of file name handlers that temporarily should not be used.
5958 This applies only to the operation `inhibit-file-name-operation'. */);
5959 Vinhibit_file_name_handlers = Qnil;
5961 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5962 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5963 Vinhibit_file_name_operation = Qnil;
5965 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
5966 doc: /* File name in which we write a list of all auto save file names.
5967 This variable is initialized automatically from `auto-save-list-file-prefix'
5968 shortly after Emacs reads your init file, if you have not yet given it
5969 a non-nil value. */);
5970 Vauto_save_list_file_name = Qnil;
5972 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
5973 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5974 Normally auto-save files are written under other names. */);
5975 Vauto_save_visited_file_name = Qnil;
5977 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
5978 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5979 If nil, deleting a substantial portion of the text disables auto-save
5980 in the buffer; this is the default behavior, because the auto-save
5981 file is usually more useful if it contains the deleted text. */);
5982 Vauto_save_include_big_deletions = Qnil;
5984 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
5985 doc: /* Non-nil means don't call fsync in `write-region'.
5986 This variable affects calls to `write-region' as well as save commands.
5987 Setting this to nil may avoid data loss if the system loses power or
5988 the operating system crashes. By default, it is non-nil in batch mode. */);
5989 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
5991 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
5992 doc: /* Specifies whether to use the system's trash can.
5993 When non-nil, certain file deletion commands use the function
5994 `move-file-to-trash' instead of deleting files outright.
5995 This includes interactive calls to `delete-file' and
5996 `delete-directory' and the Dired deletion commands. */);
5997 delete_by_moving_to_trash = 0;
5998 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
6000 /* Lisp function for moving files to trash. */
6001 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6003 /* Lisp function for recursively copying directories. */
6004 DEFSYM (Qcopy_directory, "copy-directory");
6006 /* Lisp function for recursively deleting directories. */
6007 DEFSYM (Qdelete_directory, "delete-directory");
6009 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6010 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6012 DEFSYM (Qstdin, "stdin");
6013 DEFSYM (Qstdout, "stdout");
6014 DEFSYM (Qstderr, "stderr");
6016 defsubr (&Sfind_file_name_handler);
6017 defsubr (&Sfile_name_directory);
6018 defsubr (&Sfile_name_nondirectory);
6019 defsubr (&Sunhandled_file_name_directory);
6020 defsubr (&Sfile_name_as_directory);
6021 defsubr (&Sdirectory_file_name);
6022 defsubr (&Smake_temp_name);
6023 defsubr (&Sexpand_file_name);
6024 defsubr (&Ssubstitute_in_file_name);
6025 defsubr (&Scopy_file);
6026 defsubr (&Smake_directory_internal);
6027 defsubr (&Sdelete_directory_internal);
6028 defsubr (&Sdelete_file);
6029 defsubr (&Srename_file);
6030 defsubr (&Sadd_name_to_file);
6031 defsubr (&Smake_symbolic_link);
6032 defsubr (&Sfile_name_absolute_p);
6033 defsubr (&Sfile_exists_p);
6034 defsubr (&Sfile_executable_p);
6035 defsubr (&Sfile_readable_p);
6036 defsubr (&Sfile_writable_p);
6037 defsubr (&Saccess_file);
6038 defsubr (&Sfile_symlink_p);
6039 defsubr (&Sfile_directory_p);
6040 defsubr (&Sfile_accessible_directory_p);
6041 defsubr (&Sfile_regular_p);
6042 defsubr (&Sfile_modes);
6043 defsubr (&Sset_file_modes);
6044 defsubr (&Sset_file_times);
6045 defsubr (&Sfile_selinux_context);
6046 defsubr (&Sfile_acl);
6047 defsubr (&Sset_file_acl);
6048 defsubr (&Sset_file_selinux_context);
6049 defsubr (&Sset_default_file_modes);
6050 defsubr (&Sdefault_file_modes);
6051 defsubr (&Sfile_newer_than_file_p);
6052 defsubr (&Sinsert_file_contents);
6053 defsubr (&Swrite_region);
6054 defsubr (&Scar_less_than_car);
6055 defsubr (&Sverify_visited_file_modtime);
6056 defsubr (&Svisited_file_modtime);
6057 defsubr (&Sset_visited_file_modtime);
6058 defsubr (&Sdo_auto_save);
6059 defsubr (&Sset_buffer_auto_saved);
6060 defsubr (&Sclear_buffer_auto_save_failure);
6061 defsubr (&Srecent_auto_save_p);
6063 defsubr (&Snext_read_file_uses_dialog_p);
6065 defsubr (&Sset_binary_mode);
6067 #ifdef HAVE_SYNC
6068 defsubr (&Sunix_sync);
6069 #endif