New unwind-protect flavors to better type-check C callbacks.
[emacs.git] / src / fileio.c
blob1b5208e5f25b56ca332b82ac82f9c28546055d01
1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2013 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 "frame.h"
53 #include "dispextern.h"
55 #ifdef WINDOWSNT
56 #define NOMINMAX 1
57 #include <windows.h>
58 #include <sys/file.h>
59 #include "w32.h"
60 #endif /* not WINDOWSNT */
62 #ifdef MSDOS
63 #include "msdos.h"
64 #include <sys/param.h>
65 #endif
67 #ifdef DOS_NT
68 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
69 redirector allows the six letters between 'Z' and 'a' as well. */
70 #ifdef MSDOS
71 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
72 #endif
73 #ifdef WINDOWSNT
74 #define IS_DRIVE(x) c_isalpha (x)
75 #endif
76 /* Need to lower-case the drive letter, or else expanded
77 filenames will sometimes compare unequal, because
78 `expand-file-name' doesn't always down-case the drive letter. */
79 #define DRIVE_LETTER(x) c_tolower (x)
80 #endif
82 #include "systime.h"
83 #include <acl.h>
84 #include <allocator.h>
85 #include <careadlinkat.h>
86 #include <stat-time.h>
88 #ifdef HPUX
89 #include <netio.h>
90 #endif
92 #include "commands.h"
94 /* True during writing of auto-save files. */
95 static bool auto_saving;
97 /* Nonzero umask during creation of auto-save directories. */
98 static mode_t auto_saving_dir_umask;
100 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
101 a new file with the same mode as the original. */
102 static mode_t auto_save_mode_bits;
104 /* Set by auto_save_1 if an error occurred during the last auto-save. */
105 static bool auto_save_error_occurred;
107 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
108 number of a file system where time stamps were observed to to work. */
109 static bool valid_timestamp_file_system;
110 static dev_t timestamp_file_system;
112 /* The symbol bound to coding-system-for-read when
113 insert-file-contents is called for recovering a file. This is not
114 an actual coding system name, but just an indicator to tell
115 insert-file-contents to use `emacs-mule' with a special flag for
116 auto saving and recovering a file. */
117 static Lisp_Object Qauto_save_coding;
119 /* Property name of a file name handler,
120 which gives a list of operations it handles.. */
121 static Lisp_Object Qoperations;
123 /* Lisp functions for translating file formats. */
124 static Lisp_Object Qformat_decode, Qformat_annotate_function;
126 /* Lisp function for setting buffer-file-coding-system and the
127 multibyteness of the current buffer after inserting a file. */
128 static Lisp_Object Qafter_insert_file_set_coding;
130 static Lisp_Object Qwrite_region_annotate_functions;
131 /* Each time an annotation function changes the buffer, the new buffer
132 is added here. */
133 static Lisp_Object Vwrite_region_annotation_buffers;
135 static Lisp_Object Qdelete_by_moving_to_trash;
137 /* Lisp function for moving files to trash. */
138 static Lisp_Object Qmove_file_to_trash;
140 /* Lisp function for recursively copying directories. */
141 static Lisp_Object Qcopy_directory;
143 /* Lisp function for recursively deleting directories. */
144 static Lisp_Object Qdelete_directory;
146 #ifdef WINDOWSNT
147 #endif
149 Lisp_Object Qfile_error, Qfile_notify_error;
150 static Lisp_Object Qfile_already_exists, Qfile_date_error;
151 static Lisp_Object Qexcl;
152 Lisp_Object Qfile_name_history;
154 static Lisp_Object Qcar_less_than_car;
156 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
157 Lisp_Object *, struct coding_system *);
158 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
159 struct coding_system *);
162 /* Signal a file-access failure. STRING describes the failure,
163 NAME the file involved, and ERRORNO the errno value.
165 If NAME is neither null nor a pair, package it up as a singleton
166 list before reporting it; this saves report_file_errno's caller the
167 trouble of preserving errno before calling list1. */
169 void
170 report_file_errno (char const *string, Lisp_Object name, int errorno)
172 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
173 Lisp_Object errstring;
174 char *str;
176 synchronize_system_messages_locale ();
177 str = strerror (errorno);
178 errstring = code_convert_string_norecord (build_unibyte_string (str),
179 Vlocale_coding_system, 0);
181 while (1)
182 switch (errorno)
184 case EEXIST:
185 xsignal (Qfile_already_exists, Fcons (errstring, data));
186 break;
187 default:
188 /* System error messages are capitalized. Downcase the initial
189 unless it is followed by a slash. (The slash case caters to
190 error messages that begin with "I/O" or, in German, "E/A".) */
191 if (STRING_MULTIBYTE (errstring)
192 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
194 int c;
196 str = SSDATA (errstring);
197 c = STRING_CHAR ((unsigned char *) str);
198 Faset (errstring, make_number (0), make_number (downcase (c)));
201 xsignal (Qfile_error,
202 Fcons (build_string (string), Fcons (errstring, data)));
206 /* Signal a file-access failure that set errno. STRING describes the
207 failure, NAME the file involved. */
209 void
210 report_file_error (char const *string, Lisp_Object name)
212 report_file_errno (string, name, errno);
215 void
216 close_file_unwind (int fd)
218 emacs_close (fd);
221 /* Restore point, having saved it as a marker. */
223 void
224 restore_point_unwind (Lisp_Object location)
226 Fgoto_char (location);
227 Fset_marker (location, Qnil, Qnil);
231 static Lisp_Object Qexpand_file_name;
232 static Lisp_Object Qsubstitute_in_file_name;
233 static Lisp_Object Qdirectory_file_name;
234 static Lisp_Object Qfile_name_directory;
235 static Lisp_Object Qfile_name_nondirectory;
236 static Lisp_Object Qunhandled_file_name_directory;
237 static Lisp_Object Qfile_name_as_directory;
238 static Lisp_Object Qcopy_file;
239 static Lisp_Object Qmake_directory_internal;
240 static Lisp_Object Qmake_directory;
241 static Lisp_Object Qdelete_directory_internal;
242 Lisp_Object Qdelete_file;
243 static Lisp_Object Qrename_file;
244 static Lisp_Object Qadd_name_to_file;
245 static Lisp_Object Qmake_symbolic_link;
246 Lisp_Object Qfile_exists_p;
247 static Lisp_Object Qfile_executable_p;
248 static Lisp_Object Qfile_readable_p;
249 static Lisp_Object Qfile_writable_p;
250 static Lisp_Object Qfile_symlink_p;
251 static Lisp_Object Qaccess_file;
252 Lisp_Object Qfile_directory_p;
253 static Lisp_Object Qfile_regular_p;
254 static Lisp_Object Qfile_accessible_directory_p;
255 static Lisp_Object Qfile_modes;
256 static Lisp_Object Qset_file_modes;
257 static Lisp_Object Qset_file_times;
258 static Lisp_Object Qfile_selinux_context;
259 static Lisp_Object Qset_file_selinux_context;
260 static Lisp_Object Qfile_acl;
261 static Lisp_Object Qset_file_acl;
262 static Lisp_Object Qfile_newer_than_file_p;
263 Lisp_Object Qinsert_file_contents;
264 static Lisp_Object Qchoose_write_coding_system;
265 Lisp_Object Qwrite_region;
266 static Lisp_Object Qverify_visited_file_modtime;
267 static Lisp_Object Qset_visited_file_modtime;
269 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
270 Sfind_file_name_handler, 2, 2, 0,
271 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
272 Otherwise, return nil.
273 A file name is handled if one of the regular expressions in
274 `file-name-handler-alist' matches it.
276 If OPERATION equals `inhibit-file-name-operation', then we ignore
277 any handlers that are members of `inhibit-file-name-handlers',
278 but we still do run any other handlers. This lets handlers
279 use the standard functions without calling themselves recursively. */)
280 (Lisp_Object filename, Lisp_Object operation)
282 /* This function must not munge the match data. */
283 Lisp_Object chain, inhibited_handlers, result;
284 ptrdiff_t pos = -1;
286 result = Qnil;
287 CHECK_STRING (filename);
289 if (EQ (operation, Vinhibit_file_name_operation))
290 inhibited_handlers = Vinhibit_file_name_handlers;
291 else
292 inhibited_handlers = Qnil;
294 for (chain = Vfile_name_handler_alist; CONSP (chain);
295 chain = XCDR (chain))
297 Lisp_Object elt;
298 elt = XCAR (chain);
299 if (CONSP (elt))
301 Lisp_Object string = XCAR (elt);
302 ptrdiff_t match_pos;
303 Lisp_Object handler = XCDR (elt);
304 Lisp_Object operations = Qnil;
306 if (SYMBOLP (handler))
307 operations = Fget (handler, Qoperations);
309 if (STRINGP (string)
310 && (match_pos = fast_string_match (string, filename)) > pos
311 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
313 Lisp_Object tem;
315 handler = XCDR (elt);
316 tem = Fmemq (handler, inhibited_handlers);
317 if (NILP (tem))
319 result = handler;
320 pos = match_pos;
325 QUIT;
327 return result;
330 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
331 1, 1, 0,
332 doc: /* Return the directory component in file name FILENAME.
333 Return nil if FILENAME does not include a directory.
334 Otherwise return a directory name.
335 Given a Unix syntax file name, returns a string ending in slash. */)
336 (Lisp_Object filename)
338 #ifndef DOS_NT
339 register const char *beg;
340 #else
341 register char *beg;
342 Lisp_Object tem_fn;
343 #endif
344 register const char *p;
345 Lisp_Object handler;
347 CHECK_STRING (filename);
349 /* If the file name has special constructs in it,
350 call the corresponding file handler. */
351 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
352 if (!NILP (handler))
354 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
355 filename);
356 return STRINGP (handled_name) ? handled_name : Qnil;
359 #ifdef DOS_NT
360 beg = alloca (SBYTES (filename) + 1);
361 memcpy (beg, SSDATA (filename), SBYTES (filename) + 1);
362 #else
363 beg = SSDATA (filename);
364 #endif
365 p = beg + SBYTES (filename);
367 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
368 #ifdef DOS_NT
369 /* only recognize drive specifier at the beginning */
370 && !(p[-1] == ':'
371 /* handle the "/:d:foo" and "/:foo" cases correctly */
372 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
373 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
374 #endif
375 ) p--;
377 if (p == beg)
378 return Qnil;
379 #ifdef DOS_NT
380 /* Expansion of "c:" to drive and default directory. */
381 if (p[-1] == ':')
383 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
384 char *res = alloca (MAXPATHLEN + 1);
385 char *r = res;
387 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
389 memcpy (res, beg, 2);
390 beg += 2;
391 r += 2;
394 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
396 size_t l = strlen (res);
398 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
399 strcat (res, "/");
400 beg = res;
401 p = beg + strlen (beg);
402 dostounix_filename (beg, 0);
403 tem_fn = make_specified_string (beg, -1, p - beg,
404 STRING_MULTIBYTE (filename));
406 else
407 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
408 STRING_MULTIBYTE (filename));
410 else if (STRING_MULTIBYTE (filename))
412 tem_fn = make_specified_string (beg, -1, p - beg, 1);
413 dostounix_filename (SSDATA (tem_fn), 1);
414 #ifdef WINDOWSNT
415 if (!NILP (Vw32_downcase_file_names))
416 tem_fn = Fdowncase (tem_fn);
417 #endif
419 else
421 dostounix_filename (beg, 0);
422 tem_fn = make_specified_string (beg, -1, p - beg, 0);
424 return tem_fn;
425 #else /* DOS_NT */
426 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
427 #endif /* DOS_NT */
430 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
431 Sfile_name_nondirectory, 1, 1, 0,
432 doc: /* Return file name FILENAME sans its directory.
433 For example, in a Unix-syntax file name,
434 this is everything after the last slash,
435 or the entire name if it contains no slash. */)
436 (Lisp_Object filename)
438 register const char *beg, *p, *end;
439 Lisp_Object handler;
441 CHECK_STRING (filename);
443 /* If the file name has special constructs in it,
444 call the corresponding file handler. */
445 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
446 if (!NILP (handler))
448 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
449 filename);
450 if (STRINGP (handled_name))
451 return handled_name;
452 error ("Invalid handler in `file-name-handler-alist'");
455 beg = SSDATA (filename);
456 end = p = beg + SBYTES (filename);
458 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
459 #ifdef DOS_NT
460 /* only recognize drive specifier at beginning */
461 && !(p[-1] == ':'
462 /* handle the "/:d:foo" case correctly */
463 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
464 #endif
466 p--;
468 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
471 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
472 Sunhandled_file_name_directory, 1, 1, 0,
473 doc: /* Return a directly usable directory name somehow associated with FILENAME.
474 A `directly usable' directory name is one that may be used without the
475 intervention of any file handler.
476 If FILENAME is a directly usable file itself, return
477 \(file-name-directory FILENAME).
478 If FILENAME refers to a file which is not accessible from a local process,
479 then this should return nil.
480 The `call-process' and `start-process' functions use this function to
481 get a current directory to run processes in. */)
482 (Lisp_Object filename)
484 Lisp_Object handler;
486 /* If the file name has special constructs in it,
487 call the corresponding file handler. */
488 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
489 if (!NILP (handler))
491 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
492 filename);
493 return STRINGP (handled_name) ? handled_name : Qnil;
496 return Ffile_name_directory (filename);
499 /* Convert from file name SRC of length SRCLEN to directory name in
500 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
501 string. On UNIX, just make sure there is a terminating /. Return
502 the length of DST in bytes. */
504 static ptrdiff_t
505 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
506 bool multibyte)
508 if (srclen == 0)
510 dst[0] = '.';
511 dst[1] = '/';
512 dst[2] = '\0';
513 return 2;
516 strcpy (dst, src);
518 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
520 dst[srclen] = DIRECTORY_SEP;
521 dst[srclen + 1] = '\0';
522 srclen++;
524 #ifdef DOS_NT
525 dostounix_filename (dst, multibyte);
526 #endif
527 return srclen;
530 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
531 Sfile_name_as_directory, 1, 1, 0,
532 doc: /* Return a string representing the file name FILE interpreted as a directory.
533 This operation exists because a directory is also a file, but its name as
534 a directory is different from its name as a file.
535 The result can be used as the value of `default-directory'
536 or passed as second argument to `expand-file-name'.
537 For a Unix-syntax file name, just appends a slash. */)
538 (Lisp_Object file)
540 char *buf;
541 ptrdiff_t length;
542 Lisp_Object handler;
544 CHECK_STRING (file);
545 if (NILP (file))
546 return Qnil;
548 /* If the file name has special constructs in it,
549 call the corresponding file handler. */
550 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
551 if (!NILP (handler))
553 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
554 file);
555 if (STRINGP (handled_name))
556 return handled_name;
557 error ("Invalid handler in `file-name-handler-alist'");
560 #ifdef WINDOWSNT
561 if (!NILP (Vw32_downcase_file_names))
562 file = Fdowncase (file);
563 #endif
564 buf = alloca (SBYTES (file) + 10);
565 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
566 STRING_MULTIBYTE (file));
567 return make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
570 /* Convert from directory name SRC of length SRCLEN to file name in
571 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
572 string. On UNIX, just make sure there isn't a terminating /.
573 Return the length of DST in bytes. */
575 static ptrdiff_t
576 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
578 /* Process as Unix format: just remove any final slash.
579 But leave "/" unchanged; do not change it to "". */
580 strcpy (dst, src);
581 if (srclen > 1
582 && IS_DIRECTORY_SEP (dst[srclen - 1])
583 #ifdef DOS_NT
584 && !IS_ANY_SEP (dst[srclen - 2])
585 #endif
588 dst[srclen - 1] = 0;
589 srclen--;
591 #ifdef DOS_NT
592 dostounix_filename (dst, multibyte);
593 #endif
594 return srclen;
597 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
598 1, 1, 0,
599 doc: /* Returns the file name of the directory named DIRECTORY.
600 This is the name of the file that holds the data for the directory DIRECTORY.
601 This operation exists because a directory is also a file, but its name as
602 a directory is different from its name as a file.
603 In Unix-syntax, this function just removes the final slash. */)
604 (Lisp_Object directory)
606 char *buf;
607 ptrdiff_t length;
608 Lisp_Object handler;
610 CHECK_STRING (directory);
612 if (NILP (directory))
613 return Qnil;
615 /* If the file name has special constructs in it,
616 call the corresponding file handler. */
617 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
618 if (!NILP (handler))
620 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
621 directory);
622 if (STRINGP (handled_name))
623 return handled_name;
624 error ("Invalid handler in `file-name-handler-alist'");
627 #ifdef WINDOWSNT
628 if (!NILP (Vw32_downcase_file_names))
629 directory = Fdowncase (directory);
630 #endif
631 buf = alloca (SBYTES (directory) + 20);
632 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
633 STRING_MULTIBYTE (directory));
634 return make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
637 static const char make_temp_name_tbl[64] =
639 'A','B','C','D','E','F','G','H',
640 'I','J','K','L','M','N','O','P',
641 'Q','R','S','T','U','V','W','X',
642 'Y','Z','a','b','c','d','e','f',
643 'g','h','i','j','k','l','m','n',
644 'o','p','q','r','s','t','u','v',
645 'w','x','y','z','0','1','2','3',
646 '4','5','6','7','8','9','-','_'
649 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
651 /* Value is a temporary file name starting with PREFIX, a string.
653 The Emacs process number forms part of the result, so there is
654 no danger of generating a name being used by another process.
655 In addition, this function makes an attempt to choose a name
656 which has no existing file. To make this work, PREFIX should be
657 an absolute file name.
659 BASE64_P means add the pid as 3 characters in base64
660 encoding. In this case, 6 characters will be added to PREFIX to
661 form the file name. Otherwise, if Emacs is running on a system
662 with long file names, add the pid as a decimal number.
664 This function signals an error if no unique file name could be
665 generated. */
667 Lisp_Object
668 make_temp_name (Lisp_Object prefix, bool base64_p)
670 Lisp_Object val;
671 int len, clen;
672 printmax_t pid;
673 char *p, *data;
674 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
675 int pidlen;
677 CHECK_STRING (prefix);
679 /* VAL is created by adding 6 characters to PREFIX. The first
680 three are the PID of this process, in base 64, and the second
681 three are incremented if the file already exists. This ensures
682 262144 unique file names per PID per PREFIX. */
684 pid = getpid ();
686 if (base64_p)
688 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
689 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
690 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
691 pidlen = 3;
693 else
695 #ifdef HAVE_LONG_FILE_NAMES
696 pidlen = sprintf (pidbuf, "%"pMd, pid);
697 #else
698 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
699 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
700 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
701 pidlen = 3;
702 #endif
705 len = SBYTES (prefix); clen = SCHARS (prefix);
706 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
707 if (!STRING_MULTIBYTE (prefix))
708 STRING_SET_UNIBYTE (val);
709 data = SSDATA (val);
710 memcpy (data, SSDATA (prefix), len);
711 p = data + len;
713 memcpy (p, pidbuf, pidlen);
714 p += pidlen;
716 /* Here we try to minimize useless stat'ing when this function is
717 invoked many times successively with the same PREFIX. We achieve
718 this by initializing count to a random value, and incrementing it
719 afterwards.
721 We don't want make-temp-name to be called while dumping,
722 because then make_temp_name_count_initialized_p would get set
723 and then make_temp_name_count would not be set when Emacs starts. */
725 if (!make_temp_name_count_initialized_p)
727 make_temp_name_count = time (NULL);
728 make_temp_name_count_initialized_p = 1;
731 while (1)
733 unsigned num = make_temp_name_count;
735 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
736 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
737 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
739 /* Poor man's congruential RN generator. Replace with
740 ++make_temp_name_count for debugging. */
741 make_temp_name_count += 25229;
742 make_temp_name_count %= 225307;
744 if (!check_existing (data))
746 /* We want to return only if errno is ENOENT. */
747 if (errno == ENOENT)
748 return val;
749 else
750 /* The error here is dubious, but there is little else we
751 can do. The alternatives are to return nil, which is
752 as bad as (and in many cases worse than) throwing the
753 error, or to ignore the error, which will likely result
754 in looping through 225307 stat's, which is not only
755 dog-slow, but also useless since eventually nil would
756 have to be returned anyway. */
757 report_file_error ("Cannot create temporary name for prefix",
758 prefix);
759 /* not reached */
765 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
766 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
767 The Emacs process number forms part of the result,
768 so there is no danger of generating a name being used by another process.
770 In addition, this function makes an attempt to choose a name
771 which has no existing file. To make this work,
772 PREFIX should be an absolute file name.
774 There is a race condition between calling `make-temp-name' and creating the
775 file which opens all kinds of security holes. For that reason, you should
776 probably use `make-temp-file' instead, except in three circumstances:
778 * If you are creating the file in the user's home directory.
779 * If you are creating a directory rather than an ordinary file.
780 * If you are taking special precautions as `make-temp-file' does. */)
781 (Lisp_Object prefix)
783 return make_temp_name (prefix, 0);
788 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
789 doc: /* Convert filename NAME to absolute, and canonicalize it.
790 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
791 \(does not start with slash or tilde); both the directory name and
792 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
793 missing, the current buffer's value of `default-directory' is used.
794 NAME should be a string that is a valid file name for the underlying
795 filesystem.
796 File name components that are `.' are removed, and
797 so are file name components followed by `..', along with the `..' itself;
798 note that these simplifications are done without checking the resulting
799 file names in the file system.
800 Multiple consecutive slashes are collapsed into a single slash,
801 except at the beginning of the file name when they are significant (e.g.,
802 UNC file names on MS-Windows.)
803 An initial `~/' expands to your home directory.
804 An initial `~USER/' expands to USER's home directory.
805 See also the function `substitute-in-file-name'.
807 For technical reasons, this function can return correct but
808 non-intuitive results for the root directory; for instance,
809 \(expand-file-name ".." "/") returns "/..". For this reason, use
810 \(directory-file-name (file-name-directory dirname)) to traverse a
811 filesystem tree, not (expand-file-name ".." dirname). */)
812 (Lisp_Object name, Lisp_Object default_directory)
814 /* These point to SDATA and need to be careful with string-relocation
815 during GC (via DECODE_FILE). */
816 char *nm;
817 const char *newdir;
818 /* This should only point to alloca'd data. */
819 char *target;
821 ptrdiff_t tlen;
822 struct passwd *pw;
823 #ifdef DOS_NT
824 int drive = 0;
825 bool collapse_newdir = 1;
826 bool is_escaped = 0;
827 #endif /* DOS_NT */
828 ptrdiff_t length;
829 Lisp_Object handler, result, handled_name;
830 bool multibyte;
831 Lisp_Object hdir;
833 CHECK_STRING (name);
835 /* If the file name has special constructs in it,
836 call the corresponding file handler. */
837 handler = Ffind_file_name_handler (name, Qexpand_file_name);
838 if (!NILP (handler))
840 handled_name = call3 (handler, Qexpand_file_name,
841 name, default_directory);
842 if (STRINGP (handled_name))
843 return handled_name;
844 error ("Invalid handler in `file-name-handler-alist'");
848 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
849 if (NILP (default_directory))
850 default_directory = BVAR (current_buffer, directory);
851 if (! STRINGP (default_directory))
853 #ifdef DOS_NT
854 /* "/" is not considered a root directory on DOS_NT, so using "/"
855 here causes an infinite recursion in, e.g., the following:
857 (let (default-directory)
858 (expand-file-name "a"))
860 To avoid this, we set default_directory to the root of the
861 current drive. */
862 default_directory = build_string (emacs_root_dir ());
863 #else
864 default_directory = build_string ("/");
865 #endif
868 if (!NILP (default_directory))
870 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
871 if (!NILP (handler))
873 handled_name = call3 (handler, Qexpand_file_name,
874 name, default_directory);
875 if (STRINGP (handled_name))
876 return handled_name;
877 error ("Invalid handler in `file-name-handler-alist'");
882 char *o = SSDATA (default_directory);
884 /* Make sure DEFAULT_DIRECTORY is properly expanded.
885 It would be better to do this down below where we actually use
886 default_directory. Unfortunately, calling Fexpand_file_name recursively
887 could invoke GC, and the strings might be relocated. This would
888 be annoying because we have pointers into strings lying around
889 that would need adjusting, and people would add new pointers to
890 the code and forget to adjust them, resulting in intermittent bugs.
891 Putting this call here avoids all that crud.
893 The EQ test avoids infinite recursion. */
894 if (! NILP (default_directory) && !EQ (default_directory, name)
895 /* Save time in some common cases - as long as default_directory
896 is not relative, it can be canonicalized with name below (if it
897 is needed at all) without requiring it to be expanded now. */
898 #ifdef DOS_NT
899 /* Detect MSDOS file names with drive specifiers. */
900 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
901 && IS_DIRECTORY_SEP (o[2]))
902 #ifdef WINDOWSNT
903 /* Detect Windows file names in UNC format. */
904 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
905 #endif
906 #else /* not DOS_NT */
907 /* Detect Unix absolute file names (/... alone is not absolute on
908 DOS or Windows). */
909 && ! (IS_DIRECTORY_SEP (o[0]))
910 #endif /* not DOS_NT */
913 struct gcpro gcpro1;
915 GCPRO1 (name);
916 default_directory = Fexpand_file_name (default_directory, Qnil);
917 UNGCPRO;
920 multibyte = STRING_MULTIBYTE (name);
921 if (multibyte != STRING_MULTIBYTE (default_directory))
923 if (multibyte)
924 default_directory = string_to_multibyte (default_directory);
925 else
927 name = string_to_multibyte (name);
928 multibyte = 1;
932 #ifdef WINDOWSNT
933 if (!NILP (Vw32_downcase_file_names))
934 default_directory = Fdowncase (default_directory);
935 #endif
937 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
938 nm = alloca (SBYTES (name) + 1);
939 memcpy (nm, SSDATA (name), SBYTES (name) + 1);
941 #ifdef DOS_NT
942 /* Note if special escape prefix is present, but remove for now. */
943 if (nm[0] == '/' && nm[1] == ':')
945 is_escaped = 1;
946 nm += 2;
949 /* Find and remove drive specifier if present; this makes nm absolute
950 even if the rest of the name appears to be relative. Only look for
951 drive specifier at the beginning. */
952 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
954 drive = (unsigned char) nm[0];
955 nm += 2;
958 #ifdef WINDOWSNT
959 /* If we see "c://somedir", we want to strip the first slash after the
960 colon when stripping the drive letter. Otherwise, this expands to
961 "//somedir". */
962 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
963 nm++;
965 /* Discard any previous drive specifier if nm is now in UNC format. */
966 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
968 drive = 0;
970 #endif /* WINDOWSNT */
971 #endif /* DOS_NT */
973 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
974 none are found, we can probably return right away. We will avoid
975 allocating a new string if name is already fully expanded. */
976 if (
977 IS_DIRECTORY_SEP (nm[0])
978 #ifdef MSDOS
979 && drive && !is_escaped
980 #endif
981 #ifdef WINDOWSNT
982 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
983 #endif
986 /* If it turns out that the filename we want to return is just a
987 suffix of FILENAME, we don't need to go through and edit
988 things; we just need to construct a new string using data
989 starting at the middle of FILENAME. If we set LOSE, that
990 means we've discovered that we can't do that cool trick. */
991 bool lose = 0;
992 char *p = nm;
994 while (*p)
996 /* Since we know the name is absolute, we can assume that each
997 element starts with a "/". */
999 /* "." and ".." are hairy. */
1000 if (IS_DIRECTORY_SEP (p[0])
1001 && p[1] == '.'
1002 && (IS_DIRECTORY_SEP (p[2])
1003 || p[2] == 0
1004 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1005 || p[3] == 0))))
1006 lose = 1;
1007 /* We want to replace multiple `/' in a row with a single
1008 slash. */
1009 else if (p > nm
1010 && IS_DIRECTORY_SEP (p[0])
1011 && IS_DIRECTORY_SEP (p[1]))
1012 lose = 1;
1013 p++;
1015 if (!lose)
1017 #ifdef DOS_NT
1018 /* Make sure directories are all separated with /, but
1019 avoid allocation of a new string when not required. */
1020 dostounix_filename (nm, multibyte);
1021 #ifdef WINDOWSNT
1022 if (IS_DIRECTORY_SEP (nm[1]))
1024 if (strcmp (nm, SSDATA (name)) != 0)
1025 name = make_specified_string (nm, -1, strlen (nm), multibyte);
1027 else
1028 #endif
1029 /* Drive must be set, so this is okay. */
1030 if (strcmp (nm - 2, SSDATA (name)) != 0)
1032 char temp[] = " :";
1034 name = make_specified_string (nm, -1, p - nm, multibyte);
1035 temp[0] = DRIVE_LETTER (drive);
1036 name = concat2 (build_string (temp), name);
1038 #ifdef WINDOWSNT
1039 if (!NILP (Vw32_downcase_file_names))
1040 name = Fdowncase (name);
1041 #endif
1042 return name;
1043 #else /* not DOS_NT */
1044 if (strcmp (nm, SSDATA (name)) == 0)
1045 return name;
1046 return make_specified_string (nm, -1, strlen (nm), multibyte);
1047 #endif /* not DOS_NT */
1051 /* At this point, nm might or might not be an absolute file name. We
1052 need to expand ~ or ~user if present, otherwise prefix nm with
1053 default_directory if nm is not absolute, and finally collapse /./
1054 and /foo/../ sequences.
1056 We set newdir to be the appropriate prefix if one is needed:
1057 - the relevant user directory if nm starts with ~ or ~user
1058 - the specified drive's working dir (DOS/NT only) if nm does not
1059 start with /
1060 - the value of default_directory.
1062 Note that these prefixes are not guaranteed to be absolute (except
1063 for the working dir of a drive). Therefore, to ensure we always
1064 return an absolute name, if the final prefix is not absolute we
1065 append it to the current working directory. */
1067 newdir = 0;
1069 if (nm[0] == '~') /* prefix ~ */
1071 if (IS_DIRECTORY_SEP (nm[1])
1072 || nm[1] == 0) /* ~ by itself */
1074 Lisp_Object tem;
1076 if (!(newdir = egetenv ("HOME")))
1077 newdir = "";
1078 nm++;
1079 /* `egetenv' may return a unibyte string, which will bite us since
1080 we expect the directory to be multibyte. */
1081 tem = build_string (newdir);
1082 if (multibyte && !STRING_MULTIBYTE (tem))
1084 hdir = DECODE_FILE (tem);
1085 newdir = SSDATA (hdir);
1087 #ifdef DOS_NT
1088 collapse_newdir = 0;
1089 #endif
1091 else /* ~user/filename */
1093 char *o, *p;
1094 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
1095 o = alloca (p - nm + 1);
1096 memcpy (o, nm, p - nm);
1097 o [p - nm] = 0;
1099 block_input ();
1100 pw = getpwnam (o + 1);
1101 unblock_input ();
1102 if (pw)
1104 Lisp_Object tem;
1106 newdir = pw->pw_dir;
1107 /* `getpwnam' may return a unibyte string, which will
1108 bite us since we expect the directory to be
1109 multibyte. */
1110 tem = build_string (newdir);
1111 if (multibyte && !STRING_MULTIBYTE (tem))
1113 hdir = DECODE_FILE (tem);
1114 newdir = SSDATA (hdir);
1116 nm = p;
1117 #ifdef DOS_NT
1118 collapse_newdir = 0;
1119 #endif
1122 /* If we don't find a user of that name, leave the name
1123 unchanged; don't move nm forward to p. */
1127 #ifdef DOS_NT
1128 /* On DOS and Windows, nm is absolute if a drive name was specified;
1129 use the drive's current directory as the prefix if needed. */
1130 if (!newdir && drive)
1132 /* Get default directory if needed to make nm absolute. */
1133 char *adir = NULL;
1134 if (!IS_DIRECTORY_SEP (nm[0]))
1136 adir = alloca (MAXPATHLEN + 1);
1137 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1138 adir = NULL;
1139 else if (multibyte)
1141 Lisp_Object tem = build_string (adir);
1143 tem = DECODE_FILE (tem);
1144 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1147 if (!adir)
1149 /* Either nm starts with /, or drive isn't mounted. */
1150 adir = alloca (4);
1151 adir[0] = DRIVE_LETTER (drive);
1152 adir[1] = ':';
1153 adir[2] = '/';
1154 adir[3] = 0;
1156 newdir = adir;
1158 #endif /* DOS_NT */
1160 /* Finally, if no prefix has been specified and nm is not absolute,
1161 then it must be expanded relative to default_directory. */
1163 if (1
1164 #ifndef DOS_NT
1165 /* /... alone is not absolute on DOS and Windows. */
1166 && !IS_DIRECTORY_SEP (nm[0])
1167 #endif
1168 #ifdef WINDOWSNT
1169 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1170 #endif
1171 && !newdir)
1173 newdir = SSDATA (default_directory);
1174 #ifdef DOS_NT
1175 /* Note if special escape prefix is present, but remove for now. */
1176 if (newdir[0] == '/' && newdir[1] == ':')
1178 is_escaped = 1;
1179 newdir += 2;
1181 #endif
1184 #ifdef DOS_NT
1185 if (newdir)
1187 /* First ensure newdir is an absolute name. */
1188 if (
1189 /* Detect MSDOS file names with drive specifiers. */
1190 ! (IS_DRIVE (newdir[0])
1191 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1192 #ifdef WINDOWSNT
1193 /* Detect Windows file names in UNC format. */
1194 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1195 #endif
1198 /* Effectively, let newdir be (expand-file-name newdir cwd).
1199 Because of the admonition against calling expand-file-name
1200 when we have pointers into lisp strings, we accomplish this
1201 indirectly by prepending newdir to nm if necessary, and using
1202 cwd (or the wd of newdir's drive) as the new newdir. */
1203 char *adir;
1205 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1207 drive = (unsigned char) newdir[0];
1208 newdir += 2;
1210 if (!IS_DIRECTORY_SEP (nm[0]))
1212 ptrdiff_t newlen = strlen (newdir);
1213 char *tmp = alloca (newlen + strlen (nm) + 2);
1214 file_name_as_directory (tmp, newdir, newlen, multibyte);
1215 strcat (tmp, nm);
1216 nm = tmp;
1218 adir = alloca (MAXPATHLEN + 1);
1219 if (drive)
1221 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1222 strcpy (adir, "/");
1224 else
1225 getcwd (adir, MAXPATHLEN + 1);
1226 if (multibyte)
1228 Lisp_Object tem = build_string (adir);
1230 tem = DECODE_FILE (tem);
1231 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1233 newdir = adir;
1236 /* Strip off drive name from prefix, if present. */
1237 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1239 drive = newdir[0];
1240 newdir += 2;
1243 /* Keep only a prefix from newdir if nm starts with slash
1244 (//server/share for UNC, nothing otherwise). */
1245 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1247 #ifdef WINDOWSNT
1248 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1250 char *adir = strcpy (alloca (strlen (newdir) + 1), newdir);
1251 char *p = adir + 2;
1252 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1253 p++;
1254 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1255 *p = 0;
1256 newdir = adir;
1258 else
1259 #endif
1260 newdir = "";
1263 #endif /* DOS_NT */
1265 if (newdir)
1267 /* Get rid of any slash at the end of newdir, unless newdir is
1268 just / or // (an incomplete UNC name). */
1269 length = strlen (newdir);
1270 tlen = length + 1;
1271 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1272 #ifdef WINDOWSNT
1273 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1274 #endif
1277 char *temp = alloca (length);
1278 memcpy (temp, newdir, length - 1);
1279 temp[length - 1] = 0;
1280 length--;
1281 newdir = temp;
1284 else
1286 length = 0;
1287 tlen = 0;
1290 /* Now concatenate the directory and name to new space in the stack frame. */
1291 tlen += strlen (nm) + 1;
1292 #ifdef DOS_NT
1293 /* Reserve space for drive specifier and escape prefix, since either
1294 or both may need to be inserted. (The Microsoft x86 compiler
1295 produces incorrect code if the following two lines are combined.) */
1296 target = alloca (tlen + 4);
1297 target += 4;
1298 #else /* not DOS_NT */
1299 target = alloca (tlen);
1300 #endif /* not DOS_NT */
1301 *target = 0;
1303 if (newdir)
1305 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1307 #ifdef DOS_NT
1308 /* If newdir is effectively "C:/", then the drive letter will have
1309 been stripped and newdir will be "/". Concatenating with an
1310 absolute directory in nm produces "//", which will then be
1311 incorrectly treated as a network share. Ignore newdir in
1312 this case (keeping the drive letter). */
1313 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1314 && newdir[1] == '\0'))
1315 #endif
1316 strcpy (target, newdir);
1318 else
1319 file_name_as_directory (target, newdir, length, multibyte);
1322 strcat (target, nm);
1324 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1325 appear. */
1327 char *p = target;
1328 char *o = target;
1330 while (*p)
1332 if (!IS_DIRECTORY_SEP (*p))
1334 *o++ = *p++;
1336 else if (p[1] == '.'
1337 && (IS_DIRECTORY_SEP (p[2])
1338 || p[2] == 0))
1340 /* If "/." is the entire filename, keep the "/". Otherwise,
1341 just delete the whole "/.". */
1342 if (o == target && p[2] == '\0')
1343 *o++ = *p;
1344 p += 2;
1346 else if (p[1] == '.' && p[2] == '.'
1347 /* `/../' is the "superroot" on certain file systems.
1348 Turned off on DOS_NT systems because they have no
1349 "superroot" and because this causes us to produce
1350 file names like "d:/../foo" which fail file-related
1351 functions of the underlying OS. (To reproduce, try a
1352 long series of "../../" in default_directory, longer
1353 than the number of levels from the root.) */
1354 #ifndef DOS_NT
1355 && o != target
1356 #endif
1357 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1359 #ifdef WINDOWSNT
1360 char *prev_o = o;
1361 #endif
1362 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1363 continue;
1364 #ifdef WINDOWSNT
1365 /* Don't go below server level in UNC filenames. */
1366 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1367 && IS_DIRECTORY_SEP (*target))
1368 o = prev_o;
1369 else
1370 #endif
1371 /* Keep initial / only if this is the whole name. */
1372 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1373 ++o;
1374 p += 3;
1376 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1377 /* Collapse multiple `/' in a row. */
1378 p++;
1379 else
1381 *o++ = *p++;
1385 #ifdef DOS_NT
1386 /* At last, set drive name. */
1387 #ifdef WINDOWSNT
1388 /* Except for network file name. */
1389 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1390 #endif /* WINDOWSNT */
1392 if (!drive) emacs_abort ();
1393 target -= 2;
1394 target[0] = DRIVE_LETTER (drive);
1395 target[1] = ':';
1397 /* Reinsert the escape prefix if required. */
1398 if (is_escaped)
1400 target -= 2;
1401 target[0] = '/';
1402 target[1] = ':';
1404 result = make_specified_string (target, -1, o - target, multibyte);
1405 dostounix_filename (SSDATA (result), multibyte);
1406 #ifdef WINDOWSNT
1407 if (!NILP (Vw32_downcase_file_names))
1408 result = Fdowncase (result);
1409 #endif
1410 #else /* !DOS_NT */
1411 result = make_specified_string (target, -1, o - target, multibyte);
1412 #endif /* !DOS_NT */
1415 /* Again look to see if the file name has special constructs in it
1416 and perhaps call the corresponding file handler. This is needed
1417 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1418 the ".." component gives us "/user@host:/bar/../baz" which needs
1419 to be expanded again. */
1420 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1421 if (!NILP (handler))
1423 handled_name = call3 (handler, Qexpand_file_name,
1424 result, default_directory);
1425 if (STRINGP (handled_name))
1426 return handled_name;
1427 error ("Invalid handler in `file-name-handler-alist'");
1430 return result;
1433 #if 0
1434 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1435 This is the old version of expand-file-name, before it was thoroughly
1436 rewritten for Emacs 10.31. We leave this version here commented-out,
1437 because the code is very complex and likely to have subtle bugs. If
1438 bugs _are_ found, it might be of interest to look at the old code and
1439 see what did it do in the relevant situation.
1441 Don't remove this code: it's true that it will be accessible
1442 from the repository, but a few years from deletion, people will
1443 forget it is there. */
1445 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1446 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1447 "Convert FILENAME to absolute, and canonicalize it.\n\
1448 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1449 \(does not start with slash); if DEFAULT is nil or missing,\n\
1450 the current buffer's value of default-directory is used.\n\
1451 Filenames containing `.' or `..' as components are simplified;\n\
1452 initial `~/' expands to your home directory.\n\
1453 See also the function `substitute-in-file-name'.")
1454 (name, defalt)
1455 Lisp_Object name, defalt;
1457 unsigned char *nm;
1459 register unsigned char *newdir, *p, *o;
1460 ptrdiff_t tlen;
1461 unsigned char *target;
1462 struct passwd *pw;
1464 CHECK_STRING (name);
1465 nm = SDATA (name);
1467 /* If nm is absolute, flush ...// and detect /./ and /../.
1468 If no /./ or /../ we can return right away. */
1469 if (nm[0] == '/')
1471 bool lose = 0;
1472 p = nm;
1473 while (*p)
1475 if (p[0] == '/' && p[1] == '/')
1476 nm = p + 1;
1477 if (p[0] == '/' && p[1] == '~')
1478 nm = p + 1, lose = 1;
1479 if (p[0] == '/' && p[1] == '.'
1480 && (p[2] == '/' || p[2] == 0
1481 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1482 lose = 1;
1483 p++;
1485 if (!lose)
1487 if (nm == SDATA (name))
1488 return name;
1489 return build_string (nm);
1493 /* Now determine directory to start with and put it in NEWDIR. */
1495 newdir = 0;
1497 if (nm[0] == '~') /* prefix ~ */
1498 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1500 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1501 newdir = (unsigned char *) "";
1502 nm++;
1504 else /* ~user/filename */
1506 /* Get past ~ to user. */
1507 unsigned char *user = nm + 1;
1508 /* Find end of name. */
1509 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1510 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1511 /* Copy the user name into temp storage. */
1512 o = alloca (len + 1);
1513 memcpy (o, user, len);
1514 o[len] = 0;
1516 /* Look up the user name. */
1517 block_input ();
1518 pw = (struct passwd *) getpwnam (o + 1);
1519 unblock_input ();
1520 if (!pw)
1521 error ("\"%s\" isn't a registered user", o + 1);
1523 newdir = (unsigned char *) pw->pw_dir;
1525 /* Discard the user name from NM. */
1526 nm += len;
1529 if (nm[0] != '/' && !newdir)
1531 if (NILP (defalt))
1532 defalt = current_buffer->directory;
1533 CHECK_STRING (defalt);
1534 newdir = SDATA (defalt);
1537 /* Now concatenate the directory and name to new space in the stack frame. */
1539 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1540 target = alloca (tlen);
1541 *target = 0;
1543 if (newdir)
1545 if (nm[0] == 0 || nm[0] == '/')
1546 strcpy (target, newdir);
1547 else
1548 file_name_as_directory (target, newdir);
1551 strcat (target, nm);
1553 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1555 p = target;
1556 o = target;
1558 while (*p)
1560 if (*p != '/')
1562 *o++ = *p++;
1564 else if (!strncmp (p, "//", 2)
1567 o = target;
1568 p++;
1570 else if (p[0] == '/' && p[1] == '.'
1571 && (p[2] == '/' || p[2] == 0))
1572 p += 2;
1573 else if (!strncmp (p, "/..", 3)
1574 /* `/../' is the "superroot" on certain file systems. */
1575 && o != target
1576 && (p[3] == '/' || p[3] == 0))
1578 while (o != target && *--o != '/')
1580 if (o == target && *o == '/')
1581 ++o;
1582 p += 3;
1584 else
1586 *o++ = *p++;
1590 return make_string (target, o - target);
1592 #endif
1594 /* If /~ or // appears, discard everything through first slash. */
1595 static bool
1596 file_name_absolute_p (const char *filename)
1598 return
1599 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1600 #ifdef DOS_NT
1601 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1602 && IS_DIRECTORY_SEP (filename[2]))
1603 #endif
1607 static char *
1608 search_embedded_absfilename (char *nm, char *endp)
1610 char *p, *s;
1612 for (p = nm + 1; p < endp; p++)
1614 if (IS_DIRECTORY_SEP (p[-1])
1615 && file_name_absolute_p (p)
1616 #if defined (WINDOWSNT) || defined (CYGWIN)
1617 /* // at start of file name is meaningful in Apollo,
1618 WindowsNT and Cygwin systems. */
1619 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1620 #endif /* not (WINDOWSNT || CYGWIN) */
1623 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1624 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1626 char *o = alloca (s - p + 1);
1627 struct passwd *pw;
1628 memcpy (o, p, s - p);
1629 o [s - p] = 0;
1631 /* If we have ~user and `user' exists, discard
1632 everything up to ~. But if `user' does not exist, leave
1633 ~user alone, it might be a literal file name. */
1634 block_input ();
1635 pw = getpwnam (o + 1);
1636 unblock_input ();
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, *s, *p, *o, *x, *endp;
1661 char *target = NULL;
1662 ptrdiff_t total = 0;
1663 bool substituted = 0;
1664 bool multibyte;
1665 char *xnm;
1666 Lisp_Object handler;
1668 CHECK_STRING (filename);
1670 multibyte = STRING_MULTIBYTE (filename);
1672 /* If the file name has special constructs in it,
1673 call the corresponding file handler. */
1674 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1675 if (!NILP (handler))
1677 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1678 filename);
1679 if (STRINGP (handled_name))
1680 return handled_name;
1681 error ("Invalid handler in `file-name-handler-alist'");
1684 /* Always work on a copy of the string, in case GC happens during
1685 decode of environment variables, causing the original Lisp_String
1686 data to be relocated. */
1687 nm = alloca (SBYTES (filename) + 1);
1688 memcpy (nm, SDATA (filename), SBYTES (filename) + 1);
1690 #ifdef DOS_NT
1691 dostounix_filename (nm, multibyte);
1692 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1693 #endif
1694 endp = nm + SBYTES (filename);
1696 /* If /~ or // appears, discard everything through first slash. */
1697 p = search_embedded_absfilename (nm, endp);
1698 if (p)
1699 /* Start over with the new string, so we check the file-name-handler
1700 again. Important with filenames like "/home/foo//:/hello///there"
1701 which would substitute to "/:/hello///there" rather than "/there". */
1702 return Fsubstitute_in_file_name
1703 (make_specified_string (p, -1, endp - p, multibyte));
1705 /* See if any variables are substituted into the string
1706 and find the total length of their values in `total'. */
1708 for (p = nm; p != endp;)
1709 if (*p != '$')
1710 p++;
1711 else
1713 p++;
1714 if (p == endp)
1715 goto badsubst;
1716 else if (*p == '$')
1718 /* "$$" means a single "$". */
1719 p++;
1720 total -= 1;
1721 substituted = 1;
1722 continue;
1724 else if (*p == '{')
1726 o = ++p;
1727 p = memchr (p, '}', endp - p);
1728 if (! p)
1729 goto missingclose;
1730 s = p;
1732 else
1734 o = p;
1735 while (p != endp && (c_isalnum (*p) || *p == '_')) p++;
1736 s = p;
1739 /* Copy out the variable name. */
1740 target = alloca (s - o + 1);
1741 memcpy (target, o, s - o);
1742 target[s - o] = 0;
1743 #ifdef DOS_NT
1744 strupr (target); /* $home == $HOME etc. */
1745 #endif /* DOS_NT */
1747 /* Get variable value. */
1748 o = egetenv (target);
1749 if (o)
1751 /* Don't try to guess a maximum length - UTF8 can use up to
1752 four bytes per character. This code is unlikely to run
1753 in a situation that requires performance, so decoding the
1754 env variables twice should be acceptable. Note that
1755 decoding may cause a garbage collect. */
1756 Lisp_Object orig, decoded;
1757 orig = build_unibyte_string (o);
1758 decoded = DECODE_FILE (orig);
1759 total += SBYTES (decoded);
1760 substituted = 1;
1762 else if (*p == '}')
1763 goto badvar;
1766 if (!substituted)
1768 #ifdef WINDOWSNT
1769 if (!NILP (Vw32_downcase_file_names))
1770 filename = Fdowncase (filename);
1771 #endif
1772 return filename;
1775 /* If substitution required, recopy the string and do it. */
1776 /* Make space in stack frame for the new copy. */
1777 xnm = alloca (SBYTES (filename) + total + 1);
1778 x = xnm;
1780 /* Copy the rest of the name through, replacing $ constructs with values. */
1781 for (p = nm; *p;)
1782 if (*p != '$')
1783 *x++ = *p++;
1784 else
1786 p++;
1787 if (p == endp)
1788 goto badsubst;
1789 else if (*p == '$')
1791 *x++ = *p++;
1792 continue;
1794 else if (*p == '{')
1796 o = ++p;
1797 p = memchr (p, '}', endp - p);
1798 if (! p)
1799 goto missingclose;
1800 s = p++;
1802 else
1804 o = p;
1805 while (p != endp && (c_isalnum (*p) || *p == '_')) p++;
1806 s = p;
1809 /* Copy out the variable name. */
1810 target = alloca (s - o + 1);
1811 memcpy (target, o, s - o);
1812 target[s - o] = 0;
1814 /* Get variable value. */
1815 o = egetenv (target);
1816 if (!o)
1818 *x++ = '$';
1819 strcpy (x, target); x+= strlen (target);
1821 else
1823 Lisp_Object orig, decoded;
1824 ptrdiff_t orig_length, decoded_length;
1825 orig_length = strlen (o);
1826 orig = make_unibyte_string (o, orig_length);
1827 decoded = DECODE_FILE (orig);
1828 decoded_length = SBYTES (decoded);
1829 memcpy (x, SDATA (decoded), decoded_length);
1830 x += decoded_length;
1832 /* If environment variable needed decoding, return value
1833 needs to be multibyte. */
1834 if (decoded_length != orig_length
1835 || memcmp (SDATA (decoded), o, orig_length))
1836 multibyte = 1;
1840 *x = 0;
1842 /* If /~ or // appears, discard everything through first slash. */
1843 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1844 /* This time we do not start over because we've already expanded envvars
1845 and replaced $$ with $. Maybe we should start over as well, but we'd
1846 need to quote some $ to $$ first. */
1847 xnm = p;
1849 #ifdef WINDOWSNT
1850 if (!NILP (Vw32_downcase_file_names))
1852 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1854 xname = Fdowncase (xname);
1855 return xname;
1857 else
1858 #endif
1859 return make_specified_string (xnm, -1, x - xnm, multibyte);
1861 badsubst:
1862 error ("Bad format environment-variable substitution");
1863 missingclose:
1864 error ("Missing \"}\" in environment-variable substitution");
1865 badvar:
1866 error ("Substituting nonexistent environment variable \"%s\"", target);
1869 /* A slightly faster and more convenient way to get
1870 (directory-file-name (expand-file-name FOO)). */
1872 Lisp_Object
1873 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1875 register Lisp_Object absname;
1877 absname = Fexpand_file_name (filename, defdir);
1879 /* Remove final slash, if any (unless this is the root dir).
1880 stat behaves differently depending! */
1881 if (SCHARS (absname) > 1
1882 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1883 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1884 /* We cannot take shortcuts; they might be wrong for magic file names. */
1885 absname = Fdirectory_file_name (absname);
1886 return absname;
1889 /* Signal an error if the file ABSNAME already exists.
1890 If INTERACTIVE, ask the user whether to proceed,
1891 and bypass the error if the user says to go ahead.
1892 QUERYSTRING is a name for the action that is being considered
1893 to alter the file.
1895 *STATPTR is used to store the stat information if the file exists.
1896 If the file does not exist, STATPTR->st_mode is set to 0.
1897 If STATPTR is null, we don't store into it.
1899 If QUICK, ask for y or n, not yes or no. */
1901 static void
1902 barf_or_query_if_file_exists (Lisp_Object absname, const char *querystring,
1903 bool interactive, struct stat *statptr,
1904 bool quick)
1906 Lisp_Object tem, encoded_filename;
1907 struct stat statbuf;
1908 struct gcpro gcpro1;
1910 encoded_filename = ENCODE_FILE (absname);
1912 /* `stat' is a good way to tell whether the file exists,
1913 regardless of what access permissions it has. */
1914 if (lstat (SSDATA (encoded_filename), &statbuf) >= 0)
1916 if (S_ISDIR (statbuf.st_mode))
1917 xsignal2 (Qfile_error,
1918 build_string ("File is a directory"), absname);
1920 if (! interactive)
1921 xsignal2 (Qfile_already_exists,
1922 build_string ("File already exists"), absname);
1923 GCPRO1 (absname);
1924 tem = format2 ("File %s already exists; %s anyway? ",
1925 absname, build_string (querystring));
1926 if (quick)
1927 tem = call1 (intern ("y-or-n-p"), tem);
1928 else
1929 tem = do_yes_or_no_p (tem);
1930 UNGCPRO;
1931 if (NILP (tem))
1932 xsignal2 (Qfile_already_exists,
1933 build_string ("File already exists"), absname);
1934 if (statptr)
1935 *statptr = statbuf;
1937 else
1939 if (statptr)
1940 statptr->st_mode = 0;
1942 return;
1945 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1946 "fCopy file: \nGCopy %s to file: \np\nP",
1947 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1948 If NEWNAME names a directory, copy FILE there.
1950 This function always sets the file modes of the output file to match
1951 the input file.
1953 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1954 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1955 signal a `file-already-exists' error without overwriting. If
1956 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1957 about overwriting; this is what happens in interactive use with M-x.
1958 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1959 existing file.
1961 Fourth arg KEEP-TIME non-nil means give the output file the same
1962 last-modified time as the old one. (This works on only some systems.)
1964 A prefix arg makes KEEP-TIME non-nil.
1966 If PRESERVE-UID-GID is non-nil, we try to transfer the
1967 uid and gid of FILE to NEWNAME.
1969 If PRESERVE-EXTENDED-ATTRIBUTES is non-nil, we try to copy additional
1970 attributes of FILE to NEWNAME, such as its SELinux context and ACL
1971 entries (depending on how Emacs was built). */)
1972 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists, Lisp_Object keep_time, Lisp_Object preserve_uid_gid, Lisp_Object preserve_extended_attributes)
1974 int ifd, ofd;
1975 int n;
1976 char buf[16 * 1024];
1977 struct stat st, out_st;
1978 Lisp_Object handler;
1979 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1980 ptrdiff_t count = SPECPDL_INDEX ();
1981 Lisp_Object encoded_file, encoded_newname;
1982 #if HAVE_LIBSELINUX
1983 security_context_t con;
1984 int conlength = 0;
1985 #endif
1986 #ifdef WINDOWSNT
1987 acl_t acl = NULL;
1988 #endif
1990 encoded_file = encoded_newname = Qnil;
1991 GCPRO4 (file, newname, encoded_file, encoded_newname);
1992 CHECK_STRING (file);
1993 CHECK_STRING (newname);
1995 if (!NILP (Ffile_directory_p (newname)))
1996 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1997 else
1998 newname = Fexpand_file_name (newname, Qnil);
2000 file = Fexpand_file_name (file, Qnil);
2002 /* If the input file name has special constructs in it,
2003 call the corresponding file handler. */
2004 handler = Ffind_file_name_handler (file, Qcopy_file);
2005 /* Likewise for output file name. */
2006 if (NILP (handler))
2007 handler = Ffind_file_name_handler (newname, Qcopy_file);
2008 if (!NILP (handler))
2009 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
2010 ok_if_already_exists, keep_time, preserve_uid_gid,
2011 preserve_extended_attributes));
2013 encoded_file = ENCODE_FILE (file);
2014 encoded_newname = ENCODE_FILE (newname);
2016 if (NILP (ok_if_already_exists)
2017 || INTEGERP (ok_if_already_exists))
2018 barf_or_query_if_file_exists (newname, "copy to it",
2019 INTEGERP (ok_if_already_exists), &out_st, 0);
2020 else if (stat (SSDATA (encoded_newname), &out_st) < 0)
2021 out_st.st_mode = 0;
2023 #ifdef WINDOWSNT
2024 if (!NILP (preserve_extended_attributes))
2026 acl = acl_get_file (SDATA (encoded_file), ACL_TYPE_ACCESS);
2027 if (acl == NULL && acl_errno_valid (errno))
2028 report_file_error ("Getting ACL", file);
2030 if (!CopyFile (SDATA (encoded_file),
2031 SDATA (encoded_newname),
2032 FALSE))
2034 /* CopyFile doesn't set errno when it fails. By far the most
2035 "popular" reason is that the target is read-only. */
2036 report_file_errno ("Copying file", list2 (file, newname),
2037 GetLastError () == 5 ? EACCES : EPERM);
2039 /* CopyFile retains the timestamp by default. */
2040 else if (NILP (keep_time))
2042 EMACS_TIME now;
2043 DWORD attributes;
2044 char * filename;
2046 filename = SDATA (encoded_newname);
2048 /* Ensure file is writable while its modified time is set. */
2049 attributes = GetFileAttributes (filename);
2050 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
2051 now = current_emacs_time ();
2052 if (set_file_times (-1, filename, now, now))
2054 /* Restore original attributes. */
2055 SetFileAttributes (filename, attributes);
2056 xsignal2 (Qfile_date_error,
2057 build_string ("Cannot set file date"), newname);
2059 /* Restore original attributes. */
2060 SetFileAttributes (filename, attributes);
2062 if (acl != NULL)
2064 bool fail =
2065 acl_set_file (SDATA (encoded_newname), ACL_TYPE_ACCESS, acl) != 0;
2066 if (fail && acl_errno_valid (errno))
2067 report_file_error ("Setting ACL", newname);
2069 acl_free (acl);
2071 #else /* not WINDOWSNT */
2072 immediate_quit = 1;
2073 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
2074 immediate_quit = 0;
2076 if (ifd < 0)
2077 report_file_error ("Opening input file", file);
2079 record_unwind_protect_int (close_file_unwind, ifd);
2081 if (fstat (ifd, &st) != 0)
2082 report_file_error ("Input file status", file);
2084 if (!NILP (preserve_extended_attributes))
2086 #if HAVE_LIBSELINUX
2087 if (is_selinux_enabled ())
2089 conlength = fgetfilecon (ifd, &con);
2090 if (conlength == -1)
2091 report_file_error ("Doing fgetfilecon", file);
2093 #endif
2096 if (out_st.st_mode != 0
2097 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2098 report_file_errno ("Input and output files are the same",
2099 list2 (file, newname), 0);
2101 /* We can copy only regular files. */
2102 if (!S_ISREG (st.st_mode))
2103 report_file_errno ("Non-regular file", file,
2104 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
2107 #ifndef MSDOS
2108 int new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0600 : 0666);
2109 #else
2110 int new_mask = S_IREAD | S_IWRITE;
2111 #endif
2112 ofd = emacs_open (SSDATA (encoded_newname),
2113 (O_WRONLY | O_TRUNC | O_CREAT
2114 | (NILP (ok_if_already_exists) ? O_EXCL : 0)),
2115 new_mask);
2117 if (ofd < 0)
2118 report_file_error ("Opening output file", newname);
2120 record_unwind_protect_int (close_file_unwind, ofd);
2122 immediate_quit = 1;
2123 QUIT;
2124 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2125 if (emacs_write_sig (ofd, buf, n) != n)
2126 report_file_error ("Write error", newname);
2127 immediate_quit = 0;
2129 #ifndef MSDOS
2130 /* Preserve the original file permissions, and if requested, also its
2131 owner and group. */
2133 mode_t mode_mask = 07777;
2134 if (!NILP (preserve_uid_gid))
2136 /* Attempt to change owner and group. If that doesn't work
2137 attempt to change just the group, as that is sometimes allowed.
2138 Adjust the mode mask to eliminate setuid or setgid bits
2139 that are inappropriate if the owner and group are wrong. */
2140 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2142 mode_mask &= ~06000;
2143 if (fchown (ofd, -1, st.st_gid) == 0)
2144 mode_mask |= 02000;
2148 switch (!NILP (preserve_extended_attributes)
2149 ? qcopy_acl (SSDATA (encoded_file), ifd,
2150 SSDATA (encoded_newname), ofd,
2151 st.st_mode & mode_mask)
2152 : fchmod (ofd, st.st_mode & mode_mask))
2154 case -2: report_file_error ("Copying permissions from", file);
2155 case -1: report_file_error ("Copying permissions to", newname);
2158 #endif /* not MSDOS */
2160 #if HAVE_LIBSELINUX
2161 if (conlength > 0)
2163 /* Set the modified context back to the file. */
2164 bool fail = fsetfilecon (ofd, con) != 0;
2165 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2166 if (fail && errno != ENOTSUP)
2167 report_file_error ("Doing fsetfilecon", newname);
2169 freecon (con);
2171 #endif
2173 if (!NILP (keep_time))
2175 EMACS_TIME atime = get_stat_atime (&st);
2176 EMACS_TIME mtime = get_stat_mtime (&st);
2177 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime))
2178 xsignal2 (Qfile_date_error,
2179 build_string ("Cannot set file date"), newname);
2182 if (emacs_close (ofd) < 0)
2183 report_file_error ("Write error", newname);
2185 emacs_close (ifd);
2187 #ifdef MSDOS
2188 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2189 and if it can't, it tells so. Otherwise, under MSDOS we usually
2190 get only the READ bit, which will make the copied file read-only,
2191 so it's better not to chmod at all. */
2192 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2193 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2194 #endif /* MSDOS */
2195 #endif /* not WINDOWSNT */
2197 /* Discard the unwind protects. */
2198 specpdl_ptr = specpdl + count;
2200 UNGCPRO;
2201 return Qnil;
2204 DEFUN ("make-directory-internal", Fmake_directory_internal,
2205 Smake_directory_internal, 1, 1, 0,
2206 doc: /* Create a new directory named DIRECTORY. */)
2207 (Lisp_Object directory)
2209 const char *dir;
2210 Lisp_Object handler;
2211 Lisp_Object encoded_dir;
2213 CHECK_STRING (directory);
2214 directory = Fexpand_file_name (directory, Qnil);
2216 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2217 if (!NILP (handler))
2218 return call2 (handler, Qmake_directory_internal, directory);
2220 encoded_dir = ENCODE_FILE (directory);
2222 dir = SSDATA (encoded_dir);
2224 #ifdef WINDOWSNT
2225 if (mkdir (dir) != 0)
2226 #else
2227 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2228 #endif
2229 report_file_error ("Creating directory", directory);
2231 return Qnil;
2234 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2235 Sdelete_directory_internal, 1, 1, 0,
2236 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2237 (Lisp_Object directory)
2239 const char *dir;
2240 Lisp_Object encoded_dir;
2242 CHECK_STRING (directory);
2243 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2244 encoded_dir = ENCODE_FILE (directory);
2245 dir = SSDATA (encoded_dir);
2247 if (rmdir (dir) != 0)
2248 report_file_error ("Removing directory", directory);
2250 return Qnil;
2253 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2254 "(list (read-file-name \
2255 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2256 \"Move file to trash: \" \"Delete file: \") \
2257 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2258 (null current-prefix-arg))",
2259 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2260 If file has multiple names, it continues to exist with the other names.
2261 TRASH non-nil means to trash the file instead of deleting, provided
2262 `delete-by-moving-to-trash' is non-nil.
2264 When called interactively, TRASH is t if no prefix argument is given.
2265 With a prefix argument, TRASH is nil. */)
2266 (Lisp_Object filename, Lisp_Object trash)
2268 Lisp_Object handler;
2269 Lisp_Object encoded_file;
2270 struct gcpro gcpro1;
2272 GCPRO1 (filename);
2273 if (!NILP (Ffile_directory_p (filename))
2274 && NILP (Ffile_symlink_p (filename)))
2275 xsignal2 (Qfile_error,
2276 build_string ("Removing old name: is a directory"),
2277 filename);
2278 UNGCPRO;
2279 filename = Fexpand_file_name (filename, Qnil);
2281 handler = Ffind_file_name_handler (filename, Qdelete_file);
2282 if (!NILP (handler))
2283 return call3 (handler, Qdelete_file, filename, trash);
2285 if (delete_by_moving_to_trash && !NILP (trash))
2286 return call1 (Qmove_file_to_trash, filename);
2288 encoded_file = ENCODE_FILE (filename);
2290 if (unlink (SSDATA (encoded_file)) < 0)
2291 report_file_error ("Removing old name", filename);
2292 return Qnil;
2295 static Lisp_Object
2296 internal_delete_file_1 (Lisp_Object ignore)
2298 return Qt;
2301 /* Delete file FILENAME, returning true if successful.
2302 This ignores `delete-by-moving-to-trash'. */
2304 bool
2305 internal_delete_file (Lisp_Object filename)
2307 Lisp_Object tem;
2309 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2310 Qt, internal_delete_file_1);
2311 return NILP (tem);
2314 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2315 "fRename file: \nGRename %s to file: \np",
2316 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2317 If file has names other than FILE, it continues to have those names.
2318 Signals a `file-already-exists' error if a file NEWNAME already exists
2319 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2320 A number as third arg means request confirmation if NEWNAME already exists.
2321 This is what happens in interactive use with M-x. */)
2322 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2324 Lisp_Object handler;
2325 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2326 Lisp_Object encoded_file, encoded_newname, symlink_target;
2328 symlink_target = encoded_file = encoded_newname = Qnil;
2329 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2330 CHECK_STRING (file);
2331 CHECK_STRING (newname);
2332 file = Fexpand_file_name (file, Qnil);
2334 if ((!NILP (Ffile_directory_p (newname)))
2335 #ifdef DOS_NT
2336 /* If the file names are identical but for the case,
2337 don't attempt to move directory to itself. */
2338 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2339 #endif
2342 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2343 ? file : Fdirectory_file_name (file));
2344 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2346 else
2347 newname = Fexpand_file_name (newname, Qnil);
2349 /* If the file name has special constructs in it,
2350 call the corresponding file handler. */
2351 handler = Ffind_file_name_handler (file, Qrename_file);
2352 if (NILP (handler))
2353 handler = Ffind_file_name_handler (newname, Qrename_file);
2354 if (!NILP (handler))
2355 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2356 file, newname, ok_if_already_exists));
2358 encoded_file = ENCODE_FILE (file);
2359 encoded_newname = ENCODE_FILE (newname);
2361 #ifdef DOS_NT
2362 /* If the file names are identical but for the case, don't ask for
2363 confirmation: they simply want to change the letter-case of the
2364 file name. */
2365 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2366 #endif
2367 if (NILP (ok_if_already_exists)
2368 || INTEGERP (ok_if_already_exists))
2369 barf_or_query_if_file_exists (newname, "rename to it",
2370 INTEGERP (ok_if_already_exists), 0, 0);
2371 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2373 if (errno == EXDEV)
2375 ptrdiff_t count;
2376 symlink_target = Ffile_symlink_p (file);
2377 if (! NILP (symlink_target))
2378 Fmake_symbolic_link (symlink_target, newname,
2379 NILP (ok_if_already_exists) ? Qnil : Qt);
2380 else if (!NILP (Ffile_directory_p (file)))
2381 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2382 else
2383 /* We have already prompted if it was an integer, so don't
2384 have copy-file prompt again. */
2385 Fcopy_file (file, newname,
2386 NILP (ok_if_already_exists) ? Qnil : Qt,
2387 Qt, Qt, Qt);
2389 count = SPECPDL_INDEX ();
2390 specbind (Qdelete_by_moving_to_trash, Qnil);
2392 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2393 call2 (Qdelete_directory, file, Qt);
2394 else
2395 Fdelete_file (file, Qnil);
2396 unbind_to (count, Qnil);
2398 else
2399 report_file_error ("Renaming", list2 (file, newname));
2401 UNGCPRO;
2402 return Qnil;
2405 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2406 "fAdd name to file: \nGName to add to %s: \np",
2407 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2408 Signals a `file-already-exists' error if a file NEWNAME already exists
2409 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2410 A number as third arg means request confirmation if NEWNAME already exists.
2411 This is what happens in interactive use with M-x. */)
2412 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2414 Lisp_Object handler;
2415 Lisp_Object encoded_file, encoded_newname;
2416 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2418 GCPRO4 (file, newname, encoded_file, encoded_newname);
2419 encoded_file = encoded_newname = Qnil;
2420 CHECK_STRING (file);
2421 CHECK_STRING (newname);
2422 file = Fexpand_file_name (file, Qnil);
2424 if (!NILP (Ffile_directory_p (newname)))
2425 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2426 else
2427 newname = Fexpand_file_name (newname, Qnil);
2429 /* If the file name has special constructs in it,
2430 call the corresponding file handler. */
2431 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2432 if (!NILP (handler))
2433 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2434 newname, ok_if_already_exists));
2436 /* If the new name has special constructs in it,
2437 call the corresponding file handler. */
2438 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2439 if (!NILP (handler))
2440 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2441 newname, ok_if_already_exists));
2443 encoded_file = ENCODE_FILE (file);
2444 encoded_newname = ENCODE_FILE (newname);
2446 if (NILP (ok_if_already_exists)
2447 || INTEGERP (ok_if_already_exists))
2448 barf_or_query_if_file_exists (newname, "make it a new name",
2449 INTEGERP (ok_if_already_exists), 0, 0);
2451 unlink (SSDATA (newname));
2452 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2453 report_file_error ("Adding new name", list2 (file, newname));
2455 UNGCPRO;
2456 return Qnil;
2459 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2460 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2461 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2462 Both args must be strings.
2463 Signals a `file-already-exists' error if a file LINKNAME already exists
2464 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2465 A number as third arg means request confirmation if LINKNAME already exists.
2466 This happens for interactive use with M-x. */)
2467 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2469 Lisp_Object handler;
2470 Lisp_Object encoded_filename, encoded_linkname;
2471 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2473 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2474 encoded_filename = encoded_linkname = Qnil;
2475 CHECK_STRING (filename);
2476 CHECK_STRING (linkname);
2477 /* If the link target has a ~, we must expand it to get
2478 a truly valid file name. Otherwise, do not expand;
2479 we want to permit links to relative file names. */
2480 if (SREF (filename, 0) == '~')
2481 filename = Fexpand_file_name (filename, Qnil);
2483 if (!NILP (Ffile_directory_p (linkname)))
2484 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2485 else
2486 linkname = Fexpand_file_name (linkname, Qnil);
2488 /* If the file name has special constructs in it,
2489 call the corresponding file handler. */
2490 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2491 if (!NILP (handler))
2492 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2493 linkname, ok_if_already_exists));
2495 /* If the new link name has special constructs in it,
2496 call the corresponding file handler. */
2497 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2498 if (!NILP (handler))
2499 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2500 linkname, ok_if_already_exists));
2502 encoded_filename = ENCODE_FILE (filename);
2503 encoded_linkname = ENCODE_FILE (linkname);
2505 if (NILP (ok_if_already_exists)
2506 || INTEGERP (ok_if_already_exists))
2507 barf_or_query_if_file_exists (linkname, "make it a link",
2508 INTEGERP (ok_if_already_exists), 0, 0);
2509 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname)) < 0)
2511 /* If we didn't complain already, silently delete existing file. */
2512 if (errno == EEXIST)
2514 unlink (SSDATA (encoded_linkname));
2515 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname))
2516 >= 0)
2518 UNGCPRO;
2519 return Qnil;
2522 if (errno == ENOSYS)
2524 UNGCPRO;
2525 xsignal1 (Qfile_error,
2526 build_string ("Symbolic links are not supported"));
2529 report_file_error ("Making symbolic link", list2 (filename, linkname));
2531 UNGCPRO;
2532 return Qnil;
2536 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2537 1, 1, 0,
2538 doc: /* Return t if file FILENAME specifies an absolute file name.
2539 On Unix, this is a name starting with a `/' or a `~'. */)
2540 (Lisp_Object filename)
2542 CHECK_STRING (filename);
2543 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2546 /* Return true if FILENAME exists. */
2547 bool
2548 check_existing (const char *filename)
2550 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
2553 /* Return true if file FILENAME exists and can be executed. */
2555 static bool
2556 check_executable (char *filename)
2558 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
2561 /* Return true if file FILENAME exists and can be accessed
2562 according to AMODE, which should include W_OK.
2563 On failure, return false and set errno. */
2565 static bool
2566 check_writable (const char *filename, int amode)
2568 #ifdef MSDOS
2569 /* FIXME: an faccessat implementation should be added to the
2570 DOS/Windows ports and this #ifdef branch should be removed. */
2571 struct stat st;
2572 if (stat (filename, &st) < 0)
2573 return 0;
2574 errno = EPERM;
2575 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
2576 #else /* not MSDOS */
2577 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
2578 #ifdef CYGWIN
2579 /* faccessat may have returned failure because Cygwin couldn't
2580 determine the file's UID or GID; if so, we return success. */
2581 if (!res)
2583 int faccessat_errno = errno;
2584 struct stat st;
2585 if (stat (filename, &st) < 0)
2586 return 0;
2587 res = (st.st_uid == -1 || st.st_gid == -1);
2588 errno = faccessat_errno;
2590 #endif /* CYGWIN */
2591 return res;
2592 #endif /* not MSDOS */
2595 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2596 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2597 See also `file-readable-p' and `file-attributes'.
2598 This returns nil for a symlink to a nonexistent file.
2599 Use `file-symlink-p' to test for such links. */)
2600 (Lisp_Object filename)
2602 Lisp_Object absname;
2603 Lisp_Object handler;
2605 CHECK_STRING (filename);
2606 absname = Fexpand_file_name (filename, Qnil);
2608 /* If the file name has special constructs in it,
2609 call the corresponding file handler. */
2610 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2611 if (!NILP (handler))
2613 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2614 errno = 0;
2615 return result;
2618 absname = ENCODE_FILE (absname);
2620 return (check_existing (SSDATA (absname))) ? Qt : Qnil;
2623 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2624 doc: /* Return t if FILENAME can be executed by you.
2625 For a directory, this means you can access files in that directory. */)
2626 (Lisp_Object filename)
2628 Lisp_Object absname;
2629 Lisp_Object handler;
2631 CHECK_STRING (filename);
2632 absname = Fexpand_file_name (filename, Qnil);
2634 /* If the file name has special constructs in it,
2635 call the corresponding file handler. */
2636 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2637 if (!NILP (handler))
2638 return call2 (handler, Qfile_executable_p, absname);
2640 absname = ENCODE_FILE (absname);
2642 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2645 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2646 doc: /* Return t if file FILENAME exists and you can read it.
2647 See also `file-exists-p' and `file-attributes'. */)
2648 (Lisp_Object filename)
2650 Lisp_Object absname;
2651 Lisp_Object handler;
2653 CHECK_STRING (filename);
2654 absname = Fexpand_file_name (filename, Qnil);
2656 /* If the file name has special constructs in it,
2657 call the corresponding file handler. */
2658 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2659 if (!NILP (handler))
2660 return call2 (handler, Qfile_readable_p, absname);
2662 absname = ENCODE_FILE (absname);
2663 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2664 ? Qt : Qnil);
2667 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2668 doc: /* Return t if file FILENAME can be written or created by you. */)
2669 (Lisp_Object filename)
2671 Lisp_Object absname, dir, encoded;
2672 Lisp_Object handler;
2674 CHECK_STRING (filename);
2675 absname = Fexpand_file_name (filename, Qnil);
2677 /* If the file name has special constructs in it,
2678 call the corresponding file handler. */
2679 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2680 if (!NILP (handler))
2681 return call2 (handler, Qfile_writable_p, absname);
2683 encoded = ENCODE_FILE (absname);
2684 if (check_writable (SSDATA (encoded), W_OK))
2685 return Qt;
2686 if (errno != ENOENT)
2687 return Qnil;
2689 dir = Ffile_name_directory (absname);
2690 eassert (!NILP (dir));
2691 #ifdef MSDOS
2692 dir = Fdirectory_file_name (dir);
2693 #endif /* MSDOS */
2695 dir = ENCODE_FILE (dir);
2696 #ifdef WINDOWSNT
2697 /* The read-only attribute of the parent directory doesn't affect
2698 whether a file or directory can be created within it. Some day we
2699 should check ACLs though, which do affect this. */
2700 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2701 #else
2702 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2703 #endif
2706 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2707 doc: /* Access file FILENAME, and get an error if that does not work.
2708 The second argument STRING is used in the error message.
2709 If there is no error, returns nil. */)
2710 (Lisp_Object filename, Lisp_Object string)
2712 Lisp_Object handler, encoded_filename, absname;
2714 CHECK_STRING (filename);
2715 absname = Fexpand_file_name (filename, Qnil);
2717 CHECK_STRING (string);
2719 /* If the file name has special constructs in it,
2720 call the corresponding file handler. */
2721 handler = Ffind_file_name_handler (absname, Qaccess_file);
2722 if (!NILP (handler))
2723 return call3 (handler, Qaccess_file, absname, string);
2725 encoded_filename = ENCODE_FILE (absname);
2727 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2728 report_file_error (SSDATA (string), filename);
2730 return Qnil;
2733 /* Relative to directory FD, return the symbolic link value of FILENAME.
2734 On failure, return nil. */
2735 Lisp_Object
2736 emacs_readlinkat (int fd, char const *filename)
2738 static struct allocator const emacs_norealloc_allocator =
2739 { xmalloc, NULL, xfree, memory_full };
2740 Lisp_Object val;
2741 char readlink_buf[1024];
2742 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2743 &emacs_norealloc_allocator, readlinkat);
2744 if (!buf)
2745 return Qnil;
2747 val = build_string (buf);
2748 if (buf[0] == '/' && strchr (buf, ':'))
2749 val = concat2 (build_string ("/:"), val);
2750 if (buf != readlink_buf)
2751 xfree (buf);
2752 val = DECODE_FILE (val);
2753 return val;
2756 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2757 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2758 The value is the link target, as a string.
2759 Otherwise it returns nil.
2761 This function returns t when given the name of a symlink that
2762 points to a nonexistent file. */)
2763 (Lisp_Object filename)
2765 Lisp_Object handler;
2767 CHECK_STRING (filename);
2768 filename = Fexpand_file_name (filename, Qnil);
2770 /* If the file name has special constructs in it,
2771 call the corresponding file handler. */
2772 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2773 if (!NILP (handler))
2774 return call2 (handler, Qfile_symlink_p, filename);
2776 filename = ENCODE_FILE (filename);
2778 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2781 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2782 doc: /* Return t if FILENAME names an existing directory.
2783 Symbolic links to directories count as directories.
2784 See `file-symlink-p' to distinguish symlinks. */)
2785 (Lisp_Object filename)
2787 Lisp_Object absname;
2788 Lisp_Object handler;
2790 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2792 /* If the file name has special constructs in it,
2793 call the corresponding file handler. */
2794 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2795 if (!NILP (handler))
2796 return call2 (handler, Qfile_directory_p, absname);
2798 absname = ENCODE_FILE (absname);
2800 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2803 /* Return true if FILE is a directory or a symlink to a directory. */
2804 bool
2805 file_directory_p (char const *file)
2807 #ifdef WINDOWSNT
2808 /* This is cheaper than 'stat'. */
2809 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2810 #else
2811 struct stat st;
2812 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2813 #endif
2816 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2817 Sfile_accessible_directory_p, 1, 1, 0,
2818 doc: /* Return t if file FILENAME names a directory you can open.
2819 For the value to be t, FILENAME must specify the name of a directory as a file,
2820 and the directory must allow you to open files in it. In order to use a
2821 directory as a buffer's current directory, this predicate must return true.
2822 A directory name spec may be given instead; then the value is t
2823 if the directory so specified exists and really is a readable and
2824 searchable directory. */)
2825 (Lisp_Object filename)
2827 Lisp_Object absname;
2828 Lisp_Object handler;
2830 CHECK_STRING (filename);
2831 absname = Fexpand_file_name (filename, Qnil);
2833 /* If the file name has special constructs in it,
2834 call the corresponding file handler. */
2835 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2836 if (!NILP (handler))
2838 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2839 errno = 0;
2840 return r;
2843 absname = ENCODE_FILE (absname);
2844 return file_accessible_directory_p (SSDATA (absname)) ? Qt : Qnil;
2847 /* If FILE is a searchable directory or a symlink to a
2848 searchable directory, return true. Otherwise return
2849 false and set errno to an error number. */
2850 bool
2851 file_accessible_directory_p (char const *file)
2853 #ifdef DOS_NT
2854 /* There's no need to test whether FILE is searchable, as the
2855 searchable/executable bit is invented on DOS_NT platforms. */
2856 return file_directory_p (file);
2857 #else
2858 /* On POSIXish platforms, use just one system call; this avoids a
2859 race and is typically faster. */
2860 ptrdiff_t len = strlen (file);
2861 char const *dir;
2862 bool ok;
2863 int saved_errno;
2864 USE_SAFE_ALLOCA;
2866 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2867 There are three exceptions: "", "/", and "//". Leave "" alone,
2868 as it's invalid. Append only "." to the other two exceptions as
2869 "/" and "//" are distinct on some platforms, whereas "/", "///",
2870 "////", etc. are all equivalent. */
2871 if (! len)
2872 dir = file;
2873 else
2875 /* Just check for trailing '/' when deciding whether to append '/'.
2876 That's simpler than testing the two special cases "/" and "//",
2877 and it's a safe optimization here. */
2878 char *buf = SAFE_ALLOCA (len + 3);
2879 memcpy (buf, file, len);
2880 strcpy (buf + len, &"/."[file[len - 1] == '/']);
2881 dir = buf;
2884 ok = check_existing (dir);
2885 saved_errno = errno;
2886 SAFE_FREE ();
2887 errno = saved_errno;
2888 return ok;
2889 #endif
2892 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2893 doc: /* Return t if FILENAME names a regular file.
2894 This is the sort of file that holds an ordinary stream of data bytes.
2895 Symbolic links to regular files count as regular files.
2896 See `file-symlink-p' to distinguish symlinks. */)
2897 (Lisp_Object filename)
2899 register Lisp_Object absname;
2900 struct stat st;
2901 Lisp_Object handler;
2903 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2905 /* If the file name has special constructs in it,
2906 call the corresponding file handler. */
2907 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2908 if (!NILP (handler))
2909 return call2 (handler, Qfile_regular_p, absname);
2911 absname = ENCODE_FILE (absname);
2913 #ifdef WINDOWSNT
2915 int result;
2916 Lisp_Object tem = Vw32_get_true_file_attributes;
2918 /* Tell stat to use expensive method to get accurate info. */
2919 Vw32_get_true_file_attributes = Qt;
2920 result = stat (SDATA (absname), &st);
2921 Vw32_get_true_file_attributes = tem;
2923 if (result < 0)
2924 return Qnil;
2925 return S_ISREG (st.st_mode) ? Qt : Qnil;
2927 #else
2928 if (stat (SSDATA (absname), &st) < 0)
2929 return Qnil;
2930 return S_ISREG (st.st_mode) ? Qt : Qnil;
2931 #endif
2934 DEFUN ("file-selinux-context", Ffile_selinux_context,
2935 Sfile_selinux_context, 1, 1, 0,
2936 doc: /* Return SELinux context of file named FILENAME.
2937 The return value is a list (USER ROLE TYPE RANGE), where the list
2938 elements are strings naming the user, role, type, and range of the
2939 file's SELinux security context.
2941 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2942 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2943 (Lisp_Object filename)
2945 Lisp_Object absname;
2946 Lisp_Object values[4];
2947 Lisp_Object handler;
2948 #if HAVE_LIBSELINUX
2949 security_context_t con;
2950 int conlength;
2951 context_t context;
2952 #endif
2954 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2956 /* If the file name has special constructs in it,
2957 call the corresponding file handler. */
2958 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2959 if (!NILP (handler))
2960 return call2 (handler, Qfile_selinux_context, absname);
2962 absname = ENCODE_FILE (absname);
2964 values[0] = Qnil;
2965 values[1] = Qnil;
2966 values[2] = Qnil;
2967 values[3] = Qnil;
2968 #if HAVE_LIBSELINUX
2969 if (is_selinux_enabled ())
2971 conlength = lgetfilecon (SSDATA (absname), &con);
2972 if (conlength > 0)
2974 context = context_new (con);
2975 if (context_user_get (context))
2976 values[0] = build_string (context_user_get (context));
2977 if (context_role_get (context))
2978 values[1] = build_string (context_role_get (context));
2979 if (context_type_get (context))
2980 values[2] = build_string (context_type_get (context));
2981 if (context_range_get (context))
2982 values[3] = build_string (context_range_get (context));
2983 context_free (context);
2984 freecon (con);
2987 #endif
2989 return Flist (sizeof (values) / sizeof (values[0]), values);
2992 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2993 Sset_file_selinux_context, 2, 2, 0,
2994 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2995 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2996 elements are strings naming the components of a SELinux context.
2998 Value is t if setting of SELinux context was successful, nil otherwise.
3000 This function does nothing and returns nil if SELinux is disabled,
3001 or if Emacs was not compiled with SELinux support. */)
3002 (Lisp_Object filename, Lisp_Object context)
3004 Lisp_Object absname;
3005 Lisp_Object handler;
3006 #if HAVE_LIBSELINUX
3007 Lisp_Object encoded_absname;
3008 Lisp_Object user = CAR_SAFE (context);
3009 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
3010 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
3011 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
3012 security_context_t con;
3013 bool fail;
3014 int conlength;
3015 context_t parsed_con;
3016 #endif
3018 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3020 /* If the file name has special constructs in it,
3021 call the corresponding file handler. */
3022 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
3023 if (!NILP (handler))
3024 return call3 (handler, Qset_file_selinux_context, absname, context);
3026 #if HAVE_LIBSELINUX
3027 if (is_selinux_enabled ())
3029 /* Get current file context. */
3030 encoded_absname = ENCODE_FILE (absname);
3031 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
3032 if (conlength > 0)
3034 parsed_con = context_new (con);
3035 /* Change the parts defined in the parameter.*/
3036 if (STRINGP (user))
3038 if (context_user_set (parsed_con, SSDATA (user)))
3039 error ("Doing context_user_set");
3041 if (STRINGP (role))
3043 if (context_role_set (parsed_con, SSDATA (role)))
3044 error ("Doing context_role_set");
3046 if (STRINGP (type))
3048 if (context_type_set (parsed_con, SSDATA (type)))
3049 error ("Doing context_type_set");
3051 if (STRINGP (range))
3053 if (context_range_set (parsed_con, SSDATA (range)))
3054 error ("Doing context_range_set");
3057 /* Set the modified context back to the file. */
3058 fail = (lsetfilecon (SSDATA (encoded_absname),
3059 context_str (parsed_con))
3060 != 0);
3061 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
3062 if (fail && errno != ENOTSUP)
3063 report_file_error ("Doing lsetfilecon", absname);
3065 context_free (parsed_con);
3066 freecon (con);
3067 return fail ? Qnil : Qt;
3069 else
3070 report_file_error ("Doing lgetfilecon", absname);
3072 #endif
3074 return Qnil;
3077 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
3078 doc: /* Return ACL entries of file named FILENAME.
3079 The entries are returned in a format suitable for use in `set-file-acl'
3080 but is otherwise undocumented and subject to change.
3081 Return nil if file does not exist or is not accessible, or if Emacs
3082 was unable to determine the ACL entries. */)
3083 (Lisp_Object filename)
3085 Lisp_Object absname;
3086 Lisp_Object handler;
3087 #ifdef HAVE_ACL_SET_FILE
3088 acl_t acl;
3089 Lisp_Object acl_string;
3090 char *str;
3091 #endif
3093 absname = expand_and_dir_to_file (filename,
3094 BVAR (current_buffer, directory));
3096 /* If the file name has special constructs in it,
3097 call the corresponding file handler. */
3098 handler = Ffind_file_name_handler (absname, Qfile_acl);
3099 if (!NILP (handler))
3100 return call2 (handler, Qfile_acl, absname);
3102 #ifdef HAVE_ACL_SET_FILE
3103 absname = ENCODE_FILE (absname);
3105 acl = acl_get_file (SSDATA (absname), ACL_TYPE_ACCESS);
3106 if (acl == NULL)
3107 return Qnil;
3109 str = acl_to_text (acl, NULL);
3110 if (str == NULL)
3112 acl_free (acl);
3113 return Qnil;
3116 acl_string = build_string (str);
3117 acl_free (str);
3118 acl_free (acl);
3120 return acl_string;
3121 #endif
3123 return Qnil;
3126 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3127 2, 2, 0,
3128 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3129 ACL-STRING should contain the textual representation of the ACL
3130 entries in a format suitable for the platform.
3132 Value is t if setting of ACL was successful, nil otherwise.
3134 Setting ACL for local files requires Emacs to be built with ACL
3135 support. */)
3136 (Lisp_Object filename, Lisp_Object acl_string)
3138 Lisp_Object absname;
3139 Lisp_Object handler;
3140 #ifdef HAVE_ACL_SET_FILE
3141 Lisp_Object encoded_absname;
3142 acl_t acl;
3143 bool fail;
3144 #endif
3146 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3148 /* If the file name has special constructs in it,
3149 call the corresponding file handler. */
3150 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3151 if (!NILP (handler))
3152 return call3 (handler, Qset_file_acl, absname, acl_string);
3154 #ifdef HAVE_ACL_SET_FILE
3155 if (STRINGP (acl_string))
3157 acl = acl_from_text (SSDATA (acl_string));
3158 if (acl == NULL)
3160 report_file_error ("Converting ACL", absname);
3161 return Qnil;
3164 encoded_absname = ENCODE_FILE (absname);
3166 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3167 acl)
3168 != 0);
3169 if (fail && acl_errno_valid (errno))
3170 report_file_error ("Setting ACL", absname);
3172 acl_free (acl);
3173 return fail ? Qnil : Qt;
3175 #endif
3177 return Qnil;
3180 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3181 doc: /* Return mode bits of file named FILENAME, as an integer.
3182 Return nil, if file does not exist or is not accessible. */)
3183 (Lisp_Object filename)
3185 Lisp_Object absname;
3186 struct stat st;
3187 Lisp_Object handler;
3189 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3191 /* If the file name has special constructs in it,
3192 call the corresponding file handler. */
3193 handler = Ffind_file_name_handler (absname, Qfile_modes);
3194 if (!NILP (handler))
3195 return call2 (handler, Qfile_modes, absname);
3197 absname = ENCODE_FILE (absname);
3199 if (stat (SSDATA (absname), &st) < 0)
3200 return Qnil;
3202 return make_number (st.st_mode & 07777);
3205 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3206 "(let ((file (read-file-name \"File: \"))) \
3207 (list file (read-file-modes nil file)))",
3208 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3209 Only the 12 low bits of MODE are used.
3211 Interactively, mode bits are read by `read-file-modes', which accepts
3212 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3213 (Lisp_Object filename, Lisp_Object mode)
3215 Lisp_Object absname, encoded_absname;
3216 Lisp_Object handler;
3218 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3219 CHECK_NUMBER (mode);
3221 /* If the file name has special constructs in it,
3222 call the corresponding file handler. */
3223 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3224 if (!NILP (handler))
3225 return call3 (handler, Qset_file_modes, absname, mode);
3227 encoded_absname = ENCODE_FILE (absname);
3229 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3230 report_file_error ("Doing chmod", absname);
3232 return Qnil;
3235 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3236 doc: /* Set the file permission bits for newly created files.
3237 The argument MODE should be an integer; only the low 9 bits are used.
3238 This setting is inherited by subprocesses. */)
3239 (Lisp_Object mode)
3241 CHECK_NUMBER (mode);
3243 umask ((~ XINT (mode)) & 0777);
3245 return Qnil;
3248 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3249 doc: /* Return the default file protection for created files.
3250 The value is an integer. */)
3251 (void)
3253 mode_t realmask;
3254 Lisp_Object value;
3256 block_input ();
3257 realmask = umask (0);
3258 umask (realmask);
3259 unblock_input ();
3261 XSETINT (value, (~ realmask) & 0777);
3262 return value;
3266 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3267 doc: /* Set times of file FILENAME to TIMESTAMP.
3268 Set both access and modification times.
3269 Return t on success, else nil.
3270 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3271 `current-time'. */)
3272 (Lisp_Object filename, Lisp_Object timestamp)
3274 Lisp_Object absname, encoded_absname;
3275 Lisp_Object handler;
3276 EMACS_TIME t = lisp_time_argument (timestamp);
3278 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3280 /* If the file name has special constructs in it,
3281 call the corresponding file handler. */
3282 handler = Ffind_file_name_handler (absname, Qset_file_times);
3283 if (!NILP (handler))
3284 return call3 (handler, Qset_file_times, absname, timestamp);
3286 encoded_absname = ENCODE_FILE (absname);
3289 if (set_file_times (-1, SSDATA (encoded_absname), t, t))
3291 #ifdef MSDOS
3292 /* Setting times on a directory always fails. */
3293 if (file_directory_p (SSDATA (encoded_absname)))
3294 return Qnil;
3295 #endif
3296 report_file_error ("Setting file times", absname);
3300 return Qt;
3303 #ifdef HAVE_SYNC
3304 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3305 doc: /* Tell Unix to finish all pending disk updates. */)
3306 (void)
3308 sync ();
3309 return Qnil;
3312 #endif /* HAVE_SYNC */
3314 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3315 doc: /* Return t if file FILE1 is newer than file FILE2.
3316 If FILE1 does not exist, the answer is nil;
3317 otherwise, if FILE2 does not exist, the answer is t. */)
3318 (Lisp_Object file1, Lisp_Object file2)
3320 Lisp_Object absname1, absname2;
3321 struct stat st1, st2;
3322 Lisp_Object handler;
3323 struct gcpro gcpro1, gcpro2;
3325 CHECK_STRING (file1);
3326 CHECK_STRING (file2);
3328 absname1 = Qnil;
3329 GCPRO2 (absname1, file2);
3330 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3331 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3332 UNGCPRO;
3334 /* If the file name has special constructs in it,
3335 call the corresponding file handler. */
3336 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3337 if (NILP (handler))
3338 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3339 if (!NILP (handler))
3340 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3342 GCPRO2 (absname1, absname2);
3343 absname1 = ENCODE_FILE (absname1);
3344 absname2 = ENCODE_FILE (absname2);
3345 UNGCPRO;
3347 if (stat (SSDATA (absname1), &st1) < 0)
3348 return Qnil;
3350 if (stat (SSDATA (absname2), &st2) < 0)
3351 return Qt;
3353 return (EMACS_TIME_LT (get_stat_mtime (&st2), get_stat_mtime (&st1))
3354 ? Qt : Qnil);
3357 #ifndef READ_BUF_SIZE
3358 #define READ_BUF_SIZE (64 << 10)
3359 #endif
3360 /* Some buffer offsets are stored in 'int' variables. */
3361 verify (READ_BUF_SIZE <= INT_MAX);
3363 /* This function is called after Lisp functions to decide a coding
3364 system are called, or when they cause an error. Before they are
3365 called, the current buffer is set unibyte and it contains only a
3366 newly inserted text (thus the buffer was empty before the
3367 insertion).
3369 The functions may set markers, overlays, text properties, or even
3370 alter the buffer contents, change the current buffer.
3372 Here, we reset all those changes by:
3373 o set back the current buffer.
3374 o move all markers and overlays to BEG.
3375 o remove all text properties.
3376 o set back the buffer multibyteness. */
3378 static void
3379 decide_coding_unwind (Lisp_Object unwind_data)
3381 Lisp_Object multibyte, undo_list, buffer;
3383 multibyte = XCAR (unwind_data);
3384 unwind_data = XCDR (unwind_data);
3385 undo_list = XCAR (unwind_data);
3386 buffer = XCDR (unwind_data);
3388 set_buffer_internal (XBUFFER (buffer));
3389 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3390 adjust_overlays_for_delete (BEG, Z - BEG);
3391 set_buffer_intervals (current_buffer, NULL);
3392 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3394 /* Now we are safe to change the buffer's multibyteness directly. */
3395 bset_enable_multibyte_characters (current_buffer, multibyte);
3396 bset_undo_list (current_buffer, undo_list);
3399 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3400 object where slot 0 is the file descriptor, slot 1 specifies
3401 an offset to put the read bytes, and slot 2 is the maximum
3402 amount of bytes to read. Value is the number of bytes read. */
3404 static Lisp_Object
3405 read_non_regular (Lisp_Object state)
3407 int nbytes;
3409 immediate_quit = 1;
3410 QUIT;
3411 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3412 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3413 + XSAVE_INTEGER (state, 1)),
3414 XSAVE_INTEGER (state, 2));
3415 immediate_quit = 0;
3416 /* Fast recycle this object for the likely next call. */
3417 free_misc (state);
3418 return make_number (nbytes);
3422 /* Condition-case handler used when reading from non-regular files
3423 in insert-file-contents. */
3425 static Lisp_Object
3426 read_non_regular_quit (Lisp_Object ignore)
3428 return Qnil;
3431 /* Return the file offset that VAL represents, checking for type
3432 errors and overflow. */
3433 static off_t
3434 file_offset (Lisp_Object val)
3436 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3437 return XINT (val);
3439 if (FLOATP (val))
3441 double v = XFLOAT_DATA (val);
3442 if (0 <= v
3443 && (sizeof (off_t) < sizeof v
3444 ? v <= TYPE_MAXIMUM (off_t)
3445 : v < TYPE_MAXIMUM (off_t)))
3446 return v;
3449 wrong_type_argument (intern ("file-offset"), val);
3452 /* Return a special time value indicating the error number ERRNUM. */
3453 static EMACS_TIME
3454 time_error_value (int errnum)
3456 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3457 ? NONEXISTENT_MODTIME_NSECS
3458 : UNKNOWN_MODTIME_NSECS);
3459 return make_emacs_time (0, ns);
3462 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3463 1, 5, 0,
3464 doc: /* Insert contents of file FILENAME after point.
3465 Returns list of absolute file name and number of characters inserted.
3466 If second argument VISIT is non-nil, the buffer's visited filename and
3467 last save file modtime are set, and it is marked unmodified. If
3468 visiting and the file does not exist, visiting is completed before the
3469 error is signaled.
3471 The optional third and fourth arguments BEG and END specify what portion
3472 of the file to insert. These arguments count bytes in the file, not
3473 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3475 If optional fifth argument REPLACE is non-nil, replace the current
3476 buffer contents (in the accessible portion) with the file contents.
3477 This is better than simply deleting and inserting the whole thing
3478 because (1) it preserves some marker positions and (2) it puts less data
3479 in the undo list. When REPLACE is non-nil, the second return value is
3480 the number of characters that replace previous buffer contents.
3482 This function does code conversion according to the value of
3483 `coding-system-for-read' or `file-coding-system-alist', and sets the
3484 variable `last-coding-system-used' to the coding system actually used.
3486 In addition, this function decodes the inserted text from known formats
3487 by calling `format-decode', which see. */)
3488 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3490 struct stat st;
3491 EMACS_TIME mtime;
3492 int fd;
3493 ptrdiff_t inserted = 0;
3494 ptrdiff_t how_much;
3495 off_t beg_offset, end_offset;
3496 int unprocessed;
3497 ptrdiff_t count = SPECPDL_INDEX ();
3498 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3499 Lisp_Object handler, val, insval, orig_filename, old_undo;
3500 Lisp_Object p;
3501 ptrdiff_t total = 0;
3502 bool not_regular = 0;
3503 int save_errno = 0;
3504 char read_buf[READ_BUF_SIZE];
3505 struct coding_system coding;
3506 bool replace_handled = 0;
3507 bool set_coding_system = 0;
3508 Lisp_Object coding_system;
3509 bool read_quit = 0;
3510 /* If the undo log only contains the insertion, there's no point
3511 keeping it. It's typically when we first fill a file-buffer. */
3512 bool empty_undo_list_p
3513 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3514 && BEG == Z);
3515 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3516 bool we_locked_file = 0;
3517 bool deferred_remove_unwind_protect = 0;
3519 if (current_buffer->base_buffer && ! NILP (visit))
3520 error ("Cannot do file visiting in an indirect buffer");
3522 if (!NILP (BVAR (current_buffer, read_only)))
3523 Fbarf_if_buffer_read_only ();
3525 val = Qnil;
3526 p = Qnil;
3527 orig_filename = Qnil;
3528 old_undo = Qnil;
3530 GCPRO5 (filename, val, p, orig_filename, old_undo);
3532 CHECK_STRING (filename);
3533 filename = Fexpand_file_name (filename, Qnil);
3535 /* The value Qnil means that the coding system is not yet
3536 decided. */
3537 coding_system = Qnil;
3539 /* If the file name has special constructs in it,
3540 call the corresponding file handler. */
3541 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3542 if (!NILP (handler))
3544 val = call6 (handler, Qinsert_file_contents, filename,
3545 visit, beg, end, replace);
3546 if (CONSP (val) && CONSP (XCDR (val))
3547 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3548 inserted = XINT (XCAR (XCDR (val)));
3549 goto handled;
3552 orig_filename = filename;
3553 filename = ENCODE_FILE (filename);
3555 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3556 if (fd < 0)
3558 save_errno = errno;
3559 if (NILP (visit))
3560 report_file_error ("Opening input file", orig_filename);
3561 mtime = time_error_value (save_errno);
3562 st.st_size = -1;
3563 if (!NILP (Vcoding_system_for_read))
3564 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3565 goto notfound;
3568 /* Replacement should preserve point as it preserves markers. */
3569 if (!NILP (replace))
3570 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3572 record_unwind_protect_int (close_file_unwind, fd);
3574 if (fstat (fd, &st) != 0)
3575 report_file_error ("Input file status", orig_filename);
3576 mtime = get_stat_mtime (&st);
3578 /* This code will need to be changed in order to work on named
3579 pipes, and it's probably just not worth it. So we should at
3580 least signal an error. */
3581 if (!S_ISREG (st.st_mode))
3583 not_regular = 1;
3585 if (! NILP (visit))
3586 goto notfound;
3588 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3589 xsignal2 (Qfile_error,
3590 build_string ("not a regular file"), orig_filename);
3593 if (!NILP (visit))
3595 if (!NILP (beg) || !NILP (end))
3596 error ("Attempt to visit less than an entire file");
3597 if (BEG < Z && NILP (replace))
3598 error ("Cannot do file visiting in a non-empty buffer");
3601 if (!NILP (beg))
3602 beg_offset = file_offset (beg);
3603 else
3604 beg_offset = 0;
3606 if (!NILP (end))
3607 end_offset = file_offset (end);
3608 else
3610 if (not_regular)
3611 end_offset = TYPE_MAXIMUM (off_t);
3612 else
3614 end_offset = st.st_size;
3616 /* A negative size can happen on a platform that allows file
3617 sizes greater than the maximum off_t value. */
3618 if (end_offset < 0)
3619 buffer_overflow ();
3621 /* The file size returned from stat may be zero, but data
3622 may be readable nonetheless, for example when this is a
3623 file in the /proc filesystem. */
3624 if (end_offset == 0)
3625 end_offset = READ_BUF_SIZE;
3629 /* Check now whether the buffer will become too large,
3630 in the likely case where the file's length is not changing.
3631 This saves a lot of needless work before a buffer overflow. */
3632 if (! not_regular)
3634 /* The likely offset where we will stop reading. We could read
3635 more (or less), if the file grows (or shrinks) as we read it. */
3636 off_t likely_end = min (end_offset, st.st_size);
3638 if (beg_offset < likely_end)
3640 ptrdiff_t buf_bytes
3641 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3642 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3643 off_t likely_growth = likely_end - beg_offset;
3644 if (buf_growth_max < likely_growth)
3645 buffer_overflow ();
3649 /* Prevent redisplay optimizations. */
3650 current_buffer->clip_changed = 1;
3652 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3654 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3655 setup_coding_system (coding_system, &coding);
3656 /* Ensure we set Vlast_coding_system_used. */
3657 set_coding_system = 1;
3659 else if (BEG < Z)
3661 /* Decide the coding system to use for reading the file now
3662 because we can't use an optimized method for handling
3663 `coding:' tag if the current buffer is not empty. */
3664 if (!NILP (Vcoding_system_for_read))
3665 coding_system = Vcoding_system_for_read;
3666 else
3668 /* Don't try looking inside a file for a coding system
3669 specification if it is not seekable. */
3670 if (! not_regular && ! NILP (Vset_auto_coding_function))
3672 /* Find a coding system specified in the heading two
3673 lines or in the tailing several lines of the file.
3674 We assume that the 1K-byte and 3K-byte for heading
3675 and tailing respectively are sufficient for this
3676 purpose. */
3677 int nread;
3679 if (st.st_size <= (1024 * 4))
3680 nread = emacs_read (fd, read_buf, 1024 * 4);
3681 else
3683 nread = emacs_read (fd, read_buf, 1024);
3684 if (nread == 1024)
3686 int ntail;
3687 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3688 report_file_error ("Setting file position",
3689 orig_filename);
3690 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3691 nread = ntail < 0 ? ntail : nread + ntail;
3695 if (nread < 0)
3696 report_file_error ("Read error", orig_filename);
3697 else if (nread > 0)
3699 struct buffer *prev = current_buffer;
3700 Lisp_Object workbuf;
3701 struct buffer *buf;
3703 record_unwind_current_buffer ();
3705 workbuf = Fget_buffer_create (build_string (" *code-converting-work*"));
3706 buf = XBUFFER (workbuf);
3708 delete_all_overlays (buf);
3709 bset_directory (buf, BVAR (current_buffer, directory));
3710 bset_read_only (buf, Qnil);
3711 bset_filename (buf, Qnil);
3712 bset_undo_list (buf, Qt);
3713 eassert (buf->overlays_before == NULL);
3714 eassert (buf->overlays_after == NULL);
3716 set_buffer_internal (buf);
3717 Ferase_buffer ();
3718 bset_enable_multibyte_characters (buf, Qnil);
3720 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3721 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3722 coding_system = call2 (Vset_auto_coding_function,
3723 filename, make_number (nread));
3724 set_buffer_internal (prev);
3726 /* Discard the unwind protect for recovering the
3727 current buffer. */
3728 specpdl_ptr--;
3730 /* Rewind the file for the actual read done later. */
3731 if (lseek (fd, 0, SEEK_SET) < 0)
3732 report_file_error ("Setting file position", orig_filename);
3736 if (NILP (coding_system))
3738 /* If we have not yet decided a coding system, check
3739 file-coding-system-alist. */
3740 Lisp_Object args[6];
3742 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3743 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3744 coding_system = Ffind_operation_coding_system (6, args);
3745 if (CONSP (coding_system))
3746 coding_system = XCAR (coding_system);
3750 if (NILP (coding_system))
3751 coding_system = Qundecided;
3752 else
3753 CHECK_CODING_SYSTEM (coding_system);
3755 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3756 /* We must suppress all character code conversion except for
3757 end-of-line conversion. */
3758 coding_system = raw_text_coding_system (coding_system);
3760 setup_coding_system (coding_system, &coding);
3761 /* Ensure we set Vlast_coding_system_used. */
3762 set_coding_system = 1;
3765 /* If requested, replace the accessible part of the buffer
3766 with the file contents. Avoid replacing text at the
3767 beginning or end of the buffer that matches the file contents;
3768 that preserves markers pointing to the unchanged parts.
3770 Here we implement this feature in an optimized way
3771 for the case where code conversion is NOT needed.
3772 The following if-statement handles the case of conversion
3773 in a less optimal way.
3775 If the code conversion is "automatic" then we try using this
3776 method and hope for the best.
3777 But if we discover the need for conversion, we give up on this method
3778 and let the following if-statement handle the replace job. */
3779 if (!NILP (replace)
3780 && BEGV < ZV
3781 && (NILP (coding_system)
3782 || ! CODING_REQUIRE_DECODING (&coding)))
3784 /* same_at_start and same_at_end count bytes,
3785 because file access counts bytes
3786 and BEG and END count bytes. */
3787 ptrdiff_t same_at_start = BEGV_BYTE;
3788 ptrdiff_t same_at_end = ZV_BYTE;
3789 ptrdiff_t overlap;
3790 /* There is still a possibility we will find the need to do code
3791 conversion. If that happens, set this variable to
3792 give up on handling REPLACE in the optimized way. */
3793 bool giveup_match_end = 0;
3795 if (beg_offset != 0)
3797 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3798 report_file_error ("Setting file position", orig_filename);
3801 immediate_quit = 1;
3802 QUIT;
3803 /* Count how many chars at the start of the file
3804 match the text at the beginning of the buffer. */
3805 while (1)
3807 int nread, bufpos;
3809 nread = emacs_read (fd, read_buf, sizeof read_buf);
3810 if (nread < 0)
3811 report_file_error ("Read error", orig_filename);
3812 else if (nread == 0)
3813 break;
3815 if (CODING_REQUIRE_DETECTION (&coding))
3817 coding_system = detect_coding_system ((unsigned char *) read_buf,
3818 nread, nread, 1, 0,
3819 coding_system);
3820 setup_coding_system (coding_system, &coding);
3823 if (CODING_REQUIRE_DECODING (&coding))
3824 /* We found that the file should be decoded somehow.
3825 Let's give up here. */
3827 giveup_match_end = 1;
3828 break;
3831 bufpos = 0;
3832 while (bufpos < nread && same_at_start < ZV_BYTE
3833 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3834 same_at_start++, bufpos++;
3835 /* If we found a discrepancy, stop the scan.
3836 Otherwise loop around and scan the next bufferful. */
3837 if (bufpos != nread)
3838 break;
3840 immediate_quit = 0;
3841 /* If the file matches the buffer completely,
3842 there's no need to replace anything. */
3843 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3845 emacs_close (fd);
3846 specpdl_ptr--;
3847 /* Truncate the buffer to the size of the file. */
3848 del_range_1 (same_at_start, same_at_end, 0, 0);
3849 goto handled;
3851 immediate_quit = 1;
3852 QUIT;
3853 /* Count how many chars at the end of the file
3854 match the text at the end of the buffer. But, if we have
3855 already found that decoding is necessary, don't waste time. */
3856 while (!giveup_match_end)
3858 int total_read, nread, bufpos, trial;
3859 off_t curpos;
3861 /* At what file position are we now scanning? */
3862 curpos = end_offset - (ZV_BYTE - same_at_end);
3863 /* If the entire file matches the buffer tail, stop the scan. */
3864 if (curpos == 0)
3865 break;
3866 /* How much can we scan in the next step? */
3867 trial = min (curpos, sizeof read_buf);
3868 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3869 report_file_error ("Setting file position", orig_filename);
3871 total_read = nread = 0;
3872 while (total_read < trial)
3874 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3875 if (nread < 0)
3876 report_file_error ("Read error", orig_filename);
3877 else if (nread == 0)
3878 break;
3879 total_read += nread;
3882 /* Scan this bufferful from the end, comparing with
3883 the Emacs buffer. */
3884 bufpos = total_read;
3886 /* Compare with same_at_start to avoid counting some buffer text
3887 as matching both at the file's beginning and at the end. */
3888 while (bufpos > 0 && same_at_end > same_at_start
3889 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3890 same_at_end--, bufpos--;
3892 /* If we found a discrepancy, stop the scan.
3893 Otherwise loop around and scan the preceding bufferful. */
3894 if (bufpos != 0)
3896 /* If this discrepancy is because of code conversion,
3897 we cannot use this method; giveup and try the other. */
3898 if (same_at_end > same_at_start
3899 && FETCH_BYTE (same_at_end - 1) >= 0200
3900 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3901 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3902 giveup_match_end = 1;
3903 break;
3906 if (nread == 0)
3907 break;
3909 immediate_quit = 0;
3911 if (! giveup_match_end)
3913 ptrdiff_t temp;
3915 /* We win! We can handle REPLACE the optimized way. */
3917 /* Extend the start of non-matching text area to multibyte
3918 character boundary. */
3919 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3920 while (same_at_start > BEGV_BYTE
3921 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3922 same_at_start--;
3924 /* Extend the end of non-matching text area to multibyte
3925 character boundary. */
3926 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3927 while (same_at_end < ZV_BYTE
3928 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3929 same_at_end++;
3931 /* Don't try to reuse the same piece of text twice. */
3932 overlap = (same_at_start - BEGV_BYTE
3933 - (same_at_end
3934 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3935 if (overlap > 0)
3936 same_at_end += overlap;
3938 /* Arrange to read only the nonmatching middle part of the file. */
3939 beg_offset += same_at_start - BEGV_BYTE;
3940 end_offset -= ZV_BYTE - same_at_end;
3942 del_range_byte (same_at_start, same_at_end, 0);
3943 /* Insert from the file at the proper position. */
3944 temp = BYTE_TO_CHAR (same_at_start);
3945 SET_PT_BOTH (temp, same_at_start);
3947 /* If display currently starts at beginning of line,
3948 keep it that way. */
3949 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3950 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3952 replace_handled = 1;
3956 /* If requested, replace the accessible part of the buffer
3957 with the file contents. Avoid replacing text at the
3958 beginning or end of the buffer that matches the file contents;
3959 that preserves markers pointing to the unchanged parts.
3961 Here we implement this feature for the case where code conversion
3962 is needed, in a simple way that needs a lot of memory.
3963 The preceding if-statement handles the case of no conversion
3964 in a more optimized way. */
3965 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3967 ptrdiff_t same_at_start = BEGV_BYTE;
3968 ptrdiff_t same_at_end = ZV_BYTE;
3969 ptrdiff_t same_at_start_charpos;
3970 ptrdiff_t inserted_chars;
3971 ptrdiff_t overlap;
3972 ptrdiff_t bufpos;
3973 unsigned char *decoded;
3974 ptrdiff_t temp;
3975 ptrdiff_t this = 0;
3976 ptrdiff_t this_count = SPECPDL_INDEX ();
3977 bool multibyte
3978 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3979 Lisp_Object conversion_buffer;
3980 struct gcpro gcpro1;
3982 conversion_buffer = code_conversion_save (1, multibyte);
3984 /* First read the whole file, performing code conversion into
3985 CONVERSION_BUFFER. */
3987 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3988 report_file_error ("Setting file position", orig_filename);
3990 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3991 unprocessed = 0; /* Bytes not processed in previous loop. */
3993 GCPRO1 (conversion_buffer);
3994 while (1)
3996 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3997 quitting while reading a huge file. */
3999 /* Allow quitting out of the actual I/O. */
4000 immediate_quit = 1;
4001 QUIT;
4002 this = emacs_read (fd, read_buf + unprocessed,
4003 READ_BUF_SIZE - unprocessed);
4004 immediate_quit = 0;
4006 if (this <= 0)
4007 break;
4009 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
4010 BUF_Z (XBUFFER (conversion_buffer)));
4011 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4012 unprocessed + this, conversion_buffer);
4013 unprocessed = coding.carryover_bytes;
4014 if (coding.carryover_bytes > 0)
4015 memcpy (read_buf, coding.carryover, unprocessed);
4017 UNGCPRO;
4018 emacs_close (fd);
4020 /* We should remove the unwind_protect calling
4021 close_file_unwind, but other stuff has been added the stack,
4022 so defer the removal till we reach the `handled' label. */
4023 deferred_remove_unwind_protect = 1;
4025 if (this < 0)
4026 report_file_error ("Read error", orig_filename);
4028 if (unprocessed > 0)
4030 coding.mode |= CODING_MODE_LAST_BLOCK;
4031 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4032 unprocessed, conversion_buffer);
4033 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4036 coding_system = CODING_ID_NAME (coding.id);
4037 set_coding_system = 1;
4038 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
4039 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4040 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4042 /* Compare the beginning of the converted string with the buffer
4043 text. */
4045 bufpos = 0;
4046 while (bufpos < inserted && same_at_start < same_at_end
4047 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4048 same_at_start++, bufpos++;
4050 /* If the file matches the head of buffer completely,
4051 there's no need to replace anything. */
4053 if (bufpos == inserted)
4055 /* Truncate the buffer to the size of the file. */
4056 if (same_at_start != same_at_end)
4057 del_range_byte (same_at_start, same_at_end, 0);
4058 inserted = 0;
4060 unbind_to (this_count, Qnil);
4061 goto handled;
4064 /* Extend the start of non-matching text area to the previous
4065 multibyte character boundary. */
4066 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4067 while (same_at_start > BEGV_BYTE
4068 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4069 same_at_start--;
4071 /* Scan this bufferful from the end, comparing with
4072 the Emacs buffer. */
4073 bufpos = inserted;
4075 /* Compare with same_at_start to avoid counting some buffer text
4076 as matching both at the file's beginning and at the end. */
4077 while (bufpos > 0 && same_at_end > same_at_start
4078 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4079 same_at_end--, bufpos--;
4081 /* Extend the end of non-matching text area to the next
4082 multibyte character boundary. */
4083 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
4084 while (same_at_end < ZV_BYTE
4085 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4086 same_at_end++;
4088 /* Don't try to reuse the same piece of text twice. */
4089 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4090 if (overlap > 0)
4091 same_at_end += overlap;
4093 /* If display currently starts at beginning of line,
4094 keep it that way. */
4095 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4096 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4098 /* Replace the chars that we need to replace,
4099 and update INSERTED to equal the number of bytes
4100 we are taking from the decoded string. */
4101 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4103 if (same_at_end != same_at_start)
4105 del_range_byte (same_at_start, same_at_end, 0);
4106 temp = GPT;
4107 eassert (same_at_start == GPT_BYTE);
4108 same_at_start = GPT_BYTE;
4110 else
4112 temp = BYTE_TO_CHAR (same_at_start);
4114 /* Insert from the file at the proper position. */
4115 SET_PT_BOTH (temp, same_at_start);
4116 same_at_start_charpos
4117 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4118 same_at_start - BEGV_BYTE
4119 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4120 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4121 inserted_chars
4122 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4123 same_at_start + inserted - BEGV_BYTE
4124 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4125 - same_at_start_charpos);
4126 /* This binding is to avoid ask-user-about-supersession-threat
4127 being called in insert_from_buffer (via in
4128 prepare_to_modify_buffer). */
4129 specbind (intern ("buffer-file-name"), Qnil);
4130 insert_from_buffer (XBUFFER (conversion_buffer),
4131 same_at_start_charpos, inserted_chars, 0);
4132 /* Set `inserted' to the number of inserted characters. */
4133 inserted = PT - temp;
4134 /* Set point before the inserted characters. */
4135 SET_PT_BOTH (temp, same_at_start);
4137 unbind_to (this_count, Qnil);
4139 goto handled;
4142 if (! not_regular)
4143 total = end_offset - beg_offset;
4144 else
4145 /* For a special file, all we can do is guess. */
4146 total = READ_BUF_SIZE;
4148 if (NILP (visit) && total > 0)
4150 #ifdef CLASH_DETECTION
4151 if (!NILP (BVAR (current_buffer, file_truename))
4152 /* Make binding buffer-file-name to nil effective. */
4153 && !NILP (BVAR (current_buffer, filename))
4154 && SAVE_MODIFF >= MODIFF)
4155 we_locked_file = 1;
4156 #endif /* CLASH_DETECTION */
4157 prepare_to_modify_buffer (GPT, GPT, NULL);
4160 move_gap_both (PT, PT_BYTE);
4161 if (GAP_SIZE < total)
4162 make_gap (total - GAP_SIZE);
4164 if (beg_offset != 0 || !NILP (replace))
4166 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4167 report_file_error ("Setting file position", orig_filename);
4170 /* In the following loop, HOW_MUCH contains the total bytes read so
4171 far for a regular file, and not changed for a special file. But,
4172 before exiting the loop, it is set to a negative value if I/O
4173 error occurs. */
4174 how_much = 0;
4176 /* Total bytes inserted. */
4177 inserted = 0;
4179 /* Here, we don't do code conversion in the loop. It is done by
4180 decode_coding_gap after all data are read into the buffer. */
4182 ptrdiff_t gap_size = GAP_SIZE;
4184 while (how_much < total)
4186 /* try is reserved in some compilers (Microsoft C) */
4187 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4188 ptrdiff_t this;
4190 if (not_regular)
4192 Lisp_Object nbytes;
4194 /* Maybe make more room. */
4195 if (gap_size < trytry)
4197 make_gap (trytry - gap_size);
4198 gap_size = GAP_SIZE - inserted;
4201 /* Read from the file, capturing `quit'. When an
4202 error occurs, end the loop, and arrange for a quit
4203 to be signaled after decoding the text we read. */
4204 nbytes = internal_condition_case_1
4205 (read_non_regular,
4206 make_save_value (SAVE_TYPE_INT_INT_INT, (ptrdiff_t) fd,
4207 inserted, trytry),
4208 Qerror, read_non_regular_quit);
4210 if (NILP (nbytes))
4212 read_quit = 1;
4213 break;
4216 this = XINT (nbytes);
4218 else
4220 /* Allow quitting out of the actual I/O. We don't make text
4221 part of the buffer until all the reading is done, so a C-g
4222 here doesn't do any harm. */
4223 immediate_quit = 1;
4224 QUIT;
4225 this = emacs_read (fd,
4226 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4227 + inserted),
4228 trytry);
4229 immediate_quit = 0;
4232 if (this <= 0)
4234 how_much = this;
4235 break;
4238 gap_size -= this;
4240 /* For a regular file, where TOTAL is the real size,
4241 count HOW_MUCH to compare with it.
4242 For a special file, where TOTAL is just a buffer size,
4243 so don't bother counting in HOW_MUCH.
4244 (INSERTED is where we count the number of characters inserted.) */
4245 if (! not_regular)
4246 how_much += this;
4247 inserted += this;
4251 /* Now we have either read all the file data into the gap,
4252 or stop reading on I/O error or quit. If nothing was
4253 read, undo marking the buffer modified. */
4255 if (inserted == 0)
4257 #ifdef CLASH_DETECTION
4258 if (we_locked_file)
4259 unlock_file (BVAR (current_buffer, file_truename));
4260 #endif
4261 Vdeactivate_mark = old_Vdeactivate_mark;
4263 else
4264 Vdeactivate_mark = Qt;
4266 emacs_close (fd);
4268 /* Discard the unwind protect for closing the file. */
4269 specpdl_ptr--;
4271 if (how_much < 0)
4272 report_file_error ("Read error", orig_filename);
4274 /* Make the text read part of the buffer. */
4275 GAP_SIZE -= inserted;
4276 GPT += inserted;
4277 GPT_BYTE += inserted;
4278 ZV += inserted;
4279 ZV_BYTE += inserted;
4280 Z += inserted;
4281 Z_BYTE += inserted;
4283 if (GAP_SIZE > 0)
4284 /* Put an anchor to ensure multi-byte form ends at gap. */
4285 *GPT_ADDR = 0;
4287 notfound:
4289 if (NILP (coding_system))
4291 /* The coding system is not yet decided. Decide it by an
4292 optimized method for handling `coding:' tag.
4294 Note that we can get here only if the buffer was empty
4295 before the insertion. */
4297 if (!NILP (Vcoding_system_for_read))
4298 coding_system = Vcoding_system_for_read;
4299 else
4301 /* Since we are sure that the current buffer was empty
4302 before the insertion, we can toggle
4303 enable-multibyte-characters directly here without taking
4304 care of marker adjustment. By this way, we can run Lisp
4305 program safely before decoding the inserted text. */
4306 Lisp_Object unwind_data;
4307 ptrdiff_t count1 = SPECPDL_INDEX ();
4309 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4310 Fcons (BVAR (current_buffer, undo_list),
4311 Fcurrent_buffer ()));
4312 bset_enable_multibyte_characters (current_buffer, Qnil);
4313 bset_undo_list (current_buffer, Qt);
4314 record_unwind_protect (decide_coding_unwind, unwind_data);
4316 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4318 coding_system = call2 (Vset_auto_coding_function,
4319 filename, make_number (inserted));
4322 if (NILP (coding_system))
4324 /* If the coding system is not yet decided, check
4325 file-coding-system-alist. */
4326 Lisp_Object args[6];
4328 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4329 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4330 coding_system = Ffind_operation_coding_system (6, args);
4331 if (CONSP (coding_system))
4332 coding_system = XCAR (coding_system);
4334 unbind_to (count1, Qnil);
4335 inserted = Z_BYTE - BEG_BYTE;
4338 if (NILP (coding_system))
4339 coding_system = Qundecided;
4340 else
4341 CHECK_CODING_SYSTEM (coding_system);
4343 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4344 /* We must suppress all character code conversion except for
4345 end-of-line conversion. */
4346 coding_system = raw_text_coding_system (coding_system);
4347 setup_coding_system (coding_system, &coding);
4348 /* Ensure we set Vlast_coding_system_used. */
4349 set_coding_system = 1;
4352 if (!NILP (visit))
4354 /* When we visit a file by raw-text, we change the buffer to
4355 unibyte. */
4356 if (CODING_FOR_UNIBYTE (&coding)
4357 /* Can't do this if part of the buffer might be preserved. */
4358 && NILP (replace))
4359 /* Visiting a file with these coding system makes the buffer
4360 unibyte. */
4361 bset_enable_multibyte_characters (current_buffer, Qnil);
4364 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4365 if (CODING_MAY_REQUIRE_DECODING (&coding)
4366 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4368 move_gap_both (PT, PT_BYTE);
4369 GAP_SIZE += inserted;
4370 ZV_BYTE -= inserted;
4371 Z_BYTE -= inserted;
4372 ZV -= inserted;
4373 Z -= inserted;
4374 decode_coding_gap (&coding, inserted, inserted);
4375 inserted = coding.produced_char;
4376 coding_system = CODING_ID_NAME (coding.id);
4378 else if (inserted > 0)
4379 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4380 inserted);
4382 /* Call after-change hooks for the inserted text, aside from the case
4383 of normal visiting (not with REPLACE), which is done in a new buffer
4384 "before" the buffer is changed. */
4385 if (inserted > 0 && total > 0
4386 && (NILP (visit) || !NILP (replace)))
4388 signal_after_change (PT, 0, inserted);
4389 update_compositions (PT, PT, CHECK_BORDER);
4392 /* Now INSERTED is measured in characters. */
4394 handled:
4396 if (deferred_remove_unwind_protect)
4397 /* If requested above, discard the unwind protect for closing the
4398 file. */
4399 specpdl_ptr--;
4401 if (!NILP (visit))
4403 if (empty_undo_list_p)
4404 bset_undo_list (current_buffer, Qnil);
4406 if (NILP (handler))
4408 current_buffer->modtime = mtime;
4409 current_buffer->modtime_size = st.st_size;
4410 bset_filename (current_buffer, orig_filename);
4413 SAVE_MODIFF = MODIFF;
4414 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4415 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4416 #ifdef CLASH_DETECTION
4417 if (NILP (handler))
4419 if (!NILP (BVAR (current_buffer, file_truename)))
4420 unlock_file (BVAR (current_buffer, file_truename));
4421 unlock_file (filename);
4423 #endif /* CLASH_DETECTION */
4424 if (not_regular)
4425 xsignal2 (Qfile_error,
4426 build_string ("not a regular file"), orig_filename);
4429 if (set_coding_system)
4430 Vlast_coding_system_used = coding_system;
4432 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4434 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4435 visit);
4436 if (! NILP (insval))
4438 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4439 wrong_type_argument (intern ("inserted-chars"), insval);
4440 inserted = XFASTINT (insval);
4444 /* Decode file format. */
4445 if (inserted > 0)
4447 /* Don't run point motion or modification hooks when decoding. */
4448 ptrdiff_t count1 = SPECPDL_INDEX ();
4449 ptrdiff_t old_inserted = inserted;
4450 specbind (Qinhibit_point_motion_hooks, Qt);
4451 specbind (Qinhibit_modification_hooks, Qt);
4453 /* Save old undo list and don't record undo for decoding. */
4454 old_undo = BVAR (current_buffer, undo_list);
4455 bset_undo_list (current_buffer, Qt);
4457 if (NILP (replace))
4459 insval = call3 (Qformat_decode,
4460 Qnil, make_number (inserted), visit);
4461 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4462 wrong_type_argument (intern ("inserted-chars"), insval);
4463 inserted = XFASTINT (insval);
4465 else
4467 /* If REPLACE is non-nil and we succeeded in not replacing the
4468 beginning or end of the buffer text with the file's contents,
4469 call format-decode with `point' positioned at the beginning
4470 of the buffer and `inserted' equaling the number of
4471 characters in the buffer. Otherwise, format-decode might
4472 fail to correctly analyze the beginning or end of the buffer.
4473 Hence we temporarily save `point' and `inserted' here and
4474 restore `point' iff format-decode did not insert or delete
4475 any text. Otherwise we leave `point' at point-min. */
4476 ptrdiff_t opoint = PT;
4477 ptrdiff_t opoint_byte = PT_BYTE;
4478 ptrdiff_t oinserted = ZV - BEGV;
4479 EMACS_INT ochars_modiff = CHARS_MODIFF;
4481 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4482 insval = call3 (Qformat_decode,
4483 Qnil, make_number (oinserted), visit);
4484 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4485 wrong_type_argument (intern ("inserted-chars"), insval);
4486 if (ochars_modiff == CHARS_MODIFF)
4487 /* format_decode didn't modify buffer's characters => move
4488 point back to position before inserted text and leave
4489 value of inserted alone. */
4490 SET_PT_BOTH (opoint, opoint_byte);
4491 else
4492 /* format_decode modified buffer's characters => consider
4493 entire buffer changed and leave point at point-min. */
4494 inserted = XFASTINT (insval);
4497 /* For consistency with format-decode call these now iff inserted > 0
4498 (martin 2007-06-28). */
4499 p = Vafter_insert_file_functions;
4500 while (CONSP (p))
4502 if (NILP (replace))
4504 insval = call1 (XCAR (p), make_number (inserted));
4505 if (!NILP (insval))
4507 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4508 wrong_type_argument (intern ("inserted-chars"), insval);
4509 inserted = XFASTINT (insval);
4512 else
4514 /* For the rationale of this see the comment on
4515 format-decode above. */
4516 ptrdiff_t opoint = PT;
4517 ptrdiff_t opoint_byte = PT_BYTE;
4518 ptrdiff_t oinserted = ZV - BEGV;
4519 EMACS_INT ochars_modiff = CHARS_MODIFF;
4521 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4522 insval = call1 (XCAR (p), make_number (oinserted));
4523 if (!NILP (insval))
4525 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4526 wrong_type_argument (intern ("inserted-chars"), insval);
4527 if (ochars_modiff == CHARS_MODIFF)
4528 /* after_insert_file_functions didn't modify
4529 buffer's characters => move point back to
4530 position before inserted text and leave value of
4531 inserted alone. */
4532 SET_PT_BOTH (opoint, opoint_byte);
4533 else
4534 /* after_insert_file_functions did modify buffer's
4535 characters => consider entire buffer changed and
4536 leave point at point-min. */
4537 inserted = XFASTINT (insval);
4541 QUIT;
4542 p = XCDR (p);
4545 if (!empty_undo_list_p)
4547 bset_undo_list (current_buffer, old_undo);
4548 if (CONSP (old_undo) && inserted != old_inserted)
4550 /* Adjust the last undo record for the size change during
4551 the format conversion. */
4552 Lisp_Object tem = XCAR (old_undo);
4553 if (CONSP (tem) && INTEGERP (XCAR (tem))
4554 && INTEGERP (XCDR (tem))
4555 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4556 XSETCDR (tem, make_number (PT + inserted));
4559 else
4560 /* If undo_list was Qt before, keep it that way.
4561 Otherwise start with an empty undo_list. */
4562 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4564 unbind_to (count1, Qnil);
4567 if (!NILP (visit)
4568 && EMACS_NSECS (current_buffer->modtime) == NONEXISTENT_MODTIME_NSECS)
4570 /* If visiting nonexistent file, return nil. */
4571 report_file_errno ("Opening input file", orig_filename, save_errno);
4574 if (read_quit)
4575 Fsignal (Qquit, Qnil);
4577 /* Retval needs to be dealt with in all cases consistently. */
4578 if (NILP (val))
4579 val = list2 (orig_filename, make_number (inserted));
4581 RETURN_UNGCPRO (unbind_to (count, val));
4584 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4586 static void
4587 build_annotations_unwind (Lisp_Object arg)
4589 Vwrite_region_annotation_buffers = arg;
4592 /* Decide the coding-system to encode the data with. */
4594 DEFUN ("choose-write-coding-system", Fchoose_write_coding_system,
4595 Schoose_write_coding_system, 3, 6, 0,
4596 doc: /* Choose the coding system for writing a file.
4597 Arguments are as for `write-region'.
4598 This function is for internal use only. It may prompt the user. */ )
4599 (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4600 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname)
4602 Lisp_Object val;
4603 Lisp_Object eol_parent = Qnil;
4605 /* Mimic write-region behavior. */
4606 if (NILP (start))
4608 XSETFASTINT (start, BEGV);
4609 XSETFASTINT (end, ZV);
4612 if (auto_saving
4613 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4614 BVAR (current_buffer, auto_save_file_name))))
4616 val = Qutf_8_emacs;
4617 eol_parent = Qunix;
4619 else if (!NILP (Vcoding_system_for_write))
4621 val = Vcoding_system_for_write;
4622 if (coding_system_require_warning
4623 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4624 /* Confirm that VAL can surely encode the current region. */
4625 val = call5 (Vselect_safe_coding_system_function,
4626 start, end, list2 (Qt, val),
4627 Qnil, filename);
4629 else
4631 /* If the variable `buffer-file-coding-system' is set locally,
4632 it means that the file was read with some kind of code
4633 conversion or the variable is explicitly set by users. We
4634 had better write it out with the same coding system even if
4635 `enable-multibyte-characters' is nil.
4637 If it is not set locally, we anyway have to convert EOL
4638 format if the default value of `buffer-file-coding-system'
4639 tells that it is not Unix-like (LF only) format. */
4640 bool using_default_coding = 0;
4641 bool force_raw_text = 0;
4643 val = BVAR (current_buffer, buffer_file_coding_system);
4644 if (NILP (val)
4645 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4647 val = Qnil;
4648 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4649 force_raw_text = 1;
4652 if (NILP (val))
4654 /* Check file-coding-system-alist. */
4655 Lisp_Object args[7], coding_systems;
4657 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4658 args[3] = filename; args[4] = append; args[5] = visit;
4659 args[6] = lockname;
4660 coding_systems = Ffind_operation_coding_system (7, args);
4661 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4662 val = XCDR (coding_systems);
4665 if (NILP (val))
4667 /* If we still have not decided a coding system, use the
4668 default value of buffer-file-coding-system. */
4669 val = BVAR (current_buffer, buffer_file_coding_system);
4670 using_default_coding = 1;
4673 if (! NILP (val) && ! force_raw_text)
4675 Lisp_Object spec, attrs;
4677 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4678 attrs = AREF (spec, 0);
4679 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4680 force_raw_text = 1;
4683 if (!force_raw_text
4684 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4685 /* Confirm that VAL can surely encode the current region. */
4686 val = call5 (Vselect_safe_coding_system_function,
4687 start, end, val, Qnil, filename);
4689 /* If the decided coding-system doesn't specify end-of-line
4690 format, we use that of
4691 `default-buffer-file-coding-system'. */
4692 if (! using_default_coding
4693 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4694 val = (coding_inherit_eol_type
4695 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4697 /* If we decide not to encode text, use `raw-text' or one of its
4698 subsidiaries. */
4699 if (force_raw_text)
4700 val = raw_text_coding_system (val);
4703 val = coding_inherit_eol_type (val, eol_parent);
4704 return val;
4707 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4708 "r\nFWrite region to file: \ni\ni\ni\np",
4709 doc: /* Write current region into specified file.
4710 When called from a program, requires three arguments:
4711 START, END and FILENAME. START and END are normally buffer positions
4712 specifying the part of the buffer to write.
4713 If START is nil, that means to use the entire buffer contents.
4714 If START is a string, then output that string to the file
4715 instead of any buffer contents; END is ignored.
4717 Optional fourth argument APPEND if non-nil means
4718 append to existing file contents (if any). If it is a number,
4719 seek to that offset in the file before writing.
4720 Optional fifth argument VISIT, if t or a string, means
4721 set the last-save-file-modtime of buffer to this file's modtime
4722 and mark buffer not modified.
4723 If VISIT is a string, it is a second file name;
4724 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4725 VISIT is also the file name to lock and unlock for clash detection.
4726 If VISIT is neither t nor nil nor a string,
4727 that means do not display the \"Wrote file\" message.
4728 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4729 use for locking and unlocking, overriding FILENAME and VISIT.
4730 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4731 for an existing file with the same name. If MUSTBENEW is `excl',
4732 that means to get an error if the file already exists; never overwrite.
4733 If MUSTBENEW is neither nil nor `excl', that means ask for
4734 confirmation before overwriting, but do go ahead and overwrite the file
4735 if the user confirms.
4737 This does code conversion according to the value of
4738 `coding-system-for-write', `buffer-file-coding-system', or
4739 `file-coding-system-alist', and sets the variable
4740 `last-coding-system-used' to the coding system actually used.
4742 This calls `write-region-annotate-functions' at the start, and
4743 `write-region-post-annotation-function' at the end. */)
4744 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append, Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4746 int desc;
4747 int open_flags;
4748 int mode;
4749 off_t offset IF_LINT (= 0);
4750 bool ok;
4751 int save_errno = 0;
4752 const char *fn;
4753 struct stat st;
4754 EMACS_TIME modtime;
4755 ptrdiff_t count = SPECPDL_INDEX ();
4756 ptrdiff_t count1;
4757 Lisp_Object handler;
4758 Lisp_Object visit_file;
4759 Lisp_Object annotations;
4760 Lisp_Object encoded_filename;
4761 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4762 bool quietly = !NILP (visit);
4763 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4764 struct buffer *given_buffer;
4765 struct coding_system coding;
4767 if (current_buffer->base_buffer && visiting)
4768 error ("Cannot do file visiting in an indirect buffer");
4770 if (!NILP (start) && !STRINGP (start))
4771 validate_region (&start, &end);
4773 visit_file = Qnil;
4774 GCPRO5 (start, filename, visit, visit_file, lockname);
4776 filename = Fexpand_file_name (filename, Qnil);
4778 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4779 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4781 if (STRINGP (visit))
4782 visit_file = Fexpand_file_name (visit, Qnil);
4783 else
4784 visit_file = filename;
4786 if (NILP (lockname))
4787 lockname = visit_file;
4789 annotations = Qnil;
4791 /* If the file name has special constructs in it,
4792 call the corresponding file handler. */
4793 handler = Ffind_file_name_handler (filename, Qwrite_region);
4794 /* If FILENAME has no handler, see if VISIT has one. */
4795 if (NILP (handler) && STRINGP (visit))
4796 handler = Ffind_file_name_handler (visit, Qwrite_region);
4798 if (!NILP (handler))
4800 Lisp_Object val;
4801 val = call6 (handler, Qwrite_region, start, end,
4802 filename, append, visit);
4804 if (visiting)
4806 SAVE_MODIFF = MODIFF;
4807 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4808 bset_filename (current_buffer, visit_file);
4810 UNGCPRO;
4811 return val;
4814 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4816 /* Special kludge to simplify auto-saving. */
4817 if (NILP (start))
4819 /* Do it later, so write-region-annotate-function can work differently
4820 if we save "the buffer" vs "a region".
4821 This is useful in tar-mode. --Stef
4822 XSETFASTINT (start, BEG);
4823 XSETFASTINT (end, Z); */
4824 Fwiden ();
4827 record_unwind_protect (build_annotations_unwind,
4828 Vwrite_region_annotation_buffers);
4829 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4830 count1 = SPECPDL_INDEX ();
4832 given_buffer = current_buffer;
4834 if (!STRINGP (start))
4836 annotations = build_annotations (start, end);
4838 if (current_buffer != given_buffer)
4840 XSETFASTINT (start, BEGV);
4841 XSETFASTINT (end, ZV);
4845 if (NILP (start))
4847 XSETFASTINT (start, BEGV);
4848 XSETFASTINT (end, ZV);
4851 UNGCPRO;
4853 GCPRO5 (start, filename, annotations, visit_file, lockname);
4855 /* Decide the coding-system to encode the data with.
4856 We used to make this choice before calling build_annotations, but that
4857 leads to problems when a write-annotate-function takes care of
4858 unsavable chars (as was the case with X-Symbol). */
4859 Vlast_coding_system_used =
4860 Fchoose_write_coding_system (start, end, filename,
4861 append, visit, lockname);
4863 setup_coding_system (Vlast_coding_system_used, &coding);
4865 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4866 coding.mode |= CODING_MODE_SELECTIVE_DISPLAY;
4868 #ifdef CLASH_DETECTION
4869 if (!auto_saving)
4870 lock_file (lockname);
4871 #endif /* CLASH_DETECTION */
4873 encoded_filename = ENCODE_FILE (filename);
4874 fn = SSDATA (encoded_filename);
4875 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4876 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4877 if (NUMBERP (append))
4878 offset = file_offset (append);
4879 else if (!NILP (append))
4880 open_flags |= O_APPEND;
4881 #ifdef DOS_NT
4882 mode = S_IREAD | S_IWRITE;
4883 #else
4884 mode = auto_saving ? auto_save_mode_bits : 0666;
4885 #endif
4887 desc = emacs_open (fn, open_flags, mode);
4889 if (desc < 0)
4891 int open_errno = errno;
4892 #ifdef CLASH_DETECTION
4893 if (!auto_saving) unlock_file (lockname);
4894 #endif /* CLASH_DETECTION */
4895 UNGCPRO;
4896 report_file_errno ("Opening output file", filename, open_errno);
4899 record_unwind_protect_int (close_file_unwind, desc);
4901 if (NUMBERP (append))
4903 off_t ret = lseek (desc, offset, SEEK_SET);
4904 if (ret < 0)
4906 int lseek_errno = errno;
4907 #ifdef CLASH_DETECTION
4908 if (!auto_saving) unlock_file (lockname);
4909 #endif /* CLASH_DETECTION */
4910 UNGCPRO;
4911 report_file_errno ("Lseek error", filename, lseek_errno);
4915 UNGCPRO;
4917 immediate_quit = 1;
4919 if (STRINGP (start))
4920 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4921 else if (XINT (start) != XINT (end))
4922 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4923 &annotations, &coding);
4924 else
4926 /* If file was empty, still need to write the annotations. */
4927 coding.mode |= CODING_MODE_LAST_BLOCK;
4928 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4930 save_errno = errno;
4932 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4933 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4935 /* We have to flush out a data. */
4936 coding.mode |= CODING_MODE_LAST_BLOCK;
4937 ok = e_write (desc, Qnil, 1, 1, &coding);
4938 save_errno = errno;
4941 immediate_quit = 0;
4943 /* fsync is not crucial for auto-save files, since they might lose
4944 some work anyway. */
4945 if (!auto_saving && !write_region_inhibit_fsync)
4947 /* Transfer data and metadata to disk, retrying if interrupted.
4948 fsync can report a write failure here, e.g., due to disk full
4949 under NFS. But ignore EINVAL, which means fsync is not
4950 supported on this file. */
4951 while (fsync (desc) != 0)
4952 if (errno != EINTR)
4954 if (errno != EINVAL)
4955 ok = 0, save_errno = errno;
4956 break;
4960 modtime = invalid_emacs_time ();
4961 if (visiting)
4963 if (fstat (desc, &st) == 0)
4964 modtime = get_stat_mtime (&st);
4965 else
4966 ok = 0, save_errno = errno;
4969 /* NFS can report a write failure now. */
4970 if (emacs_close (desc) < 0)
4971 ok = 0, save_errno = errno;
4973 /* Discard the unwind protect for close_file_unwind. */
4974 specpdl_ptr = specpdl + count1;
4976 /* Some file systems have a bug where st_mtime is not updated
4977 properly after a write. For example, CIFS might not see the
4978 st_mtime change until after the file is opened again.
4980 Attempt to detect this file system bug, and update MODTIME to the
4981 newer st_mtime if the bug appears to be present. This introduces
4982 a race condition, so to avoid most instances of the race condition
4983 on non-buggy file systems, skip this check if the most recently
4984 encountered non-buggy file system was the current file system.
4986 A race condition can occur if some other process modifies the
4987 file between the fstat above and the fstat below, but the race is
4988 unlikely and a similar race between the last write and the fstat
4989 above cannot possibly be closed anyway. */
4991 if (EMACS_TIME_VALID_P (modtime)
4992 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4994 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4995 if (desc1 >= 0)
4997 struct stat st1;
4998 if (fstat (desc1, &st1) == 0
4999 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
5001 /* Use the heuristic if it appears to be valid. With neither
5002 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
5003 file, the time stamp won't change. Also, some non-POSIX
5004 systems don't update an empty file's time stamp when
5005 truncating it. Finally, file systems with 100 ns or worse
5006 resolution sometimes seem to have bugs: on a system with ns
5007 resolution, checking ns % 100 incorrectly avoids the heuristic
5008 1% of the time, but the problem should be temporary as we will
5009 try again on the next time stamp. */
5010 bool use_heuristic
5011 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
5012 && st.st_size != 0
5013 && EMACS_NSECS (modtime) % 100 != 0);
5015 EMACS_TIME modtime1 = get_stat_mtime (&st1);
5016 if (use_heuristic
5017 && EMACS_TIME_EQ (modtime, modtime1)
5018 && st.st_size == st1.st_size)
5020 timestamp_file_system = st.st_dev;
5021 valid_timestamp_file_system = 1;
5023 else
5025 st.st_size = st1.st_size;
5026 modtime = modtime1;
5029 emacs_close (desc1);
5033 /* Call write-region-post-annotation-function. */
5034 while (CONSP (Vwrite_region_annotation_buffers))
5036 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5037 if (!NILP (Fbuffer_live_p (buf)))
5039 Fset_buffer (buf);
5040 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5041 call0 (Vwrite_region_post_annotation_function);
5043 Vwrite_region_annotation_buffers
5044 = XCDR (Vwrite_region_annotation_buffers);
5047 unbind_to (count, Qnil);
5049 #ifdef CLASH_DETECTION
5050 if (!auto_saving)
5051 unlock_file (lockname);
5052 #endif /* CLASH_DETECTION */
5054 /* Do this before reporting IO error
5055 to avoid a "file has changed on disk" warning on
5056 next attempt to save. */
5057 if (EMACS_TIME_VALID_P (modtime))
5059 current_buffer->modtime = modtime;
5060 current_buffer->modtime_size = st.st_size;
5063 if (! ok)
5064 report_file_errno ("Write error", filename, save_errno);
5066 if (visiting)
5068 SAVE_MODIFF = MODIFF;
5069 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5070 bset_filename (current_buffer, visit_file);
5071 update_mode_lines++;
5073 else if (quietly)
5075 if (auto_saving
5076 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5077 BVAR (current_buffer, auto_save_file_name))))
5078 SAVE_MODIFF = MODIFF;
5080 return Qnil;
5083 if (!auto_saving)
5084 message_with_string ((NUMBERP (append)
5085 ? "Updated %s"
5086 : ! NILP (append)
5087 ? "Added to %s"
5088 : "Wrote %s"),
5089 visit_file, 1);
5091 return Qnil;
5094 Lisp_Object merge (Lisp_Object, Lisp_Object, Lisp_Object);
5096 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5097 doc: /* Return t if (car A) is numerically less than (car B). */)
5098 (Lisp_Object a, Lisp_Object b)
5100 return Flss (Fcar (a), Fcar (b));
5103 /* Build the complete list of annotations appropriate for writing out
5104 the text between START and END, by calling all the functions in
5105 write-region-annotate-functions and merging the lists they return.
5106 If one of these functions switches to a different buffer, we assume
5107 that buffer contains altered text. Therefore, the caller must
5108 make sure to restore the current buffer in all cases,
5109 as save-excursion would do. */
5111 static Lisp_Object
5112 build_annotations (Lisp_Object start, Lisp_Object end)
5114 Lisp_Object annotations;
5115 Lisp_Object p, res;
5116 struct gcpro gcpro1, gcpro2;
5117 Lisp_Object original_buffer;
5118 int i;
5119 bool used_global = 0;
5121 XSETBUFFER (original_buffer, current_buffer);
5123 annotations = Qnil;
5124 p = Vwrite_region_annotate_functions;
5125 GCPRO2 (annotations, p);
5126 while (CONSP (p))
5128 struct buffer *given_buffer = current_buffer;
5129 if (EQ (Qt, XCAR (p)) && !used_global)
5130 { /* Use the global value of the hook. */
5131 Lisp_Object arg[2];
5132 used_global = 1;
5133 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
5134 arg[1] = XCDR (p);
5135 p = Fappend (2, arg);
5136 continue;
5138 Vwrite_region_annotations_so_far = annotations;
5139 res = call2 (XCAR (p), start, end);
5140 /* If the function makes a different buffer current,
5141 assume that means this buffer contains altered text to be output.
5142 Reset START and END from the buffer bounds
5143 and discard all previous annotations because they should have
5144 been dealt with by this function. */
5145 if (current_buffer != given_buffer)
5147 Vwrite_region_annotation_buffers
5148 = Fcons (Fcurrent_buffer (),
5149 Vwrite_region_annotation_buffers);
5150 XSETFASTINT (start, BEGV);
5151 XSETFASTINT (end, ZV);
5152 annotations = Qnil;
5154 Flength (res); /* Check basic validity of return value */
5155 annotations = merge (annotations, res, Qcar_less_than_car);
5156 p = XCDR (p);
5159 /* Now do the same for annotation functions implied by the file-format */
5160 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5161 p = BVAR (current_buffer, auto_save_file_format);
5162 else
5163 p = BVAR (current_buffer, file_format);
5164 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5166 struct buffer *given_buffer = current_buffer;
5168 Vwrite_region_annotations_so_far = annotations;
5170 /* Value is either a list of annotations or nil if the function
5171 has written annotations to a temporary buffer, which is now
5172 current. */
5173 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5174 original_buffer, make_number (i));
5175 if (current_buffer != given_buffer)
5177 XSETFASTINT (start, BEGV);
5178 XSETFASTINT (end, ZV);
5179 annotations = Qnil;
5182 if (CONSP (res))
5183 annotations = merge (annotations, res, Qcar_less_than_car);
5186 UNGCPRO;
5187 return annotations;
5191 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5192 If STRING is nil, POS is the character position in the current buffer.
5193 Intersperse with them the annotations from *ANNOT
5194 which fall within the range of POS to POS + NCHARS,
5195 each at its appropriate position.
5197 We modify *ANNOT by discarding elements as we use them up.
5199 Return true if successful. */
5201 static bool
5202 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5203 ptrdiff_t nchars, Lisp_Object *annot,
5204 struct coding_system *coding)
5206 Lisp_Object tem;
5207 ptrdiff_t nextpos;
5208 ptrdiff_t lastpos = pos + nchars;
5210 while (NILP (*annot) || CONSP (*annot))
5212 tem = Fcar_safe (Fcar (*annot));
5213 nextpos = pos - 1;
5214 if (INTEGERP (tem))
5215 nextpos = XFASTINT (tem);
5217 /* If there are no more annotations in this range,
5218 output the rest of the range all at once. */
5219 if (! (nextpos >= pos && nextpos <= lastpos))
5220 return e_write (desc, string, pos, lastpos, coding);
5222 /* Output buffer text up to the next annotation's position. */
5223 if (nextpos > pos)
5225 if (!e_write (desc, string, pos, nextpos, coding))
5226 return 0;
5227 pos = nextpos;
5229 /* Output the annotation. */
5230 tem = Fcdr (Fcar (*annot));
5231 if (STRINGP (tem))
5233 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5234 return 0;
5236 *annot = Fcdr (*annot);
5238 return 1;
5242 /* Write text in the range START and END into descriptor DESC,
5243 encoding them with coding system CODING. If STRING is nil, START
5244 and END are character positions of the current buffer, else they
5245 are indexes to the string STRING. Return true if successful. */
5247 static bool
5248 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5249 struct coding_system *coding)
5251 if (STRINGP (string))
5253 start = 0;
5254 end = SCHARS (string);
5257 /* We used to have a code for handling selective display here. But,
5258 now it is handled within encode_coding. */
5260 while (start < end)
5262 if (STRINGP (string))
5264 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5265 if (CODING_REQUIRE_ENCODING (coding))
5267 encode_coding_object (coding, string,
5268 start, string_char_to_byte (string, start),
5269 end, string_char_to_byte (string, end), Qt);
5271 else
5273 coding->dst_object = string;
5274 coding->consumed_char = SCHARS (string);
5275 coding->produced = SBYTES (string);
5278 else
5280 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5281 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5283 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5284 if (CODING_REQUIRE_ENCODING (coding))
5286 encode_coding_object (coding, Fcurrent_buffer (),
5287 start, start_byte, end, end_byte, Qt);
5289 else
5291 coding->dst_object = Qnil;
5292 coding->dst_pos_byte = start_byte;
5293 if (start >= GPT || end <= GPT)
5295 coding->consumed_char = end - start;
5296 coding->produced = end_byte - start_byte;
5298 else
5300 coding->consumed_char = GPT - start;
5301 coding->produced = GPT_BYTE - start_byte;
5306 if (coding->produced > 0)
5308 char *buf = (STRINGP (coding->dst_object)
5309 ? SSDATA (coding->dst_object)
5310 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte));
5311 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5313 if (coding->produced)
5314 return 0;
5316 start += coding->consumed_char;
5319 return 1;
5322 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5323 Sverify_visited_file_modtime, 0, 1, 0,
5324 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5325 This means that the file has not been changed since it was visited or saved.
5326 If BUF is omitted or nil, it defaults to the current buffer.
5327 See Info node `(elisp)Modification Time' for more details. */)
5328 (Lisp_Object buf)
5330 struct buffer *b;
5331 struct stat st;
5332 Lisp_Object handler;
5333 Lisp_Object filename;
5334 EMACS_TIME mtime;
5336 if (NILP (buf))
5337 b = current_buffer;
5338 else
5340 CHECK_BUFFER (buf);
5341 b = XBUFFER (buf);
5344 if (!STRINGP (BVAR (b, filename))) return Qt;
5345 if (EMACS_NSECS (b->modtime) == UNKNOWN_MODTIME_NSECS) return Qt;
5347 /* If the file name has special constructs in it,
5348 call the corresponding file handler. */
5349 handler = Ffind_file_name_handler (BVAR (b, filename),
5350 Qverify_visited_file_modtime);
5351 if (!NILP (handler))
5352 return call2 (handler, Qverify_visited_file_modtime, buf);
5354 filename = ENCODE_FILE (BVAR (b, filename));
5356 mtime = (stat (SSDATA (filename), &st) == 0
5357 ? get_stat_mtime (&st)
5358 : time_error_value (errno));
5359 if (EMACS_TIME_EQ (mtime, b->modtime)
5360 && (b->modtime_size < 0
5361 || st.st_size == b->modtime_size))
5362 return Qt;
5363 return Qnil;
5366 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5367 Svisited_file_modtime, 0, 0, 0,
5368 doc: /* Return the current buffer's recorded visited file modification time.
5369 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5370 `file-attributes' returns. If the current buffer has no recorded file
5371 modification time, this function returns 0. If the visited file
5372 doesn't exist, return -1.
5373 See Info node `(elisp)Modification Time' for more details. */)
5374 (void)
5376 int ns = EMACS_NSECS (current_buffer->modtime);
5377 if (ns < 0)
5378 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5379 return make_lisp_time (current_buffer->modtime);
5382 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5383 Sset_visited_file_modtime, 0, 1, 0,
5384 doc: /* Update buffer's recorded modification time from the visited file's time.
5385 Useful if the buffer was not read from the file normally
5386 or if the file itself has been changed for some known benign reason.
5387 An argument specifies the modification time value to use
5388 \(instead of that of the visited file), in the form of a list
5389 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5390 `visited-file-modtime'. */)
5391 (Lisp_Object time_flag)
5393 if (!NILP (time_flag))
5395 EMACS_TIME mtime;
5396 if (INTEGERP (time_flag))
5398 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5399 mtime = make_emacs_time (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5401 else
5402 mtime = lisp_time_argument (time_flag);
5404 current_buffer->modtime = mtime;
5405 current_buffer->modtime_size = -1;
5407 else
5409 register Lisp_Object filename;
5410 struct stat st;
5411 Lisp_Object handler;
5413 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5415 /* If the file name has special constructs in it,
5416 call the corresponding file handler. */
5417 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5418 if (!NILP (handler))
5419 /* The handler can find the file name the same way we did. */
5420 return call2 (handler, Qset_visited_file_modtime, Qnil);
5422 filename = ENCODE_FILE (filename);
5424 if (stat (SSDATA (filename), &st) >= 0)
5426 current_buffer->modtime = get_stat_mtime (&st);
5427 current_buffer->modtime_size = st.st_size;
5431 return Qnil;
5434 static Lisp_Object
5435 auto_save_error (Lisp_Object error_val)
5437 Lisp_Object args[3], msg;
5438 int i;
5439 struct gcpro gcpro1;
5441 auto_save_error_occurred = 1;
5443 ring_bell (XFRAME (selected_frame));
5445 args[0] = build_string ("Auto-saving %s: %s");
5446 args[1] = BVAR (current_buffer, name);
5447 args[2] = Ferror_message_string (error_val);
5448 msg = Fformat (3, args);
5449 GCPRO1 (msg);
5451 for (i = 0; i < 3; ++i)
5453 if (i == 0)
5454 message3 (msg);
5455 else
5456 message3_nolog (msg);
5457 Fsleep_for (make_number (1), Qnil);
5460 UNGCPRO;
5461 return Qnil;
5464 static Lisp_Object
5465 auto_save_1 (void)
5467 struct stat st;
5468 Lisp_Object modes;
5470 auto_save_mode_bits = 0666;
5472 /* Get visited file's mode to become the auto save file's mode. */
5473 if (! NILP (BVAR (current_buffer, filename)))
5475 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5476 /* But make sure we can overwrite it later! */
5477 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5478 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5479 INTEGERP (modes))
5480 /* Remote files don't cooperate with stat. */
5481 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5484 return
5485 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5486 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5487 Qnil, Qnil);
5490 struct auto_save_unwind
5492 FILE *stream;
5493 bool auto_raise;
5496 static void
5497 do_auto_save_unwind (void *arg)
5499 struct auto_save_unwind *p = arg;
5500 FILE *stream = p->stream;
5501 minibuffer_auto_raise = p->auto_raise;
5502 auto_saving = 0;
5503 if (stream != NULL)
5505 block_input ();
5506 fclose (stream);
5507 unblock_input ();
5511 static Lisp_Object
5512 do_auto_save_make_dir (Lisp_Object dir)
5514 Lisp_Object result;
5516 auto_saving_dir_umask = 077;
5517 result = call2 (Qmake_directory, dir, Qt);
5518 auto_saving_dir_umask = 0;
5519 return result;
5522 static Lisp_Object
5523 do_auto_save_eh (Lisp_Object ignore)
5525 auto_saving_dir_umask = 0;
5526 return Qnil;
5529 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5530 doc: /* Auto-save all buffers that need it.
5531 This is all buffers that have auto-saving enabled
5532 and are changed since last auto-saved.
5533 Auto-saving writes the buffer into a file
5534 so that your editing is not lost if the system crashes.
5535 This file is not the file you visited; that changes only when you save.
5536 Normally we run the normal hook `auto-save-hook' before saving.
5538 A non-nil NO-MESSAGE argument means do not print any message if successful.
5539 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5540 (Lisp_Object no_message, Lisp_Object current_only)
5542 struct buffer *old = current_buffer, *b;
5543 Lisp_Object tail, buf, hook;
5544 bool auto_saved = 0;
5545 int do_handled_files;
5546 Lisp_Object oquit;
5547 FILE *stream = NULL;
5548 ptrdiff_t count = SPECPDL_INDEX ();
5549 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5550 bool old_message_p = 0;
5551 struct auto_save_unwind auto_save_unwind;
5552 struct gcpro gcpro1, gcpro2;
5554 if (max_specpdl_size < specpdl_size + 40)
5555 max_specpdl_size = specpdl_size + 40;
5557 if (minibuf_level)
5558 no_message = Qt;
5560 if (NILP (no_message))
5562 old_message_p = push_message ();
5563 record_unwind_protect_void (pop_message_unwind);
5566 /* Ordinarily don't quit within this function,
5567 but don't make it impossible to quit (in case we get hung in I/O). */
5568 oquit = Vquit_flag;
5569 Vquit_flag = Qnil;
5571 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5572 point to non-strings reached from Vbuffer_alist. */
5574 hook = intern ("auto-save-hook");
5575 safe_run_hooks (hook);
5577 if (STRINGP (Vauto_save_list_file_name))
5579 Lisp_Object listfile;
5581 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5583 /* Don't try to create the directory when shutting down Emacs,
5584 because creating the directory might signal an error, and
5585 that would leave Emacs in a strange state. */
5586 if (!NILP (Vrun_hooks))
5588 Lisp_Object dir;
5589 dir = Qnil;
5590 GCPRO2 (dir, listfile);
5591 dir = Ffile_name_directory (listfile);
5592 if (NILP (Ffile_directory_p (dir)))
5593 internal_condition_case_1 (do_auto_save_make_dir,
5594 dir, Qt,
5595 do_auto_save_eh);
5596 UNGCPRO;
5599 stream = emacs_fopen (SSDATA (listfile), "w");
5602 auto_save_unwind.stream = stream;
5603 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5604 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5605 minibuffer_auto_raise = 0;
5606 auto_saving = 1;
5607 auto_save_error_occurred = 0;
5609 /* On first pass, save all files that don't have handlers.
5610 On second pass, save all files that do have handlers.
5612 If Emacs is crashing, the handlers may tweak what is causing
5613 Emacs to crash in the first place, and it would be a shame if
5614 Emacs failed to autosave perfectly ordinary files because it
5615 couldn't handle some ange-ftp'd file. */
5617 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5618 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5620 buf = XCDR (XCAR (tail));
5621 b = XBUFFER (buf);
5623 /* Record all the buffers that have auto save mode
5624 in the special file that lists them. For each of these buffers,
5625 Record visited name (if any) and auto save name. */
5626 if (STRINGP (BVAR (b, auto_save_file_name))
5627 && stream != NULL && do_handled_files == 0)
5629 block_input ();
5630 if (!NILP (BVAR (b, filename)))
5632 fwrite (SDATA (BVAR (b, filename)), 1,
5633 SBYTES (BVAR (b, filename)), stream);
5635 putc ('\n', stream);
5636 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5637 SBYTES (BVAR (b, auto_save_file_name)), stream);
5638 putc ('\n', stream);
5639 unblock_input ();
5642 if (!NILP (current_only)
5643 && b != current_buffer)
5644 continue;
5646 /* Don't auto-save indirect buffers.
5647 The base buffer takes care of it. */
5648 if (b->base_buffer)
5649 continue;
5651 /* Check for auto save enabled
5652 and file changed since last auto save
5653 and file changed since last real save. */
5654 if (STRINGP (BVAR (b, auto_save_file_name))
5655 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5656 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5657 /* -1 means we've turned off autosaving for a while--see below. */
5658 && XINT (BVAR (b, save_length)) >= 0
5659 && (do_handled_files
5660 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5661 Qwrite_region))))
5663 EMACS_TIME before_time = current_emacs_time ();
5664 EMACS_TIME after_time;
5666 /* If we had a failure, don't try again for 20 minutes. */
5667 if (b->auto_save_failure_time > 0
5668 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5669 continue;
5671 set_buffer_internal (b);
5672 if (NILP (Vauto_save_include_big_deletions)
5673 && (XFASTINT (BVAR (b, save_length)) * 10
5674 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5675 /* A short file is likely to change a large fraction;
5676 spare the user annoying messages. */
5677 && XFASTINT (BVAR (b, save_length)) > 5000
5678 /* These messages are frequent and annoying for `*mail*'. */
5679 && !EQ (BVAR (b, filename), Qnil)
5680 && NILP (no_message))
5682 /* It has shrunk too much; turn off auto-saving here. */
5683 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5684 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5685 BVAR (b, name), 1);
5686 minibuffer_auto_raise = 0;
5687 /* Turn off auto-saving until there's a real save,
5688 and prevent any more warnings. */
5689 XSETINT (BVAR (b, save_length), -1);
5690 Fsleep_for (make_number (1), Qnil);
5691 continue;
5693 if (!auto_saved && NILP (no_message))
5694 message1 ("Auto-saving...");
5695 internal_condition_case (auto_save_1, Qt, auto_save_error);
5696 auto_saved = 1;
5697 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5698 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5699 set_buffer_internal (old);
5701 after_time = current_emacs_time ();
5703 /* If auto-save took more than 60 seconds,
5704 assume it was an NFS failure that got a timeout. */
5705 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5706 b->auto_save_failure_time = EMACS_SECS (after_time);
5710 /* Prevent another auto save till enough input events come in. */
5711 record_auto_save ();
5713 if (auto_saved && NILP (no_message))
5715 if (old_message_p)
5717 /* If we are going to restore an old message,
5718 give time to read ours. */
5719 sit_for (make_number (1), 0, 0);
5720 restore_message ();
5722 else if (!auto_save_error_occurred)
5723 /* Don't overwrite the error message if an error occurred.
5724 If we displayed a message and then restored a state
5725 with no message, leave a "done" message on the screen. */
5726 message1 ("Auto-saving...done");
5729 Vquit_flag = oquit;
5731 /* This restores the message-stack status. */
5732 unbind_to (count, Qnil);
5733 return Qnil;
5736 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5737 Sset_buffer_auto_saved, 0, 0, 0,
5738 doc: /* Mark current buffer as auto-saved with its current text.
5739 No auto-save file will be written until the buffer changes again. */)
5740 (void)
5742 /* FIXME: This should not be called in indirect buffers, since
5743 they're not autosaved. */
5744 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5745 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5746 current_buffer->auto_save_failure_time = 0;
5747 return Qnil;
5750 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5751 Sclear_buffer_auto_save_failure, 0, 0, 0,
5752 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5753 (void)
5755 current_buffer->auto_save_failure_time = 0;
5756 return Qnil;
5759 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5760 0, 0, 0,
5761 doc: /* Return t if current buffer has been auto-saved recently.
5762 More precisely, if it has been auto-saved since last read from or saved
5763 in the visited file. If the buffer has no visited file,
5764 then any auto-save counts as "recent". */)
5765 (void)
5767 /* FIXME: maybe we should return nil for indirect buffers since
5768 they're never autosaved. */
5769 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5772 /* Reading and completing file names */
5774 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5775 Snext_read_file_uses_dialog_p, 0, 0, 0,
5776 doc: /* Return t if a call to `read-file-name' will use a dialog.
5777 The return value is only relevant for a call to `read-file-name' that happens
5778 before any other event (mouse or keypress) is handled. */)
5779 (void)
5781 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) \
5782 || defined (HAVE_NS)
5783 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5784 && use_dialog_box
5785 && use_file_dialog
5786 && window_system_available (SELECTED_FRAME ()))
5787 return Qt;
5788 #endif
5789 return Qnil;
5792 Lisp_Object
5793 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5795 struct gcpro gcpro1;
5796 Lisp_Object args[7];
5798 GCPRO1 (default_filename);
5799 args[0] = intern ("read-file-name");
5800 args[1] = prompt;
5801 args[2] = dir;
5802 args[3] = default_filename;
5803 args[4] = mustmatch;
5804 args[5] = initial;
5805 args[6] = predicate;
5806 RETURN_UNGCPRO (Ffuncall (7, args));
5810 void
5811 init_fileio (void)
5813 valid_timestamp_file_system = 0;
5816 void
5817 syms_of_fileio (void)
5819 DEFSYM (Qoperations, "operations");
5820 DEFSYM (Qexpand_file_name, "expand-file-name");
5821 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5822 DEFSYM (Qdirectory_file_name, "directory-file-name");
5823 DEFSYM (Qfile_name_directory, "file-name-directory");
5824 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5825 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5826 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5827 DEFSYM (Qcopy_file, "copy-file");
5828 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5829 DEFSYM (Qmake_directory, "make-directory");
5830 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5831 DEFSYM (Qdelete_file, "delete-file");
5832 DEFSYM (Qrename_file, "rename-file");
5833 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5834 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5835 DEFSYM (Qfile_exists_p, "file-exists-p");
5836 DEFSYM (Qfile_executable_p, "file-executable-p");
5837 DEFSYM (Qfile_readable_p, "file-readable-p");
5838 DEFSYM (Qfile_writable_p, "file-writable-p");
5839 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5840 DEFSYM (Qaccess_file, "access-file");
5841 DEFSYM (Qfile_directory_p, "file-directory-p");
5842 DEFSYM (Qfile_regular_p, "file-regular-p");
5843 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5844 DEFSYM (Qfile_modes, "file-modes");
5845 DEFSYM (Qset_file_modes, "set-file-modes");
5846 DEFSYM (Qset_file_times, "set-file-times");
5847 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5848 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5849 DEFSYM (Qfile_acl, "file-acl");
5850 DEFSYM (Qset_file_acl, "set-file-acl");
5851 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5852 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5853 DEFSYM (Qchoose_write_coding_system, "choose-write-coding-system");
5854 DEFSYM (Qwrite_region, "write-region");
5855 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5856 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5857 DEFSYM (Qauto_save_coding, "auto-save-coding");
5859 DEFSYM (Qfile_name_history, "file-name-history");
5860 Fset (Qfile_name_history, Qnil);
5862 DEFSYM (Qfile_error, "file-error");
5863 DEFSYM (Qfile_already_exists, "file-already-exists");
5864 DEFSYM (Qfile_date_error, "file-date-error");
5865 DEFSYM (Qfile_notify_error, "file-notify-error");
5866 DEFSYM (Qexcl, "excl");
5868 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5869 doc: /* Coding system for encoding file names.
5870 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5871 Vfile_name_coding_system = Qnil;
5873 DEFVAR_LISP ("default-file-name-coding-system",
5874 Vdefault_file_name_coding_system,
5875 doc: /* Default coding system for encoding file names.
5876 This variable is used only when `file-name-coding-system' is nil.
5878 This variable is set/changed by the command `set-language-environment'.
5879 User should not set this variable manually,
5880 instead use `file-name-coding-system' to get a constant encoding
5881 of file names regardless of the current language environment. */);
5882 Vdefault_file_name_coding_system = Qnil;
5884 DEFSYM (Qformat_decode, "format-decode");
5885 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5886 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5887 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5889 Fput (Qfile_error, Qerror_conditions,
5890 Fpurecopy (list2 (Qfile_error, Qerror)));
5891 Fput (Qfile_error, Qerror_message,
5892 build_pure_c_string ("File error"));
5894 Fput (Qfile_already_exists, Qerror_conditions,
5895 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5896 Fput (Qfile_already_exists, Qerror_message,
5897 build_pure_c_string ("File already exists"));
5899 Fput (Qfile_date_error, Qerror_conditions,
5900 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5901 Fput (Qfile_date_error, Qerror_message,
5902 build_pure_c_string ("Cannot set file date"));
5904 Fput (Qfile_notify_error, Qerror_conditions,
5905 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5906 Fput (Qfile_notify_error, Qerror_message,
5907 build_pure_c_string ("File notification error"));
5909 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5910 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5911 If a file name matches REGEXP, all I/O on that file is done by calling
5912 HANDLER. If a file name matches more than one handler, the handler
5913 whose match starts last in the file name gets precedence. The
5914 function `find-file-name-handler' checks this list for a handler for
5915 its argument.
5917 HANDLER should be a function. The first argument given to it is the
5918 name of the I/O primitive to be handled; the remaining arguments are
5919 the arguments that were passed to that primitive. For example, if you
5920 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5921 HANDLER is called like this:
5923 (funcall HANDLER 'file-exists-p FILENAME)
5925 Note that HANDLER must be able to handle all I/O primitives; if it has
5926 nothing special to do for a primitive, it should reinvoke the
5927 primitive to handle the operation \"the usual way\".
5928 See Info node `(elisp)Magic File Names' for more details. */);
5929 Vfile_name_handler_alist = Qnil;
5931 DEFVAR_LISP ("set-auto-coding-function",
5932 Vset_auto_coding_function,
5933 doc: /* If non-nil, a function to call to decide a coding system of file.
5934 Two arguments are passed to this function: the file name
5935 and the length of a file contents following the point.
5936 This function should return a coding system to decode the file contents.
5937 It should check the file name against `auto-coding-alist'.
5938 If no coding system is decided, it should check a coding system
5939 specified in the heading lines with the format:
5940 -*- ... coding: CODING-SYSTEM; ... -*-
5941 or local variable spec of the tailing lines with `coding:' tag. */);
5942 Vset_auto_coding_function = Qnil;
5944 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5945 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5946 Each is passed one argument, the number of characters inserted,
5947 with point at the start of the inserted text. Each function
5948 should leave point the same, and return the new character count.
5949 If `insert-file-contents' is intercepted by a handler from
5950 `file-name-handler-alist', that handler is responsible for calling the
5951 functions in `after-insert-file-functions' if appropriate. */);
5952 Vafter_insert_file_functions = Qnil;
5954 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5955 doc: /* A list of functions to be called at the start of `write-region'.
5956 Each is passed two arguments, START and END as for `write-region'.
5957 These are usually two numbers but not always; see the documentation
5958 for `write-region'. The function should return a list of pairs
5959 of the form (POSITION . STRING), consisting of strings to be effectively
5960 inserted at the specified positions of the file being written (1 means to
5961 insert before the first byte written). The POSITIONs must be sorted into
5962 increasing order.
5964 If there are several annotation functions, the lists returned by these
5965 functions are merged destructively. As each annotation function runs,
5966 the variable `write-region-annotations-so-far' contains a list of all
5967 annotations returned by previous annotation functions.
5969 An annotation function can return with a different buffer current.
5970 Doing so removes the annotations returned by previous functions, and
5971 resets START and END to `point-min' and `point-max' of the new buffer.
5973 After `write-region' completes, Emacs calls the function stored in
5974 `write-region-post-annotation-function', once for each buffer that was
5975 current when building the annotations (i.e., at least once), with that
5976 buffer current. */);
5977 Vwrite_region_annotate_functions = Qnil;
5978 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5980 DEFVAR_LISP ("write-region-post-annotation-function",
5981 Vwrite_region_post_annotation_function,
5982 doc: /* Function to call after `write-region' completes.
5983 The function is called with no arguments. If one or more of the
5984 annotation functions in `write-region-annotate-functions' changed the
5985 current buffer, the function stored in this variable is called for
5986 each of those additional buffers as well, in addition to the original
5987 buffer. The relevant buffer is current during each function call. */);
5988 Vwrite_region_post_annotation_function = Qnil;
5989 staticpro (&Vwrite_region_annotation_buffers);
5991 DEFVAR_LISP ("write-region-annotations-so-far",
5992 Vwrite_region_annotations_so_far,
5993 doc: /* When an annotation function is called, this holds the previous annotations.
5994 These are the annotations made by other annotation functions
5995 that were already called. See also `write-region-annotate-functions'. */);
5996 Vwrite_region_annotations_so_far = Qnil;
5998 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5999 doc: /* A list of file name handlers that temporarily should not be used.
6000 This applies only to the operation `inhibit-file-name-operation'. */);
6001 Vinhibit_file_name_handlers = Qnil;
6003 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
6004 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6005 Vinhibit_file_name_operation = Qnil;
6007 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
6008 doc: /* File name in which we write a list of all auto save file names.
6009 This variable is initialized automatically from `auto-save-list-file-prefix'
6010 shortly after Emacs reads your init file, if you have not yet given it
6011 a non-nil value. */);
6012 Vauto_save_list_file_name = Qnil;
6014 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
6015 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6016 Normally auto-save files are written under other names. */);
6017 Vauto_save_visited_file_name = Qnil;
6019 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
6020 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6021 If nil, deleting a substantial portion of the text disables auto-save
6022 in the buffer; this is the default behavior, because the auto-save
6023 file is usually more useful if it contains the deleted text. */);
6024 Vauto_save_include_big_deletions = Qnil;
6026 /* fsync can be a significant performance hit. Often it doesn't
6027 suffice to make the file-save operation survive a crash. For
6028 batch scripts, which are typically part of larger shell commands
6029 that don't fsync other files, its effect on performance can be
6030 significant so its utility is particularly questionable.
6031 Hence, for now by default fsync is used only when interactive.
6033 For more on why fsync often fails to work on today's hardware, see:
6034 Zheng M et al. Understanding the robustness of SSDs under power fault.
6035 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
6036 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
6038 For more on why fsync does not suffice even if it works properly, see:
6039 Roche X. Necessary step(s) to synchronize filename operations on disk.
6040 Austin Group Defect 672, 2013-03-19
6041 http://austingroupbugs.net/view.php?id=672 */
6042 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
6043 doc: /* Non-nil means don't call fsync in `write-region'.
6044 This variable affects calls to `write-region' as well as save commands.
6045 Setting this to nil may avoid data loss if the system loses power or
6046 the operating system crashes. */);
6047 write_region_inhibit_fsync = noninteractive;
6049 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6050 doc: /* Specifies whether to use the system's trash can.
6051 When non-nil, certain file deletion commands use the function
6052 `move-file-to-trash' instead of deleting files outright.
6053 This includes interactive calls to `delete-file' and
6054 `delete-directory' and the Dired deletion commands. */);
6055 delete_by_moving_to_trash = 0;
6056 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
6058 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6059 DEFSYM (Qcopy_directory, "copy-directory");
6060 DEFSYM (Qdelete_directory, "delete-directory");
6062 defsubr (&Sfind_file_name_handler);
6063 defsubr (&Sfile_name_directory);
6064 defsubr (&Sfile_name_nondirectory);
6065 defsubr (&Sunhandled_file_name_directory);
6066 defsubr (&Sfile_name_as_directory);
6067 defsubr (&Sdirectory_file_name);
6068 defsubr (&Smake_temp_name);
6069 defsubr (&Sexpand_file_name);
6070 defsubr (&Ssubstitute_in_file_name);
6071 defsubr (&Scopy_file);
6072 defsubr (&Smake_directory_internal);
6073 defsubr (&Sdelete_directory_internal);
6074 defsubr (&Sdelete_file);
6075 defsubr (&Srename_file);
6076 defsubr (&Sadd_name_to_file);
6077 defsubr (&Smake_symbolic_link);
6078 defsubr (&Sfile_name_absolute_p);
6079 defsubr (&Sfile_exists_p);
6080 defsubr (&Sfile_executable_p);
6081 defsubr (&Sfile_readable_p);
6082 defsubr (&Sfile_writable_p);
6083 defsubr (&Saccess_file);
6084 defsubr (&Sfile_symlink_p);
6085 defsubr (&Sfile_directory_p);
6086 defsubr (&Sfile_accessible_directory_p);
6087 defsubr (&Sfile_regular_p);
6088 defsubr (&Sfile_modes);
6089 defsubr (&Sset_file_modes);
6090 defsubr (&Sset_file_times);
6091 defsubr (&Sfile_selinux_context);
6092 defsubr (&Sfile_acl);
6093 defsubr (&Sset_file_acl);
6094 defsubr (&Sset_file_selinux_context);
6095 defsubr (&Sset_default_file_modes);
6096 defsubr (&Sdefault_file_modes);
6097 defsubr (&Sfile_newer_than_file_p);
6098 defsubr (&Sinsert_file_contents);
6099 defsubr (&Schoose_write_coding_system);
6100 defsubr (&Swrite_region);
6101 defsubr (&Scar_less_than_car);
6102 defsubr (&Sverify_visited_file_modtime);
6103 defsubr (&Svisited_file_modtime);
6104 defsubr (&Sset_visited_file_modtime);
6105 defsubr (&Sdo_auto_save);
6106 defsubr (&Sset_buffer_auto_saved);
6107 defsubr (&Sclear_buffer_auto_save_failure);
6108 defsubr (&Srecent_auto_save_p);
6110 defsubr (&Snext_read_file_uses_dialog_p);
6112 #ifdef HAVE_SYNC
6113 defsubr (&Sunix_sync);
6114 #endif