Assume GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS
[emacs.git] / src / fileio.c
blobdebd1f30a4fe4d111356cc38ca741ce7238f27e6
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.
2660 The result might be a false positive on MS-Windows in some rare cases,
2661 i.e., this function could return t for a directory that is not
2662 accessible by the current user. */)
2663 (Lisp_Object filename)
2665 Lisp_Object absname;
2666 Lisp_Object handler;
2668 CHECK_STRING (filename);
2669 absname = Fexpand_file_name (filename, Qnil);
2671 /* If the file name has special constructs in it,
2672 call the corresponding file handler. */
2673 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2674 if (!NILP (handler))
2676 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2677 errno = 0;
2678 return r;
2681 absname = ENCODE_FILE (absname);
2682 return file_accessible_directory_p (absname) ? Qt : Qnil;
2685 /* If FILE is a searchable directory or a symlink to a
2686 searchable directory, return true. Otherwise return
2687 false and set errno to an error number. */
2688 bool
2689 file_accessible_directory_p (Lisp_Object file)
2691 #ifdef DOS_NT
2692 /* There's no need to test whether FILE is searchable, as the
2693 searchable/executable bit is invented on DOS_NT platforms. */
2694 return file_directory_p (SSDATA (file));
2695 #else
2696 /* On POSIXish platforms, use just one system call; this avoids a
2697 race and is typically faster. */
2698 const char *data = SSDATA (file);
2699 ptrdiff_t len = SBYTES (file);
2700 char const *dir;
2701 bool ok;
2702 int saved_errno;
2703 USE_SAFE_ALLOCA;
2705 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2706 There are three exceptions: "", "/", and "//". Leave "" alone,
2707 as it's invalid. Append only "." to the other two exceptions as
2708 "/" and "//" are distinct on some platforms, whereas "/", "///",
2709 "////", etc. are all equivalent. */
2710 if (! len)
2711 dir = data;
2712 else
2714 /* Just check for trailing '/' when deciding whether to append '/'.
2715 That's simpler than testing the two special cases "/" and "//",
2716 and it's a safe optimization here. */
2717 char *buf = SAFE_ALLOCA (len + 3);
2718 memcpy (buf, data, len);
2719 strcpy (buf + len, &"/."[data[len - 1] == '/']);
2720 dir = buf;
2723 ok = check_existing (dir);
2724 saved_errno = errno;
2725 SAFE_FREE ();
2726 errno = saved_errno;
2727 return ok;
2728 #endif
2731 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2732 doc: /* Return t if FILENAME names a regular file.
2733 This is the sort of file that holds an ordinary stream of data bytes.
2734 Symbolic links to regular files count as regular files.
2735 See `file-symlink-p' to distinguish symlinks. */)
2736 (Lisp_Object filename)
2738 register Lisp_Object absname;
2739 struct stat st;
2740 Lisp_Object handler;
2742 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2744 /* If the file name has special constructs in it,
2745 call the corresponding file handler. */
2746 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2747 if (!NILP (handler))
2748 return call2 (handler, Qfile_regular_p, absname);
2750 absname = ENCODE_FILE (absname);
2752 #ifdef WINDOWSNT
2754 int result;
2755 Lisp_Object tem = Vw32_get_true_file_attributes;
2757 /* Tell stat to use expensive method to get accurate info. */
2758 Vw32_get_true_file_attributes = Qt;
2759 result = stat (SDATA (absname), &st);
2760 Vw32_get_true_file_attributes = tem;
2762 if (result < 0)
2763 return Qnil;
2764 return S_ISREG (st.st_mode) ? Qt : Qnil;
2766 #else
2767 if (stat (SSDATA (absname), &st) < 0)
2768 return Qnil;
2769 return S_ISREG (st.st_mode) ? Qt : Qnil;
2770 #endif
2773 DEFUN ("file-selinux-context", Ffile_selinux_context,
2774 Sfile_selinux_context, 1, 1, 0,
2775 doc: /* Return SELinux context of file named FILENAME.
2776 The return value is a list (USER ROLE TYPE RANGE), where the list
2777 elements are strings naming the user, role, type, and range of the
2778 file's SELinux security context.
2780 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2781 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2782 (Lisp_Object filename)
2784 Lisp_Object absname;
2785 Lisp_Object user = Qnil, role = Qnil, type = Qnil, range = Qnil;
2787 Lisp_Object handler;
2788 #if HAVE_LIBSELINUX
2789 security_context_t con;
2790 int conlength;
2791 context_t context;
2792 #endif
2794 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2796 /* If the file name has special constructs in it,
2797 call the corresponding file handler. */
2798 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2799 if (!NILP (handler))
2800 return call2 (handler, Qfile_selinux_context, absname);
2802 absname = ENCODE_FILE (absname);
2804 #if HAVE_LIBSELINUX
2805 if (is_selinux_enabled ())
2807 conlength = lgetfilecon (SSDATA (absname), &con);
2808 if (conlength > 0)
2810 context = context_new (con);
2811 if (context_user_get (context))
2812 user = build_string (context_user_get (context));
2813 if (context_role_get (context))
2814 role = build_string (context_role_get (context));
2815 if (context_type_get (context))
2816 type = build_string (context_type_get (context));
2817 if (context_range_get (context))
2818 range = build_string (context_range_get (context));
2819 context_free (context);
2820 freecon (con);
2823 #endif
2825 return list4 (user, role, type, range);
2828 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2829 Sset_file_selinux_context, 2, 2, 0,
2830 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2831 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2832 elements are strings naming the components of a SELinux context.
2834 Value is t if setting of SELinux context was successful, nil otherwise.
2836 This function does nothing and returns nil if SELinux is disabled,
2837 or if Emacs was not compiled with SELinux support. */)
2838 (Lisp_Object filename, Lisp_Object context)
2840 Lisp_Object absname;
2841 Lisp_Object handler;
2842 #if HAVE_LIBSELINUX
2843 Lisp_Object encoded_absname;
2844 Lisp_Object user = CAR_SAFE (context);
2845 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2846 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2847 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2848 security_context_t con;
2849 bool fail;
2850 int conlength;
2851 context_t parsed_con;
2852 #endif
2854 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2856 /* If the file name has special constructs in it,
2857 call the corresponding file handler. */
2858 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2859 if (!NILP (handler))
2860 return call3 (handler, Qset_file_selinux_context, absname, context);
2862 #if HAVE_LIBSELINUX
2863 if (is_selinux_enabled ())
2865 /* Get current file context. */
2866 encoded_absname = ENCODE_FILE (absname);
2867 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2868 if (conlength > 0)
2870 parsed_con = context_new (con);
2871 /* Change the parts defined in the parameter.*/
2872 if (STRINGP (user))
2874 if (context_user_set (parsed_con, SSDATA (user)))
2875 error ("Doing context_user_set");
2877 if (STRINGP (role))
2879 if (context_role_set (parsed_con, SSDATA (role)))
2880 error ("Doing context_role_set");
2882 if (STRINGP (type))
2884 if (context_type_set (parsed_con, SSDATA (type)))
2885 error ("Doing context_type_set");
2887 if (STRINGP (range))
2889 if (context_range_set (parsed_con, SSDATA (range)))
2890 error ("Doing context_range_set");
2893 /* Set the modified context back to the file. */
2894 fail = (lsetfilecon (SSDATA (encoded_absname),
2895 context_str (parsed_con))
2896 != 0);
2897 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2898 if (fail && errno != ENOTSUP)
2899 report_file_error ("Doing lsetfilecon", absname);
2901 context_free (parsed_con);
2902 freecon (con);
2903 return fail ? Qnil : Qt;
2905 else
2906 report_file_error ("Doing lgetfilecon", absname);
2908 #endif
2910 return Qnil;
2913 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2914 doc: /* Return ACL entries of file named FILENAME.
2915 The entries are returned in a format suitable for use in `set-file-acl'
2916 but is otherwise undocumented and subject to change.
2917 Return nil if file does not exist or is not accessible, or if Emacs
2918 was unable to determine the ACL entries. */)
2919 (Lisp_Object filename)
2921 Lisp_Object absname;
2922 Lisp_Object handler;
2923 #ifdef HAVE_ACL_SET_FILE
2924 acl_t acl;
2925 Lisp_Object acl_string;
2926 char *str;
2927 # ifndef HAVE_ACL_TYPE_EXTENDED
2928 acl_type_t ACL_TYPE_EXTENDED = ACL_TYPE_ACCESS;
2929 # endif
2930 #endif
2932 absname = expand_and_dir_to_file (filename,
2933 BVAR (current_buffer, directory));
2935 /* If the file name has special constructs in it,
2936 call the corresponding file handler. */
2937 handler = Ffind_file_name_handler (absname, Qfile_acl);
2938 if (!NILP (handler))
2939 return call2 (handler, Qfile_acl, absname);
2941 #ifdef HAVE_ACL_SET_FILE
2942 absname = ENCODE_FILE (absname);
2944 acl = acl_get_file (SSDATA (absname), ACL_TYPE_EXTENDED);
2945 if (acl == NULL)
2946 return Qnil;
2948 str = acl_to_text (acl, NULL);
2949 if (str == NULL)
2951 acl_free (acl);
2952 return Qnil;
2955 acl_string = build_string (str);
2956 acl_free (str);
2957 acl_free (acl);
2959 return acl_string;
2960 #endif
2962 return Qnil;
2965 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
2966 2, 2, 0,
2967 doc: /* Set ACL of file named FILENAME to ACL-STRING.
2968 ACL-STRING should contain the textual representation of the ACL
2969 entries in a format suitable for the platform.
2971 Value is t if setting of ACL was successful, nil otherwise.
2973 Setting ACL for local files requires Emacs to be built with ACL
2974 support. */)
2975 (Lisp_Object filename, Lisp_Object acl_string)
2977 Lisp_Object absname;
2978 Lisp_Object handler;
2979 #ifdef HAVE_ACL_SET_FILE
2980 Lisp_Object encoded_absname;
2981 acl_t acl;
2982 bool fail;
2983 #endif
2985 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2987 /* If the file name has special constructs in it,
2988 call the corresponding file handler. */
2989 handler = Ffind_file_name_handler (absname, Qset_file_acl);
2990 if (!NILP (handler))
2991 return call3 (handler, Qset_file_acl, absname, acl_string);
2993 #ifdef HAVE_ACL_SET_FILE
2994 if (STRINGP (acl_string))
2996 acl = acl_from_text (SSDATA (acl_string));
2997 if (acl == NULL)
2999 report_file_error ("Converting ACL", absname);
3000 return Qnil;
3003 encoded_absname = ENCODE_FILE (absname);
3005 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3006 acl)
3007 != 0);
3008 if (fail && acl_errno_valid (errno))
3009 report_file_error ("Setting ACL", absname);
3011 acl_free (acl);
3012 return fail ? Qnil : Qt;
3014 #endif
3016 return Qnil;
3019 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3020 doc: /* Return mode bits of file named FILENAME, as an integer.
3021 Return nil, if file does not exist or is not accessible. */)
3022 (Lisp_Object filename)
3024 Lisp_Object absname;
3025 struct stat st;
3026 Lisp_Object handler;
3028 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3030 /* If the file name has special constructs in it,
3031 call the corresponding file handler. */
3032 handler = Ffind_file_name_handler (absname, Qfile_modes);
3033 if (!NILP (handler))
3034 return call2 (handler, Qfile_modes, absname);
3036 absname = ENCODE_FILE (absname);
3038 if (stat (SSDATA (absname), &st) < 0)
3039 return Qnil;
3041 return make_number (st.st_mode & 07777);
3044 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3045 "(let ((file (read-file-name \"File: \"))) \
3046 (list file (read-file-modes nil file)))",
3047 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3048 Only the 12 low bits of MODE are used.
3050 Interactively, mode bits are read by `read-file-modes', which accepts
3051 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3052 (Lisp_Object filename, Lisp_Object mode)
3054 Lisp_Object absname, encoded_absname;
3055 Lisp_Object handler;
3057 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3058 CHECK_NUMBER (mode);
3060 /* If the file name has special constructs in it,
3061 call the corresponding file handler. */
3062 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3063 if (!NILP (handler))
3064 return call3 (handler, Qset_file_modes, absname, mode);
3066 encoded_absname = ENCODE_FILE (absname);
3068 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3069 report_file_error ("Doing chmod", absname);
3071 return Qnil;
3074 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3075 doc: /* Set the file permission bits for newly created files.
3076 The argument MODE should be an integer; only the low 9 bits are used.
3077 This setting is inherited by subprocesses. */)
3078 (Lisp_Object mode)
3080 mode_t oldrealmask, oldumask, newumask;
3081 CHECK_NUMBER (mode);
3082 oldrealmask = realmask;
3083 newumask = ~ XINT (mode) & 0777;
3085 block_input ();
3086 realmask = newumask;
3087 oldumask = umask (newumask);
3088 unblock_input ();
3090 eassert (oldumask == oldrealmask);
3091 return Qnil;
3094 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3095 doc: /* Return the default file protection for created files.
3096 The value is an integer. */)
3097 (void)
3099 Lisp_Object value;
3100 XSETINT (value, (~ realmask) & 0777);
3101 return value;
3105 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3106 doc: /* Set times of file FILENAME to TIMESTAMP.
3107 Set both access and modification times.
3108 Return t on success, else nil.
3109 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3110 `current-time'. */)
3111 (Lisp_Object filename, Lisp_Object timestamp)
3113 Lisp_Object absname, encoded_absname;
3114 Lisp_Object handler;
3115 struct timespec t = lisp_time_argument (timestamp);
3117 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3119 /* If the file name has special constructs in it,
3120 call the corresponding file handler. */
3121 handler = Ffind_file_name_handler (absname, Qset_file_times);
3122 if (!NILP (handler))
3123 return call3 (handler, Qset_file_times, absname, timestamp);
3125 encoded_absname = ENCODE_FILE (absname);
3128 if (set_file_times (-1, SSDATA (encoded_absname), t, t) != 0)
3130 #ifdef MSDOS
3131 /* Setting times on a directory always fails. */
3132 if (file_directory_p (SSDATA (encoded_absname)))
3133 return Qnil;
3134 #endif
3135 report_file_error ("Setting file times", absname);
3139 return Qt;
3142 #ifdef HAVE_SYNC
3143 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3144 doc: /* Tell Unix to finish all pending disk updates. */)
3145 (void)
3147 sync ();
3148 return Qnil;
3151 #endif /* HAVE_SYNC */
3153 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3154 doc: /* Return t if file FILE1 is newer than file FILE2.
3155 If FILE1 does not exist, the answer is nil;
3156 otherwise, if FILE2 does not exist, the answer is t. */)
3157 (Lisp_Object file1, Lisp_Object file2)
3159 Lisp_Object absname1, absname2;
3160 struct stat st1, st2;
3161 Lisp_Object handler;
3163 CHECK_STRING (file1);
3164 CHECK_STRING (file2);
3166 absname1 = Qnil;
3167 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3168 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3170 /* If the file name has special constructs in it,
3171 call the corresponding file handler. */
3172 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3173 if (NILP (handler))
3174 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3175 if (!NILP (handler))
3176 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3178 absname1 = ENCODE_FILE (absname1);
3179 absname2 = ENCODE_FILE (absname2);
3181 if (stat (SSDATA (absname1), &st1) < 0)
3182 return Qnil;
3184 if (stat (SSDATA (absname2), &st2) < 0)
3185 return Qt;
3187 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3188 ? Qt : Qnil);
3191 #ifndef READ_BUF_SIZE
3192 #define READ_BUF_SIZE (64 << 10)
3193 #endif
3194 /* Some buffer offsets are stored in 'int' variables. */
3195 verify (READ_BUF_SIZE <= INT_MAX);
3197 /* This function is called after Lisp functions to decide a coding
3198 system are called, or when they cause an error. Before they are
3199 called, the current buffer is set unibyte and it contains only a
3200 newly inserted text (thus the buffer was empty before the
3201 insertion).
3203 The functions may set markers, overlays, text properties, or even
3204 alter the buffer contents, change the current buffer.
3206 Here, we reset all those changes by:
3207 o set back the current buffer.
3208 o move all markers and overlays to BEG.
3209 o remove all text properties.
3210 o set back the buffer multibyteness. */
3212 static void
3213 decide_coding_unwind (Lisp_Object unwind_data)
3215 Lisp_Object multibyte, undo_list, buffer;
3217 multibyte = XCAR (unwind_data);
3218 unwind_data = XCDR (unwind_data);
3219 undo_list = XCAR (unwind_data);
3220 buffer = XCDR (unwind_data);
3222 set_buffer_internal (XBUFFER (buffer));
3223 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3224 adjust_overlays_for_delete (BEG, Z - BEG);
3225 set_buffer_intervals (current_buffer, NULL);
3226 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3228 /* Now we are safe to change the buffer's multibyteness directly. */
3229 bset_enable_multibyte_characters (current_buffer, multibyte);
3230 bset_undo_list (current_buffer, undo_list);
3233 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3234 object where slot 0 is the file descriptor, slot 1 specifies
3235 an offset to put the read bytes, and slot 2 is the maximum
3236 amount of bytes to read. Value is the number of bytes read. */
3238 static Lisp_Object
3239 read_non_regular (Lisp_Object state)
3241 int nbytes;
3243 immediate_quit = 1;
3244 QUIT;
3245 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3246 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3247 + XSAVE_INTEGER (state, 1)),
3248 XSAVE_INTEGER (state, 2));
3249 immediate_quit = 0;
3250 /* Fast recycle this object for the likely next call. */
3251 free_misc (state);
3252 return make_number (nbytes);
3256 /* Condition-case handler used when reading from non-regular files
3257 in insert-file-contents. */
3259 static Lisp_Object
3260 read_non_regular_quit (Lisp_Object ignore)
3262 return Qnil;
3265 /* Return the file offset that VAL represents, checking for type
3266 errors and overflow. */
3267 static off_t
3268 file_offset (Lisp_Object val)
3270 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3271 return XINT (val);
3273 if (FLOATP (val))
3275 double v = XFLOAT_DATA (val);
3276 if (0 <= v
3277 && (sizeof (off_t) < sizeof v
3278 ? v <= TYPE_MAXIMUM (off_t)
3279 : v < TYPE_MAXIMUM (off_t)))
3280 return v;
3283 wrong_type_argument (intern ("file-offset"), val);
3286 /* Return a special time value indicating the error number ERRNUM. */
3287 static struct timespec
3288 time_error_value (int errnum)
3290 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3291 ? NONEXISTENT_MODTIME_NSECS
3292 : UNKNOWN_MODTIME_NSECS);
3293 return make_timespec (0, ns);
3296 static Lisp_Object
3297 get_window_points_and_markers (void)
3299 Lisp_Object pt_marker = Fpoint_marker ();
3300 Lisp_Object windows
3301 = call3 (Qget_buffer_window_list, Fcurrent_buffer (), Qnil, Qt);
3302 Lisp_Object window_markers = windows;
3303 /* Window markers (and point) are handled specially: rather than move to
3304 just before or just after the modified text, we try to keep the
3305 markers at the same distance (bug#19161).
3306 In general, this is wrong, but for window-markers, this should be harmless
3307 and is convenient for the end user when most of the file is unmodified,
3308 except for a few minor details near the beginning and near the end. */
3309 for (; CONSP (windows); windows = XCDR (windows))
3310 if (WINDOWP (XCAR (windows)))
3312 Lisp_Object window_marker = XWINDOW (XCAR (windows))->pointm;
3313 XSETCAR (windows,
3314 Fcons (window_marker, Fmarker_position (window_marker)));
3316 return Fcons (Fcons (pt_marker, Fpoint ()), window_markers);
3319 static void
3320 restore_window_points (Lisp_Object window_markers, ptrdiff_t inserted,
3321 ptrdiff_t same_at_start, ptrdiff_t same_at_end)
3323 for (; CONSP (window_markers); window_markers = XCDR (window_markers))
3324 if (CONSP (XCAR (window_markers)))
3326 Lisp_Object car = XCAR (window_markers);
3327 Lisp_Object marker = XCAR (car);
3328 Lisp_Object oldpos = XCDR (car);
3329 if (MARKERP (marker) && INTEGERP (oldpos)
3330 && XINT (oldpos) > same_at_start
3331 && XINT (oldpos) < same_at_end)
3333 ptrdiff_t oldsize = same_at_end - same_at_start;
3334 ptrdiff_t newsize = inserted;
3335 double growth = newsize / (double)oldsize;
3336 ptrdiff_t newpos
3337 = same_at_start + growth * (XINT (oldpos) - same_at_start);
3338 Fset_marker (marker, make_number (newpos), Qnil);
3343 /* FIXME: insert-file-contents should be split with the top-level moved to
3344 Elisp and only the core kept in C. */
3346 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3347 1, 5, 0,
3348 doc: /* Insert contents of file FILENAME after point.
3349 Returns list of absolute file name and number of characters inserted.
3350 If second argument VISIT is non-nil, the buffer's visited filename and
3351 last save file modtime are set, and it is marked unmodified. If
3352 visiting and the file does not exist, visiting is completed before the
3353 error is signaled.
3355 The optional third and fourth arguments BEG and END specify what portion
3356 of the file to insert. These arguments count bytes in the file, not
3357 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3359 If optional fifth argument REPLACE is non-nil, replace the current
3360 buffer contents (in the accessible portion) with the file contents.
3361 This is better than simply deleting and inserting the whole thing
3362 because (1) it preserves some marker positions and (2) it puts less data
3363 in the undo list. When REPLACE is non-nil, the second return value is
3364 the number of characters that replace previous buffer contents.
3366 This function does code conversion according to the value of
3367 `coding-system-for-read' or `file-coding-system-alist', and sets the
3368 variable `last-coding-system-used' to the coding system actually used.
3370 In addition, this function decodes the inserted text from known formats
3371 by calling `format-decode', which see. */)
3372 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3374 struct stat st;
3375 struct timespec mtime;
3376 int fd;
3377 ptrdiff_t inserted = 0;
3378 ptrdiff_t how_much;
3379 off_t beg_offset, end_offset;
3380 int unprocessed;
3381 ptrdiff_t count = SPECPDL_INDEX ();
3382 Lisp_Object handler, val, insval, orig_filename, old_undo;
3383 Lisp_Object p;
3384 ptrdiff_t total = 0;
3385 bool not_regular = 0;
3386 int save_errno = 0;
3387 char read_buf[READ_BUF_SIZE];
3388 struct coding_system coding;
3389 bool replace_handled = false;
3390 bool set_coding_system = false;
3391 Lisp_Object coding_system;
3392 bool read_quit = false;
3393 /* If the undo log only contains the insertion, there's no point
3394 keeping it. It's typically when we first fill a file-buffer. */
3395 bool empty_undo_list_p
3396 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3397 && BEG == Z);
3398 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3399 bool we_locked_file = false;
3400 ptrdiff_t fd_index;
3401 Lisp_Object window_markers = Qnil;
3402 /* same_at_start and same_at_end count bytes, because file access counts
3403 bytes and BEG and END count bytes. */
3404 ptrdiff_t same_at_start = BEGV_BYTE;
3405 ptrdiff_t same_at_end = ZV_BYTE;
3406 /* SAME_AT_END_CHARPOS counts characters, because
3407 restore_window_points needs the old character count. */
3408 ptrdiff_t same_at_end_charpos = ZV;
3410 if (current_buffer->base_buffer && ! NILP (visit))
3411 error ("Cannot do file visiting in an indirect buffer");
3413 if (!NILP (BVAR (current_buffer, read_only)))
3414 Fbarf_if_buffer_read_only (Qnil);
3416 val = Qnil;
3417 p = Qnil;
3418 orig_filename = Qnil;
3419 old_undo = Qnil;
3421 CHECK_STRING (filename);
3422 filename = Fexpand_file_name (filename, Qnil);
3424 /* The value Qnil means that the coding system is not yet
3425 decided. */
3426 coding_system = Qnil;
3428 /* If the file name has special constructs in it,
3429 call the corresponding file handler. */
3430 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3431 if (!NILP (handler))
3433 val = call6 (handler, Qinsert_file_contents, filename,
3434 visit, beg, end, replace);
3435 if (CONSP (val) && CONSP (XCDR (val))
3436 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3437 inserted = XINT (XCAR (XCDR (val)));
3438 goto handled;
3441 orig_filename = filename;
3442 filename = ENCODE_FILE (filename);
3444 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3445 if (fd < 0)
3447 save_errno = errno;
3448 if (NILP (visit))
3449 report_file_error ("Opening input file", orig_filename);
3450 mtime = time_error_value (save_errno);
3451 st.st_size = -1;
3452 if (!NILP (Vcoding_system_for_read))
3453 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3454 goto notfound;
3457 fd_index = SPECPDL_INDEX ();
3458 record_unwind_protect_int (close_file_unwind, fd);
3460 /* Replacement should preserve point as it preserves markers. */
3461 if (!NILP (replace))
3463 window_markers = get_window_points_and_markers ();
3464 record_unwind_protect (restore_point_unwind,
3465 XCAR (XCAR (window_markers)));
3468 if (fstat (fd, &st) != 0)
3469 report_file_error ("Input file status", orig_filename);
3470 mtime = get_stat_mtime (&st);
3472 /* This code will need to be changed in order to work on named
3473 pipes, and it's probably just not worth it. So we should at
3474 least signal an error. */
3475 if (!S_ISREG (st.st_mode))
3477 not_regular = 1;
3479 if (! NILP (visit))
3480 goto notfound;
3482 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3483 xsignal2 (Qfile_error,
3484 build_string ("not a regular file"), orig_filename);
3487 if (!NILP (visit))
3489 if (!NILP (beg) || !NILP (end))
3490 error ("Attempt to visit less than an entire file");
3491 if (BEG < Z && NILP (replace))
3492 error ("Cannot do file visiting in a non-empty buffer");
3495 if (!NILP (beg))
3496 beg_offset = file_offset (beg);
3497 else
3498 beg_offset = 0;
3500 if (!NILP (end))
3501 end_offset = file_offset (end);
3502 else
3504 if (not_regular)
3505 end_offset = TYPE_MAXIMUM (off_t);
3506 else
3508 end_offset = st.st_size;
3510 /* A negative size can happen on a platform that allows file
3511 sizes greater than the maximum off_t value. */
3512 if (end_offset < 0)
3513 buffer_overflow ();
3515 /* The file size returned from stat may be zero, but data
3516 may be readable nonetheless, for example when this is a
3517 file in the /proc filesystem. */
3518 if (end_offset == 0)
3519 end_offset = READ_BUF_SIZE;
3523 /* Check now whether the buffer will become too large,
3524 in the likely case where the file's length is not changing.
3525 This saves a lot of needless work before a buffer overflow. */
3526 if (! not_regular)
3528 /* The likely offset where we will stop reading. We could read
3529 more (or less), if the file grows (or shrinks) as we read it. */
3530 off_t likely_end = min (end_offset, st.st_size);
3532 if (beg_offset < likely_end)
3534 ptrdiff_t buf_bytes
3535 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3536 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3537 off_t likely_growth = likely_end - beg_offset;
3538 if (buf_growth_max < likely_growth)
3539 buffer_overflow ();
3543 /* Prevent redisplay optimizations. */
3544 current_buffer->clip_changed = true;
3546 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3548 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3549 setup_coding_system (coding_system, &coding);
3550 /* Ensure we set Vlast_coding_system_used. */
3551 set_coding_system = true;
3553 else if (BEG < Z)
3555 /* Decide the coding system to use for reading the file now
3556 because we can't use an optimized method for handling
3557 `coding:' tag if the current buffer is not empty. */
3558 if (!NILP (Vcoding_system_for_read))
3559 coding_system = Vcoding_system_for_read;
3560 else
3562 /* Don't try looking inside a file for a coding system
3563 specification if it is not seekable. */
3564 if (! not_regular && ! NILP (Vset_auto_coding_function))
3566 /* Find a coding system specified in the heading two
3567 lines or in the tailing several lines of the file.
3568 We assume that the 1K-byte and 3K-byte for heading
3569 and tailing respectively are sufficient for this
3570 purpose. */
3571 int nread;
3573 if (st.st_size <= (1024 * 4))
3574 nread = emacs_read (fd, read_buf, 1024 * 4);
3575 else
3577 nread = emacs_read (fd, read_buf, 1024);
3578 if (nread == 1024)
3580 int ntail;
3581 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3582 report_file_error ("Setting file position",
3583 orig_filename);
3584 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3585 nread = ntail < 0 ? ntail : nread + ntail;
3589 if (nread < 0)
3590 report_file_error ("Read error", orig_filename);
3591 else if (nread > 0)
3593 AUTO_STRING (name, " *code-converting-work*");
3594 struct buffer *prev = current_buffer;
3595 Lisp_Object workbuf;
3596 struct buffer *buf;
3598 record_unwind_current_buffer ();
3600 workbuf = Fget_buffer_create (name);
3601 buf = XBUFFER (workbuf);
3603 delete_all_overlays (buf);
3604 bset_directory (buf, BVAR (current_buffer, directory));
3605 bset_read_only (buf, Qnil);
3606 bset_filename (buf, Qnil);
3607 bset_undo_list (buf, Qt);
3608 eassert (buf->overlays_before == NULL);
3609 eassert (buf->overlays_after == NULL);
3611 set_buffer_internal (buf);
3612 Ferase_buffer ();
3613 bset_enable_multibyte_characters (buf, Qnil);
3615 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3616 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3617 coding_system = call2 (Vset_auto_coding_function,
3618 filename, make_number (nread));
3619 set_buffer_internal (prev);
3621 /* Discard the unwind protect for recovering the
3622 current buffer. */
3623 specpdl_ptr--;
3625 /* Rewind the file for the actual read done later. */
3626 if (lseek (fd, 0, SEEK_SET) < 0)
3627 report_file_error ("Setting file position", orig_filename);
3631 if (NILP (coding_system))
3633 /* If we have not yet decided a coding system, check
3634 file-coding-system-alist. */
3635 coding_system = CALLN (Ffind_operation_coding_system,
3636 Qinsert_file_contents, orig_filename,
3637 visit, beg, end, replace);
3638 if (CONSP (coding_system))
3639 coding_system = XCAR (coding_system);
3643 if (NILP (coding_system))
3644 coding_system = Qundecided;
3645 else
3646 CHECK_CODING_SYSTEM (coding_system);
3648 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3649 /* We must suppress all character code conversion except for
3650 end-of-line conversion. */
3651 coding_system = raw_text_coding_system (coding_system);
3653 setup_coding_system (coding_system, &coding);
3654 /* Ensure we set Vlast_coding_system_used. */
3655 set_coding_system = true;
3658 /* If requested, replace the accessible part of the buffer
3659 with the file contents. Avoid replacing text at the
3660 beginning or end of the buffer that matches the file contents;
3661 that preserves markers pointing to the unchanged parts.
3663 Here we implement this feature in an optimized way
3664 for the case where code conversion is NOT needed.
3665 The following if-statement handles the case of conversion
3666 in a less optimal way.
3668 If the code conversion is "automatic" then we try using this
3669 method and hope for the best.
3670 But if we discover the need for conversion, we give up on this method
3671 and let the following if-statement handle the replace job. */
3672 if (!NILP (replace)
3673 && BEGV < ZV
3674 && (NILP (coding_system)
3675 || ! CODING_REQUIRE_DECODING (&coding)))
3677 ptrdiff_t overlap;
3678 /* There is still a possibility we will find the need to do code
3679 conversion. If that happens, set this variable to
3680 give up on handling REPLACE in the optimized way. */
3681 bool giveup_match_end = false;
3683 if (beg_offset != 0)
3685 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3686 report_file_error ("Setting file position", orig_filename);
3689 immediate_quit = 1;
3690 QUIT;
3691 /* Count how many chars at the start of the file
3692 match the text at the beginning of the buffer. */
3693 while (1)
3695 int nread, bufpos;
3697 nread = emacs_read (fd, read_buf, sizeof read_buf);
3698 if (nread < 0)
3699 report_file_error ("Read error", orig_filename);
3700 else if (nread == 0)
3701 break;
3703 if (CODING_REQUIRE_DETECTION (&coding))
3705 coding_system = detect_coding_system ((unsigned char *) read_buf,
3706 nread, nread, 1, 0,
3707 coding_system);
3708 setup_coding_system (coding_system, &coding);
3711 if (CODING_REQUIRE_DECODING (&coding))
3712 /* We found that the file should be decoded somehow.
3713 Let's give up here. */
3715 giveup_match_end = true;
3716 break;
3719 bufpos = 0;
3720 while (bufpos < nread && same_at_start < ZV_BYTE
3721 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3722 same_at_start++, bufpos++;
3723 /* If we found a discrepancy, stop the scan.
3724 Otherwise loop around and scan the next bufferful. */
3725 if (bufpos != nread)
3726 break;
3728 immediate_quit = false;
3729 /* If the file matches the buffer completely,
3730 there's no need to replace anything. */
3731 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3733 emacs_close (fd);
3734 clear_unwind_protect (fd_index);
3736 /* Truncate the buffer to the size of the file. */
3737 del_range_1 (same_at_start, same_at_end, 0, 0);
3738 goto handled;
3740 immediate_quit = true;
3741 QUIT;
3742 /* Count how many chars at the end of the file
3743 match the text at the end of the buffer. But, if we have
3744 already found that decoding is necessary, don't waste time. */
3745 while (!giveup_match_end)
3747 int total_read, nread, bufpos, trial;
3748 off_t curpos;
3750 /* At what file position are we now scanning? */
3751 curpos = end_offset - (ZV_BYTE - same_at_end);
3752 /* If the entire file matches the buffer tail, stop the scan. */
3753 if (curpos == 0)
3754 break;
3755 /* How much can we scan in the next step? */
3756 trial = min (curpos, sizeof read_buf);
3757 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3758 report_file_error ("Setting file position", orig_filename);
3760 total_read = nread = 0;
3761 while (total_read < trial)
3763 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3764 if (nread < 0)
3765 report_file_error ("Read error", orig_filename);
3766 else if (nread == 0)
3767 break;
3768 total_read += nread;
3771 /* Scan this bufferful from the end, comparing with
3772 the Emacs buffer. */
3773 bufpos = total_read;
3775 /* Compare with same_at_start to avoid counting some buffer text
3776 as matching both at the file's beginning and at the end. */
3777 while (bufpos > 0 && same_at_end > same_at_start
3778 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3779 same_at_end--, bufpos--;
3781 /* If we found a discrepancy, stop the scan.
3782 Otherwise loop around and scan the preceding bufferful. */
3783 if (bufpos != 0)
3785 /* If this discrepancy is because of code conversion,
3786 we cannot use this method; giveup and try the other. */
3787 if (same_at_end > same_at_start
3788 && FETCH_BYTE (same_at_end - 1) >= 0200
3789 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3790 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3791 giveup_match_end = true;
3792 break;
3795 if (nread == 0)
3796 break;
3798 immediate_quit = 0;
3800 if (! giveup_match_end)
3802 ptrdiff_t temp;
3804 /* We win! We can handle REPLACE the optimized way. */
3806 /* Extend the start of non-matching text area to multibyte
3807 character boundary. */
3808 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3809 while (same_at_start > BEGV_BYTE
3810 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3811 same_at_start--;
3813 /* Extend the end of non-matching text area to multibyte
3814 character boundary. */
3815 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3816 while (same_at_end < ZV_BYTE
3817 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3818 same_at_end++;
3820 /* Don't try to reuse the same piece of text twice. */
3821 overlap = (same_at_start - BEGV_BYTE
3822 - (same_at_end
3823 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3824 if (overlap > 0)
3825 same_at_end += overlap;
3826 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3828 /* Arrange to read only the nonmatching middle part of the file. */
3829 beg_offset += same_at_start - BEGV_BYTE;
3830 end_offset -= ZV_BYTE - same_at_end;
3832 invalidate_buffer_caches (current_buffer,
3833 BYTE_TO_CHAR (same_at_start),
3834 same_at_end_charpos);
3835 del_range_byte (same_at_start, same_at_end, 0);
3836 /* Insert from the file at the proper position. */
3837 temp = BYTE_TO_CHAR (same_at_start);
3838 SET_PT_BOTH (temp, same_at_start);
3840 /* If display currently starts at beginning of line,
3841 keep it that way. */
3842 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3843 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3845 replace_handled = true;
3849 /* If requested, replace the accessible part of the buffer
3850 with the file contents. Avoid replacing text at the
3851 beginning or end of the buffer that matches the file contents;
3852 that preserves markers pointing to the unchanged parts.
3854 Here we implement this feature for the case where code conversion
3855 is needed, in a simple way that needs a lot of memory.
3856 The preceding if-statement handles the case of no conversion
3857 in a more optimized way. */
3858 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3860 ptrdiff_t same_at_start_charpos;
3861 ptrdiff_t inserted_chars;
3862 ptrdiff_t overlap;
3863 ptrdiff_t bufpos;
3864 unsigned char *decoded;
3865 ptrdiff_t temp;
3866 ptrdiff_t this = 0;
3867 ptrdiff_t this_count = SPECPDL_INDEX ();
3868 bool multibyte
3869 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3870 Lisp_Object conversion_buffer;
3872 conversion_buffer = code_conversion_save (1, multibyte);
3874 /* First read the whole file, performing code conversion into
3875 CONVERSION_BUFFER. */
3877 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3878 report_file_error ("Setting file position", orig_filename);
3880 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3881 unprocessed = 0; /* Bytes not processed in previous loop. */
3883 while (1)
3885 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3886 quitting while reading a huge file. */
3888 /* Allow quitting out of the actual I/O. */
3889 immediate_quit = 1;
3890 QUIT;
3891 this = emacs_read (fd, read_buf + unprocessed,
3892 READ_BUF_SIZE - unprocessed);
3893 immediate_quit = 0;
3895 if (this <= 0)
3896 break;
3898 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3899 BUF_Z (XBUFFER (conversion_buffer)));
3900 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3901 unprocessed + this, conversion_buffer);
3902 unprocessed = coding.carryover_bytes;
3903 if (coding.carryover_bytes > 0)
3904 memcpy (read_buf, coding.carryover, unprocessed);
3907 if (this < 0)
3908 report_file_error ("Read error", orig_filename);
3909 emacs_close (fd);
3910 clear_unwind_protect (fd_index);
3912 if (unprocessed > 0)
3914 coding.mode |= CODING_MODE_LAST_BLOCK;
3915 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3916 unprocessed, conversion_buffer);
3917 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3920 coding_system = CODING_ID_NAME (coding.id);
3921 set_coding_system = true;
3922 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3923 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3924 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3926 /* Compare the beginning of the converted string with the buffer
3927 text. */
3929 bufpos = 0;
3930 while (bufpos < inserted && same_at_start < same_at_end
3931 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3932 same_at_start++, bufpos++;
3934 /* If the file matches the head of buffer completely,
3935 there's no need to replace anything. */
3937 if (bufpos == inserted)
3939 /* Truncate the buffer to the size of the file. */
3940 if (same_at_start != same_at_end)
3942 invalidate_buffer_caches (current_buffer,
3943 BYTE_TO_CHAR (same_at_start),
3944 BYTE_TO_CHAR (same_at_end));
3945 del_range_byte (same_at_start, same_at_end, 0);
3947 inserted = 0;
3949 unbind_to (this_count, Qnil);
3950 goto handled;
3953 /* Extend the start of non-matching text area to the previous
3954 multibyte character boundary. */
3955 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3956 while (same_at_start > BEGV_BYTE
3957 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3958 same_at_start--;
3960 /* Scan this bufferful from the end, comparing with
3961 the Emacs buffer. */
3962 bufpos = inserted;
3964 /* Compare with same_at_start to avoid counting some buffer text
3965 as matching both at the file's beginning and at the end. */
3966 while (bufpos > 0 && same_at_end > same_at_start
3967 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3968 same_at_end--, bufpos--;
3970 /* Extend the end of non-matching text area to the next
3971 multibyte character boundary. */
3972 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3973 while (same_at_end < ZV_BYTE
3974 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3975 same_at_end++;
3977 /* Don't try to reuse the same piece of text twice. */
3978 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3979 if (overlap > 0)
3980 same_at_end += overlap;
3981 same_at_end_charpos = BYTE_TO_CHAR (same_at_end);
3983 /* If display currently starts at beginning of line,
3984 keep it that way. */
3985 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3986 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3988 /* Replace the chars that we need to replace,
3989 and update INSERTED to equal the number of bytes
3990 we are taking from the decoded string. */
3991 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
3993 if (same_at_end != same_at_start)
3995 invalidate_buffer_caches (current_buffer,
3996 BYTE_TO_CHAR (same_at_start),
3997 same_at_end_charpos);
3998 del_range_byte (same_at_start, same_at_end, 0);
3999 temp = GPT;
4000 eassert (same_at_start == GPT_BYTE);
4001 same_at_start = GPT_BYTE;
4003 else
4005 temp = same_at_end_charpos;
4007 /* Insert from the file at the proper position. */
4008 SET_PT_BOTH (temp, same_at_start);
4009 same_at_start_charpos
4010 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4011 same_at_start - BEGV_BYTE
4012 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4013 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4014 inserted_chars
4015 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4016 same_at_start + inserted - BEGV_BYTE
4017 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4018 - same_at_start_charpos);
4019 /* This binding is to avoid ask-user-about-supersession-threat
4020 being called in insert_from_buffer (via in
4021 prepare_to_modify_buffer). */
4022 specbind (intern ("buffer-file-name"), Qnil);
4023 insert_from_buffer (XBUFFER (conversion_buffer),
4024 same_at_start_charpos, inserted_chars, 0);
4025 /* Set `inserted' to the number of inserted characters. */
4026 inserted = PT - temp;
4027 /* Set point before the inserted characters. */
4028 SET_PT_BOTH (temp, same_at_start);
4030 unbind_to (this_count, Qnil);
4032 goto handled;
4035 if (! not_regular)
4036 total = end_offset - beg_offset;
4037 else
4038 /* For a special file, all we can do is guess. */
4039 total = READ_BUF_SIZE;
4041 if (NILP (visit) && total > 0)
4043 if (!NILP (BVAR (current_buffer, file_truename))
4044 /* Make binding buffer-file-name to nil effective. */
4045 && !NILP (BVAR (current_buffer, filename))
4046 && SAVE_MODIFF >= MODIFF)
4047 we_locked_file = true;
4048 prepare_to_modify_buffer (PT, PT, NULL);
4051 move_gap_both (PT, PT_BYTE);
4052 if (GAP_SIZE < total)
4053 make_gap (total - GAP_SIZE);
4055 if (beg_offset != 0 || !NILP (replace))
4057 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4058 report_file_error ("Setting file position", orig_filename);
4061 /* In the following loop, HOW_MUCH contains the total bytes read so
4062 far for a regular file, and not changed for a special file. But,
4063 before exiting the loop, it is set to a negative value if I/O
4064 error occurs. */
4065 how_much = 0;
4067 /* Total bytes inserted. */
4068 inserted = 0;
4070 /* Here, we don't do code conversion in the loop. It is done by
4071 decode_coding_gap after all data are read into the buffer. */
4073 ptrdiff_t gap_size = GAP_SIZE;
4075 while (how_much < total)
4077 /* `try' is reserved in some compilers (Microsoft C). */
4078 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4079 ptrdiff_t this;
4081 if (not_regular)
4083 Lisp_Object nbytes;
4085 /* Maybe make more room. */
4086 if (gap_size < trytry)
4088 make_gap (trytry - gap_size);
4089 gap_size = GAP_SIZE - inserted;
4092 /* Read from the file, capturing `quit'. When an
4093 error occurs, end the loop, and arrange for a quit
4094 to be signaled after decoding the text we read. */
4095 nbytes = internal_condition_case_1
4096 (read_non_regular,
4097 make_save_int_int_int (fd, inserted, trytry),
4098 Qerror, read_non_regular_quit);
4100 if (NILP (nbytes))
4102 read_quit = true;
4103 break;
4106 this = XINT (nbytes);
4108 else
4110 /* Allow quitting out of the actual I/O. We don't make text
4111 part of the buffer until all the reading is done, so a C-g
4112 here doesn't do any harm. */
4113 immediate_quit = 1;
4114 QUIT;
4115 this = emacs_read (fd,
4116 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4117 + inserted),
4118 trytry);
4119 immediate_quit = 0;
4122 if (this <= 0)
4124 how_much = this;
4125 break;
4128 gap_size -= this;
4130 /* For a regular file, where TOTAL is the real size,
4131 count HOW_MUCH to compare with it.
4132 For a special file, where TOTAL is just a buffer size,
4133 so don't bother counting in HOW_MUCH.
4134 (INSERTED is where we count the number of characters inserted.) */
4135 if (! not_regular)
4136 how_much += this;
4137 inserted += this;
4141 /* Now we have either read all the file data into the gap,
4142 or stop reading on I/O error or quit. If nothing was
4143 read, undo marking the buffer modified. */
4145 if (inserted == 0)
4147 if (we_locked_file)
4148 unlock_file (BVAR (current_buffer, file_truename));
4149 Vdeactivate_mark = old_Vdeactivate_mark;
4151 else
4152 Fset (Qdeactivate_mark, Qt);
4154 emacs_close (fd);
4155 clear_unwind_protect (fd_index);
4157 if (how_much < 0)
4158 report_file_error ("Read error", orig_filename);
4160 /* Make the text read part of the buffer. */
4161 GAP_SIZE -= inserted;
4162 GPT += inserted;
4163 GPT_BYTE += inserted;
4164 ZV += inserted;
4165 ZV_BYTE += inserted;
4166 Z += inserted;
4167 Z_BYTE += inserted;
4169 if (GAP_SIZE > 0)
4170 /* Put an anchor to ensure multi-byte form ends at gap. */
4171 *GPT_ADDR = 0;
4173 notfound:
4175 if (NILP (coding_system))
4177 /* The coding system is not yet decided. Decide it by an
4178 optimized method for handling `coding:' tag.
4180 Note that we can get here only if the buffer was empty
4181 before the insertion. */
4183 if (!NILP (Vcoding_system_for_read))
4184 coding_system = Vcoding_system_for_read;
4185 else
4187 /* Since we are sure that the current buffer was empty
4188 before the insertion, we can toggle
4189 enable-multibyte-characters directly here without taking
4190 care of marker adjustment. By this way, we can run Lisp
4191 program safely before decoding the inserted text. */
4192 Lisp_Object unwind_data;
4193 ptrdiff_t count1 = SPECPDL_INDEX ();
4195 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4196 Fcons (BVAR (current_buffer, undo_list),
4197 Fcurrent_buffer ()));
4198 bset_enable_multibyte_characters (current_buffer, Qnil);
4199 bset_undo_list (current_buffer, Qt);
4200 record_unwind_protect (decide_coding_unwind, unwind_data);
4202 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4204 coding_system = call2 (Vset_auto_coding_function,
4205 filename, make_number (inserted));
4208 if (NILP (coding_system))
4210 /* If the coding system is not yet decided, check
4211 file-coding-system-alist. */
4212 coding_system = CALLN (Ffind_operation_coding_system,
4213 Qinsert_file_contents, orig_filename,
4214 visit, beg, end, Qnil);
4215 if (CONSP (coding_system))
4216 coding_system = XCAR (coding_system);
4218 unbind_to (count1, Qnil);
4219 inserted = Z_BYTE - BEG_BYTE;
4222 if (NILP (coding_system))
4223 coding_system = Qundecided;
4224 else
4225 CHECK_CODING_SYSTEM (coding_system);
4227 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4228 /* We must suppress all character code conversion except for
4229 end-of-line conversion. */
4230 coding_system = raw_text_coding_system (coding_system);
4231 setup_coding_system (coding_system, &coding);
4232 /* Ensure we set Vlast_coding_system_used. */
4233 set_coding_system = true;
4236 if (!NILP (visit))
4238 /* When we visit a file by raw-text, we change the buffer to
4239 unibyte. */
4240 if (CODING_FOR_UNIBYTE (&coding)
4241 /* Can't do this if part of the buffer might be preserved. */
4242 && NILP (replace))
4243 /* Visiting a file with these coding system makes the buffer
4244 unibyte. */
4245 bset_enable_multibyte_characters (current_buffer, Qnil);
4248 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4249 if (CODING_MAY_REQUIRE_DECODING (&coding)
4250 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4252 move_gap_both (PT, PT_BYTE);
4253 GAP_SIZE += inserted;
4254 ZV_BYTE -= inserted;
4255 Z_BYTE -= inserted;
4256 ZV -= inserted;
4257 Z -= inserted;
4258 decode_coding_gap (&coding, inserted, inserted);
4259 inserted = coding.produced_char;
4260 coding_system = CODING_ID_NAME (coding.id);
4262 else if (inserted > 0)
4264 invalidate_buffer_caches (current_buffer, PT, PT + inserted);
4265 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4266 inserted);
4269 /* Call after-change hooks for the inserted text, aside from the case
4270 of normal visiting (not with REPLACE), which is done in a new buffer
4271 "before" the buffer is changed. */
4272 if (inserted > 0 && total > 0
4273 && (NILP (visit) || !NILP (replace)))
4275 signal_after_change (PT, 0, inserted);
4276 update_compositions (PT, PT, CHECK_BORDER);
4279 /* Now INSERTED is measured in characters. */
4281 handled:
4283 if (inserted > 0)
4284 restore_window_points (window_markers, inserted,
4285 BYTE_TO_CHAR (same_at_start),
4286 same_at_end_charpos);
4288 if (!NILP (visit))
4290 if (empty_undo_list_p)
4291 bset_undo_list (current_buffer, Qnil);
4293 if (NILP (handler))
4295 current_buffer->modtime = mtime;
4296 current_buffer->modtime_size = st.st_size;
4297 bset_filename (current_buffer, orig_filename);
4300 SAVE_MODIFF = MODIFF;
4301 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4302 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4303 if (NILP (handler))
4305 if (!NILP (BVAR (current_buffer, file_truename)))
4306 unlock_file (BVAR (current_buffer, file_truename));
4307 unlock_file (filename);
4309 if (not_regular)
4310 xsignal2 (Qfile_error,
4311 build_string ("not a regular file"), orig_filename);
4314 if (set_coding_system)
4315 Vlast_coding_system_used = coding_system;
4317 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4319 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4320 visit);
4321 if (! NILP (insval))
4323 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4324 wrong_type_argument (intern ("inserted-chars"), insval);
4325 inserted = XFASTINT (insval);
4329 /* Decode file format. */
4330 if (inserted > 0)
4332 /* Don't run point motion or modification hooks when decoding. */
4333 ptrdiff_t count1 = SPECPDL_INDEX ();
4334 ptrdiff_t old_inserted = inserted;
4335 specbind (Qinhibit_point_motion_hooks, Qt);
4336 specbind (Qinhibit_modification_hooks, Qt);
4338 /* Save old undo list and don't record undo for decoding. */
4339 old_undo = BVAR (current_buffer, undo_list);
4340 bset_undo_list (current_buffer, Qt);
4342 if (NILP (replace))
4344 insval = call3 (Qformat_decode,
4345 Qnil, make_number (inserted), visit);
4346 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4347 wrong_type_argument (intern ("inserted-chars"), insval);
4348 inserted = XFASTINT (insval);
4350 else
4352 /* If REPLACE is non-nil and we succeeded in not replacing the
4353 beginning or end of the buffer text with the file's contents,
4354 call format-decode with `point' positioned at the beginning
4355 of the buffer and `inserted' equaling the number of
4356 characters in the buffer. Otherwise, format-decode might
4357 fail to correctly analyze the beginning or end of the buffer.
4358 Hence we temporarily save `point' and `inserted' here and
4359 restore `point' iff format-decode did not insert or delete
4360 any text. Otherwise we leave `point' at point-min. */
4361 ptrdiff_t opoint = PT;
4362 ptrdiff_t opoint_byte = PT_BYTE;
4363 ptrdiff_t oinserted = ZV - BEGV;
4364 EMACS_INT ochars_modiff = CHARS_MODIFF;
4366 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4367 insval = call3 (Qformat_decode,
4368 Qnil, make_number (oinserted), visit);
4369 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4370 wrong_type_argument (intern ("inserted-chars"), insval);
4371 if (ochars_modiff == CHARS_MODIFF)
4372 /* format_decode didn't modify buffer's characters => move
4373 point back to position before inserted text and leave
4374 value of inserted alone. */
4375 SET_PT_BOTH (opoint, opoint_byte);
4376 else
4377 /* format_decode modified buffer's characters => consider
4378 entire buffer changed and leave point at point-min. */
4379 inserted = XFASTINT (insval);
4382 /* For consistency with format-decode call these now iff inserted > 0
4383 (martin 2007-06-28). */
4384 p = Vafter_insert_file_functions;
4385 while (CONSP (p))
4387 if (NILP (replace))
4389 insval = call1 (XCAR (p), make_number (inserted));
4390 if (!NILP (insval))
4392 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4393 wrong_type_argument (intern ("inserted-chars"), insval);
4394 inserted = XFASTINT (insval);
4397 else
4399 /* For the rationale of this see the comment on
4400 format-decode above. */
4401 ptrdiff_t opoint = PT;
4402 ptrdiff_t opoint_byte = PT_BYTE;
4403 ptrdiff_t oinserted = ZV - BEGV;
4404 EMACS_INT ochars_modiff = CHARS_MODIFF;
4406 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4407 insval = call1 (XCAR (p), make_number (oinserted));
4408 if (!NILP (insval))
4410 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4411 wrong_type_argument (intern ("inserted-chars"), insval);
4412 if (ochars_modiff == CHARS_MODIFF)
4413 /* after_insert_file_functions didn't modify
4414 buffer's characters => move point back to
4415 position before inserted text and leave value of
4416 inserted alone. */
4417 SET_PT_BOTH (opoint, opoint_byte);
4418 else
4419 /* after_insert_file_functions did modify buffer's
4420 characters => consider entire buffer changed and
4421 leave point at point-min. */
4422 inserted = XFASTINT (insval);
4426 QUIT;
4427 p = XCDR (p);
4430 if (!empty_undo_list_p)
4432 bset_undo_list (current_buffer, old_undo);
4433 if (CONSP (old_undo) && inserted != old_inserted)
4435 /* Adjust the last undo record for the size change during
4436 the format conversion. */
4437 Lisp_Object tem = XCAR (old_undo);
4438 if (CONSP (tem) && INTEGERP (XCAR (tem))
4439 && INTEGERP (XCDR (tem))
4440 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4441 XSETCDR (tem, make_number (PT + inserted));
4444 else
4445 /* If undo_list was Qt before, keep it that way.
4446 Otherwise start with an empty undo_list. */
4447 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4449 unbind_to (count1, Qnil);
4452 if (!NILP (visit)
4453 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4455 /* If visiting nonexistent file, return nil. */
4456 report_file_errno ("Opening input file", orig_filename, save_errno);
4459 /* We made a lot of deletions and insertions above, so invalidate
4460 the newline cache for the entire region of the inserted
4461 characters. */
4462 if (current_buffer->base_buffer && current_buffer->base_buffer->newline_cache)
4463 invalidate_region_cache (current_buffer->base_buffer,
4464 current_buffer->base_buffer->newline_cache,
4465 PT - BEG, Z - PT - inserted);
4466 else if (current_buffer->newline_cache)
4467 invalidate_region_cache (current_buffer,
4468 current_buffer->newline_cache,
4469 PT - BEG, Z - PT - inserted);
4471 if (read_quit)
4472 Fsignal (Qquit, Qnil);
4474 /* Retval needs to be dealt with in all cases consistently. */
4475 if (NILP (val))
4476 val = list2 (orig_filename, make_number (inserted));
4478 return unbind_to (count, val);
4481 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4483 static void
4484 build_annotations_unwind (Lisp_Object arg)
4486 Vwrite_region_annotation_buffers = arg;
4489 /* Decide the coding-system to encode the data with. */
4491 static Lisp_Object
4492 choose_write_coding_system (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4493 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4494 struct coding_system *coding)
4496 Lisp_Object val;
4497 Lisp_Object eol_parent = Qnil;
4499 if (auto_saving
4500 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4501 BVAR (current_buffer, auto_save_file_name))))
4503 val = Qutf_8_emacs;
4504 eol_parent = Qunix;
4506 else if (!NILP (Vcoding_system_for_write))
4508 val = Vcoding_system_for_write;
4509 if (coding_system_require_warning
4510 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4511 /* Confirm that VAL can surely encode the current region. */
4512 val = call5 (Vselect_safe_coding_system_function,
4513 start, end, list2 (Qt, val),
4514 Qnil, filename);
4516 else
4518 /* If the variable `buffer-file-coding-system' is set locally,
4519 it means that the file was read with some kind of code
4520 conversion or the variable is explicitly set by users. We
4521 had better write it out with the same coding system even if
4522 `enable-multibyte-characters' is nil.
4524 If it is not set locally, we anyway have to convert EOL
4525 format if the default value of `buffer-file-coding-system'
4526 tells that it is not Unix-like (LF only) format. */
4527 bool using_default_coding = 0;
4528 bool force_raw_text = 0;
4530 val = BVAR (current_buffer, buffer_file_coding_system);
4531 if (NILP (val)
4532 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4534 val = Qnil;
4535 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4536 force_raw_text = 1;
4539 if (NILP (val))
4541 /* Check file-coding-system-alist. */
4542 Lisp_Object coding_systems
4543 = CALLN (Ffind_operation_coding_system, Qwrite_region, start, end,
4544 filename, append, visit, lockname);
4545 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4546 val = XCDR (coding_systems);
4549 if (NILP (val))
4551 /* If we still have not decided a coding system, use the
4552 default value of buffer-file-coding-system. */
4553 val = BVAR (current_buffer, buffer_file_coding_system);
4554 using_default_coding = 1;
4557 if (! NILP (val) && ! force_raw_text)
4559 Lisp_Object spec, attrs;
4561 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4562 attrs = AREF (spec, 0);
4563 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4564 force_raw_text = 1;
4567 if (!force_raw_text
4568 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4569 /* Confirm that VAL can surely encode the current region. */
4570 val = call5 (Vselect_safe_coding_system_function,
4571 start, end, val, Qnil, filename);
4573 /* If the decided coding-system doesn't specify end-of-line
4574 format, we use that of
4575 `default-buffer-file-coding-system'. */
4576 if (! using_default_coding
4577 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4578 val = (coding_inherit_eol_type
4579 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4581 /* If we decide not to encode text, use `raw-text' or one of its
4582 subsidiaries. */
4583 if (force_raw_text)
4584 val = raw_text_coding_system (val);
4587 val = coding_inherit_eol_type (val, eol_parent);
4588 setup_coding_system (val, coding);
4590 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4591 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4592 return val;
4595 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4596 "r\nFWrite region to file: \ni\ni\ni\np",
4597 doc: /* Write current region into specified file.
4598 When called from a program, requires three arguments:
4599 START, END and FILENAME. START and END are normally buffer positions
4600 specifying the part of the buffer to write.
4601 If START is nil, that means to use the entire buffer contents.
4602 If START is a string, then output that string to the file
4603 instead of any buffer contents; END is ignored.
4605 Optional fourth argument APPEND if non-nil means
4606 append to existing file contents (if any). If it is a number,
4607 seek to that offset in the file before writing.
4608 Optional fifth argument VISIT, if t or a string, means
4609 set the last-save-file-modtime of buffer to this file's modtime
4610 and mark buffer not modified.
4611 If VISIT is a string, it is a second file name;
4612 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4613 VISIT is also the file name to lock and unlock for clash detection.
4614 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4615 do not display the \"Wrote file\" message.
4616 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4617 use for locking and unlocking, overriding FILENAME and VISIT.
4618 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4619 for an existing file with the same name. If MUSTBENEW is `excl',
4620 that means to get an error if the file already exists; never overwrite.
4621 If MUSTBENEW is neither nil nor `excl', that means ask for
4622 confirmation before overwriting, but do go ahead and overwrite the file
4623 if the user confirms.
4625 This does code conversion according to the value of
4626 `coding-system-for-write', `buffer-file-coding-system', or
4627 `file-coding-system-alist', and sets the variable
4628 `last-coding-system-used' to the coding system actually used.
4630 This calls `write-region-annotate-functions' at the start, and
4631 `write-region-post-annotation-function' at the end. */)
4632 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4633 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4635 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4636 -1);
4639 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4640 descriptor for FILENAME, so do not open or close FILENAME. */
4642 Lisp_Object
4643 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4644 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4645 Lisp_Object mustbenew, int desc)
4647 int open_flags;
4648 int mode;
4649 off_t offset IF_LINT (= 0);
4650 bool open_and_close_file = desc < 0;
4651 bool ok;
4652 int save_errno = 0;
4653 const char *fn;
4654 struct stat st;
4655 struct timespec modtime;
4656 ptrdiff_t count = SPECPDL_INDEX ();
4657 ptrdiff_t count1 IF_LINT (= 0);
4658 Lisp_Object handler;
4659 Lisp_Object visit_file;
4660 Lisp_Object annotations;
4661 Lisp_Object encoded_filename;
4662 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4663 bool quietly = !NILP (visit);
4664 bool file_locked = 0;
4665 struct buffer *given_buffer;
4666 struct coding_system coding;
4668 if (current_buffer->base_buffer && visiting)
4669 error ("Cannot do file visiting in an indirect buffer");
4671 if (!NILP (start) && !STRINGP (start))
4672 validate_region (&start, &end);
4674 visit_file = Qnil;
4676 filename = Fexpand_file_name (filename, Qnil);
4678 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4679 barf_or_query_if_file_exists (filename, false, "overwrite", true, true);
4681 if (STRINGP (visit))
4682 visit_file = Fexpand_file_name (visit, Qnil);
4683 else
4684 visit_file = filename;
4686 if (NILP (lockname))
4687 lockname = visit_file;
4689 annotations = Qnil;
4691 /* If the file name has special constructs in it,
4692 call the corresponding file handler. */
4693 handler = Ffind_file_name_handler (filename, Qwrite_region);
4694 /* If FILENAME has no handler, see if VISIT has one. */
4695 if (NILP (handler) && STRINGP (visit))
4696 handler = Ffind_file_name_handler (visit, Qwrite_region);
4698 if (!NILP (handler))
4700 Lisp_Object val;
4701 val = call6 (handler, Qwrite_region, start, end,
4702 filename, append, visit);
4704 if (visiting)
4706 SAVE_MODIFF = MODIFF;
4707 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4708 bset_filename (current_buffer, visit_file);
4711 return val;
4714 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4716 /* Special kludge to simplify auto-saving. */
4717 if (NILP (start))
4719 /* Do it later, so write-region-annotate-function can work differently
4720 if we save "the buffer" vs "a region".
4721 This is useful in tar-mode. --Stef
4722 XSETFASTINT (start, BEG);
4723 XSETFASTINT (end, Z); */
4724 Fwiden ();
4727 record_unwind_protect (build_annotations_unwind,
4728 Vwrite_region_annotation_buffers);
4729 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4731 given_buffer = current_buffer;
4733 if (!STRINGP (start))
4735 annotations = build_annotations (start, end);
4737 if (current_buffer != given_buffer)
4739 XSETFASTINT (start, BEGV);
4740 XSETFASTINT (end, ZV);
4744 if (NILP (start))
4746 XSETFASTINT (start, BEGV);
4747 XSETFASTINT (end, ZV);
4750 /* Decide the coding-system to encode the data with.
4751 We used to make this choice before calling build_annotations, but that
4752 leads to problems when a write-annotate-function takes care of
4753 unsavable chars (as was the case with X-Symbol). */
4754 Vlast_coding_system_used
4755 = choose_write_coding_system (start, end, filename,
4756 append, visit, lockname, &coding);
4758 if (open_and_close_file && !auto_saving)
4760 lock_file (lockname);
4761 file_locked = 1;
4764 encoded_filename = ENCODE_FILE (filename);
4765 fn = SSDATA (encoded_filename);
4766 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4767 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4768 if (NUMBERP (append))
4769 offset = file_offset (append);
4770 else if (!NILP (append))
4771 open_flags |= O_APPEND;
4772 #ifdef DOS_NT
4773 mode = S_IREAD | S_IWRITE;
4774 #else
4775 mode = auto_saving ? auto_save_mode_bits : 0666;
4776 #endif
4778 if (open_and_close_file)
4780 desc = emacs_open (fn, open_flags, mode);
4781 if (desc < 0)
4783 int open_errno = errno;
4784 if (file_locked)
4785 unlock_file (lockname);
4786 report_file_errno ("Opening output file", filename, open_errno);
4789 count1 = SPECPDL_INDEX ();
4790 record_unwind_protect_int (close_file_unwind, desc);
4793 if (NUMBERP (append))
4795 off_t ret = lseek (desc, offset, SEEK_SET);
4796 if (ret < 0)
4798 int lseek_errno = errno;
4799 if (file_locked)
4800 unlock_file (lockname);
4801 report_file_errno ("Lseek error", filename, lseek_errno);
4805 immediate_quit = 1;
4807 if (STRINGP (start))
4808 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4809 else if (XINT (start) != XINT (end))
4810 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4811 &annotations, &coding);
4812 else
4814 /* If file was empty, still need to write the annotations. */
4815 coding.mode |= CODING_MODE_LAST_BLOCK;
4816 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4818 save_errno = errno;
4820 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4821 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4823 /* We have to flush out a data. */
4824 coding.mode |= CODING_MODE_LAST_BLOCK;
4825 ok = e_write (desc, Qnil, 1, 1, &coding);
4826 save_errno = errno;
4829 immediate_quit = 0;
4831 /* fsync is not crucial for temporary files. Nor for auto-save
4832 files, since they might lose some work anyway. */
4833 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4835 /* Transfer data and metadata to disk, retrying if interrupted.
4836 fsync can report a write failure here, e.g., due to disk full
4837 under NFS. But ignore EINVAL, which means fsync is not
4838 supported on this file. */
4839 while (fsync (desc) != 0)
4840 if (errno != EINTR)
4842 if (errno != EINVAL)
4843 ok = 0, save_errno = errno;
4844 break;
4848 modtime = invalid_timespec ();
4849 if (visiting)
4851 if (fstat (desc, &st) == 0)
4852 modtime = get_stat_mtime (&st);
4853 else
4854 ok = 0, save_errno = errno;
4857 if (open_and_close_file)
4859 /* NFS can report a write failure now. */
4860 if (emacs_close (desc) < 0)
4861 ok = 0, save_errno = errno;
4863 /* Discard the unwind protect for close_file_unwind. */
4864 specpdl_ptr = specpdl + count1;
4867 /* Some file systems have a bug where st_mtime is not updated
4868 properly after a write. For example, CIFS might not see the
4869 st_mtime change until after the file is opened again.
4871 Attempt to detect this file system bug, and update MODTIME to the
4872 newer st_mtime if the bug appears to be present. This introduces
4873 a race condition, so to avoid most instances of the race condition
4874 on non-buggy file systems, skip this check if the most recently
4875 encountered non-buggy file system was the current file system.
4877 A race condition can occur if some other process modifies the
4878 file between the fstat above and the fstat below, but the race is
4879 unlikely and a similar race between the last write and the fstat
4880 above cannot possibly be closed anyway. */
4882 if (timespec_valid_p (modtime)
4883 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4885 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4886 if (desc1 >= 0)
4888 struct stat st1;
4889 if (fstat (desc1, &st1) == 0
4890 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4892 /* Use the heuristic if it appears to be valid. With neither
4893 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4894 file, the time stamp won't change. Also, some non-POSIX
4895 systems don't update an empty file's time stamp when
4896 truncating it. Finally, file systems with 100 ns or worse
4897 resolution sometimes seem to have bugs: on a system with ns
4898 resolution, checking ns % 100 incorrectly avoids the heuristic
4899 1% of the time, but the problem should be temporary as we will
4900 try again on the next time stamp. */
4901 bool use_heuristic
4902 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4903 && st.st_size != 0
4904 && modtime.tv_nsec % 100 != 0);
4906 struct timespec modtime1 = get_stat_mtime (&st1);
4907 if (use_heuristic
4908 && timespec_cmp (modtime, modtime1) == 0
4909 && st.st_size == st1.st_size)
4911 timestamp_file_system = st.st_dev;
4912 valid_timestamp_file_system = 1;
4914 else
4916 st.st_size = st1.st_size;
4917 modtime = modtime1;
4920 emacs_close (desc1);
4924 /* Call write-region-post-annotation-function. */
4925 while (CONSP (Vwrite_region_annotation_buffers))
4927 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4928 if (!NILP (Fbuffer_live_p (buf)))
4930 Fset_buffer (buf);
4931 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4932 call0 (Vwrite_region_post_annotation_function);
4934 Vwrite_region_annotation_buffers
4935 = XCDR (Vwrite_region_annotation_buffers);
4938 unbind_to (count, Qnil);
4940 if (file_locked)
4941 unlock_file (lockname);
4943 /* Do this before reporting IO error
4944 to avoid a "file has changed on disk" warning on
4945 next attempt to save. */
4946 if (timespec_valid_p (modtime))
4948 current_buffer->modtime = modtime;
4949 current_buffer->modtime_size = st.st_size;
4952 if (! ok)
4953 report_file_errno ("Write error", filename, save_errno);
4955 if (visiting)
4957 SAVE_MODIFF = MODIFF;
4958 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4959 bset_filename (current_buffer, visit_file);
4960 update_mode_lines = 14;
4962 else if (quietly)
4964 if (auto_saving
4965 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
4966 BVAR (current_buffer, auto_save_file_name))))
4967 SAVE_MODIFF = MODIFF;
4969 return Qnil;
4972 if (!auto_saving && !noninteractive)
4973 message_with_string ((NUMBERP (append)
4974 ? "Updated %s"
4975 : ! NILP (append)
4976 ? "Added to %s"
4977 : "Wrote %s"),
4978 visit_file, 1);
4980 return Qnil;
4983 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4984 doc: /* Return t if (car A) is numerically less than (car B). */)
4985 (Lisp_Object a, Lisp_Object b)
4987 return CALLN (Flss, Fcar (a), Fcar (b));
4990 /* Build the complete list of annotations appropriate for writing out
4991 the text between START and END, by calling all the functions in
4992 write-region-annotate-functions and merging the lists they return.
4993 If one of these functions switches to a different buffer, we assume
4994 that buffer contains altered text. Therefore, the caller must
4995 make sure to restore the current buffer in all cases,
4996 as save-excursion would do. */
4998 static Lisp_Object
4999 build_annotations (Lisp_Object start, Lisp_Object end)
5001 Lisp_Object annotations;
5002 Lisp_Object p, res;
5003 Lisp_Object original_buffer;
5004 int i;
5005 bool used_global = false;
5007 XSETBUFFER (original_buffer, current_buffer);
5009 annotations = Qnil;
5010 p = Vwrite_region_annotate_functions;
5011 while (CONSP (p))
5013 struct buffer *given_buffer = current_buffer;
5014 if (EQ (Qt, XCAR (p)) && !used_global)
5015 { /* Use the global value of the hook. */
5016 used_global = true;
5017 p = CALLN (Fappend,
5018 Fdefault_value (Qwrite_region_annotate_functions),
5019 XCDR (p));
5020 continue;
5022 Vwrite_region_annotations_so_far = annotations;
5023 res = call2 (XCAR (p), start, end);
5024 /* If the function makes a different buffer current,
5025 assume that means this buffer contains altered text to be output.
5026 Reset START and END from the buffer bounds
5027 and discard all previous annotations because they should have
5028 been dealt with by this function. */
5029 if (current_buffer != given_buffer)
5031 Vwrite_region_annotation_buffers
5032 = Fcons (Fcurrent_buffer (),
5033 Vwrite_region_annotation_buffers);
5034 XSETFASTINT (start, BEGV);
5035 XSETFASTINT (end, ZV);
5036 annotations = Qnil;
5038 Flength (res); /* Check basic validity of return value */
5039 annotations = merge (annotations, res, Qcar_less_than_car);
5040 p = XCDR (p);
5043 /* Now do the same for annotation functions implied by the file-format */
5044 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5045 p = BVAR (current_buffer, auto_save_file_format);
5046 else
5047 p = BVAR (current_buffer, file_format);
5048 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5050 struct buffer *given_buffer = current_buffer;
5052 Vwrite_region_annotations_so_far = annotations;
5054 /* Value is either a list of annotations or nil if the function
5055 has written annotations to a temporary buffer, which is now
5056 current. */
5057 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5058 original_buffer, make_number (i));
5059 if (current_buffer != given_buffer)
5061 XSETFASTINT (start, BEGV);
5062 XSETFASTINT (end, ZV);
5063 annotations = Qnil;
5066 if (CONSP (res))
5067 annotations = merge (annotations, res, Qcar_less_than_car);
5070 return annotations;
5074 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5075 If STRING is nil, POS is the character position in the current buffer.
5076 Intersperse with them the annotations from *ANNOT
5077 which fall within the range of POS to POS + NCHARS,
5078 each at its appropriate position.
5080 We modify *ANNOT by discarding elements as we use them up.
5082 Return true if successful. */
5084 static bool
5085 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5086 ptrdiff_t nchars, Lisp_Object *annot,
5087 struct coding_system *coding)
5089 Lisp_Object tem;
5090 ptrdiff_t nextpos;
5091 ptrdiff_t lastpos = pos + nchars;
5093 while (NILP (*annot) || CONSP (*annot))
5095 tem = Fcar_safe (Fcar (*annot));
5096 nextpos = pos - 1;
5097 if (INTEGERP (tem))
5098 nextpos = XFASTINT (tem);
5100 /* If there are no more annotations in this range,
5101 output the rest of the range all at once. */
5102 if (! (nextpos >= pos && nextpos <= lastpos))
5103 return e_write (desc, string, pos, lastpos, coding);
5105 /* Output buffer text up to the next annotation's position. */
5106 if (nextpos > pos)
5108 if (!e_write (desc, string, pos, nextpos, coding))
5109 return 0;
5110 pos = nextpos;
5112 /* Output the annotation. */
5113 tem = Fcdr (Fcar (*annot));
5114 if (STRINGP (tem))
5116 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5117 return 0;
5119 *annot = Fcdr (*annot);
5121 return 1;
5124 /* Maximum number of characters that the next
5125 function encodes per one loop iteration. */
5127 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5129 /* Write text in the range START and END into descriptor DESC,
5130 encoding them with coding system CODING. If STRING is nil, START
5131 and END are character positions of the current buffer, else they
5132 are indexes to the string STRING. Return true if successful. */
5134 static bool
5135 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5136 struct coding_system *coding)
5138 if (STRINGP (string))
5140 start = 0;
5141 end = SCHARS (string);
5144 /* We used to have a code for handling selective display here. But,
5145 now it is handled within encode_coding. */
5147 while (start < end)
5149 if (STRINGP (string))
5151 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5152 if (CODING_REQUIRE_ENCODING (coding))
5154 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5156 /* Avoid creating huge Lisp string in encode_coding_object. */
5157 if (nchars == E_WRITE_MAX)
5158 coding->raw_destination = 1;
5160 encode_coding_object
5161 (coding, string, start, string_char_to_byte (string, start),
5162 start + nchars, string_char_to_byte (string, start + nchars),
5163 Qt);
5165 else
5167 coding->dst_object = string;
5168 coding->consumed_char = SCHARS (string);
5169 coding->produced = SBYTES (string);
5172 else
5174 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5175 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5177 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5178 if (CODING_REQUIRE_ENCODING (coding))
5180 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5182 /* Likewise. */
5183 if (nchars == E_WRITE_MAX)
5184 coding->raw_destination = 1;
5186 encode_coding_object
5187 (coding, Fcurrent_buffer (), start, start_byte,
5188 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5190 else
5192 coding->dst_object = Qnil;
5193 coding->dst_pos_byte = start_byte;
5194 if (start >= GPT || end <= GPT)
5196 coding->consumed_char = end - start;
5197 coding->produced = end_byte - start_byte;
5199 else
5201 coding->consumed_char = GPT - start;
5202 coding->produced = GPT_BYTE - start_byte;
5207 if (coding->produced > 0)
5209 char *buf = (coding->raw_destination ? (char *) coding->destination
5210 : (STRINGP (coding->dst_object)
5211 ? SSDATA (coding->dst_object)
5212 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5213 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5215 if (coding->raw_destination)
5217 /* We're responsible for freeing this, see
5218 encode_coding_object to check why. */
5219 xfree (coding->destination);
5220 coding->raw_destination = 0;
5222 if (coding->produced)
5223 return 0;
5225 start += coding->consumed_char;
5228 return 1;
5231 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5232 Sverify_visited_file_modtime, 0, 1, 0,
5233 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5234 This means that the file has not been changed since it was visited or saved.
5235 If BUF is omitted or nil, it defaults to the current buffer.
5236 See Info node `(elisp)Modification Time' for more details. */)
5237 (Lisp_Object buf)
5239 struct buffer *b = decode_buffer (buf);
5240 struct stat st;
5241 Lisp_Object handler;
5242 Lisp_Object filename;
5243 struct timespec mtime;
5245 if (!STRINGP (BVAR (b, filename))) return Qt;
5246 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5248 /* If the file name has special constructs in it,
5249 call the corresponding file handler. */
5250 handler = Ffind_file_name_handler (BVAR (b, filename),
5251 Qverify_visited_file_modtime);
5252 if (!NILP (handler))
5253 return call2 (handler, Qverify_visited_file_modtime, buf);
5255 filename = ENCODE_FILE (BVAR (b, filename));
5257 mtime = (stat (SSDATA (filename), &st) == 0
5258 ? get_stat_mtime (&st)
5259 : time_error_value (errno));
5260 if (timespec_cmp (mtime, b->modtime) == 0
5261 && (b->modtime_size < 0
5262 || st.st_size == b->modtime_size))
5263 return Qt;
5264 return Qnil;
5267 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5268 Svisited_file_modtime, 0, 0, 0,
5269 doc: /* Return the current buffer's recorded visited file modification time.
5270 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5271 `file-attributes' returns. If the current buffer has no recorded file
5272 modification time, this function returns 0. If the visited file
5273 doesn't exist, return -1.
5274 See Info node `(elisp)Modification Time' for more details. */)
5275 (void)
5277 int ns = current_buffer->modtime.tv_nsec;
5278 if (ns < 0)
5279 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5280 return make_lisp_time (current_buffer->modtime);
5283 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5284 Sset_visited_file_modtime, 0, 1, 0,
5285 doc: /* Update buffer's recorded modification time from the visited file's time.
5286 Useful if the buffer was not read from the file normally
5287 or if the file itself has been changed for some known benign reason.
5288 An argument specifies the modification time value to use
5289 \(instead of that of the visited file), in the form of a list
5290 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5291 `visited-file-modtime'. */)
5292 (Lisp_Object time_flag)
5294 if (!NILP (time_flag))
5296 struct timespec mtime;
5297 if (INTEGERP (time_flag))
5299 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5300 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5302 else
5303 mtime = lisp_time_argument (time_flag);
5305 current_buffer->modtime = mtime;
5306 current_buffer->modtime_size = -1;
5308 else
5310 register Lisp_Object filename;
5311 struct stat st;
5312 Lisp_Object handler;
5314 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5316 /* If the file name has special constructs in it,
5317 call the corresponding file handler. */
5318 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5319 if (!NILP (handler))
5320 /* The handler can find the file name the same way we did. */
5321 return call2 (handler, Qset_visited_file_modtime, Qnil);
5323 filename = ENCODE_FILE (filename);
5325 if (stat (SSDATA (filename), &st) >= 0)
5327 current_buffer->modtime = get_stat_mtime (&st);
5328 current_buffer->modtime_size = st.st_size;
5332 return Qnil;
5335 static Lisp_Object
5336 auto_save_error (Lisp_Object error_val)
5338 Lisp_Object msg;
5339 int i;
5341 auto_save_error_occurred = 1;
5343 ring_bell (XFRAME (selected_frame));
5345 AUTO_STRING (format, "Auto-saving %s: %s");
5346 msg = CALLN (Fformat, format, BVAR (current_buffer, name),
5347 Ferror_message_string (error_val));
5349 for (i = 0; i < 3; ++i)
5351 if (i == 0)
5352 message3 (msg);
5353 else
5354 message3_nolog (msg);
5355 Fsleep_for (make_number (1), Qnil);
5358 return Qnil;
5361 static Lisp_Object
5362 auto_save_1 (void)
5364 struct stat st;
5365 Lisp_Object modes;
5367 auto_save_mode_bits = 0666;
5369 /* Get visited file's mode to become the auto save file's mode. */
5370 if (! NILP (BVAR (current_buffer, filename)))
5372 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5373 /* But make sure we can overwrite it later! */
5374 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5375 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5376 INTEGERP (modes))
5377 /* Remote files don't cooperate with stat. */
5378 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5381 return
5382 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5383 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5384 Qnil, Qnil);
5387 struct auto_save_unwind
5389 FILE *stream;
5390 bool auto_raise;
5393 static void
5394 do_auto_save_unwind (void *arg)
5396 struct auto_save_unwind *p = arg;
5397 FILE *stream = p->stream;
5398 minibuffer_auto_raise = p->auto_raise;
5399 auto_saving = 0;
5400 if (stream != NULL)
5402 block_input ();
5403 fclose (stream);
5404 unblock_input ();
5408 static Lisp_Object
5409 do_auto_save_make_dir (Lisp_Object dir)
5411 Lisp_Object result;
5413 auto_saving_dir_umask = 077;
5414 result = call2 (Qmake_directory, dir, Qt);
5415 auto_saving_dir_umask = 0;
5416 return result;
5419 static Lisp_Object
5420 do_auto_save_eh (Lisp_Object ignore)
5422 auto_saving_dir_umask = 0;
5423 return Qnil;
5426 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5427 doc: /* Auto-save all buffers that need it.
5428 This is all buffers that have auto-saving enabled
5429 and are changed since last auto-saved.
5430 Auto-saving writes the buffer into a file
5431 so that your editing is not lost if the system crashes.
5432 This file is not the file you visited; that changes only when you save.
5433 Normally we run the normal hook `auto-save-hook' before saving.
5435 A non-nil NO-MESSAGE argument means do not print any message if successful.
5436 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5437 (Lisp_Object no_message, Lisp_Object current_only)
5439 struct buffer *old = current_buffer, *b;
5440 Lisp_Object tail, buf, hook;
5441 bool auto_saved = 0;
5442 int do_handled_files;
5443 Lisp_Object oquit;
5444 FILE *stream = NULL;
5445 ptrdiff_t count = SPECPDL_INDEX ();
5446 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5447 bool old_message_p = 0;
5448 struct auto_save_unwind auto_save_unwind;
5450 if (max_specpdl_size < specpdl_size + 40)
5451 max_specpdl_size = specpdl_size + 40;
5453 if (minibuf_level)
5454 no_message = Qt;
5456 if (NILP (no_message))
5458 old_message_p = push_message ();
5459 record_unwind_protect_void (pop_message_unwind);
5462 /* Ordinarily don't quit within this function,
5463 but don't make it impossible to quit (in case we get hung in I/O). */
5464 oquit = Vquit_flag;
5465 Vquit_flag = Qnil;
5467 hook = intern ("auto-save-hook");
5468 safe_run_hooks (hook);
5470 if (STRINGP (Vauto_save_list_file_name))
5472 Lisp_Object listfile;
5474 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5476 /* Don't try to create the directory when shutting down Emacs,
5477 because creating the directory might signal an error, and
5478 that would leave Emacs in a strange state. */
5479 if (!NILP (Vrun_hooks))
5481 Lisp_Object dir;
5482 dir = Ffile_name_directory (listfile);
5483 if (NILP (Ffile_directory_p (dir)))
5484 internal_condition_case_1 (do_auto_save_make_dir,
5485 dir, Qt,
5486 do_auto_save_eh);
5489 stream = emacs_fopen (SSDATA (listfile), "w");
5492 auto_save_unwind.stream = stream;
5493 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5494 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5495 minibuffer_auto_raise = 0;
5496 auto_saving = 1;
5497 auto_save_error_occurred = 0;
5499 /* On first pass, save all files that don't have handlers.
5500 On second pass, save all files that do have handlers.
5502 If Emacs is crashing, the handlers may tweak what is causing
5503 Emacs to crash in the first place, and it would be a shame if
5504 Emacs failed to autosave perfectly ordinary files because it
5505 couldn't handle some ange-ftp'd file. */
5507 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5508 FOR_EACH_LIVE_BUFFER (tail, buf)
5510 b = XBUFFER (buf);
5512 /* Record all the buffers that have auto save mode
5513 in the special file that lists them. For each of these buffers,
5514 Record visited name (if any) and auto save name. */
5515 if (STRINGP (BVAR (b, auto_save_file_name))
5516 && stream != NULL && do_handled_files == 0)
5518 block_input ();
5519 if (!NILP (BVAR (b, filename)))
5521 fwrite (SDATA (BVAR (b, filename)), 1,
5522 SBYTES (BVAR (b, filename)), stream);
5524 putc ('\n', stream);
5525 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5526 SBYTES (BVAR (b, auto_save_file_name)), stream);
5527 putc ('\n', stream);
5528 unblock_input ();
5531 if (!NILP (current_only)
5532 && b != current_buffer)
5533 continue;
5535 /* Don't auto-save indirect buffers.
5536 The base buffer takes care of it. */
5537 if (b->base_buffer)
5538 continue;
5540 /* Check for auto save enabled
5541 and file changed since last auto save
5542 and file changed since last real save. */
5543 if (STRINGP (BVAR (b, auto_save_file_name))
5544 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5545 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5546 /* -1 means we've turned off autosaving for a while--see below. */
5547 && XINT (BVAR (b, save_length)) >= 0
5548 && (do_handled_files
5549 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5550 Qwrite_region))))
5552 struct timespec before_time = current_timespec ();
5553 struct timespec after_time;
5555 /* If we had a failure, don't try again for 20 minutes. */
5556 if (b->auto_save_failure_time > 0
5557 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5558 continue;
5560 set_buffer_internal (b);
5561 if (NILP (Vauto_save_include_big_deletions)
5562 && (XFASTINT (BVAR (b, save_length)) * 10
5563 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5564 /* A short file is likely to change a large fraction;
5565 spare the user annoying messages. */
5566 && XFASTINT (BVAR (b, save_length)) > 5000
5567 /* These messages are frequent and annoying for `*mail*'. */
5568 && !EQ (BVAR (b, filename), Qnil)
5569 && NILP (no_message))
5571 /* It has shrunk too much; turn off auto-saving here. */
5572 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5573 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5574 BVAR (b, name), 1);
5575 minibuffer_auto_raise = 0;
5576 /* Turn off auto-saving until there's a real save,
5577 and prevent any more warnings. */
5578 XSETINT (BVAR (b, save_length), -1);
5579 Fsleep_for (make_number (1), Qnil);
5580 continue;
5582 if (!auto_saved && NILP (no_message))
5583 message1 ("Auto-saving...");
5584 internal_condition_case (auto_save_1, Qt, auto_save_error);
5585 auto_saved = 1;
5586 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5587 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5588 set_buffer_internal (old);
5590 after_time = current_timespec ();
5592 /* If auto-save took more than 60 seconds,
5593 assume it was an NFS failure that got a timeout. */
5594 if (after_time.tv_sec - before_time.tv_sec > 60)
5595 b->auto_save_failure_time = after_time.tv_sec;
5599 /* Prevent another auto save till enough input events come in. */
5600 record_auto_save ();
5602 if (auto_saved && NILP (no_message))
5604 if (old_message_p)
5606 /* If we are going to restore an old message,
5607 give time to read ours. */
5608 sit_for (make_number (1), 0, 0);
5609 restore_message ();
5611 else if (!auto_save_error_occurred)
5612 /* Don't overwrite the error message if an error occurred.
5613 If we displayed a message and then restored a state
5614 with no message, leave a "done" message on the screen. */
5615 message1 ("Auto-saving...done");
5618 Vquit_flag = oquit;
5620 /* This restores the message-stack status. */
5621 unbind_to (count, Qnil);
5622 return Qnil;
5625 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5626 Sset_buffer_auto_saved, 0, 0, 0,
5627 doc: /* Mark current buffer as auto-saved with its current text.
5628 No auto-save file will be written until the buffer changes again. */)
5629 (void)
5631 /* FIXME: This should not be called in indirect buffers, since
5632 they're not autosaved. */
5633 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5634 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5635 current_buffer->auto_save_failure_time = 0;
5636 return Qnil;
5639 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5640 Sclear_buffer_auto_save_failure, 0, 0, 0,
5641 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5642 (void)
5644 current_buffer->auto_save_failure_time = 0;
5645 return Qnil;
5648 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5649 0, 0, 0,
5650 doc: /* Return t if current buffer has been auto-saved recently.
5651 More precisely, if it has been auto-saved since last read from or saved
5652 in the visited file. If the buffer has no visited file,
5653 then any auto-save counts as "recent". */)
5654 (void)
5656 /* FIXME: maybe we should return nil for indirect buffers since
5657 they're never autosaved. */
5658 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5661 /* Reading and completing file names. */
5663 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5664 Snext_read_file_uses_dialog_p, 0, 0, 0,
5665 doc: /* Return t if a call to `read-file-name' will use a dialog.
5666 The return value is only relevant for a call to `read-file-name' that happens
5667 before any other event (mouse or keypress) is handled. */)
5668 (void)
5670 #if (defined USE_GTK || defined USE_MOTIF \
5671 || defined HAVE_NS || defined HAVE_NTGUI)
5672 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5673 && use_dialog_box
5674 && use_file_dialog
5675 && window_system_available (SELECTED_FRAME ()))
5676 return Qt;
5677 #endif
5678 return Qnil;
5682 DEFUN ("set-binary-mode", Fset_binary_mode, Sset_binary_mode, 2, 2, 0,
5683 doc: /* Switch STREAM to binary I/O mode or text I/O mode.
5684 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5685 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5686 it to text mode.
5688 As a side effect, this function flushes any pending STREAM's data.
5690 Value is the previous value of STREAM's I/O mode, nil for text mode,
5691 non-nil for binary mode.
5693 On MS-Windows and MS-DOS, binary mode is needed to read or write
5694 arbitrary binary data, and for disabling translation between CR-LF
5695 pairs and a single newline character. Examples include generation
5696 of text files with Unix-style end-of-line format using `princ' in
5697 batch mode, with standard output redirected to a file.
5699 On Posix systems, this function always returns non-nil, and has no
5700 effect except for flushing STREAM's data. */)
5701 (Lisp_Object stream, Lisp_Object mode)
5703 FILE *fp = NULL;
5704 int binmode;
5706 CHECK_SYMBOL (stream);
5707 if (EQ (stream, Qstdin))
5708 fp = stdin;
5709 else if (EQ (stream, Qstdout))
5710 fp = stdout;
5711 else if (EQ (stream, Qstderr))
5712 fp = stderr;
5713 else
5714 xsignal2 (Qerror, build_string ("unsupported stream"), stream);
5716 binmode = NILP (mode) ? O_TEXT : O_BINARY;
5717 if (fp != stdin)
5718 fflush (fp);
5720 return (set_binary_mode (fileno (fp), binmode) == O_BINARY) ? Qt : Qnil;
5723 void
5724 init_fileio (void)
5726 realmask = umask (0);
5727 umask (realmask);
5729 valid_timestamp_file_system = 0;
5731 /* fsync can be a significant performance hit. Often it doesn't
5732 suffice to make the file-save operation survive a crash. For
5733 batch scripts, which are typically part of larger shell commands
5734 that don't fsync other files, its effect on performance can be
5735 significant so its utility is particularly questionable.
5736 Hence, for now by default fsync is used only when interactive.
5738 For more on why fsync often fails to work on today's hardware, see:
5739 Zheng M et al. Understanding the robustness of SSDs under power fault.
5740 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5741 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5743 For more on why fsync does not suffice even if it works properly, see:
5744 Roche X. Necessary step(s) to synchronize filename operations on disk.
5745 Austin Group Defect 672, 2013-03-19
5746 http://austingroupbugs.net/view.php?id=672 */
5747 write_region_inhibit_fsync = noninteractive;
5750 void
5751 syms_of_fileio (void)
5753 /* Property name of a file name handler,
5754 which gives a list of operations it handles. */
5755 DEFSYM (Qoperations, "operations");
5757 DEFSYM (Qexpand_file_name, "expand-file-name");
5758 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5759 DEFSYM (Qdirectory_file_name, "directory-file-name");
5760 DEFSYM (Qfile_name_directory, "file-name-directory");
5761 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5762 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5763 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5764 DEFSYM (Qcopy_file, "copy-file");
5765 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5766 DEFSYM (Qmake_directory, "make-directory");
5767 DEFSYM (Qdelete_file, "delete-file");
5768 DEFSYM (Qrename_file, "rename-file");
5769 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5770 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5771 DEFSYM (Qfile_exists_p, "file-exists-p");
5772 DEFSYM (Qfile_executable_p, "file-executable-p");
5773 DEFSYM (Qfile_readable_p, "file-readable-p");
5774 DEFSYM (Qfile_writable_p, "file-writable-p");
5775 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5776 DEFSYM (Qaccess_file, "access-file");
5777 DEFSYM (Qfile_directory_p, "file-directory-p");
5778 DEFSYM (Qfile_regular_p, "file-regular-p");
5779 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5780 DEFSYM (Qfile_modes, "file-modes");
5781 DEFSYM (Qset_file_modes, "set-file-modes");
5782 DEFSYM (Qset_file_times, "set-file-times");
5783 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5784 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5785 DEFSYM (Qfile_acl, "file-acl");
5786 DEFSYM (Qset_file_acl, "set-file-acl");
5787 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5788 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5789 DEFSYM (Qwrite_region, "write-region");
5790 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5791 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5793 /* The symbol bound to coding-system-for-read when
5794 insert-file-contents is called for recovering a file. This is not
5795 an actual coding system name, but just an indicator to tell
5796 insert-file-contents to use `emacs-mule' with a special flag for
5797 auto saving and recovering a file. */
5798 DEFSYM (Qauto_save_coding, "auto-save-coding");
5800 DEFSYM (Qfile_name_history, "file-name-history");
5801 Fset (Qfile_name_history, Qnil);
5803 DEFSYM (Qfile_error, "file-error");
5804 DEFSYM (Qfile_already_exists, "file-already-exists");
5805 DEFSYM (Qfile_date_error, "file-date-error");
5806 DEFSYM (Qfile_notify_error, "file-notify-error");
5807 DEFSYM (Qexcl, "excl");
5809 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5810 doc: /* Coding system for encoding file names.
5811 If it is nil, `default-file-name-coding-system' (which see) is used.
5813 On MS-Windows, the value of this variable is largely ignored if
5814 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5815 behaves as if file names were encoded in `utf-8'. */);
5816 Vfile_name_coding_system = Qnil;
5818 DEFVAR_LISP ("default-file-name-coding-system",
5819 Vdefault_file_name_coding_system,
5820 doc: /* Default coding system for encoding file names.
5821 This variable is used only when `file-name-coding-system' is nil.
5823 This variable is set/changed by the command `set-language-environment'.
5824 User should not set this variable manually,
5825 instead use `file-name-coding-system' to get a constant encoding
5826 of file names regardless of the current language environment.
5828 On MS-Windows, the value of this variable is largely ignored if
5829 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5830 behaves as if file names were encoded in `utf-8'. */);
5831 Vdefault_file_name_coding_system = Qnil;
5833 /* Lisp functions for translating file formats. */
5834 DEFSYM (Qformat_decode, "format-decode");
5835 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5837 /* Lisp function for setting buffer-file-coding-system and the
5838 multibyteness of the current buffer after inserting a file. */
5839 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5841 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5843 Fput (Qfile_error, Qerror_conditions,
5844 Fpurecopy (list2 (Qfile_error, Qerror)));
5845 Fput (Qfile_error, Qerror_message,
5846 build_pure_c_string ("File error"));
5848 Fput (Qfile_already_exists, Qerror_conditions,
5849 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5850 Fput (Qfile_already_exists, Qerror_message,
5851 build_pure_c_string ("File already exists"));
5853 Fput (Qfile_date_error, Qerror_conditions,
5854 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5855 Fput (Qfile_date_error, Qerror_message,
5856 build_pure_c_string ("Cannot set file date"));
5858 Fput (Qfile_notify_error, Qerror_conditions,
5859 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5860 Fput (Qfile_notify_error, Qerror_message,
5861 build_pure_c_string ("File notification error"));
5863 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5864 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5865 If a file name matches REGEXP, all I/O on that file is done by calling
5866 HANDLER. If a file name matches more than one handler, the handler
5867 whose match starts last in the file name gets precedence. The
5868 function `find-file-name-handler' checks this list for a handler for
5869 its argument.
5871 HANDLER should be a function. The first argument given to it is the
5872 name of the I/O primitive to be handled; the remaining arguments are
5873 the arguments that were passed to that primitive. For example, if you
5874 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5875 HANDLER is called like this:
5877 (funcall HANDLER 'file-exists-p FILENAME)
5879 Note that HANDLER must be able to handle all I/O primitives; if it has
5880 nothing special to do for a primitive, it should reinvoke the
5881 primitive to handle the operation \"the usual way\".
5882 See Info node `(elisp)Magic File Names' for more details. */);
5883 Vfile_name_handler_alist = Qnil;
5885 DEFVAR_LISP ("set-auto-coding-function",
5886 Vset_auto_coding_function,
5887 doc: /* If non-nil, a function to call to decide a coding system of file.
5888 Two arguments are passed to this function: the file name
5889 and the length of a file contents following the point.
5890 This function should return a coding system to decode the file contents.
5891 It should check the file name against `auto-coding-alist'.
5892 If no coding system is decided, it should check a coding system
5893 specified in the heading lines with the format:
5894 -*- ... coding: CODING-SYSTEM; ... -*-
5895 or local variable spec of the tailing lines with `coding:' tag. */);
5896 Vset_auto_coding_function = Qnil;
5898 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5899 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5900 Each is passed one argument, the number of characters inserted,
5901 with point at the start of the inserted text. Each function
5902 should leave point the same, and return the new character count.
5903 If `insert-file-contents' is intercepted by a handler from
5904 `file-name-handler-alist', that handler is responsible for calling the
5905 functions in `after-insert-file-functions' if appropriate. */);
5906 Vafter_insert_file_functions = Qnil;
5908 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5909 doc: /* A list of functions to be called at the start of `write-region'.
5910 Each is passed two arguments, START and END as for `write-region'.
5911 These are usually two numbers but not always; see the documentation
5912 for `write-region'. The function should return a list of pairs
5913 of the form (POSITION . STRING), consisting of strings to be effectively
5914 inserted at the specified positions of the file being written (1 means to
5915 insert before the first byte written). The POSITIONs must be sorted into
5916 increasing order.
5918 If there are several annotation functions, the lists returned by these
5919 functions are merged destructively. As each annotation function runs,
5920 the variable `write-region-annotations-so-far' contains a list of all
5921 annotations returned by previous annotation functions.
5923 An annotation function can return with a different buffer current.
5924 Doing so removes the annotations returned by previous functions, and
5925 resets START and END to `point-min' and `point-max' of the new buffer.
5927 After `write-region' completes, Emacs calls the function stored in
5928 `write-region-post-annotation-function', once for each buffer that was
5929 current when building the annotations (i.e., at least once), with that
5930 buffer current. */);
5931 Vwrite_region_annotate_functions = Qnil;
5932 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5934 DEFVAR_LISP ("write-region-post-annotation-function",
5935 Vwrite_region_post_annotation_function,
5936 doc: /* Function to call after `write-region' completes.
5937 The function is called with no arguments. If one or more of the
5938 annotation functions in `write-region-annotate-functions' changed the
5939 current buffer, the function stored in this variable is called for
5940 each of those additional buffers as well, in addition to the original
5941 buffer. The relevant buffer is current during each function call. */);
5942 Vwrite_region_post_annotation_function = Qnil;
5943 staticpro (&Vwrite_region_annotation_buffers);
5945 DEFVAR_LISP ("write-region-annotations-so-far",
5946 Vwrite_region_annotations_so_far,
5947 doc: /* When an annotation function is called, this holds the previous annotations.
5948 These are the annotations made by other annotation functions
5949 that were already called. See also `write-region-annotate-functions'. */);
5950 Vwrite_region_annotations_so_far = Qnil;
5952 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5953 doc: /* A list of file name handlers that temporarily should not be used.
5954 This applies only to the operation `inhibit-file-name-operation'. */);
5955 Vinhibit_file_name_handlers = Qnil;
5957 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5958 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5959 Vinhibit_file_name_operation = Qnil;
5961 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
5962 doc: /* File name in which we write a list of all auto save file names.
5963 This variable is initialized automatically from `auto-save-list-file-prefix'
5964 shortly after Emacs reads your init file, if you have not yet given it
5965 a non-nil value. */);
5966 Vauto_save_list_file_name = Qnil;
5968 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
5969 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5970 Normally auto-save files are written under other names. */);
5971 Vauto_save_visited_file_name = Qnil;
5973 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
5974 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5975 If nil, deleting a substantial portion of the text disables auto-save
5976 in the buffer; this is the default behavior, because the auto-save
5977 file is usually more useful if it contains the deleted text. */);
5978 Vauto_save_include_big_deletions = Qnil;
5980 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
5981 doc: /* Non-nil means don't call fsync in `write-region'.
5982 This variable affects calls to `write-region' as well as save commands.
5983 Setting this to nil may avoid data loss if the system loses power or
5984 the operating system crashes. By default, it is non-nil in batch mode. */);
5985 write_region_inhibit_fsync = 0; /* See also `init_fileio' above. */
5987 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
5988 doc: /* Specifies whether to use the system's trash can.
5989 When non-nil, certain file deletion commands use the function
5990 `move-file-to-trash' instead of deleting files outright.
5991 This includes interactive calls to `delete-file' and
5992 `delete-directory' and the Dired deletion commands. */);
5993 delete_by_moving_to_trash = 0;
5994 DEFSYM (Qdelete_by_moving_to_trash, "delete-by-moving-to-trash");
5996 /* Lisp function for moving files to trash. */
5997 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
5999 /* Lisp function for recursively copying directories. */
6000 DEFSYM (Qcopy_directory, "copy-directory");
6002 /* Lisp function for recursively deleting directories. */
6003 DEFSYM (Qdelete_directory, "delete-directory");
6005 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6006 DEFSYM (Qget_buffer_window_list, "get-buffer-window-list");
6008 DEFSYM (Qstdin, "stdin");
6009 DEFSYM (Qstdout, "stdout");
6010 DEFSYM (Qstderr, "stderr");
6012 defsubr (&Sfind_file_name_handler);
6013 defsubr (&Sfile_name_directory);
6014 defsubr (&Sfile_name_nondirectory);
6015 defsubr (&Sunhandled_file_name_directory);
6016 defsubr (&Sfile_name_as_directory);
6017 defsubr (&Sdirectory_file_name);
6018 defsubr (&Smake_temp_name);
6019 defsubr (&Sexpand_file_name);
6020 defsubr (&Ssubstitute_in_file_name);
6021 defsubr (&Scopy_file);
6022 defsubr (&Smake_directory_internal);
6023 defsubr (&Sdelete_directory_internal);
6024 defsubr (&Sdelete_file);
6025 defsubr (&Srename_file);
6026 defsubr (&Sadd_name_to_file);
6027 defsubr (&Smake_symbolic_link);
6028 defsubr (&Sfile_name_absolute_p);
6029 defsubr (&Sfile_exists_p);
6030 defsubr (&Sfile_executable_p);
6031 defsubr (&Sfile_readable_p);
6032 defsubr (&Sfile_writable_p);
6033 defsubr (&Saccess_file);
6034 defsubr (&Sfile_symlink_p);
6035 defsubr (&Sfile_directory_p);
6036 defsubr (&Sfile_accessible_directory_p);
6037 defsubr (&Sfile_regular_p);
6038 defsubr (&Sfile_modes);
6039 defsubr (&Sset_file_modes);
6040 defsubr (&Sset_file_times);
6041 defsubr (&Sfile_selinux_context);
6042 defsubr (&Sfile_acl);
6043 defsubr (&Sset_file_acl);
6044 defsubr (&Sset_file_selinux_context);
6045 defsubr (&Sset_default_file_modes);
6046 defsubr (&Sdefault_file_modes);
6047 defsubr (&Sfile_newer_than_file_p);
6048 defsubr (&Sinsert_file_contents);
6049 defsubr (&Swrite_region);
6050 defsubr (&Scar_less_than_car);
6051 defsubr (&Sverify_visited_file_modtime);
6052 defsubr (&Svisited_file_modtime);
6053 defsubr (&Sset_visited_file_modtime);
6054 defsubr (&Sdo_auto_save);
6055 defsubr (&Sset_buffer_auto_saved);
6056 defsubr (&Sclear_buffer_auto_save_failure);
6057 defsubr (&Srecent_auto_save_p);
6059 defsubr (&Snext_read_file_uses_dialog_p);
6061 defsubr (&Sset_binary_mode);
6063 #ifdef HAVE_SYNC
6064 defsubr (&Sunix_sync);
6065 #endif