* lisp/progmodes/ruby-mode.el (ruby-mode-set-encoding):
[emacs.git] / src / fileio.c
blobd42b3811d76d557e1b34ee386bb38b8a79498e22
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 static Lisp_Object Qsubstitute_env_in_file_name;
148 #ifdef WINDOWSNT
149 #endif
151 Lisp_Object Qfile_error, Qfile_notify_error;
152 static Lisp_Object Qfile_already_exists, Qfile_date_error;
153 static Lisp_Object Qexcl;
154 Lisp_Object Qfile_name_history;
156 static Lisp_Object Qcar_less_than_car;
158 static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
159 Lisp_Object *, struct coding_system *);
160 static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
161 struct coding_system *);
164 /* Return true if FILENAME exists. */
166 static bool
167 check_existing (const char *filename)
169 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
172 /* Return true if file FILENAME exists and can be executed. */
174 static bool
175 check_executable (char *filename)
177 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
180 /* Return true if file FILENAME exists and can be accessed
181 according to AMODE, which should include W_OK.
182 On failure, return false and set errno. */
184 static bool
185 check_writable (const char *filename, int amode)
187 #ifdef MSDOS
188 /* FIXME: an faccessat implementation should be added to the
189 DOS/Windows ports and this #ifdef branch should be removed. */
190 struct stat st;
191 if (stat (filename, &st) < 0)
192 return 0;
193 errno = EPERM;
194 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
195 #else /* not MSDOS */
196 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
197 #ifdef CYGWIN
198 /* faccessat may have returned failure because Cygwin couldn't
199 determine the file's UID or GID; if so, we return success. */
200 if (!res)
202 int faccessat_errno = errno;
203 struct stat st;
204 if (stat (filename, &st) < 0)
205 return 0;
206 res = (st.st_uid == -1 || st.st_gid == -1);
207 errno = faccessat_errno;
209 #endif /* CYGWIN */
210 return res;
211 #endif /* not MSDOS */
214 /* Signal a file-access failure. STRING describes the failure,
215 NAME the file involved, and ERRORNO the errno value.
217 If NAME is neither null nor a pair, package it up as a singleton
218 list before reporting it; this saves report_file_errno's caller the
219 trouble of preserving errno before calling list1. */
221 void
222 report_file_errno (char const *string, Lisp_Object name, int errorno)
224 Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
225 Lisp_Object errstring;
226 char *str;
228 synchronize_system_messages_locale ();
229 str = strerror (errorno);
230 errstring = code_convert_string_norecord (build_unibyte_string (str),
231 Vlocale_coding_system, 0);
233 while (1)
234 switch (errorno)
236 case EEXIST:
237 xsignal (Qfile_already_exists, Fcons (errstring, data));
238 break;
239 default:
240 /* System error messages are capitalized. Downcase the initial
241 unless it is followed by a slash. (The slash case caters to
242 error messages that begin with "I/O" or, in German, "E/A".) */
243 if (STRING_MULTIBYTE (errstring)
244 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
246 int c;
248 str = SSDATA (errstring);
249 c = STRING_CHAR ((unsigned char *) str);
250 Faset (errstring, make_number (0), make_number (downcase (c)));
253 xsignal (Qfile_error,
254 Fcons (build_string (string), Fcons (errstring, data)));
258 /* Signal a file-access failure that set errno. STRING describes the
259 failure, NAME the file involved. When invoking this function, take
260 care to not use arguments such as build_string ("foo") that involve
261 side effects that may set errno. */
263 void
264 report_file_error (char const *string, Lisp_Object name)
266 report_file_errno (string, name, errno);
269 void
270 close_file_unwind (int fd)
272 emacs_close (fd);
275 void
276 fclose_unwind (void *arg)
278 FILE *stream = arg;
279 fclose (stream);
282 /* Restore point, having saved it as a marker. */
284 void
285 restore_point_unwind (Lisp_Object location)
287 Fgoto_char (location);
288 unchain_marker (XMARKER (location));
292 static Lisp_Object Qexpand_file_name;
293 static Lisp_Object Qsubstitute_in_file_name;
294 static Lisp_Object Qdirectory_file_name;
295 static Lisp_Object Qfile_name_directory;
296 static Lisp_Object Qfile_name_nondirectory;
297 static Lisp_Object Qunhandled_file_name_directory;
298 static Lisp_Object Qfile_name_as_directory;
299 static Lisp_Object Qcopy_file;
300 static Lisp_Object Qmake_directory_internal;
301 static Lisp_Object Qmake_directory;
302 static Lisp_Object Qdelete_directory_internal;
303 Lisp_Object Qdelete_file;
304 static Lisp_Object Qrename_file;
305 static Lisp_Object Qadd_name_to_file;
306 static Lisp_Object Qmake_symbolic_link;
307 Lisp_Object Qfile_exists_p;
308 static Lisp_Object Qfile_executable_p;
309 static Lisp_Object Qfile_readable_p;
310 static Lisp_Object Qfile_writable_p;
311 static Lisp_Object Qfile_symlink_p;
312 static Lisp_Object Qaccess_file;
313 Lisp_Object Qfile_directory_p;
314 static Lisp_Object Qfile_regular_p;
315 static Lisp_Object Qfile_accessible_directory_p;
316 static Lisp_Object Qfile_modes;
317 static Lisp_Object Qset_file_modes;
318 static Lisp_Object Qset_file_times;
319 static Lisp_Object Qfile_selinux_context;
320 static Lisp_Object Qset_file_selinux_context;
321 static Lisp_Object Qfile_acl;
322 static Lisp_Object Qset_file_acl;
323 static Lisp_Object Qfile_newer_than_file_p;
324 Lisp_Object Qinsert_file_contents;
325 static Lisp_Object Qchoose_write_coding_system;
326 Lisp_Object Qwrite_region;
327 static Lisp_Object Qverify_visited_file_modtime;
328 static Lisp_Object Qset_visited_file_modtime;
330 DEFUN ("find-file-name-handler", Ffind_file_name_handler,
331 Sfind_file_name_handler, 2, 2, 0,
332 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
333 Otherwise, return nil.
334 A file name is handled if one of the regular expressions in
335 `file-name-handler-alist' matches it.
337 If OPERATION equals `inhibit-file-name-operation', then we ignore
338 any handlers that are members of `inhibit-file-name-handlers',
339 but we still do run any other handlers. This lets handlers
340 use the standard functions without calling themselves recursively. */)
341 (Lisp_Object filename, Lisp_Object operation)
343 /* This function must not munge the match data. */
344 Lisp_Object chain, inhibited_handlers, result;
345 ptrdiff_t pos = -1;
347 result = Qnil;
348 CHECK_STRING (filename);
350 if (EQ (operation, Vinhibit_file_name_operation))
351 inhibited_handlers = Vinhibit_file_name_handlers;
352 else
353 inhibited_handlers = Qnil;
355 for (chain = Vfile_name_handler_alist; CONSP (chain);
356 chain = XCDR (chain))
358 Lisp_Object elt;
359 elt = XCAR (chain);
360 if (CONSP (elt))
362 Lisp_Object string = XCAR (elt);
363 ptrdiff_t match_pos;
364 Lisp_Object handler = XCDR (elt);
365 Lisp_Object operations = Qnil;
367 if (SYMBOLP (handler))
368 operations = Fget (handler, Qoperations);
370 if (STRINGP (string)
371 && (match_pos = fast_string_match (string, filename)) > pos
372 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
374 Lisp_Object tem;
376 handler = XCDR (elt);
377 tem = Fmemq (handler, inhibited_handlers);
378 if (NILP (tem))
380 result = handler;
381 pos = match_pos;
386 QUIT;
388 return result;
391 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
392 1, 1, 0,
393 doc: /* Return the directory component in file name FILENAME.
394 Return nil if FILENAME does not include a directory.
395 Otherwise return a directory name.
396 Given a Unix syntax file name, returns a string ending in slash. */)
397 (Lisp_Object filename)
399 #ifndef DOS_NT
400 register const char *beg;
401 #else
402 register char *beg;
403 Lisp_Object tem_fn;
404 #endif
405 register const char *p;
406 Lisp_Object handler;
408 CHECK_STRING (filename);
410 /* If the file name has special constructs in it,
411 call the corresponding file handler. */
412 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
413 if (!NILP (handler))
415 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
416 filename);
417 return STRINGP (handled_name) ? handled_name : Qnil;
420 #ifdef DOS_NT
421 beg = xlispstrdupa (filename);
422 #else
423 beg = SSDATA (filename);
424 #endif
425 p = beg + SBYTES (filename);
427 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
428 #ifdef DOS_NT
429 /* only recognize drive specifier at the beginning */
430 && !(p[-1] == ':'
431 /* handle the "/:d:foo" and "/:foo" cases correctly */
432 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
433 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
434 #endif
435 ) p--;
437 if (p == beg)
438 return Qnil;
439 #ifdef DOS_NT
440 /* Expansion of "c:" to drive and default directory. */
441 if (p[-1] == ':')
443 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
444 char *res = alloca (MAXPATHLEN + 1);
445 char *r = res;
447 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
449 memcpy (res, beg, 2);
450 beg += 2;
451 r += 2;
454 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
456 size_t l = strlen (res);
458 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
459 strcat (res, "/");
460 beg = res;
461 p = beg + strlen (beg);
462 dostounix_filename (beg, 0);
463 tem_fn = make_specified_string (beg, -1, p - beg,
464 STRING_MULTIBYTE (filename));
466 else
467 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
468 STRING_MULTIBYTE (filename));
470 else if (STRING_MULTIBYTE (filename))
472 tem_fn = make_specified_string (beg, -1, p - beg, 1);
473 dostounix_filename (SSDATA (tem_fn), 1);
474 #ifdef WINDOWSNT
475 if (!NILP (Vw32_downcase_file_names))
476 tem_fn = Fdowncase (tem_fn);
477 #endif
479 else
481 dostounix_filename (beg, 0);
482 tem_fn = make_specified_string (beg, -1, p - beg, 0);
484 return tem_fn;
485 #else /* DOS_NT */
486 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
487 #endif /* DOS_NT */
490 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
491 Sfile_name_nondirectory, 1, 1, 0,
492 doc: /* Return file name FILENAME sans its directory.
493 For example, in a Unix-syntax file name,
494 this is everything after the last slash,
495 or the entire name if it contains no slash. */)
496 (Lisp_Object filename)
498 register const char *beg, *p, *end;
499 Lisp_Object handler;
501 CHECK_STRING (filename);
503 /* If the file name has special constructs in it,
504 call the corresponding file handler. */
505 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
506 if (!NILP (handler))
508 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
509 filename);
510 if (STRINGP (handled_name))
511 return handled_name;
512 error ("Invalid handler in `file-name-handler-alist'");
515 beg = SSDATA (filename);
516 end = p = beg + SBYTES (filename);
518 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
519 #ifdef DOS_NT
520 /* only recognize drive specifier at beginning */
521 && !(p[-1] == ':'
522 /* handle the "/:d:foo" case correctly */
523 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
524 #endif
526 p--;
528 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
531 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
532 Sunhandled_file_name_directory, 1, 1, 0,
533 doc: /* Return a directly usable directory name somehow associated with FILENAME.
534 A `directly usable' directory name is one that may be used without the
535 intervention of any file handler.
536 If FILENAME is a directly usable file itself, return
537 \(file-name-directory FILENAME).
538 If FILENAME refers to a file which is not accessible from a local process,
539 then this should return nil.
540 The `call-process' and `start-process' functions use this function to
541 get a current directory to run processes in. */)
542 (Lisp_Object filename)
544 Lisp_Object handler;
546 /* If the file name has special constructs in it,
547 call the corresponding file handler. */
548 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
549 if (!NILP (handler))
551 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
552 filename);
553 return STRINGP (handled_name) ? handled_name : Qnil;
556 return Ffile_name_directory (filename);
559 /* Maximum number of bytes that DST will be longer than SRC
560 in file_name_as_directory. This occurs when SRCLEN == 0. */
561 enum { file_name_as_directory_slop = 2 };
563 /* Convert from file name SRC of length SRCLEN to directory name in
564 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
565 string. On UNIX, just make sure there is a terminating /. Return
566 the length of DST in bytes. */
568 static ptrdiff_t
569 file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
570 bool multibyte)
572 if (srclen == 0)
574 dst[0] = '.';
575 dst[1] = '/';
576 dst[2] = '\0';
577 return 2;
580 memcpy (dst, src, srclen);
581 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
582 dst[srclen++] = DIRECTORY_SEP;
583 dst[srclen] = 0;
584 #ifdef DOS_NT
585 dostounix_filename (dst, multibyte);
586 #endif
587 return srclen;
590 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
591 Sfile_name_as_directory, 1, 1, 0,
592 doc: /* Return a string representing the file name FILE interpreted as a directory.
593 This operation exists because a directory is also a file, but its name as
594 a directory is different from its name as a file.
595 The result can be used as the value of `default-directory'
596 or passed as second argument to `expand-file-name'.
597 For a Unix-syntax file name, just appends a slash. */)
598 (Lisp_Object file)
600 char *buf;
601 ptrdiff_t length;
602 Lisp_Object handler, val;
603 USE_SAFE_ALLOCA;
605 CHECK_STRING (file);
606 if (NILP (file))
607 return Qnil;
609 /* If the file name has special constructs in it,
610 call the corresponding file handler. */
611 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
612 if (!NILP (handler))
614 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
615 file);
616 if (STRINGP (handled_name))
617 return handled_name;
618 error ("Invalid handler in `file-name-handler-alist'");
621 #ifdef WINDOWSNT
622 if (!NILP (Vw32_downcase_file_names))
623 file = Fdowncase (file);
624 #endif
625 buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
626 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
627 STRING_MULTIBYTE (file));
628 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
629 SAFE_FREE ();
630 return val;
633 /* Convert from directory name SRC of length SRCLEN to file name in
634 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
635 string. On UNIX, just make sure there isn't a terminating /.
636 Return the length of DST in bytes. */
638 static ptrdiff_t
639 directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
641 /* Process as Unix format: just remove any final slash.
642 But leave "/" and "//" unchanged. */
643 while (srclen > 1
644 #ifdef DOS_NT
645 && !IS_ANY_SEP (src[srclen - 2])
646 #endif
647 && IS_DIRECTORY_SEP (src[srclen - 1])
648 && ! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
649 srclen--;
651 memcpy (dst, src, srclen);
652 dst[srclen] = 0;
653 #ifdef DOS_NT
654 dostounix_filename (dst, multibyte);
655 #endif
656 return srclen;
659 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
660 1, 1, 0,
661 doc: /* Returns the file name of the directory named DIRECTORY.
662 This is the name of the file that holds the data for the directory DIRECTORY.
663 This operation exists because a directory is also a file, but its name as
664 a directory is different from its name as a file.
665 In Unix-syntax, this function just removes the final slash. */)
666 (Lisp_Object directory)
668 char *buf;
669 ptrdiff_t length;
670 Lisp_Object handler, val;
671 USE_SAFE_ALLOCA;
673 CHECK_STRING (directory);
675 if (NILP (directory))
676 return Qnil;
678 /* If the file name has special constructs in it,
679 call the corresponding file handler. */
680 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
681 if (!NILP (handler))
683 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
684 directory);
685 if (STRINGP (handled_name))
686 return handled_name;
687 error ("Invalid handler in `file-name-handler-alist'");
690 #ifdef WINDOWSNT
691 if (!NILP (Vw32_downcase_file_names))
692 directory = Fdowncase (directory);
693 #endif
694 buf = SAFE_ALLOCA (SBYTES (directory) + 1);
695 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
696 STRING_MULTIBYTE (directory));
697 val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
698 SAFE_FREE ();
699 return val;
702 static const char make_temp_name_tbl[64] =
704 'A','B','C','D','E','F','G','H',
705 'I','J','K','L','M','N','O','P',
706 'Q','R','S','T','U','V','W','X',
707 'Y','Z','a','b','c','d','e','f',
708 'g','h','i','j','k','l','m','n',
709 'o','p','q','r','s','t','u','v',
710 'w','x','y','z','0','1','2','3',
711 '4','5','6','7','8','9','-','_'
714 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
716 /* Value is a temporary file name starting with PREFIX, a string.
718 The Emacs process number forms part of the result, so there is
719 no danger of generating a name being used by another process.
720 In addition, this function makes an attempt to choose a name
721 which has no existing file. To make this work, PREFIX should be
722 an absolute file name.
724 BASE64_P means add the pid as 3 characters in base64
725 encoding. In this case, 6 characters will be added to PREFIX to
726 form the file name. Otherwise, if Emacs is running on a system
727 with long file names, add the pid as a decimal number.
729 This function signals an error if no unique file name could be
730 generated. */
732 Lisp_Object
733 make_temp_name (Lisp_Object prefix, bool base64_p)
735 Lisp_Object val, encoded_prefix;
736 int len;
737 printmax_t pid;
738 char *p, *data;
739 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
740 int pidlen;
742 CHECK_STRING (prefix);
744 /* VAL is created by adding 6 characters to PREFIX. The first
745 three are the PID of this process, in base 64, and the second
746 three are incremented if the file already exists. This ensures
747 262144 unique file names per PID per PREFIX. */
749 pid = getpid ();
751 if (base64_p)
753 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
754 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
755 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
756 pidlen = 3;
758 else
760 #ifdef HAVE_LONG_FILE_NAMES
761 pidlen = sprintf (pidbuf, "%"pMd, pid);
762 #else
763 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
764 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
765 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
766 pidlen = 3;
767 #endif
770 encoded_prefix = ENCODE_FILE (prefix);
771 len = SBYTES (encoded_prefix);
772 val = make_uninit_string (len + 3 + pidlen);
773 data = SSDATA (val);
774 memcpy (data, SSDATA (encoded_prefix), len);
775 p = data + len;
777 memcpy (p, pidbuf, pidlen);
778 p += pidlen;
780 /* Here we try to minimize useless stat'ing when this function is
781 invoked many times successively with the same PREFIX. We achieve
782 this by initializing count to a random value, and incrementing it
783 afterwards.
785 We don't want make-temp-name to be called while dumping,
786 because then make_temp_name_count_initialized_p would get set
787 and then make_temp_name_count would not be set when Emacs starts. */
789 if (!make_temp_name_count_initialized_p)
791 make_temp_name_count = time (NULL);
792 make_temp_name_count_initialized_p = 1;
795 while (1)
797 unsigned num = make_temp_name_count;
799 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
800 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
801 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
803 /* Poor man's congruential RN generator. Replace with
804 ++make_temp_name_count for debugging. */
805 make_temp_name_count += 25229;
806 make_temp_name_count %= 225307;
808 if (!check_existing (data))
810 /* We want to return only if errno is ENOENT. */
811 if (errno == ENOENT)
812 return DECODE_FILE (val);
813 else
814 /* The error here is dubious, but there is little else we
815 can do. The alternatives are to return nil, which is
816 as bad as (and in many cases worse than) throwing the
817 error, or to ignore the error, which will likely result
818 in looping through 225307 stat's, which is not only
819 dog-slow, but also useless since eventually nil would
820 have to be returned anyway. */
821 report_file_error ("Cannot create temporary name for prefix",
822 prefix);
823 /* not reached */
829 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
830 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
831 The Emacs process number forms part of the result,
832 so there is no danger of generating a name being used by another process.
834 In addition, this function makes an attempt to choose a name
835 which has no existing file. To make this work,
836 PREFIX should be an absolute file name.
838 There is a race condition between calling `make-temp-name' and creating the
839 file which opens all kinds of security holes. For that reason, you should
840 probably use `make-temp-file' instead, except in three circumstances:
842 * If you are creating the file in the user's home directory.
843 * If you are creating a directory rather than an ordinary file.
844 * If you are taking special precautions as `make-temp-file' does. */)
845 (Lisp_Object prefix)
847 return make_temp_name (prefix, 0);
852 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
853 doc: /* Convert filename NAME to absolute, and canonicalize it.
854 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
855 \(does not start with slash or tilde); both the directory name and
856 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
857 missing, the current buffer's value of `default-directory' is used.
858 NAME should be a string that is a valid file name for the underlying
859 filesystem.
860 File name components that are `.' are removed, and
861 so are file name components followed by `..', along with the `..' itself;
862 note that these simplifications are done without checking the resulting
863 file names in the file system.
864 Multiple consecutive slashes are collapsed into a single slash,
865 except at the beginning of the file name when they are significant (e.g.,
866 UNC file names on MS-Windows.)
867 An initial `~/' expands to your home directory.
868 An initial `~USER/' expands to USER's home directory.
869 See also the function `substitute-in-file-name'.
871 For technical reasons, this function can return correct but
872 non-intuitive results for the root directory; for instance,
873 \(expand-file-name ".." "/") returns "/..". For this reason, use
874 \(directory-file-name (file-name-directory dirname)) to traverse a
875 filesystem tree, not (expand-file-name ".." dirname). */)
876 (Lisp_Object name, Lisp_Object default_directory)
878 /* These point to SDATA and need to be careful with string-relocation
879 during GC (via DECODE_FILE). */
880 char *nm;
881 const char *newdir;
882 /* This should only point to alloca'd data. */
883 char *target;
885 ptrdiff_t tlen;
886 struct passwd *pw;
887 #ifdef DOS_NT
888 int drive = 0;
889 bool collapse_newdir = 1;
890 bool is_escaped = 0;
891 #endif /* DOS_NT */
892 ptrdiff_t length;
893 Lisp_Object handler, result, handled_name;
894 bool multibyte;
895 Lisp_Object hdir;
896 USE_SAFE_ALLOCA;
898 CHECK_STRING (name);
900 /* If the file name has special constructs in it,
901 call the corresponding file handler. */
902 handler = Ffind_file_name_handler (name, Qexpand_file_name);
903 if (!NILP (handler))
905 handled_name = call3 (handler, Qexpand_file_name,
906 name, default_directory);
907 if (STRINGP (handled_name))
908 return handled_name;
909 error ("Invalid handler in `file-name-handler-alist'");
913 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
914 if (NILP (default_directory))
915 default_directory = BVAR (current_buffer, directory);
916 if (! STRINGP (default_directory))
918 #ifdef DOS_NT
919 /* "/" is not considered a root directory on DOS_NT, so using "/"
920 here causes an infinite recursion in, e.g., the following:
922 (let (default-directory)
923 (expand-file-name "a"))
925 To avoid this, we set default_directory to the root of the
926 current drive. */
927 default_directory = build_string (emacs_root_dir ());
928 #else
929 default_directory = build_string ("/");
930 #endif
933 if (!NILP (default_directory))
935 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
936 if (!NILP (handler))
938 handled_name = call3 (handler, Qexpand_file_name,
939 name, default_directory);
940 if (STRINGP (handled_name))
941 return handled_name;
942 error ("Invalid handler in `file-name-handler-alist'");
947 char *o = SSDATA (default_directory);
949 /* Make sure DEFAULT_DIRECTORY is properly expanded.
950 It would be better to do this down below where we actually use
951 default_directory. Unfortunately, calling Fexpand_file_name recursively
952 could invoke GC, and the strings might be relocated. This would
953 be annoying because we have pointers into strings lying around
954 that would need adjusting, and people would add new pointers to
955 the code and forget to adjust them, resulting in intermittent bugs.
956 Putting this call here avoids all that crud.
958 The EQ test avoids infinite recursion. */
959 if (! NILP (default_directory) && !EQ (default_directory, name)
960 /* Save time in some common cases - as long as default_directory
961 is not relative, it can be canonicalized with name below (if it
962 is needed at all) without requiring it to be expanded now. */
963 #ifdef DOS_NT
964 /* Detect MSDOS file names with drive specifiers. */
965 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
966 && IS_DIRECTORY_SEP (o[2]))
967 #ifdef WINDOWSNT
968 /* Detect Windows file names in UNC format. */
969 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
970 #endif
971 #else /* not DOS_NT */
972 /* Detect Unix absolute file names (/... alone is not absolute on
973 DOS or Windows). */
974 && ! (IS_DIRECTORY_SEP (o[0]))
975 #endif /* not DOS_NT */
978 struct gcpro gcpro1;
980 GCPRO1 (name);
981 default_directory = Fexpand_file_name (default_directory, Qnil);
982 UNGCPRO;
985 multibyte = STRING_MULTIBYTE (name);
986 if (multibyte != STRING_MULTIBYTE (default_directory))
988 if (multibyte)
990 unsigned char *p = SDATA (name);
992 while (*p && ASCII_BYTE_P (*p))
993 p++;
994 if (*p == '\0')
996 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
997 unibyte. Do not convert DEFAULT_DIRECTORY to
998 multibyte; instead, convert NAME to a unibyte string,
999 so that the result of this function is also a unibyte
1000 string. This is needed during bootstrapping and
1001 dumping, when Emacs cannot decode file names, because
1002 the locale environment is not set up. */
1003 name = make_unibyte_string (SSDATA (name), SBYTES (name));
1004 multibyte = 0;
1006 else
1007 default_directory = string_to_multibyte (default_directory);
1009 else
1011 name = string_to_multibyte (name);
1012 multibyte = 1;
1016 #ifdef WINDOWSNT
1017 if (!NILP (Vw32_downcase_file_names))
1018 default_directory = Fdowncase (default_directory);
1019 #endif
1021 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
1022 nm = xlispstrdupa (name);
1024 #ifdef DOS_NT
1025 /* Note if special escape prefix is present, but remove for now. */
1026 if (nm[0] == '/' && nm[1] == ':')
1028 is_escaped = 1;
1029 nm += 2;
1032 /* Find and remove drive specifier if present; this makes nm absolute
1033 even if the rest of the name appears to be relative. Only look for
1034 drive specifier at the beginning. */
1035 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
1037 drive = (unsigned char) nm[0];
1038 nm += 2;
1041 #ifdef WINDOWSNT
1042 /* If we see "c://somedir", we want to strip the first slash after the
1043 colon when stripping the drive letter. Otherwise, this expands to
1044 "//somedir". */
1045 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1046 nm++;
1048 /* Discard any previous drive specifier if nm is now in UNC format. */
1049 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1051 drive = 0;
1053 #endif /* WINDOWSNT */
1054 #endif /* DOS_NT */
1056 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
1057 none are found, we can probably return right away. We will avoid
1058 allocating a new string if name is already fully expanded. */
1059 if (
1060 IS_DIRECTORY_SEP (nm[0])
1061 #ifdef MSDOS
1062 && drive && !is_escaped
1063 #endif
1064 #ifdef WINDOWSNT
1065 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
1066 #endif
1069 /* If it turns out that the filename we want to return is just a
1070 suffix of FILENAME, we don't need to go through and edit
1071 things; we just need to construct a new string using data
1072 starting at the middle of FILENAME. If we set LOSE, that
1073 means we've discovered that we can't do that cool trick. */
1074 bool lose = 0;
1075 char *p = nm;
1077 while (*p)
1079 /* Since we know the name is absolute, we can assume that each
1080 element starts with a "/". */
1082 /* "." and ".." are hairy. */
1083 if (IS_DIRECTORY_SEP (p[0])
1084 && p[1] == '.'
1085 && (IS_DIRECTORY_SEP (p[2])
1086 || p[2] == 0
1087 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1088 || p[3] == 0))))
1089 lose = 1;
1090 /* Replace multiple slashes with a single one, except
1091 leave leading "//" alone. */
1092 else if (IS_DIRECTORY_SEP (p[0])
1093 && IS_DIRECTORY_SEP (p[1])
1094 && (p != nm || IS_DIRECTORY_SEP (p[2])))
1095 lose = 1;
1096 p++;
1098 if (!lose)
1100 #ifdef DOS_NT
1101 /* Make sure directories are all separated with /, but
1102 avoid allocation of a new string when not required. */
1103 dostounix_filename (nm, multibyte);
1104 #ifdef WINDOWSNT
1105 if (IS_DIRECTORY_SEP (nm[1]))
1107 if (strcmp (nm, SSDATA (name)) != 0)
1108 name = make_specified_string (nm, -1, strlen (nm), multibyte);
1110 else
1111 #endif
1112 /* Drive must be set, so this is okay. */
1113 if (strcmp (nm - 2, SSDATA (name)) != 0)
1115 char temp[] = " :";
1117 name = make_specified_string (nm, -1, p - nm, multibyte);
1118 temp[0] = DRIVE_LETTER (drive);
1119 name = concat2 (build_string (temp), name);
1121 #ifdef WINDOWSNT
1122 if (!NILP (Vw32_downcase_file_names))
1123 name = Fdowncase (name);
1124 #endif
1125 return name;
1126 #else /* not DOS_NT */
1127 if (strcmp (nm, SSDATA (name)) == 0)
1128 return name;
1129 return make_specified_string (nm, -1, strlen (nm), multibyte);
1130 #endif /* not DOS_NT */
1134 /* At this point, nm might or might not be an absolute file name. We
1135 need to expand ~ or ~user if present, otherwise prefix nm with
1136 default_directory if nm is not absolute, and finally collapse /./
1137 and /foo/../ sequences.
1139 We set newdir to be the appropriate prefix if one is needed:
1140 - the relevant user directory if nm starts with ~ or ~user
1141 - the specified drive's working dir (DOS/NT only) if nm does not
1142 start with /
1143 - the value of default_directory.
1145 Note that these prefixes are not guaranteed to be absolute (except
1146 for the working dir of a drive). Therefore, to ensure we always
1147 return an absolute name, if the final prefix is not absolute we
1148 append it to the current working directory. */
1150 newdir = 0;
1152 if (nm[0] == '~') /* prefix ~ */
1154 if (IS_DIRECTORY_SEP (nm[1])
1155 || nm[1] == 0) /* ~ by itself */
1157 Lisp_Object tem;
1159 if (!(newdir = egetenv ("HOME")))
1160 newdir = "";
1161 nm++;
1162 /* `egetenv' may return a unibyte string, which will bite us since
1163 we expect the directory to be multibyte. */
1164 tem = build_string (newdir);
1165 if (multibyte && !STRING_MULTIBYTE (tem))
1167 hdir = DECODE_FILE (tem);
1168 newdir = SSDATA (hdir);
1170 #ifdef DOS_NT
1171 collapse_newdir = 0;
1172 #endif
1174 else /* ~user/filename */
1176 char *o, *p;
1177 for (p = nm; *p && !IS_DIRECTORY_SEP (*p); p++)
1178 continue;
1179 o = SAFE_ALLOCA (p - nm + 1);
1180 memcpy (o, nm, p - nm);
1181 o[p - nm] = 0;
1183 block_input ();
1184 pw = getpwnam (o + 1);
1185 unblock_input ();
1186 if (pw)
1188 Lisp_Object tem;
1190 newdir = pw->pw_dir;
1191 /* `getpwnam' may return a unibyte string, which will
1192 bite us since we expect the directory to be
1193 multibyte. */
1194 tem = build_string (newdir);
1195 if (multibyte && !STRING_MULTIBYTE (tem))
1197 hdir = DECODE_FILE (tem);
1198 newdir = SSDATA (hdir);
1200 nm = p;
1201 #ifdef DOS_NT
1202 collapse_newdir = 0;
1203 #endif
1206 /* If we don't find a user of that name, leave the name
1207 unchanged; don't move nm forward to p. */
1211 #ifdef DOS_NT
1212 /* On DOS and Windows, nm is absolute if a drive name was specified;
1213 use the drive's current directory as the prefix if needed. */
1214 if (!newdir && drive)
1216 /* Get default directory if needed to make nm absolute. */
1217 char *adir = NULL;
1218 if (!IS_DIRECTORY_SEP (nm[0]))
1220 adir = alloca (MAXPATHLEN + 1);
1221 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1222 adir = NULL;
1223 else if (multibyte)
1225 Lisp_Object tem = build_string (adir);
1227 tem = DECODE_FILE (tem);
1228 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1231 if (!adir)
1233 /* Either nm starts with /, or drive isn't mounted. */
1234 adir = alloca (4);
1235 adir[0] = DRIVE_LETTER (drive);
1236 adir[1] = ':';
1237 adir[2] = '/';
1238 adir[3] = 0;
1240 newdir = adir;
1242 #endif /* DOS_NT */
1244 /* Finally, if no prefix has been specified and nm is not absolute,
1245 then it must be expanded relative to default_directory. */
1247 if (1
1248 #ifndef DOS_NT
1249 /* /... alone is not absolute on DOS and Windows. */
1250 && !IS_DIRECTORY_SEP (nm[0])
1251 #endif
1252 #ifdef WINDOWSNT
1253 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1254 #endif
1255 && !newdir)
1257 newdir = SSDATA (default_directory);
1258 #ifdef DOS_NT
1259 /* Note if special escape prefix is present, but remove for now. */
1260 if (newdir[0] == '/' && newdir[1] == ':')
1262 is_escaped = 1;
1263 newdir += 2;
1265 #endif
1268 #ifdef DOS_NT
1269 if (newdir)
1271 /* First ensure newdir is an absolute name. */
1272 if (
1273 /* Detect MSDOS file names with drive specifiers. */
1274 ! (IS_DRIVE (newdir[0])
1275 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1276 #ifdef WINDOWSNT
1277 /* Detect Windows file names in UNC format. */
1278 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1279 #endif
1282 /* Effectively, let newdir be (expand-file-name newdir cwd).
1283 Because of the admonition against calling expand-file-name
1284 when we have pointers into lisp strings, we accomplish this
1285 indirectly by prepending newdir to nm if necessary, and using
1286 cwd (or the wd of newdir's drive) as the new newdir. */
1287 char *adir;
1289 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1291 drive = (unsigned char) newdir[0];
1292 newdir += 2;
1294 if (!IS_DIRECTORY_SEP (nm[0]))
1296 ptrdiff_t newlen = strlen (newdir);
1297 char *tmp = alloca (newlen + file_name_as_directory_slop
1298 + strlen (nm) + 1);
1299 file_name_as_directory (tmp, newdir, newlen, multibyte);
1300 strcat (tmp, nm);
1301 nm = tmp;
1303 adir = alloca (MAXPATHLEN + 1);
1304 if (drive)
1306 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
1307 strcpy (adir, "/");
1309 else
1310 getcwd (adir, MAXPATHLEN + 1);
1311 if (multibyte)
1313 Lisp_Object tem = build_string (adir);
1315 tem = DECODE_FILE (tem);
1316 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1318 newdir = adir;
1321 /* Strip off drive name from prefix, if present. */
1322 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1324 drive = newdir[0];
1325 newdir += 2;
1328 /* Keep only a prefix from newdir if nm starts with slash
1329 (//server/share for UNC, nothing otherwise). */
1330 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1332 #ifdef WINDOWSNT
1333 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1335 char *adir = strcpy (alloca (strlen (newdir) + 1), newdir);
1336 char *p = adir + 2;
1337 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1338 p++;
1339 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1340 *p = 0;
1341 newdir = adir;
1343 else
1344 #endif
1345 newdir = "";
1348 #endif /* DOS_NT */
1350 if (newdir)
1352 /* Ignore any slash at the end of newdir, unless newdir is
1353 just "/" or "//". */
1354 length = strlen (newdir);
1355 while (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1356 && ! (length == 2 && IS_DIRECTORY_SEP (newdir[0])))
1357 length--;
1359 else
1360 length = 0;
1362 /* Now concatenate the directory and name to new space in the stack frame. */
1363 tlen = length + file_name_as_directory_slop + strlen (nm) + 1;
1364 #ifdef DOS_NT
1365 /* Reserve space for drive specifier and escape prefix, since either
1366 or both may need to be inserted. (The Microsoft x86 compiler
1367 produces incorrect code if the following two lines are combined.) */
1368 target = alloca (tlen + 4);
1369 target += 4;
1370 #else /* not DOS_NT */
1371 target = SAFE_ALLOCA (tlen);
1372 #endif /* not DOS_NT */
1373 *target = 0;
1375 if (newdir)
1377 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1379 #ifdef DOS_NT
1380 /* If newdir is effectively "C:/", then the drive letter will have
1381 been stripped and newdir will be "/". Concatenating with an
1382 absolute directory in nm produces "//", which will then be
1383 incorrectly treated as a network share. Ignore newdir in
1384 this case (keeping the drive letter). */
1385 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1386 && newdir[1] == '\0'))
1387 #endif
1389 memcpy (target, newdir, length);
1390 target[length] = 0;
1393 else
1394 file_name_as_directory (target, newdir, length, multibyte);
1397 strcat (target, nm);
1399 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1400 appear. */
1402 char *p = target;
1403 char *o = target;
1405 while (*p)
1407 if (!IS_DIRECTORY_SEP (*p))
1409 *o++ = *p++;
1411 else if (p[1] == '.'
1412 && (IS_DIRECTORY_SEP (p[2])
1413 || p[2] == 0))
1415 /* If "/." is the entire filename, keep the "/". Otherwise,
1416 just delete the whole "/.". */
1417 if (o == target && p[2] == '\0')
1418 *o++ = *p;
1419 p += 2;
1421 else if (p[1] == '.' && p[2] == '.'
1422 /* `/../' is the "superroot" on certain file systems.
1423 Turned off on DOS_NT systems because they have no
1424 "superroot" and because this causes us to produce
1425 file names like "d:/../foo" which fail file-related
1426 functions of the underlying OS. (To reproduce, try a
1427 long series of "../../" in default_directory, longer
1428 than the number of levels from the root.) */
1429 #ifndef DOS_NT
1430 && o != target
1431 #endif
1432 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1434 #ifdef WINDOWSNT
1435 char *prev_o = o;
1436 #endif
1437 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1438 continue;
1439 #ifdef WINDOWSNT
1440 /* Don't go below server level in UNC filenames. */
1441 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1442 && IS_DIRECTORY_SEP (*target))
1443 o = prev_o;
1444 else
1445 #endif
1446 /* Keep initial / only if this is the whole name. */
1447 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1448 ++o;
1449 p += 3;
1451 else if (IS_DIRECTORY_SEP (p[1])
1452 && (p != target || IS_DIRECTORY_SEP (p[2])))
1453 /* Collapse multiple "/", except leave leading "//" alone. */
1454 p++;
1455 else
1457 *o++ = *p++;
1461 #ifdef DOS_NT
1462 /* At last, set drive name. */
1463 #ifdef WINDOWSNT
1464 /* Except for network file name. */
1465 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1466 #endif /* WINDOWSNT */
1468 if (!drive) emacs_abort ();
1469 target -= 2;
1470 target[0] = DRIVE_LETTER (drive);
1471 target[1] = ':';
1473 /* Reinsert the escape prefix if required. */
1474 if (is_escaped)
1476 target -= 2;
1477 target[0] = '/';
1478 target[1] = ':';
1480 result = make_specified_string (target, -1, o - target, multibyte);
1481 dostounix_filename (SSDATA (result), multibyte);
1482 #ifdef WINDOWSNT
1483 if (!NILP (Vw32_downcase_file_names))
1484 result = Fdowncase (result);
1485 #endif
1486 #else /* !DOS_NT */
1487 result = make_specified_string (target, -1, o - target, multibyte);
1488 #endif /* !DOS_NT */
1491 /* Again look to see if the file name has special constructs in it
1492 and perhaps call the corresponding file handler. This is needed
1493 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1494 the ".." component gives us "/user@host:/bar/../baz" which needs
1495 to be expanded again. */
1496 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1497 if (!NILP (handler))
1499 handled_name = call3 (handler, Qexpand_file_name,
1500 result, default_directory);
1501 if (! STRINGP (handled_name))
1502 error ("Invalid handler in `file-name-handler-alist'");
1503 result = handled_name;
1506 SAFE_FREE ();
1507 return result;
1510 #if 0
1511 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1512 This is the old version of expand-file-name, before it was thoroughly
1513 rewritten for Emacs 10.31. We leave this version here commented-out,
1514 because the code is very complex and likely to have subtle bugs. If
1515 bugs _are_ found, it might be of interest to look at the old code and
1516 see what did it do in the relevant situation.
1518 Don't remove this code: it's true that it will be accessible
1519 from the repository, but a few years from deletion, people will
1520 forget it is there. */
1522 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1523 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1524 "Convert FILENAME to absolute, and canonicalize it.\n\
1525 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1526 \(does not start with slash); if DEFAULT is nil or missing,\n\
1527 the current buffer's value of default-directory is used.\n\
1528 Filenames containing `.' or `..' as components are simplified;\n\
1529 initial `~/' expands to your home directory.\n\
1530 See also the function `substitute-in-file-name'.")
1531 (name, defalt)
1532 Lisp_Object name, defalt;
1534 unsigned char *nm;
1536 register unsigned char *newdir, *p, *o;
1537 ptrdiff_t tlen;
1538 unsigned char *target;
1539 struct passwd *pw;
1541 CHECK_STRING (name);
1542 nm = SDATA (name);
1544 /* If nm is absolute, flush ...// and detect /./ and /../.
1545 If no /./ or /../ we can return right away. */
1546 if (nm[0] == '/')
1548 bool lose = 0;
1549 p = nm;
1550 while (*p)
1552 if (p[0] == '/' && p[1] == '/')
1553 nm = p + 1;
1554 if (p[0] == '/' && p[1] == '~')
1555 nm = p + 1, lose = 1;
1556 if (p[0] == '/' && p[1] == '.'
1557 && (p[2] == '/' || p[2] == 0
1558 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1559 lose = 1;
1560 p++;
1562 if (!lose)
1564 if (nm == SDATA (name))
1565 return name;
1566 return build_string (nm);
1570 /* Now determine directory to start with and put it in NEWDIR. */
1572 newdir = 0;
1574 if (nm[0] == '~') /* prefix ~ */
1575 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
1577 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1578 newdir = (unsigned char *) "";
1579 nm++;
1581 else /* ~user/filename */
1583 /* Get past ~ to user. */
1584 unsigned char *user = nm + 1;
1585 /* Find end of name. */
1586 unsigned char *ptr = (unsigned char *) strchr (user, '/');
1587 ptrdiff_t len = ptr ? ptr - user : strlen (user);
1588 /* Copy the user name into temp storage. */
1589 o = alloca (len + 1);
1590 memcpy (o, user, len);
1591 o[len] = 0;
1593 /* Look up the user name. */
1594 block_input ();
1595 pw = (struct passwd *) getpwnam (o + 1);
1596 unblock_input ();
1597 if (!pw)
1598 error ("\"%s\" isn't a registered user", o + 1);
1600 newdir = (unsigned char *) pw->pw_dir;
1602 /* Discard the user name from NM. */
1603 nm += len;
1606 if (nm[0] != '/' && !newdir)
1608 if (NILP (defalt))
1609 defalt = current_buffer->directory;
1610 CHECK_STRING (defalt);
1611 newdir = SDATA (defalt);
1614 /* Now concatenate the directory and name to new space in the stack frame. */
1616 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1617 target = alloca (tlen);
1618 *target = 0;
1620 if (newdir)
1622 if (nm[0] == 0 || nm[0] == '/')
1623 strcpy (target, newdir);
1624 else
1625 file_name_as_directory (target, newdir);
1628 strcat (target, nm);
1630 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1632 p = target;
1633 o = target;
1635 while (*p)
1637 if (*p != '/')
1639 *o++ = *p++;
1641 else if (!strncmp (p, "//", 2)
1644 o = target;
1645 p++;
1647 else if (p[0] == '/' && p[1] == '.'
1648 && (p[2] == '/' || p[2] == 0))
1649 p += 2;
1650 else if (!strncmp (p, "/..", 3)
1651 /* `/../' is the "superroot" on certain file systems. */
1652 && o != target
1653 && (p[3] == '/' || p[3] == 0))
1655 while (o != target && *--o != '/')
1657 if (o == target && *o == '/')
1658 ++o;
1659 p += 3;
1661 else
1663 *o++ = *p++;
1667 return make_string (target, o - target);
1669 #endif
1671 /* If /~ or // appears, discard everything through first slash. */
1672 static bool
1673 file_name_absolute_p (const char *filename)
1675 return
1676 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
1677 #ifdef DOS_NT
1678 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1679 && IS_DIRECTORY_SEP (filename[2]))
1680 #endif
1684 static char *
1685 search_embedded_absfilename (char *nm, char *endp)
1687 char *p, *s;
1689 for (p = nm + 1; p < endp; p++)
1691 if (IS_DIRECTORY_SEP (p[-1])
1692 && file_name_absolute_p (p)
1693 #if defined (WINDOWSNT) || defined (CYGWIN)
1694 /* // at start of file name is meaningful in Apollo,
1695 WindowsNT and Cygwin systems. */
1696 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
1697 #endif /* not (WINDOWSNT || CYGWIN) */
1700 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
1701 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
1703 char *o = alloca (s - p + 1);
1704 struct passwd *pw;
1705 memcpy (o, p, s - p);
1706 o [s - p] = 0;
1708 /* If we have ~user and `user' exists, discard
1709 everything up to ~. But if `user' does not exist, leave
1710 ~user alone, it might be a literal file name. */
1711 block_input ();
1712 pw = getpwnam (o + 1);
1713 unblock_input ();
1714 if (pw)
1715 return p;
1717 else
1718 return p;
1721 return NULL;
1724 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1725 Ssubstitute_in_file_name, 1, 1, 0,
1726 doc: /* Substitute environment variables referred to in FILENAME.
1727 `$FOO' where FOO is an environment variable name means to substitute
1728 the value of that variable. The variable name should be terminated
1729 with a character not a letter, digit or underscore; otherwise, enclose
1730 the entire variable name in braces.
1732 If `/~' appears, all of FILENAME through that `/' is discarded.
1733 If `//' appears, everything up to and including the first of
1734 those `/' is discarded. */)
1735 (Lisp_Object filename)
1737 char *nm, *p, *x, *endp;
1738 bool substituted = false;
1739 bool multibyte;
1740 char *xnm;
1741 Lisp_Object handler;
1743 CHECK_STRING (filename);
1745 multibyte = STRING_MULTIBYTE (filename);
1747 /* If the file name has special constructs in it,
1748 call the corresponding file handler. */
1749 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1750 if (!NILP (handler))
1752 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1753 filename);
1754 if (STRINGP (handled_name))
1755 return handled_name;
1756 error ("Invalid handler in `file-name-handler-alist'");
1759 /* Always work on a copy of the string, in case GC happens during
1760 decode of environment variables, causing the original Lisp_String
1761 data to be relocated. */
1762 nm = xlispstrdupa (filename);
1764 #ifdef DOS_NT
1765 dostounix_filename (nm, multibyte);
1766 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
1767 #endif
1768 endp = nm + SBYTES (filename);
1770 /* If /~ or // appears, discard everything through first slash. */
1771 p = search_embedded_absfilename (nm, endp);
1772 if (p)
1773 /* Start over with the new string, so we check the file-name-handler
1774 again. Important with filenames like "/home/foo//:/hello///there"
1775 which would substitute to "/:/hello///there" rather than "/there". */
1776 return Fsubstitute_in_file_name
1777 (make_specified_string (p, -1, endp - p, multibyte));
1779 /* See if any variables are substituted into the string. */
1781 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name)))
1783 Lisp_Object name
1784 = (!substituted ? filename
1785 : make_specified_string (nm, -1, endp - nm, multibyte));
1786 Lisp_Object tmp = call1 (Qsubstitute_env_in_file_name, name);
1787 CHECK_STRING (tmp);
1788 if (!EQ (tmp, name))
1789 substituted = true;
1790 filename = tmp;
1793 if (!substituted)
1795 #ifdef WINDOWSNT
1796 if (!NILP (Vw32_downcase_file_names))
1797 filename = Fdowncase (filename);
1798 #endif
1799 return filename;
1802 xnm = SSDATA (filename);
1803 x = xnm + SBYTES (filename);
1805 /* If /~ or // appears, discard everything through first slash. */
1806 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
1807 /* This time we do not start over because we've already expanded envvars
1808 and replaced $$ with $. Maybe we should start over as well, but we'd
1809 need to quote some $ to $$ first. */
1810 xnm = p;
1812 #ifdef WINDOWSNT
1813 if (!NILP (Vw32_downcase_file_names))
1815 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1817 xname = Fdowncase (xname);
1818 return xname;
1820 else
1821 #endif
1822 return (xnm == SSDATA (filename)
1823 ? filename
1824 : make_specified_string (xnm, -1, x - xnm, multibyte));
1827 /* A slightly faster and more convenient way to get
1828 (directory-file-name (expand-file-name FOO)). */
1830 Lisp_Object
1831 expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
1833 register Lisp_Object absname;
1835 absname = Fexpand_file_name (filename, defdir);
1837 /* Remove final slash, if any (unless this is the root dir).
1838 stat behaves differently depending! */
1839 if (SCHARS (absname) > 1
1840 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
1841 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
1842 /* We cannot take shortcuts; they might be wrong for magic file names. */
1843 absname = Fdirectory_file_name (absname);
1844 return absname;
1847 /* Signal an error if the file ABSNAME already exists.
1848 If INTERACTIVE, ask the user whether to proceed,
1849 and bypass the error if the user says to go ahead.
1850 QUERYSTRING is a name for the action that is being considered
1851 to alter the file.
1853 *STATPTR is used to store the stat information if the file exists.
1854 If the file does not exist, STATPTR->st_mode is set to 0.
1855 If STATPTR is null, we don't store into it.
1857 If QUICK, ask for y or n, not yes or no. */
1859 static void
1860 barf_or_query_if_file_exists (Lisp_Object absname, const char *querystring,
1861 bool interactive, struct stat *statptr,
1862 bool quick)
1864 Lisp_Object tem, encoded_filename;
1865 struct stat statbuf;
1866 struct gcpro gcpro1;
1868 encoded_filename = ENCODE_FILE (absname);
1870 /* `stat' is a good way to tell whether the file exists,
1871 regardless of what access permissions it has. */
1872 if (lstat (SSDATA (encoded_filename), &statbuf) >= 0)
1874 if (S_ISDIR (statbuf.st_mode))
1875 xsignal2 (Qfile_error,
1876 build_string ("File is a directory"), absname);
1878 if (! interactive)
1879 xsignal2 (Qfile_already_exists,
1880 build_string ("File already exists"), absname);
1881 GCPRO1 (absname);
1882 tem = format2 ("File %s already exists; %s anyway? ",
1883 absname, build_string (querystring));
1884 if (quick)
1885 tem = call1 (intern ("y-or-n-p"), tem);
1886 else
1887 tem = do_yes_or_no_p (tem);
1888 UNGCPRO;
1889 if (NILP (tem))
1890 xsignal2 (Qfile_already_exists,
1891 build_string ("File already exists"), absname);
1892 if (statptr)
1893 *statptr = statbuf;
1895 else
1897 if (statptr)
1898 statptr->st_mode = 0;
1900 return;
1903 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
1904 "fCopy file: \nGCopy %s to file: \np\nP",
1905 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1906 If NEWNAME names a directory, copy FILE there.
1908 This function always sets the file modes of the output file to match
1909 the input file.
1911 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1912 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1913 signal a `file-already-exists' error without overwriting. If
1914 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1915 about overwriting; this is what happens in interactive use with M-x.
1916 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1917 existing file.
1919 Fourth arg KEEP-TIME non-nil means give the output file the same
1920 last-modified time as the old one. (This works on only some systems.)
1922 A prefix arg makes KEEP-TIME non-nil.
1924 If PRESERVE-UID-GID is non-nil, we try to transfer the
1925 uid and gid of FILE to NEWNAME.
1927 If PRESERVE-EXTENDED-ATTRIBUTES is non-nil, we try to copy additional
1928 attributes of FILE to NEWNAME, such as its SELinux context and ACL
1929 entries (depending on how Emacs was built). */)
1930 (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)
1932 int ifd, ofd;
1933 int n;
1934 char buf[16 * 1024];
1935 struct stat st, out_st;
1936 Lisp_Object handler;
1937 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1938 ptrdiff_t count = SPECPDL_INDEX ();
1939 Lisp_Object encoded_file, encoded_newname;
1940 #if HAVE_LIBSELINUX
1941 security_context_t con;
1942 int conlength = 0;
1943 #endif
1944 #ifdef WINDOWSNT
1945 acl_t acl = NULL;
1946 #endif
1948 encoded_file = encoded_newname = Qnil;
1949 GCPRO4 (file, newname, encoded_file, encoded_newname);
1950 CHECK_STRING (file);
1951 CHECK_STRING (newname);
1953 if (!NILP (Ffile_directory_p (newname)))
1954 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
1955 else
1956 newname = Fexpand_file_name (newname, Qnil);
1958 file = Fexpand_file_name (file, Qnil);
1960 /* If the input file name has special constructs in it,
1961 call the corresponding file handler. */
1962 handler = Ffind_file_name_handler (file, Qcopy_file);
1963 /* Likewise for output file name. */
1964 if (NILP (handler))
1965 handler = Ffind_file_name_handler (newname, Qcopy_file);
1966 if (!NILP (handler))
1967 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
1968 ok_if_already_exists, keep_time, preserve_uid_gid,
1969 preserve_extended_attributes));
1971 encoded_file = ENCODE_FILE (file);
1972 encoded_newname = ENCODE_FILE (newname);
1974 if (NILP (ok_if_already_exists)
1975 || INTEGERP (ok_if_already_exists))
1976 barf_or_query_if_file_exists (newname, "copy to it",
1977 INTEGERP (ok_if_already_exists), &out_st, 0);
1978 else if (stat (SSDATA (encoded_newname), &out_st) < 0)
1979 out_st.st_mode = 0;
1981 #ifdef WINDOWSNT
1982 if (!NILP (preserve_extended_attributes))
1984 acl = acl_get_file (SDATA (encoded_file), ACL_TYPE_ACCESS);
1985 if (acl == NULL && acl_errno_valid (errno))
1986 report_file_error ("Getting ACL", file);
1988 if (!CopyFile (SDATA (encoded_file),
1989 SDATA (encoded_newname),
1990 FALSE))
1992 /* CopyFile doesn't set errno when it fails. By far the most
1993 "popular" reason is that the target is read-only. */
1994 report_file_errno ("Copying file", list2 (file, newname),
1995 GetLastError () == 5 ? EACCES : EPERM);
1997 /* CopyFile retains the timestamp by default. */
1998 else if (NILP (keep_time))
2000 struct timespec now;
2001 DWORD attributes;
2002 char * filename;
2004 filename = SDATA (encoded_newname);
2006 /* Ensure file is writable while its modified time is set. */
2007 attributes = GetFileAttributes (filename);
2008 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
2009 now = current_timespec ();
2010 if (set_file_times (-1, filename, now, now))
2012 /* Restore original attributes. */
2013 SetFileAttributes (filename, attributes);
2014 xsignal2 (Qfile_date_error,
2015 build_string ("Cannot set file date"), newname);
2017 /* Restore original attributes. */
2018 SetFileAttributes (filename, attributes);
2020 if (acl != NULL)
2022 bool fail =
2023 acl_set_file (SDATA (encoded_newname), ACL_TYPE_ACCESS, acl) != 0;
2024 if (fail && acl_errno_valid (errno))
2025 report_file_error ("Setting ACL", newname);
2027 acl_free (acl);
2029 #else /* not WINDOWSNT */
2030 immediate_quit = 1;
2031 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
2032 immediate_quit = 0;
2034 if (ifd < 0)
2035 report_file_error ("Opening input file", file);
2037 record_unwind_protect_int (close_file_unwind, ifd);
2039 if (fstat (ifd, &st) != 0)
2040 report_file_error ("Input file status", file);
2042 if (!NILP (preserve_extended_attributes))
2044 #if HAVE_LIBSELINUX
2045 if (is_selinux_enabled ())
2047 conlength = fgetfilecon (ifd, &con);
2048 if (conlength == -1)
2049 report_file_error ("Doing fgetfilecon", file);
2051 #endif
2054 if (out_st.st_mode != 0
2055 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2056 report_file_errno ("Input and output files are the same",
2057 list2 (file, newname), 0);
2059 /* We can copy only regular files. */
2060 if (!S_ISREG (st.st_mode))
2061 report_file_errno ("Non-regular file", file,
2062 S_ISDIR (st.st_mode) ? EISDIR : EINVAL);
2065 #ifndef MSDOS
2066 int new_mask = st.st_mode & (!NILP (preserve_uid_gid) ? 0600 : 0666);
2067 #else
2068 int new_mask = S_IREAD | S_IWRITE;
2069 #endif
2070 ofd = emacs_open (SSDATA (encoded_newname),
2071 (O_WRONLY | O_TRUNC | O_CREAT
2072 | (NILP (ok_if_already_exists) ? O_EXCL : 0)),
2073 new_mask);
2075 if (ofd < 0)
2076 report_file_error ("Opening output file", newname);
2078 record_unwind_protect_int (close_file_unwind, ofd);
2080 immediate_quit = 1;
2081 QUIT;
2082 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2083 if (emacs_write_sig (ofd, buf, n) != n)
2084 report_file_error ("Write error", newname);
2085 immediate_quit = 0;
2087 #ifndef MSDOS
2088 /* Preserve the original file permissions, and if requested, also its
2089 owner and group. */
2091 mode_t mode_mask = 07777;
2092 if (!NILP (preserve_uid_gid))
2094 /* Attempt to change owner and group. If that doesn't work
2095 attempt to change just the group, as that is sometimes allowed.
2096 Adjust the mode mask to eliminate setuid or setgid bits
2097 that are inappropriate if the owner and group are wrong. */
2098 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2100 mode_mask &= ~06000;
2101 if (fchown (ofd, -1, st.st_gid) == 0)
2102 mode_mask |= 02000;
2106 switch (!NILP (preserve_extended_attributes)
2107 ? qcopy_acl (SSDATA (encoded_file), ifd,
2108 SSDATA (encoded_newname), ofd,
2109 st.st_mode & mode_mask)
2110 : fchmod (ofd, st.st_mode & mode_mask))
2112 case -2: report_file_error ("Copying permissions from", file);
2113 case -1: report_file_error ("Copying permissions to", newname);
2116 #endif /* not MSDOS */
2118 #if HAVE_LIBSELINUX
2119 if (conlength > 0)
2121 /* Set the modified context back to the file. */
2122 bool fail = fsetfilecon (ofd, con) != 0;
2123 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2124 if (fail && errno != ENOTSUP)
2125 report_file_error ("Doing fsetfilecon", newname);
2127 freecon (con);
2129 #endif
2131 if (!NILP (keep_time))
2133 struct timespec atime = get_stat_atime (&st);
2134 struct timespec mtime = get_stat_mtime (&st);
2135 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime))
2136 xsignal2 (Qfile_date_error,
2137 build_string ("Cannot set file date"), newname);
2140 if (emacs_close (ofd) < 0)
2141 report_file_error ("Write error", newname);
2143 emacs_close (ifd);
2145 #ifdef MSDOS
2146 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2147 and if it can't, it tells so. Otherwise, under MSDOS we usually
2148 get only the READ bit, which will make the copied file read-only,
2149 so it's better not to chmod at all. */
2150 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2151 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2152 #endif /* MSDOS */
2153 #endif /* not WINDOWSNT */
2155 /* Discard the unwind protects. */
2156 specpdl_ptr = specpdl + count;
2158 UNGCPRO;
2159 return Qnil;
2162 DEFUN ("make-directory-internal", Fmake_directory_internal,
2163 Smake_directory_internal, 1, 1, 0,
2164 doc: /* Create a new directory named DIRECTORY. */)
2165 (Lisp_Object directory)
2167 const char *dir;
2168 Lisp_Object handler;
2169 Lisp_Object encoded_dir;
2171 CHECK_STRING (directory);
2172 directory = Fexpand_file_name (directory, Qnil);
2174 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2175 if (!NILP (handler))
2176 return call2 (handler, Qmake_directory_internal, directory);
2178 encoded_dir = ENCODE_FILE (directory);
2180 dir = SSDATA (encoded_dir);
2182 #ifdef WINDOWSNT
2183 if (mkdir (dir) != 0)
2184 #else
2185 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
2186 #endif
2187 report_file_error ("Creating directory", directory);
2189 return Qnil;
2192 DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2193 Sdelete_directory_internal, 1, 1, 0,
2194 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2195 (Lisp_Object directory)
2197 const char *dir;
2198 Lisp_Object encoded_dir;
2200 CHECK_STRING (directory);
2201 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2202 encoded_dir = ENCODE_FILE (directory);
2203 dir = SSDATA (encoded_dir);
2205 if (rmdir (dir) != 0)
2206 report_file_error ("Removing directory", directory);
2208 return Qnil;
2211 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
2212 "(list (read-file-name \
2213 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2214 \"Move file to trash: \" \"Delete file: \") \
2215 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2216 (null current-prefix-arg))",
2217 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2218 If file has multiple names, it continues to exist with the other names.
2219 TRASH non-nil means to trash the file instead of deleting, provided
2220 `delete-by-moving-to-trash' is non-nil.
2222 When called interactively, TRASH is t if no prefix argument is given.
2223 With a prefix argument, TRASH is nil. */)
2224 (Lisp_Object filename, Lisp_Object trash)
2226 Lisp_Object handler;
2227 Lisp_Object encoded_file;
2228 struct gcpro gcpro1;
2230 GCPRO1 (filename);
2231 if (!NILP (Ffile_directory_p (filename))
2232 && NILP (Ffile_symlink_p (filename)))
2233 xsignal2 (Qfile_error,
2234 build_string ("Removing old name: is a directory"),
2235 filename);
2236 UNGCPRO;
2237 filename = Fexpand_file_name (filename, Qnil);
2239 handler = Ffind_file_name_handler (filename, Qdelete_file);
2240 if (!NILP (handler))
2241 return call3 (handler, Qdelete_file, filename, trash);
2243 if (delete_by_moving_to_trash && !NILP (trash))
2244 return call1 (Qmove_file_to_trash, filename);
2246 encoded_file = ENCODE_FILE (filename);
2248 if (unlink (SSDATA (encoded_file)) < 0)
2249 report_file_error ("Removing old name", filename);
2250 return Qnil;
2253 static Lisp_Object
2254 internal_delete_file_1 (Lisp_Object ignore)
2256 return Qt;
2259 /* Delete file FILENAME, returning true if successful.
2260 This ignores `delete-by-moving-to-trash'. */
2262 bool
2263 internal_delete_file (Lisp_Object filename)
2265 Lisp_Object tem;
2267 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2268 Qt, internal_delete_file_1);
2269 return NILP (tem);
2272 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2273 "fRename file: \nGRename %s to file: \np",
2274 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2275 If file has names other than FILE, it continues to have those names.
2276 Signals a `file-already-exists' error if a file NEWNAME already exists
2277 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2278 A number as third arg means request confirmation if NEWNAME already exists.
2279 This is what happens in interactive use with M-x. */)
2280 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2282 Lisp_Object handler;
2283 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2284 Lisp_Object encoded_file, encoded_newname, symlink_target;
2286 symlink_target = encoded_file = encoded_newname = Qnil;
2287 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2288 CHECK_STRING (file);
2289 CHECK_STRING (newname);
2290 file = Fexpand_file_name (file, Qnil);
2292 if ((!NILP (Ffile_directory_p (newname)))
2293 #ifdef DOS_NT
2294 /* If the file names are identical but for the case,
2295 don't attempt to move directory to itself. */
2296 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2297 #endif
2300 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2301 ? file : Fdirectory_file_name (file));
2302 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2304 else
2305 newname = Fexpand_file_name (newname, Qnil);
2307 /* If the file name has special constructs in it,
2308 call the corresponding file handler. */
2309 handler = Ffind_file_name_handler (file, Qrename_file);
2310 if (NILP (handler))
2311 handler = Ffind_file_name_handler (newname, Qrename_file);
2312 if (!NILP (handler))
2313 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2314 file, newname, ok_if_already_exists));
2316 encoded_file = ENCODE_FILE (file);
2317 encoded_newname = ENCODE_FILE (newname);
2319 #ifdef DOS_NT
2320 /* If the file names are identical but for the case, don't ask for
2321 confirmation: they simply want to change the letter-case of the
2322 file name. */
2323 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2324 #endif
2325 if (NILP (ok_if_already_exists)
2326 || INTEGERP (ok_if_already_exists))
2327 barf_or_query_if_file_exists (newname, "rename to it",
2328 INTEGERP (ok_if_already_exists), 0, 0);
2329 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2331 int rename_errno = errno;
2332 if (rename_errno == EXDEV)
2334 ptrdiff_t count;
2335 symlink_target = Ffile_symlink_p (file);
2336 if (! NILP (symlink_target))
2337 Fmake_symbolic_link (symlink_target, newname,
2338 NILP (ok_if_already_exists) ? Qnil : Qt);
2339 else if (!NILP (Ffile_directory_p (file)))
2340 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2341 else
2342 /* We have already prompted if it was an integer, so don't
2343 have copy-file prompt again. */
2344 Fcopy_file (file, newname,
2345 NILP (ok_if_already_exists) ? Qnil : Qt,
2346 Qt, Qt, Qt);
2348 count = SPECPDL_INDEX ();
2349 specbind (Qdelete_by_moving_to_trash, Qnil);
2351 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
2352 call2 (Qdelete_directory, file, Qt);
2353 else
2354 Fdelete_file (file, Qnil);
2355 unbind_to (count, Qnil);
2357 else
2358 report_file_errno ("Renaming", list2 (file, newname), rename_errno);
2360 UNGCPRO;
2361 return Qnil;
2364 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2365 "fAdd name to file: \nGName to add to %s: \np",
2366 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2367 Signals a `file-already-exists' error if a file NEWNAME already exists
2368 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2369 A number as third arg means request confirmation if NEWNAME already exists.
2370 This is what happens in interactive use with M-x. */)
2371 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
2373 Lisp_Object handler;
2374 Lisp_Object encoded_file, encoded_newname;
2375 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2377 GCPRO4 (file, newname, encoded_file, encoded_newname);
2378 encoded_file = encoded_newname = Qnil;
2379 CHECK_STRING (file);
2380 CHECK_STRING (newname);
2381 file = Fexpand_file_name (file, Qnil);
2383 if (!NILP (Ffile_directory_p (newname)))
2384 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2385 else
2386 newname = Fexpand_file_name (newname, Qnil);
2388 /* If the file name has special constructs in it,
2389 call the corresponding file handler. */
2390 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2391 if (!NILP (handler))
2392 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2393 newname, ok_if_already_exists));
2395 /* If the new name has special constructs in it,
2396 call the corresponding file handler. */
2397 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2398 if (!NILP (handler))
2399 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2400 newname, ok_if_already_exists));
2402 encoded_file = ENCODE_FILE (file);
2403 encoded_newname = ENCODE_FILE (newname);
2405 if (NILP (ok_if_already_exists)
2406 || INTEGERP (ok_if_already_exists))
2407 barf_or_query_if_file_exists (newname, "make it a new name",
2408 INTEGERP (ok_if_already_exists), 0, 0);
2410 unlink (SSDATA (newname));
2411 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
2413 int link_errno = errno;
2414 report_file_errno ("Adding new name", list2 (file, newname), link_errno);
2417 UNGCPRO;
2418 return Qnil;
2421 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2422 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2423 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2424 Both args must be strings.
2425 Signals a `file-already-exists' error if a file LINKNAME already exists
2426 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2427 A number as third arg means request confirmation if LINKNAME already exists.
2428 This happens for interactive use with M-x. */)
2429 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
2431 Lisp_Object handler;
2432 Lisp_Object encoded_filename, encoded_linkname;
2433 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2435 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2436 encoded_filename = encoded_linkname = Qnil;
2437 CHECK_STRING (filename);
2438 CHECK_STRING (linkname);
2439 /* If the link target has a ~, we must expand it to get
2440 a truly valid file name. Otherwise, do not expand;
2441 we want to permit links to relative file names. */
2442 if (SREF (filename, 0) == '~')
2443 filename = Fexpand_file_name (filename, Qnil);
2445 if (!NILP (Ffile_directory_p (linkname)))
2446 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2447 else
2448 linkname = Fexpand_file_name (linkname, Qnil);
2450 /* If the file name has special constructs in it,
2451 call the corresponding file handler. */
2452 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2453 if (!NILP (handler))
2454 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2455 linkname, ok_if_already_exists));
2457 /* If the new link name has special constructs in it,
2458 call the corresponding file handler. */
2459 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2460 if (!NILP (handler))
2461 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2462 linkname, ok_if_already_exists));
2464 encoded_filename = ENCODE_FILE (filename);
2465 encoded_linkname = ENCODE_FILE (linkname);
2467 if (NILP (ok_if_already_exists)
2468 || INTEGERP (ok_if_already_exists))
2469 barf_or_query_if_file_exists (linkname, "make it a link",
2470 INTEGERP (ok_if_already_exists), 0, 0);
2471 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname)) < 0)
2473 /* If we didn't complain already, silently delete existing file. */
2474 int symlink_errno;
2475 if (errno == EEXIST)
2477 unlink (SSDATA (encoded_linkname));
2478 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname))
2479 >= 0)
2481 UNGCPRO;
2482 return Qnil;
2485 if (errno == ENOSYS)
2487 UNGCPRO;
2488 xsignal1 (Qfile_error,
2489 build_string ("Symbolic links are not supported"));
2492 symlink_errno = errno;
2493 report_file_errno ("Making symbolic link", list2 (filename, linkname),
2494 symlink_errno);
2496 UNGCPRO;
2497 return Qnil;
2501 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2502 1, 1, 0,
2503 doc: /* Return t if file FILENAME specifies an absolute file name.
2504 On Unix, this is a name starting with a `/' or a `~'. */)
2505 (Lisp_Object filename)
2507 CHECK_STRING (filename);
2508 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
2511 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2512 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2513 See also `file-readable-p' and `file-attributes'.
2514 This returns nil for a symlink to a nonexistent file.
2515 Use `file-symlink-p' to test for such links. */)
2516 (Lisp_Object filename)
2518 Lisp_Object absname;
2519 Lisp_Object handler;
2521 CHECK_STRING (filename);
2522 absname = Fexpand_file_name (filename, Qnil);
2524 /* If the file name has special constructs in it,
2525 call the corresponding file handler. */
2526 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2527 if (!NILP (handler))
2529 Lisp_Object result = call2 (handler, Qfile_exists_p, absname);
2530 errno = 0;
2531 return result;
2534 absname = ENCODE_FILE (absname);
2536 return check_existing (SSDATA (absname)) ? Qt : Qnil;
2539 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2540 doc: /* Return t if FILENAME can be executed by you.
2541 For a directory, this means you can access files in that directory. */)
2542 (Lisp_Object filename)
2544 Lisp_Object absname;
2545 Lisp_Object handler;
2547 CHECK_STRING (filename);
2548 absname = Fexpand_file_name (filename, Qnil);
2550 /* If the file name has special constructs in it,
2551 call the corresponding file handler. */
2552 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2553 if (!NILP (handler))
2554 return call2 (handler, Qfile_executable_p, absname);
2556 absname = ENCODE_FILE (absname);
2558 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
2561 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2562 doc: /* Return t if file FILENAME exists and you can read it.
2563 See also `file-exists-p' and `file-attributes'. */)
2564 (Lisp_Object filename)
2566 Lisp_Object absname;
2567 Lisp_Object handler;
2569 CHECK_STRING (filename);
2570 absname = Fexpand_file_name (filename, Qnil);
2572 /* If the file name has special constructs in it,
2573 call the corresponding file handler. */
2574 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2575 if (!NILP (handler))
2576 return call2 (handler, Qfile_readable_p, absname);
2578 absname = ENCODE_FILE (absname);
2579 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2580 ? Qt : Qnil);
2583 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2584 doc: /* Return t if file FILENAME can be written or created by you. */)
2585 (Lisp_Object filename)
2587 Lisp_Object absname, dir, encoded;
2588 Lisp_Object handler;
2590 CHECK_STRING (filename);
2591 absname = Fexpand_file_name (filename, Qnil);
2593 /* If the file name has special constructs in it,
2594 call the corresponding file handler. */
2595 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2596 if (!NILP (handler))
2597 return call2 (handler, Qfile_writable_p, absname);
2599 encoded = ENCODE_FILE (absname);
2600 if (check_writable (SSDATA (encoded), W_OK))
2601 return Qt;
2602 if (errno != ENOENT)
2603 return Qnil;
2605 dir = Ffile_name_directory (absname);
2606 eassert (!NILP (dir));
2607 #ifdef MSDOS
2608 dir = Fdirectory_file_name (dir);
2609 #endif /* MSDOS */
2611 dir = ENCODE_FILE (dir);
2612 #ifdef WINDOWSNT
2613 /* The read-only attribute of the parent directory doesn't affect
2614 whether a file or directory can be created within it. Some day we
2615 should check ACLs though, which do affect this. */
2616 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
2617 #else
2618 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
2619 #endif
2622 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2623 doc: /* Access file FILENAME, and get an error if that does not work.
2624 The second argument STRING is used in the error message.
2625 If there is no error, returns nil. */)
2626 (Lisp_Object filename, Lisp_Object string)
2628 Lisp_Object handler, encoded_filename, absname;
2630 CHECK_STRING (filename);
2631 absname = Fexpand_file_name (filename, Qnil);
2633 CHECK_STRING (string);
2635 /* If the file name has special constructs in it,
2636 call the corresponding file handler. */
2637 handler = Ffind_file_name_handler (absname, Qaccess_file);
2638 if (!NILP (handler))
2639 return call3 (handler, Qaccess_file, absname, string);
2641 encoded_filename = ENCODE_FILE (absname);
2643 if (faccessat (AT_FDCWD, SSDATA (encoded_filename), R_OK, AT_EACCESS) != 0)
2644 report_file_error (SSDATA (string), filename);
2646 return Qnil;
2649 /* Relative to directory FD, return the symbolic link value of FILENAME.
2650 On failure, return nil. */
2651 Lisp_Object
2652 emacs_readlinkat (int fd, char const *filename)
2654 static struct allocator const emacs_norealloc_allocator =
2655 { xmalloc, NULL, xfree, memory_full };
2656 Lisp_Object val;
2657 char readlink_buf[1024];
2658 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2659 &emacs_norealloc_allocator, readlinkat);
2660 if (!buf)
2661 return Qnil;
2663 val = build_string (buf);
2664 if (buf[0] == '/' && strchr (buf, ':'))
2665 val = concat2 (build_string ("/:"), val);
2666 if (buf != readlink_buf)
2667 xfree (buf);
2668 val = DECODE_FILE (val);
2669 return val;
2672 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2673 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
2674 The value is the link target, as a string.
2675 Otherwise it returns nil.
2677 This function returns t when given the name of a symlink that
2678 points to a nonexistent file. */)
2679 (Lisp_Object filename)
2681 Lisp_Object handler;
2683 CHECK_STRING (filename);
2684 filename = Fexpand_file_name (filename, Qnil);
2686 /* If the file name has special constructs in it,
2687 call the corresponding file handler. */
2688 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
2689 if (!NILP (handler))
2690 return call2 (handler, Qfile_symlink_p, filename);
2692 filename = ENCODE_FILE (filename);
2694 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
2697 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
2698 doc: /* Return t if FILENAME names an existing directory.
2699 Symbolic links to directories count as directories.
2700 See `file-symlink-p' to distinguish symlinks. */)
2701 (Lisp_Object filename)
2703 Lisp_Object absname;
2704 Lisp_Object handler;
2706 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2708 /* If the file name has special constructs in it,
2709 call the corresponding file handler. */
2710 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
2711 if (!NILP (handler))
2712 return call2 (handler, Qfile_directory_p, absname);
2714 absname = ENCODE_FILE (absname);
2716 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2719 /* Return true if FILE is a directory or a symlink to a directory. */
2720 bool
2721 file_directory_p (char const *file)
2723 #ifdef WINDOWSNT
2724 /* This is cheaper than 'stat'. */
2725 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2726 #else
2727 struct stat st;
2728 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2729 #endif
2732 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
2733 Sfile_accessible_directory_p, 1, 1, 0,
2734 doc: /* Return t if file FILENAME names a directory you can open.
2735 For the value to be t, FILENAME must specify the name of a directory as a file,
2736 and the directory must allow you to open files in it. In order to use a
2737 directory as a buffer's current directory, this predicate must return true.
2738 A directory name spec may be given instead; then the value is t
2739 if the directory so specified exists and really is a readable and
2740 searchable directory. */)
2741 (Lisp_Object filename)
2743 Lisp_Object absname;
2744 Lisp_Object handler;
2746 CHECK_STRING (filename);
2747 absname = Fexpand_file_name (filename, Qnil);
2749 /* If the file name has special constructs in it,
2750 call the corresponding file handler. */
2751 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
2752 if (!NILP (handler))
2754 Lisp_Object r = call2 (handler, Qfile_accessible_directory_p, absname);
2755 errno = 0;
2756 return r;
2759 absname = ENCODE_FILE (absname);
2760 return file_accessible_directory_p (SSDATA (absname)) ? Qt : Qnil;
2763 /* If FILE is a searchable directory or a symlink to a
2764 searchable directory, return true. Otherwise return
2765 false and set errno to an error number. */
2766 bool
2767 file_accessible_directory_p (char const *file)
2769 #ifdef DOS_NT
2770 /* There's no need to test whether FILE is searchable, as the
2771 searchable/executable bit is invented on DOS_NT platforms. */
2772 return file_directory_p (file);
2773 #else
2774 /* On POSIXish platforms, use just one system call; this avoids a
2775 race and is typically faster. */
2776 ptrdiff_t len = strlen (file);
2777 char const *dir;
2778 bool ok;
2779 int saved_errno;
2780 USE_SAFE_ALLOCA;
2782 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2783 There are three exceptions: "", "/", and "//". Leave "" alone,
2784 as it's invalid. Append only "." to the other two exceptions as
2785 "/" and "//" are distinct on some platforms, whereas "/", "///",
2786 "////", etc. are all equivalent. */
2787 if (! len)
2788 dir = file;
2789 else
2791 /* Just check for trailing '/' when deciding whether to append '/'.
2792 That's simpler than testing the two special cases "/" and "//",
2793 and it's a safe optimization here. */
2794 char *buf = SAFE_ALLOCA (len + 3);
2795 memcpy (buf, file, len);
2796 strcpy (buf + len, &"/."[file[len - 1] == '/']);
2797 dir = buf;
2800 ok = check_existing (dir);
2801 saved_errno = errno;
2802 SAFE_FREE ();
2803 errno = saved_errno;
2804 return ok;
2805 #endif
2808 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
2809 doc: /* Return t if FILENAME names a regular file.
2810 This is the sort of file that holds an ordinary stream of data bytes.
2811 Symbolic links to regular files count as regular files.
2812 See `file-symlink-p' to distinguish symlinks. */)
2813 (Lisp_Object filename)
2815 register Lisp_Object absname;
2816 struct stat st;
2817 Lisp_Object handler;
2819 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2821 /* If the file name has special constructs in it,
2822 call the corresponding file handler. */
2823 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
2824 if (!NILP (handler))
2825 return call2 (handler, Qfile_regular_p, absname);
2827 absname = ENCODE_FILE (absname);
2829 #ifdef WINDOWSNT
2831 int result;
2832 Lisp_Object tem = Vw32_get_true_file_attributes;
2834 /* Tell stat to use expensive method to get accurate info. */
2835 Vw32_get_true_file_attributes = Qt;
2836 result = stat (SDATA (absname), &st);
2837 Vw32_get_true_file_attributes = tem;
2839 if (result < 0)
2840 return Qnil;
2841 return S_ISREG (st.st_mode) ? Qt : Qnil;
2843 #else
2844 if (stat (SSDATA (absname), &st) < 0)
2845 return Qnil;
2846 return S_ISREG (st.st_mode) ? Qt : Qnil;
2847 #endif
2850 DEFUN ("file-selinux-context", Ffile_selinux_context,
2851 Sfile_selinux_context, 1, 1, 0,
2852 doc: /* Return SELinux context of file named FILENAME.
2853 The return value is a list (USER ROLE TYPE RANGE), where the list
2854 elements are strings naming the user, role, type, and range of the
2855 file's SELinux security context.
2857 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2858 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2859 (Lisp_Object filename)
2861 Lisp_Object absname;
2862 Lisp_Object values[4];
2863 Lisp_Object handler;
2864 #if HAVE_LIBSELINUX
2865 security_context_t con;
2866 int conlength;
2867 context_t context;
2868 #endif
2870 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
2872 /* If the file name has special constructs in it,
2873 call the corresponding file handler. */
2874 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2875 if (!NILP (handler))
2876 return call2 (handler, Qfile_selinux_context, absname);
2878 absname = ENCODE_FILE (absname);
2880 values[0] = Qnil;
2881 values[1] = Qnil;
2882 values[2] = Qnil;
2883 values[3] = Qnil;
2884 #if HAVE_LIBSELINUX
2885 if (is_selinux_enabled ())
2887 conlength = lgetfilecon (SSDATA (absname), &con);
2888 if (conlength > 0)
2890 context = context_new (con);
2891 if (context_user_get (context))
2892 values[0] = build_string (context_user_get (context));
2893 if (context_role_get (context))
2894 values[1] = build_string (context_role_get (context));
2895 if (context_type_get (context))
2896 values[2] = build_string (context_type_get (context));
2897 if (context_range_get (context))
2898 values[3] = build_string (context_range_get (context));
2899 context_free (context);
2900 freecon (con);
2903 #endif
2905 return Flist (sizeof (values) / sizeof (values[0]), values);
2908 DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
2909 Sset_file_selinux_context, 2, 2, 0,
2910 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
2911 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2912 elements are strings naming the components of a SELinux context.
2914 Value is t if setting of SELinux context was successful, nil otherwise.
2916 This function does nothing and returns nil if SELinux is disabled,
2917 or if Emacs was not compiled with SELinux support. */)
2918 (Lisp_Object filename, Lisp_Object context)
2920 Lisp_Object absname;
2921 Lisp_Object handler;
2922 #if HAVE_LIBSELINUX
2923 Lisp_Object encoded_absname;
2924 Lisp_Object user = CAR_SAFE (context);
2925 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
2926 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
2927 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
2928 security_context_t con;
2929 bool fail;
2930 int conlength;
2931 context_t parsed_con;
2932 #endif
2934 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
2936 /* If the file name has special constructs in it,
2937 call the corresponding file handler. */
2938 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
2939 if (!NILP (handler))
2940 return call3 (handler, Qset_file_selinux_context, absname, context);
2942 #if HAVE_LIBSELINUX
2943 if (is_selinux_enabled ())
2945 /* Get current file context. */
2946 encoded_absname = ENCODE_FILE (absname);
2947 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
2948 if (conlength > 0)
2950 parsed_con = context_new (con);
2951 /* Change the parts defined in the parameter.*/
2952 if (STRINGP (user))
2954 if (context_user_set (parsed_con, SSDATA (user)))
2955 error ("Doing context_user_set");
2957 if (STRINGP (role))
2959 if (context_role_set (parsed_con, SSDATA (role)))
2960 error ("Doing context_role_set");
2962 if (STRINGP (type))
2964 if (context_type_set (parsed_con, SSDATA (type)))
2965 error ("Doing context_type_set");
2967 if (STRINGP (range))
2969 if (context_range_set (parsed_con, SSDATA (range)))
2970 error ("Doing context_range_set");
2973 /* Set the modified context back to the file. */
2974 fail = (lsetfilecon (SSDATA (encoded_absname),
2975 context_str (parsed_con))
2976 != 0);
2977 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2978 if (fail && errno != ENOTSUP)
2979 report_file_error ("Doing lsetfilecon", absname);
2981 context_free (parsed_con);
2982 freecon (con);
2983 return fail ? Qnil : Qt;
2985 else
2986 report_file_error ("Doing lgetfilecon", absname);
2988 #endif
2990 return Qnil;
2993 DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
2994 doc: /* Return ACL entries of file named FILENAME.
2995 The entries are returned in a format suitable for use in `set-file-acl'
2996 but is otherwise undocumented and subject to change.
2997 Return nil if file does not exist or is not accessible, or if Emacs
2998 was unable to determine the ACL entries. */)
2999 (Lisp_Object filename)
3001 Lisp_Object absname;
3002 Lisp_Object handler;
3003 #ifdef HAVE_ACL_SET_FILE
3004 acl_t acl;
3005 Lisp_Object acl_string;
3006 char *str;
3007 #endif
3009 absname = expand_and_dir_to_file (filename,
3010 BVAR (current_buffer, directory));
3012 /* If the file name has special constructs in it,
3013 call the corresponding file handler. */
3014 handler = Ffind_file_name_handler (absname, Qfile_acl);
3015 if (!NILP (handler))
3016 return call2 (handler, Qfile_acl, absname);
3018 #ifdef HAVE_ACL_SET_FILE
3019 absname = ENCODE_FILE (absname);
3021 acl = acl_get_file (SSDATA (absname), ACL_TYPE_ACCESS);
3022 if (acl == NULL)
3023 return Qnil;
3025 str = acl_to_text (acl, NULL);
3026 if (str == NULL)
3028 acl_free (acl);
3029 return Qnil;
3032 acl_string = build_string (str);
3033 acl_free (str);
3034 acl_free (acl);
3036 return acl_string;
3037 #endif
3039 return Qnil;
3042 DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3043 2, 2, 0,
3044 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3045 ACL-STRING should contain the textual representation of the ACL
3046 entries in a format suitable for the platform.
3048 Value is t if setting of ACL was successful, nil otherwise.
3050 Setting ACL for local files requires Emacs to be built with ACL
3051 support. */)
3052 (Lisp_Object filename, Lisp_Object acl_string)
3054 Lisp_Object absname;
3055 Lisp_Object handler;
3056 #ifdef HAVE_ACL_SET_FILE
3057 Lisp_Object encoded_absname;
3058 acl_t acl;
3059 bool fail;
3060 #endif
3062 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3064 /* If the file name has special constructs in it,
3065 call the corresponding file handler. */
3066 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3067 if (!NILP (handler))
3068 return call3 (handler, Qset_file_acl, absname, acl_string);
3070 #ifdef HAVE_ACL_SET_FILE
3071 if (STRINGP (acl_string))
3073 acl = acl_from_text (SSDATA (acl_string));
3074 if (acl == NULL)
3076 report_file_error ("Converting ACL", absname);
3077 return Qnil;
3080 encoded_absname = ENCODE_FILE (absname);
3082 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3083 acl)
3084 != 0);
3085 if (fail && acl_errno_valid (errno))
3086 report_file_error ("Setting ACL", absname);
3088 acl_free (acl);
3089 return fail ? Qnil : Qt;
3091 #endif
3093 return Qnil;
3096 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3097 doc: /* Return mode bits of file named FILENAME, as an integer.
3098 Return nil, if file does not exist or is not accessible. */)
3099 (Lisp_Object filename)
3101 Lisp_Object absname;
3102 struct stat st;
3103 Lisp_Object handler;
3105 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
3107 /* If the file name has special constructs in it,
3108 call the corresponding file handler. */
3109 handler = Ffind_file_name_handler (absname, Qfile_modes);
3110 if (!NILP (handler))
3111 return call2 (handler, Qfile_modes, absname);
3113 absname = ENCODE_FILE (absname);
3115 if (stat (SSDATA (absname), &st) < 0)
3116 return Qnil;
3118 return make_number (st.st_mode & 07777);
3121 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3122 "(let ((file (read-file-name \"File: \"))) \
3123 (list file (read-file-modes nil file)))",
3124 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3125 Only the 12 low bits of MODE are used.
3127 Interactively, mode bits are read by `read-file-modes', which accepts
3128 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3129 (Lisp_Object filename, Lisp_Object mode)
3131 Lisp_Object absname, encoded_absname;
3132 Lisp_Object handler;
3134 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3135 CHECK_NUMBER (mode);
3137 /* If the file name has special constructs in it,
3138 call the corresponding file handler. */
3139 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3140 if (!NILP (handler))
3141 return call3 (handler, Qset_file_modes, absname, mode);
3143 encoded_absname = ENCODE_FILE (absname);
3145 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
3146 report_file_error ("Doing chmod", absname);
3148 return Qnil;
3151 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3152 doc: /* Set the file permission bits for newly created files.
3153 The argument MODE should be an integer; only the low 9 bits are used.
3154 This setting is inherited by subprocesses. */)
3155 (Lisp_Object mode)
3157 CHECK_NUMBER (mode);
3159 umask ((~ XINT (mode)) & 0777);
3161 return Qnil;
3164 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3165 doc: /* Return the default file protection for created files.
3166 The value is an integer. */)
3167 (void)
3169 mode_t realmask;
3170 Lisp_Object value;
3172 block_input ();
3173 realmask = umask (0);
3174 umask (realmask);
3175 unblock_input ();
3177 XSETINT (value, (~ realmask) & 0777);
3178 return value;
3182 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3183 doc: /* Set times of file FILENAME to TIMESTAMP.
3184 Set both access and modification times.
3185 Return t on success, else nil.
3186 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3187 `current-time'. */)
3188 (Lisp_Object filename, Lisp_Object timestamp)
3190 Lisp_Object absname, encoded_absname;
3191 Lisp_Object handler;
3192 struct timespec t = lisp_time_argument (timestamp);
3194 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3196 /* If the file name has special constructs in it,
3197 call the corresponding file handler. */
3198 handler = Ffind_file_name_handler (absname, Qset_file_times);
3199 if (!NILP (handler))
3200 return call3 (handler, Qset_file_times, absname, timestamp);
3202 encoded_absname = ENCODE_FILE (absname);
3205 if (set_file_times (-1, SSDATA (encoded_absname), t, t))
3207 #ifdef MSDOS
3208 /* Setting times on a directory always fails. */
3209 if (file_directory_p (SSDATA (encoded_absname)))
3210 return Qnil;
3211 #endif
3212 report_file_error ("Setting file times", absname);
3216 return Qt;
3219 #ifdef HAVE_SYNC
3220 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3221 doc: /* Tell Unix to finish all pending disk updates. */)
3222 (void)
3224 sync ();
3225 return Qnil;
3228 #endif /* HAVE_SYNC */
3230 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3231 doc: /* Return t if file FILE1 is newer than file FILE2.
3232 If FILE1 does not exist, the answer is nil;
3233 otherwise, if FILE2 does not exist, the answer is t. */)
3234 (Lisp_Object file1, Lisp_Object file2)
3236 Lisp_Object absname1, absname2;
3237 struct stat st1, st2;
3238 Lisp_Object handler;
3239 struct gcpro gcpro1, gcpro2;
3241 CHECK_STRING (file1);
3242 CHECK_STRING (file2);
3244 absname1 = Qnil;
3245 GCPRO2 (absname1, file2);
3246 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3247 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
3248 UNGCPRO;
3250 /* If the file name has special constructs in it,
3251 call the corresponding file handler. */
3252 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3253 if (NILP (handler))
3254 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3255 if (!NILP (handler))
3256 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3258 GCPRO2 (absname1, absname2);
3259 absname1 = ENCODE_FILE (absname1);
3260 absname2 = ENCODE_FILE (absname2);
3261 UNGCPRO;
3263 if (stat (SSDATA (absname1), &st1) < 0)
3264 return Qnil;
3266 if (stat (SSDATA (absname2), &st2) < 0)
3267 return Qt;
3269 return (timespec_cmp (get_stat_mtime (&st2), get_stat_mtime (&st1)) < 0
3270 ? Qt : Qnil);
3273 #ifndef READ_BUF_SIZE
3274 #define READ_BUF_SIZE (64 << 10)
3275 #endif
3276 /* Some buffer offsets are stored in 'int' variables. */
3277 verify (READ_BUF_SIZE <= INT_MAX);
3279 /* This function is called after Lisp functions to decide a coding
3280 system are called, or when they cause an error. Before they are
3281 called, the current buffer is set unibyte and it contains only a
3282 newly inserted text (thus the buffer was empty before the
3283 insertion).
3285 The functions may set markers, overlays, text properties, or even
3286 alter the buffer contents, change the current buffer.
3288 Here, we reset all those changes by:
3289 o set back the current buffer.
3290 o move all markers and overlays to BEG.
3291 o remove all text properties.
3292 o set back the buffer multibyteness. */
3294 static void
3295 decide_coding_unwind (Lisp_Object unwind_data)
3297 Lisp_Object multibyte, undo_list, buffer;
3299 multibyte = XCAR (unwind_data);
3300 unwind_data = XCDR (unwind_data);
3301 undo_list = XCAR (unwind_data);
3302 buffer = XCDR (unwind_data);
3304 set_buffer_internal (XBUFFER (buffer));
3305 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3306 adjust_overlays_for_delete (BEG, Z - BEG);
3307 set_buffer_intervals (current_buffer, NULL);
3308 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3310 /* Now we are safe to change the buffer's multibyteness directly. */
3311 bset_enable_multibyte_characters (current_buffer, multibyte);
3312 bset_undo_list (current_buffer, undo_list);
3315 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3316 object where slot 0 is the file descriptor, slot 1 specifies
3317 an offset to put the read bytes, and slot 2 is the maximum
3318 amount of bytes to read. Value is the number of bytes read. */
3320 static Lisp_Object
3321 read_non_regular (Lisp_Object state)
3323 int nbytes;
3325 immediate_quit = 1;
3326 QUIT;
3327 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
3328 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3329 + XSAVE_INTEGER (state, 1)),
3330 XSAVE_INTEGER (state, 2));
3331 immediate_quit = 0;
3332 /* Fast recycle this object for the likely next call. */
3333 free_misc (state);
3334 return make_number (nbytes);
3338 /* Condition-case handler used when reading from non-regular files
3339 in insert-file-contents. */
3341 static Lisp_Object
3342 read_non_regular_quit (Lisp_Object ignore)
3344 return Qnil;
3347 /* Return the file offset that VAL represents, checking for type
3348 errors and overflow. */
3349 static off_t
3350 file_offset (Lisp_Object val)
3352 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3353 return XINT (val);
3355 if (FLOATP (val))
3357 double v = XFLOAT_DATA (val);
3358 if (0 <= v
3359 && (sizeof (off_t) < sizeof v
3360 ? v <= TYPE_MAXIMUM (off_t)
3361 : v < TYPE_MAXIMUM (off_t)))
3362 return v;
3365 wrong_type_argument (intern ("file-offset"), val);
3368 /* Return a special time value indicating the error number ERRNUM. */
3369 static struct timespec
3370 time_error_value (int errnum)
3372 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
3373 ? NONEXISTENT_MODTIME_NSECS
3374 : UNKNOWN_MODTIME_NSECS);
3375 return make_timespec (0, ns);
3378 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3379 1, 5, 0,
3380 doc: /* Insert contents of file FILENAME after point.
3381 Returns list of absolute file name and number of characters inserted.
3382 If second argument VISIT is non-nil, the buffer's visited filename and
3383 last save file modtime are set, and it is marked unmodified. If
3384 visiting and the file does not exist, visiting is completed before the
3385 error is signaled.
3387 The optional third and fourth arguments BEG and END specify what portion
3388 of the file to insert. These arguments count bytes in the file, not
3389 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3391 If optional fifth argument REPLACE is non-nil, replace the current
3392 buffer contents (in the accessible portion) with the file contents.
3393 This is better than simply deleting and inserting the whole thing
3394 because (1) it preserves some marker positions and (2) it puts less data
3395 in the undo list. When REPLACE is non-nil, the second return value is
3396 the number of characters that replace previous buffer contents.
3398 This function does code conversion according to the value of
3399 `coding-system-for-read' or `file-coding-system-alist', and sets the
3400 variable `last-coding-system-used' to the coding system actually used.
3402 In addition, this function decodes the inserted text from known formats
3403 by calling `format-decode', which see. */)
3404 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
3406 struct stat st;
3407 struct timespec mtime;
3408 int fd;
3409 ptrdiff_t inserted = 0;
3410 ptrdiff_t how_much;
3411 off_t beg_offset, end_offset;
3412 int unprocessed;
3413 ptrdiff_t count = SPECPDL_INDEX ();
3414 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3415 Lisp_Object handler, val, insval, orig_filename, old_undo;
3416 Lisp_Object p;
3417 ptrdiff_t total = 0;
3418 bool not_regular = 0;
3419 int save_errno = 0;
3420 char read_buf[READ_BUF_SIZE];
3421 struct coding_system coding;
3422 bool replace_handled = 0;
3423 bool set_coding_system = 0;
3424 Lisp_Object coding_system;
3425 bool read_quit = 0;
3426 /* If the undo log only contains the insertion, there's no point
3427 keeping it. It's typically when we first fill a file-buffer. */
3428 bool empty_undo_list_p
3429 = (!NILP (visit) && NILP (BVAR (current_buffer, undo_list))
3430 && BEG == Z);
3431 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3432 bool we_locked_file = 0;
3433 ptrdiff_t fd_index;
3435 if (current_buffer->base_buffer && ! NILP (visit))
3436 error ("Cannot do file visiting in an indirect buffer");
3438 if (!NILP (BVAR (current_buffer, read_only)))
3439 Fbarf_if_buffer_read_only ();
3441 val = Qnil;
3442 p = Qnil;
3443 orig_filename = Qnil;
3444 old_undo = Qnil;
3446 GCPRO5 (filename, val, p, orig_filename, old_undo);
3448 CHECK_STRING (filename);
3449 filename = Fexpand_file_name (filename, Qnil);
3451 /* The value Qnil means that the coding system is not yet
3452 decided. */
3453 coding_system = Qnil;
3455 /* If the file name has special constructs in it,
3456 call the corresponding file handler. */
3457 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3458 if (!NILP (handler))
3460 val = call6 (handler, Qinsert_file_contents, filename,
3461 visit, beg, end, replace);
3462 if (CONSP (val) && CONSP (XCDR (val))
3463 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
3464 inserted = XINT (XCAR (XCDR (val)));
3465 goto handled;
3468 orig_filename = filename;
3469 filename = ENCODE_FILE (filename);
3471 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3472 if (fd < 0)
3474 save_errno = errno;
3475 if (NILP (visit))
3476 report_file_error ("Opening input file", orig_filename);
3477 mtime = time_error_value (save_errno);
3478 st.st_size = -1;
3479 if (!NILP (Vcoding_system_for_read))
3480 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3481 goto notfound;
3484 fd_index = SPECPDL_INDEX ();
3485 record_unwind_protect_int (close_file_unwind, fd);
3487 /* Replacement should preserve point as it preserves markers. */
3488 if (!NILP (replace))
3489 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3491 if (fstat (fd, &st) != 0)
3492 report_file_error ("Input file status", orig_filename);
3493 mtime = get_stat_mtime (&st);
3495 /* This code will need to be changed in order to work on named
3496 pipes, and it's probably just not worth it. So we should at
3497 least signal an error. */
3498 if (!S_ISREG (st.st_mode))
3500 not_regular = 1;
3502 if (! NILP (visit))
3503 goto notfound;
3505 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3506 xsignal2 (Qfile_error,
3507 build_string ("not a regular file"), orig_filename);
3510 if (!NILP (visit))
3512 if (!NILP (beg) || !NILP (end))
3513 error ("Attempt to visit less than an entire file");
3514 if (BEG < Z && NILP (replace))
3515 error ("Cannot do file visiting in a non-empty buffer");
3518 if (!NILP (beg))
3519 beg_offset = file_offset (beg);
3520 else
3521 beg_offset = 0;
3523 if (!NILP (end))
3524 end_offset = file_offset (end);
3525 else
3527 if (not_regular)
3528 end_offset = TYPE_MAXIMUM (off_t);
3529 else
3531 end_offset = st.st_size;
3533 /* A negative size can happen on a platform that allows file
3534 sizes greater than the maximum off_t value. */
3535 if (end_offset < 0)
3536 buffer_overflow ();
3538 /* The file size returned from stat may be zero, but data
3539 may be readable nonetheless, for example when this is a
3540 file in the /proc filesystem. */
3541 if (end_offset == 0)
3542 end_offset = READ_BUF_SIZE;
3546 /* Check now whether the buffer will become too large,
3547 in the likely case where the file's length is not changing.
3548 This saves a lot of needless work before a buffer overflow. */
3549 if (! not_regular)
3551 /* The likely offset where we will stop reading. We could read
3552 more (or less), if the file grows (or shrinks) as we read it. */
3553 off_t likely_end = min (end_offset, st.st_size);
3555 if (beg_offset < likely_end)
3557 ptrdiff_t buf_bytes
3558 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
3559 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3560 off_t likely_growth = likely_end - beg_offset;
3561 if (buf_growth_max < likely_growth)
3562 buffer_overflow ();
3566 /* Prevent redisplay optimizations. */
3567 current_buffer->clip_changed = 1;
3569 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3571 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3572 setup_coding_system (coding_system, &coding);
3573 /* Ensure we set Vlast_coding_system_used. */
3574 set_coding_system = 1;
3576 else if (BEG < Z)
3578 /* Decide the coding system to use for reading the file now
3579 because we can't use an optimized method for handling
3580 `coding:' tag if the current buffer is not empty. */
3581 if (!NILP (Vcoding_system_for_read))
3582 coding_system = Vcoding_system_for_read;
3583 else
3585 /* Don't try looking inside a file for a coding system
3586 specification if it is not seekable. */
3587 if (! not_regular && ! NILP (Vset_auto_coding_function))
3589 /* Find a coding system specified in the heading two
3590 lines or in the tailing several lines of the file.
3591 We assume that the 1K-byte and 3K-byte for heading
3592 and tailing respectively are sufficient for this
3593 purpose. */
3594 int nread;
3596 if (st.st_size <= (1024 * 4))
3597 nread = emacs_read (fd, read_buf, 1024 * 4);
3598 else
3600 nread = emacs_read (fd, read_buf, 1024);
3601 if (nread == 1024)
3603 int ntail;
3604 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
3605 report_file_error ("Setting file position",
3606 orig_filename);
3607 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3608 nread = ntail < 0 ? ntail : nread + ntail;
3612 if (nread < 0)
3613 report_file_error ("Read error", orig_filename);
3614 else if (nread > 0)
3616 struct buffer *prev = current_buffer;
3617 Lisp_Object workbuf;
3618 struct buffer *buf;
3620 record_unwind_current_buffer ();
3622 workbuf = Fget_buffer_create (build_string (" *code-converting-work*"));
3623 buf = XBUFFER (workbuf);
3625 delete_all_overlays (buf);
3626 bset_directory (buf, BVAR (current_buffer, directory));
3627 bset_read_only (buf, Qnil);
3628 bset_filename (buf, Qnil);
3629 bset_undo_list (buf, Qt);
3630 eassert (buf->overlays_before == NULL);
3631 eassert (buf->overlays_after == NULL);
3633 set_buffer_internal (buf);
3634 Ferase_buffer ();
3635 bset_enable_multibyte_characters (buf, Qnil);
3637 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
3638 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3639 coding_system = call2 (Vset_auto_coding_function,
3640 filename, make_number (nread));
3641 set_buffer_internal (prev);
3643 /* Discard the unwind protect for recovering the
3644 current buffer. */
3645 specpdl_ptr--;
3647 /* Rewind the file for the actual read done later. */
3648 if (lseek (fd, 0, SEEK_SET) < 0)
3649 report_file_error ("Setting file position", orig_filename);
3653 if (NILP (coding_system))
3655 /* If we have not yet decided a coding system, check
3656 file-coding-system-alist. */
3657 Lisp_Object args[6];
3659 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3660 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3661 coding_system = Ffind_operation_coding_system (6, args);
3662 if (CONSP (coding_system))
3663 coding_system = XCAR (coding_system);
3667 if (NILP (coding_system))
3668 coding_system = Qundecided;
3669 else
3670 CHECK_CODING_SYSTEM (coding_system);
3672 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3673 /* We must suppress all character code conversion except for
3674 end-of-line conversion. */
3675 coding_system = raw_text_coding_system (coding_system);
3677 setup_coding_system (coding_system, &coding);
3678 /* Ensure we set Vlast_coding_system_used. */
3679 set_coding_system = 1;
3682 /* If requested, replace the accessible part of the buffer
3683 with the file contents. Avoid replacing text at the
3684 beginning or end of the buffer that matches the file contents;
3685 that preserves markers pointing to the unchanged parts.
3687 Here we implement this feature in an optimized way
3688 for the case where code conversion is NOT needed.
3689 The following if-statement handles the case of conversion
3690 in a less optimal way.
3692 If the code conversion is "automatic" then we try using this
3693 method and hope for the best.
3694 But if we discover the need for conversion, we give up on this method
3695 and let the following if-statement handle the replace job. */
3696 if (!NILP (replace)
3697 && BEGV < ZV
3698 && (NILP (coding_system)
3699 || ! CODING_REQUIRE_DECODING (&coding)))
3701 /* same_at_start and same_at_end count bytes,
3702 because file access counts bytes
3703 and BEG and END count bytes. */
3704 ptrdiff_t same_at_start = BEGV_BYTE;
3705 ptrdiff_t same_at_end = ZV_BYTE;
3706 ptrdiff_t overlap;
3707 /* There is still a possibility we will find the need to do code
3708 conversion. If that happens, set this variable to
3709 give up on handling REPLACE in the optimized way. */
3710 bool giveup_match_end = 0;
3712 if (beg_offset != 0)
3714 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3715 report_file_error ("Setting file position", orig_filename);
3718 immediate_quit = 1;
3719 QUIT;
3720 /* Count how many chars at the start of the file
3721 match the text at the beginning of the buffer. */
3722 while (1)
3724 int nread, bufpos;
3726 nread = emacs_read (fd, read_buf, sizeof read_buf);
3727 if (nread < 0)
3728 report_file_error ("Read error", orig_filename);
3729 else if (nread == 0)
3730 break;
3732 if (CODING_REQUIRE_DETECTION (&coding))
3734 coding_system = detect_coding_system ((unsigned char *) read_buf,
3735 nread, nread, 1, 0,
3736 coding_system);
3737 setup_coding_system (coding_system, &coding);
3740 if (CODING_REQUIRE_DECODING (&coding))
3741 /* We found that the file should be decoded somehow.
3742 Let's give up here. */
3744 giveup_match_end = 1;
3745 break;
3748 bufpos = 0;
3749 while (bufpos < nread && same_at_start < ZV_BYTE
3750 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3751 same_at_start++, bufpos++;
3752 /* If we found a discrepancy, stop the scan.
3753 Otherwise loop around and scan the next bufferful. */
3754 if (bufpos != nread)
3755 break;
3757 immediate_quit = 0;
3758 /* If the file matches the buffer completely,
3759 there's no need to replace anything. */
3760 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3762 emacs_close (fd);
3763 clear_unwind_protect (fd_index);
3765 /* Truncate the buffer to the size of the file. */
3766 del_range_1 (same_at_start, same_at_end, 0, 0);
3767 goto handled;
3769 immediate_quit = 1;
3770 QUIT;
3771 /* Count how many chars at the end of the file
3772 match the text at the end of the buffer. But, if we have
3773 already found that decoding is necessary, don't waste time. */
3774 while (!giveup_match_end)
3776 int total_read, nread, bufpos, trial;
3777 off_t curpos;
3779 /* At what file position are we now scanning? */
3780 curpos = end_offset - (ZV_BYTE - same_at_end);
3781 /* If the entire file matches the buffer tail, stop the scan. */
3782 if (curpos == 0)
3783 break;
3784 /* How much can we scan in the next step? */
3785 trial = min (curpos, sizeof read_buf);
3786 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3787 report_file_error ("Setting file position", orig_filename);
3789 total_read = nread = 0;
3790 while (total_read < trial)
3792 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
3793 if (nread < 0)
3794 report_file_error ("Read error", orig_filename);
3795 else if (nread == 0)
3796 break;
3797 total_read += nread;
3800 /* Scan this bufferful from the end, comparing with
3801 the Emacs buffer. */
3802 bufpos = total_read;
3804 /* Compare with same_at_start to avoid counting some buffer text
3805 as matching both at the file's beginning and at the end. */
3806 while (bufpos > 0 && same_at_end > same_at_start
3807 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3808 same_at_end--, bufpos--;
3810 /* If we found a discrepancy, stop the scan.
3811 Otherwise loop around and scan the preceding bufferful. */
3812 if (bufpos != 0)
3814 /* If this discrepancy is because of code conversion,
3815 we cannot use this method; giveup and try the other. */
3816 if (same_at_end > same_at_start
3817 && FETCH_BYTE (same_at_end - 1) >= 0200
3818 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
3819 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3820 giveup_match_end = 1;
3821 break;
3824 if (nread == 0)
3825 break;
3827 immediate_quit = 0;
3829 if (! giveup_match_end)
3831 ptrdiff_t temp;
3833 /* We win! We can handle REPLACE the optimized way. */
3835 /* Extend the start of non-matching text area to multibyte
3836 character boundary. */
3837 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3838 while (same_at_start > BEGV_BYTE
3839 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3840 same_at_start--;
3842 /* Extend the end of non-matching text area to multibyte
3843 character boundary. */
3844 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3845 while (same_at_end < ZV_BYTE
3846 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3847 same_at_end++;
3849 /* Don't try to reuse the same piece of text twice. */
3850 overlap = (same_at_start - BEGV_BYTE
3851 - (same_at_end
3852 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
3853 if (overlap > 0)
3854 same_at_end += overlap;
3856 /* Arrange to read only the nonmatching middle part of the file. */
3857 beg_offset += same_at_start - BEGV_BYTE;
3858 end_offset -= ZV_BYTE - same_at_end;
3860 del_range_byte (same_at_start, same_at_end, 0);
3861 /* Insert from the file at the proper position. */
3862 temp = BYTE_TO_CHAR (same_at_start);
3863 SET_PT_BOTH (temp, same_at_start);
3865 /* If display currently starts at beginning of line,
3866 keep it that way. */
3867 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
3868 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
3870 replace_handled = 1;
3874 /* If requested, replace the accessible part of the buffer
3875 with the file contents. Avoid replacing text at the
3876 beginning or end of the buffer that matches the file contents;
3877 that preserves markers pointing to the unchanged parts.
3879 Here we implement this feature for the case where code conversion
3880 is needed, in a simple way that needs a lot of memory.
3881 The preceding if-statement handles the case of no conversion
3882 in a more optimized way. */
3883 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3885 ptrdiff_t same_at_start = BEGV_BYTE;
3886 ptrdiff_t same_at_end = ZV_BYTE;
3887 ptrdiff_t same_at_start_charpos;
3888 ptrdiff_t inserted_chars;
3889 ptrdiff_t overlap;
3890 ptrdiff_t bufpos;
3891 unsigned char *decoded;
3892 ptrdiff_t temp;
3893 ptrdiff_t this = 0;
3894 ptrdiff_t this_count = SPECPDL_INDEX ();
3895 bool multibyte
3896 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3897 Lisp_Object conversion_buffer;
3898 struct gcpro gcpro1;
3900 conversion_buffer = code_conversion_save (1, multibyte);
3902 /* First read the whole file, performing code conversion into
3903 CONVERSION_BUFFER. */
3905 if (lseek (fd, beg_offset, SEEK_SET) < 0)
3906 report_file_error ("Setting file position", orig_filename);
3908 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3909 unprocessed = 0; /* Bytes not processed in previous loop. */
3911 GCPRO1 (conversion_buffer);
3912 while (1)
3914 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3915 quitting while reading a huge file. */
3917 /* Allow quitting out of the actual I/O. */
3918 immediate_quit = 1;
3919 QUIT;
3920 this = emacs_read (fd, read_buf + unprocessed,
3921 READ_BUF_SIZE - unprocessed);
3922 immediate_quit = 0;
3924 if (this <= 0)
3925 break;
3927 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
3928 BUF_Z (XBUFFER (conversion_buffer)));
3929 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3930 unprocessed + this, conversion_buffer);
3931 unprocessed = coding.carryover_bytes;
3932 if (coding.carryover_bytes > 0)
3933 memcpy (read_buf, coding.carryover, unprocessed);
3935 UNGCPRO;
3936 if (this < 0)
3937 report_file_error ("Read error", orig_filename);
3938 emacs_close (fd);
3939 clear_unwind_protect (fd_index);
3941 if (unprocessed > 0)
3943 coding.mode |= CODING_MODE_LAST_BLOCK;
3944 decode_coding_c_string (&coding, (unsigned char *) read_buf,
3945 unprocessed, conversion_buffer);
3946 coding.mode &= ~CODING_MODE_LAST_BLOCK;
3949 coding_system = CODING_ID_NAME (coding.id);
3950 set_coding_system = 1;
3951 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
3952 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
3953 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
3955 /* Compare the beginning of the converted string with the buffer
3956 text. */
3958 bufpos = 0;
3959 while (bufpos < inserted && same_at_start < same_at_end
3960 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3961 same_at_start++, bufpos++;
3963 /* If the file matches the head of buffer completely,
3964 there's no need to replace anything. */
3966 if (bufpos == inserted)
3968 /* Truncate the buffer to the size of the file. */
3969 if (same_at_start != same_at_end)
3970 del_range_byte (same_at_start, same_at_end, 0);
3971 inserted = 0;
3973 unbind_to (this_count, Qnil);
3974 goto handled;
3977 /* Extend the start of non-matching text area to the previous
3978 multibyte character boundary. */
3979 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3980 while (same_at_start > BEGV_BYTE
3981 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3982 same_at_start--;
3984 /* Scan this bufferful from the end, comparing with
3985 the Emacs buffer. */
3986 bufpos = inserted;
3988 /* Compare with same_at_start to avoid counting some buffer text
3989 as matching both at the file's beginning and at the end. */
3990 while (bufpos > 0 && same_at_end > same_at_start
3991 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3992 same_at_end--, bufpos--;
3994 /* Extend the end of non-matching text area to the next
3995 multibyte character boundary. */
3996 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
3997 while (same_at_end < ZV_BYTE
3998 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3999 same_at_end++;
4001 /* Don't try to reuse the same piece of text twice. */
4002 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4003 if (overlap > 0)
4004 same_at_end += overlap;
4006 /* If display currently starts at beginning of line,
4007 keep it that way. */
4008 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
4009 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
4011 /* Replace the chars that we need to replace,
4012 and update INSERTED to equal the number of bytes
4013 we are taking from the decoded string. */
4014 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4016 if (same_at_end != same_at_start)
4018 del_range_byte (same_at_start, same_at_end, 0);
4019 temp = GPT;
4020 eassert (same_at_start == GPT_BYTE);
4021 same_at_start = GPT_BYTE;
4023 else
4025 temp = BYTE_TO_CHAR (same_at_start);
4027 /* Insert from the file at the proper position. */
4028 SET_PT_BOTH (temp, same_at_start);
4029 same_at_start_charpos
4030 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4031 same_at_start - BEGV_BYTE
4032 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4033 eassert (same_at_start_charpos == temp - (BEGV - BEG));
4034 inserted_chars
4035 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4036 same_at_start + inserted - BEGV_BYTE
4037 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
4038 - same_at_start_charpos);
4039 /* This binding is to avoid ask-user-about-supersession-threat
4040 being called in insert_from_buffer (via in
4041 prepare_to_modify_buffer). */
4042 specbind (intern ("buffer-file-name"), Qnil);
4043 insert_from_buffer (XBUFFER (conversion_buffer),
4044 same_at_start_charpos, inserted_chars, 0);
4045 /* Set `inserted' to the number of inserted characters. */
4046 inserted = PT - temp;
4047 /* Set point before the inserted characters. */
4048 SET_PT_BOTH (temp, same_at_start);
4050 unbind_to (this_count, Qnil);
4052 goto handled;
4055 if (! not_regular)
4056 total = end_offset - beg_offset;
4057 else
4058 /* For a special file, all we can do is guess. */
4059 total = READ_BUF_SIZE;
4061 if (NILP (visit) && total > 0)
4063 #ifdef CLASH_DETECTION
4064 if (!NILP (BVAR (current_buffer, file_truename))
4065 /* Make binding buffer-file-name to nil effective. */
4066 && !NILP (BVAR (current_buffer, filename))
4067 && SAVE_MODIFF >= MODIFF)
4068 we_locked_file = 1;
4069 #endif /* CLASH_DETECTION */
4070 prepare_to_modify_buffer (GPT, GPT, NULL);
4073 move_gap_both (PT, PT_BYTE);
4074 if (GAP_SIZE < total)
4075 make_gap (total - GAP_SIZE);
4077 if (beg_offset != 0 || !NILP (replace))
4079 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4080 report_file_error ("Setting file position", orig_filename);
4083 /* In the following loop, HOW_MUCH contains the total bytes read so
4084 far for a regular file, and not changed for a special file. But,
4085 before exiting the loop, it is set to a negative value if I/O
4086 error occurs. */
4087 how_much = 0;
4089 /* Total bytes inserted. */
4090 inserted = 0;
4092 /* Here, we don't do code conversion in the loop. It is done by
4093 decode_coding_gap after all data are read into the buffer. */
4095 ptrdiff_t gap_size = GAP_SIZE;
4097 while (how_much < total)
4099 /* try is reserved in some compilers (Microsoft C) */
4100 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4101 ptrdiff_t this;
4103 if (not_regular)
4105 Lisp_Object nbytes;
4107 /* Maybe make more room. */
4108 if (gap_size < trytry)
4110 make_gap (trytry - gap_size);
4111 gap_size = GAP_SIZE - inserted;
4114 /* Read from the file, capturing `quit'. When an
4115 error occurs, end the loop, and arrange for a quit
4116 to be signaled after decoding the text we read. */
4117 nbytes = internal_condition_case_1
4118 (read_non_regular,
4119 make_save_int_int_int (fd, inserted, trytry),
4120 Qerror, read_non_regular_quit);
4122 if (NILP (nbytes))
4124 read_quit = 1;
4125 break;
4128 this = XINT (nbytes);
4130 else
4132 /* Allow quitting out of the actual I/O. We don't make text
4133 part of the buffer until all the reading is done, so a C-g
4134 here doesn't do any harm. */
4135 immediate_quit = 1;
4136 QUIT;
4137 this = emacs_read (fd,
4138 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4139 + inserted),
4140 trytry);
4141 immediate_quit = 0;
4144 if (this <= 0)
4146 how_much = this;
4147 break;
4150 gap_size -= this;
4152 /* For a regular file, where TOTAL is the real size,
4153 count HOW_MUCH to compare with it.
4154 For a special file, where TOTAL is just a buffer size,
4155 so don't bother counting in HOW_MUCH.
4156 (INSERTED is where we count the number of characters inserted.) */
4157 if (! not_regular)
4158 how_much += this;
4159 inserted += this;
4163 /* Now we have either read all the file data into the gap,
4164 or stop reading on I/O error or quit. If nothing was
4165 read, undo marking the buffer modified. */
4167 if (inserted == 0)
4169 #ifdef CLASH_DETECTION
4170 if (we_locked_file)
4171 unlock_file (BVAR (current_buffer, file_truename));
4172 #endif
4173 Vdeactivate_mark = old_Vdeactivate_mark;
4175 else
4176 Vdeactivate_mark = Qt;
4178 emacs_close (fd);
4179 clear_unwind_protect (fd_index);
4181 if (how_much < 0)
4182 report_file_error ("Read error", orig_filename);
4184 /* Make the text read part of the buffer. */
4185 GAP_SIZE -= inserted;
4186 GPT += inserted;
4187 GPT_BYTE += inserted;
4188 ZV += inserted;
4189 ZV_BYTE += inserted;
4190 Z += inserted;
4191 Z_BYTE += inserted;
4193 if (GAP_SIZE > 0)
4194 /* Put an anchor to ensure multi-byte form ends at gap. */
4195 *GPT_ADDR = 0;
4197 notfound:
4199 if (NILP (coding_system))
4201 /* The coding system is not yet decided. Decide it by an
4202 optimized method for handling `coding:' tag.
4204 Note that we can get here only if the buffer was empty
4205 before the insertion. */
4207 if (!NILP (Vcoding_system_for_read))
4208 coding_system = Vcoding_system_for_read;
4209 else
4211 /* Since we are sure that the current buffer was empty
4212 before the insertion, we can toggle
4213 enable-multibyte-characters directly here without taking
4214 care of marker adjustment. By this way, we can run Lisp
4215 program safely before decoding the inserted text. */
4216 Lisp_Object unwind_data;
4217 ptrdiff_t count1 = SPECPDL_INDEX ();
4219 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4220 Fcons (BVAR (current_buffer, undo_list),
4221 Fcurrent_buffer ()));
4222 bset_enable_multibyte_characters (current_buffer, Qnil);
4223 bset_undo_list (current_buffer, Qt);
4224 record_unwind_protect (decide_coding_unwind, unwind_data);
4226 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4228 coding_system = call2 (Vset_auto_coding_function,
4229 filename, make_number (inserted));
4232 if (NILP (coding_system))
4234 /* If the coding system is not yet decided, check
4235 file-coding-system-alist. */
4236 Lisp_Object args[6];
4238 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4239 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4240 coding_system = Ffind_operation_coding_system (6, args);
4241 if (CONSP (coding_system))
4242 coding_system = XCAR (coding_system);
4244 unbind_to (count1, Qnil);
4245 inserted = Z_BYTE - BEG_BYTE;
4248 if (NILP (coding_system))
4249 coding_system = Qundecided;
4250 else
4251 CHECK_CODING_SYSTEM (coding_system);
4253 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4254 /* We must suppress all character code conversion except for
4255 end-of-line conversion. */
4256 coding_system = raw_text_coding_system (coding_system);
4257 setup_coding_system (coding_system, &coding);
4258 /* Ensure we set Vlast_coding_system_used. */
4259 set_coding_system = 1;
4262 if (!NILP (visit))
4264 /* When we visit a file by raw-text, we change the buffer to
4265 unibyte. */
4266 if (CODING_FOR_UNIBYTE (&coding)
4267 /* Can't do this if part of the buffer might be preserved. */
4268 && NILP (replace))
4269 /* Visiting a file with these coding system makes the buffer
4270 unibyte. */
4271 bset_enable_multibyte_characters (current_buffer, Qnil);
4274 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
4275 if (CODING_MAY_REQUIRE_DECODING (&coding)
4276 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4278 move_gap_both (PT, PT_BYTE);
4279 GAP_SIZE += inserted;
4280 ZV_BYTE -= inserted;
4281 Z_BYTE -= inserted;
4282 ZV -= inserted;
4283 Z -= inserted;
4284 decode_coding_gap (&coding, inserted, inserted);
4285 inserted = coding.produced_char;
4286 coding_system = CODING_ID_NAME (coding.id);
4288 else if (inserted > 0)
4289 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4290 inserted);
4292 /* Call after-change hooks for the inserted text, aside from the case
4293 of normal visiting (not with REPLACE), which is done in a new buffer
4294 "before" the buffer is changed. */
4295 if (inserted > 0 && total > 0
4296 && (NILP (visit) || !NILP (replace)))
4298 signal_after_change (PT, 0, inserted);
4299 update_compositions (PT, PT, CHECK_BORDER);
4302 /* Now INSERTED is measured in characters. */
4304 handled:
4306 if (!NILP (visit))
4308 if (empty_undo_list_p)
4309 bset_undo_list (current_buffer, Qnil);
4311 if (NILP (handler))
4313 current_buffer->modtime = mtime;
4314 current_buffer->modtime_size = st.st_size;
4315 bset_filename (current_buffer, orig_filename);
4318 SAVE_MODIFF = MODIFF;
4319 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4320 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4321 #ifdef CLASH_DETECTION
4322 if (NILP (handler))
4324 if (!NILP (BVAR (current_buffer, file_truename)))
4325 unlock_file (BVAR (current_buffer, file_truename));
4326 unlock_file (filename);
4328 #endif /* CLASH_DETECTION */
4329 if (not_regular)
4330 xsignal2 (Qfile_error,
4331 build_string ("not a regular file"), orig_filename);
4334 if (set_coding_system)
4335 Vlast_coding_system_used = coding_system;
4337 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4339 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4340 visit);
4341 if (! NILP (insval))
4343 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4344 wrong_type_argument (intern ("inserted-chars"), insval);
4345 inserted = XFASTINT (insval);
4349 /* Decode file format. */
4350 if (inserted > 0)
4352 /* Don't run point motion or modification hooks when decoding. */
4353 ptrdiff_t count1 = SPECPDL_INDEX ();
4354 ptrdiff_t old_inserted = inserted;
4355 specbind (Qinhibit_point_motion_hooks, Qt);
4356 specbind (Qinhibit_modification_hooks, Qt);
4358 /* Save old undo list and don't record undo for decoding. */
4359 old_undo = BVAR (current_buffer, undo_list);
4360 bset_undo_list (current_buffer, Qt);
4362 if (NILP (replace))
4364 insval = call3 (Qformat_decode,
4365 Qnil, make_number (inserted), visit);
4366 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4367 wrong_type_argument (intern ("inserted-chars"), insval);
4368 inserted = XFASTINT (insval);
4370 else
4372 /* If REPLACE is non-nil and we succeeded in not replacing the
4373 beginning or end of the buffer text with the file's contents,
4374 call format-decode with `point' positioned at the beginning
4375 of the buffer and `inserted' equaling the number of
4376 characters in the buffer. Otherwise, format-decode might
4377 fail to correctly analyze the beginning or end of the buffer.
4378 Hence we temporarily save `point' and `inserted' here and
4379 restore `point' iff format-decode did not insert or delete
4380 any text. Otherwise we leave `point' at point-min. */
4381 ptrdiff_t opoint = PT;
4382 ptrdiff_t opoint_byte = PT_BYTE;
4383 ptrdiff_t oinserted = ZV - BEGV;
4384 EMACS_INT ochars_modiff = CHARS_MODIFF;
4386 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4387 insval = call3 (Qformat_decode,
4388 Qnil, make_number (oinserted), visit);
4389 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4390 wrong_type_argument (intern ("inserted-chars"), insval);
4391 if (ochars_modiff == CHARS_MODIFF)
4392 /* format_decode didn't modify buffer's characters => move
4393 point back to position before inserted text and leave
4394 value of inserted alone. */
4395 SET_PT_BOTH (opoint, opoint_byte);
4396 else
4397 /* format_decode modified buffer's characters => consider
4398 entire buffer changed and leave point at point-min. */
4399 inserted = XFASTINT (insval);
4402 /* For consistency with format-decode call these now iff inserted > 0
4403 (martin 2007-06-28). */
4404 p = Vafter_insert_file_functions;
4405 while (CONSP (p))
4407 if (NILP (replace))
4409 insval = call1 (XCAR (p), make_number (inserted));
4410 if (!NILP (insval))
4412 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4413 wrong_type_argument (intern ("inserted-chars"), insval);
4414 inserted = XFASTINT (insval);
4417 else
4419 /* For the rationale of this see the comment on
4420 format-decode above. */
4421 ptrdiff_t opoint = PT;
4422 ptrdiff_t opoint_byte = PT_BYTE;
4423 ptrdiff_t oinserted = ZV - BEGV;
4424 EMACS_INT ochars_modiff = CHARS_MODIFF;
4426 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4427 insval = call1 (XCAR (p), make_number (oinserted));
4428 if (!NILP (insval))
4430 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4431 wrong_type_argument (intern ("inserted-chars"), insval);
4432 if (ochars_modiff == CHARS_MODIFF)
4433 /* after_insert_file_functions didn't modify
4434 buffer's characters => move point back to
4435 position before inserted text and leave value of
4436 inserted alone. */
4437 SET_PT_BOTH (opoint, opoint_byte);
4438 else
4439 /* after_insert_file_functions did modify buffer's
4440 characters => consider entire buffer changed and
4441 leave point at point-min. */
4442 inserted = XFASTINT (insval);
4446 QUIT;
4447 p = XCDR (p);
4450 if (!empty_undo_list_p)
4452 bset_undo_list (current_buffer, old_undo);
4453 if (CONSP (old_undo) && inserted != old_inserted)
4455 /* Adjust the last undo record for the size change during
4456 the format conversion. */
4457 Lisp_Object tem = XCAR (old_undo);
4458 if (CONSP (tem) && INTEGERP (XCAR (tem))
4459 && INTEGERP (XCDR (tem))
4460 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4461 XSETCDR (tem, make_number (PT + inserted));
4464 else
4465 /* If undo_list was Qt before, keep it that way.
4466 Otherwise start with an empty undo_list. */
4467 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
4469 unbind_to (count1, Qnil);
4472 if (!NILP (visit)
4473 && current_buffer->modtime.tv_nsec == NONEXISTENT_MODTIME_NSECS)
4475 /* If visiting nonexistent file, return nil. */
4476 report_file_errno ("Opening input file", orig_filename, save_errno);
4479 if (read_quit)
4480 Fsignal (Qquit, Qnil);
4482 /* Retval needs to be dealt with in all cases consistently. */
4483 if (NILP (val))
4484 val = list2 (orig_filename, make_number (inserted));
4486 RETURN_UNGCPRO (unbind_to (count, val));
4489 static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
4491 static void
4492 build_annotations_unwind (Lisp_Object arg)
4494 Vwrite_region_annotation_buffers = arg;
4497 /* Decide the coding-system to encode the data with. */
4499 DEFUN ("choose-write-coding-system", Fchoose_write_coding_system,
4500 Schoose_write_coding_system, 3, 6, 0,
4501 doc: /* Choose the coding system for writing a file.
4502 Arguments are as for `write-region'.
4503 This function is for internal use only. It may prompt the user. */ )
4504 (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4505 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname)
4507 Lisp_Object val;
4508 Lisp_Object eol_parent = Qnil;
4510 /* Mimic write-region behavior. */
4511 if (NILP (start))
4513 XSETFASTINT (start, BEGV);
4514 XSETFASTINT (end, ZV);
4517 if (auto_saving
4518 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4519 BVAR (current_buffer, auto_save_file_name))))
4521 val = Qutf_8_emacs;
4522 eol_parent = Qunix;
4524 else if (!NILP (Vcoding_system_for_write))
4526 val = Vcoding_system_for_write;
4527 if (coding_system_require_warning
4528 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4529 /* Confirm that VAL can surely encode the current region. */
4530 val = call5 (Vselect_safe_coding_system_function,
4531 start, end, list2 (Qt, val),
4532 Qnil, filename);
4534 else
4536 /* If the variable `buffer-file-coding-system' is set locally,
4537 it means that the file was read with some kind of code
4538 conversion or the variable is explicitly set by users. We
4539 had better write it out with the same coding system even if
4540 `enable-multibyte-characters' is nil.
4542 If it is not set locally, we anyway have to convert EOL
4543 format if the default value of `buffer-file-coding-system'
4544 tells that it is not Unix-like (LF only) format. */
4545 bool using_default_coding = 0;
4546 bool force_raw_text = 0;
4548 val = BVAR (current_buffer, buffer_file_coding_system);
4549 if (NILP (val)
4550 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4552 val = Qnil;
4553 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4554 force_raw_text = 1;
4557 if (NILP (val))
4559 /* Check file-coding-system-alist. */
4560 Lisp_Object args[7], coding_systems;
4562 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4563 args[3] = filename; args[4] = append; args[5] = visit;
4564 args[6] = lockname;
4565 coding_systems = Ffind_operation_coding_system (7, args);
4566 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4567 val = XCDR (coding_systems);
4570 if (NILP (val))
4572 /* If we still have not decided a coding system, use the
4573 default value of buffer-file-coding-system. */
4574 val = BVAR (current_buffer, buffer_file_coding_system);
4575 using_default_coding = 1;
4578 if (! NILP (val) && ! force_raw_text)
4580 Lisp_Object spec, attrs;
4582 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4583 attrs = AREF (spec, 0);
4584 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4585 force_raw_text = 1;
4588 if (!force_raw_text
4589 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4590 /* Confirm that VAL can surely encode the current region. */
4591 val = call5 (Vselect_safe_coding_system_function,
4592 start, end, val, Qnil, filename);
4594 /* If the decided coding-system doesn't specify end-of-line
4595 format, we use that of
4596 `default-buffer-file-coding-system'. */
4597 if (! using_default_coding
4598 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
4599 val = (coding_inherit_eol_type
4600 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
4602 /* If we decide not to encode text, use `raw-text' or one of its
4603 subsidiaries. */
4604 if (force_raw_text)
4605 val = raw_text_coding_system (val);
4608 val = coding_inherit_eol_type (val, eol_parent);
4609 return val;
4612 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4613 "r\nFWrite region to file: \ni\ni\ni\np",
4614 doc: /* Write current region into specified file.
4615 When called from a program, requires three arguments:
4616 START, END and FILENAME. START and END are normally buffer positions
4617 specifying the part of the buffer to write.
4618 If START is nil, that means to use the entire buffer contents.
4619 If START is a string, then output that string to the file
4620 instead of any buffer contents; END is ignored.
4622 Optional fourth argument APPEND if non-nil means
4623 append to existing file contents (if any). If it is a number,
4624 seek to that offset in the file before writing.
4625 Optional fifth argument VISIT, if t or a string, means
4626 set the last-save-file-modtime of buffer to this file's modtime
4627 and mark buffer not modified.
4628 If VISIT is a string, it is a second file name;
4629 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4630 VISIT is also the file name to lock and unlock for clash detection.
4631 If VISIT is neither t nor nil nor a string,
4632 that means do not display the \"Wrote file\" message.
4633 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4634 use for locking and unlocking, overriding FILENAME and VISIT.
4635 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4636 for an existing file with the same name. If MUSTBENEW is `excl',
4637 that means to get an error if the file already exists; never overwrite.
4638 If MUSTBENEW is neither nil nor `excl', that means ask for
4639 confirmation before overwriting, but do go ahead and overwrite the file
4640 if the user confirms.
4642 This does code conversion according to the value of
4643 `coding-system-for-write', `buffer-file-coding-system', or
4644 `file-coding-system-alist', and sets the variable
4645 `last-coding-system-used' to the coding system actually used.
4647 This calls `write-region-annotate-functions' at the start, and
4648 `write-region-post-annotation-function' at the end. */)
4649 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append,
4650 Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
4652 return write_region (start, end, filename, append, visit, lockname, mustbenew,
4653 -1);
4656 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4657 descriptor for FILENAME, so do not open or close FILENAME. */
4659 Lisp_Object
4660 write_region (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4661 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname,
4662 Lisp_Object mustbenew, int desc)
4664 int open_flags;
4665 int mode;
4666 off_t offset IF_LINT (= 0);
4667 bool open_and_close_file = desc < 0;
4668 bool ok;
4669 int save_errno = 0;
4670 const char *fn;
4671 struct stat st;
4672 struct timespec modtime;
4673 ptrdiff_t count = SPECPDL_INDEX ();
4674 ptrdiff_t count1 IF_LINT (= 0);
4675 Lisp_Object handler;
4676 Lisp_Object visit_file;
4677 Lisp_Object annotations;
4678 Lisp_Object encoded_filename;
4679 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4680 bool quietly = !NILP (visit);
4681 bool file_locked = 0;
4682 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4683 struct buffer *given_buffer;
4684 struct coding_system coding;
4686 if (current_buffer->base_buffer && visiting)
4687 error ("Cannot do file visiting in an indirect buffer");
4689 if (!NILP (start) && !STRINGP (start))
4690 validate_region (&start, &end);
4692 visit_file = Qnil;
4693 GCPRO5 (start, filename, visit, visit_file, lockname);
4695 filename = Fexpand_file_name (filename, Qnil);
4697 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4698 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4700 if (STRINGP (visit))
4701 visit_file = Fexpand_file_name (visit, Qnil);
4702 else
4703 visit_file = filename;
4705 if (NILP (lockname))
4706 lockname = visit_file;
4708 annotations = Qnil;
4710 /* If the file name has special constructs in it,
4711 call the corresponding file handler. */
4712 handler = Ffind_file_name_handler (filename, Qwrite_region);
4713 /* If FILENAME has no handler, see if VISIT has one. */
4714 if (NILP (handler) && STRINGP (visit))
4715 handler = Ffind_file_name_handler (visit, Qwrite_region);
4717 if (!NILP (handler))
4719 Lisp_Object val;
4720 val = call6 (handler, Qwrite_region, start, end,
4721 filename, append, visit);
4723 if (visiting)
4725 SAVE_MODIFF = MODIFF;
4726 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4727 bset_filename (current_buffer, visit_file);
4729 UNGCPRO;
4730 return val;
4733 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4735 /* Special kludge to simplify auto-saving. */
4736 if (NILP (start))
4738 /* Do it later, so write-region-annotate-function can work differently
4739 if we save "the buffer" vs "a region".
4740 This is useful in tar-mode. --Stef
4741 XSETFASTINT (start, BEG);
4742 XSETFASTINT (end, Z); */
4743 Fwiden ();
4746 record_unwind_protect (build_annotations_unwind,
4747 Vwrite_region_annotation_buffers);
4748 Vwrite_region_annotation_buffers = list1 (Fcurrent_buffer ());
4750 given_buffer = current_buffer;
4752 if (!STRINGP (start))
4754 annotations = build_annotations (start, end);
4756 if (current_buffer != given_buffer)
4758 XSETFASTINT (start, BEGV);
4759 XSETFASTINT (end, ZV);
4763 if (NILP (start))
4765 XSETFASTINT (start, BEGV);
4766 XSETFASTINT (end, ZV);
4769 UNGCPRO;
4771 GCPRO5 (start, filename, annotations, visit_file, lockname);
4773 /* Decide the coding-system to encode the data with.
4774 We used to make this choice before calling build_annotations, but that
4775 leads to problems when a write-annotate-function takes care of
4776 unsavable chars (as was the case with X-Symbol). */
4777 Vlast_coding_system_used =
4778 Fchoose_write_coding_system (start, end, filename,
4779 append, visit, lockname);
4781 setup_coding_system (Vlast_coding_system_used, &coding);
4783 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4784 coding.mode |= CODING_MODE_SELECTIVE_DISPLAY;
4786 #ifdef CLASH_DETECTION
4787 if (open_and_close_file && !auto_saving)
4789 lock_file (lockname);
4790 file_locked = 1;
4792 #endif /* CLASH_DETECTION */
4794 encoded_filename = ENCODE_FILE (filename);
4795 fn = SSDATA (encoded_filename);
4796 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4797 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4798 if (NUMBERP (append))
4799 offset = file_offset (append);
4800 else if (!NILP (append))
4801 open_flags |= O_APPEND;
4802 #ifdef DOS_NT
4803 mode = S_IREAD | S_IWRITE;
4804 #else
4805 mode = auto_saving ? auto_save_mode_bits : 0666;
4806 #endif
4808 if (open_and_close_file)
4810 desc = emacs_open (fn, open_flags, mode);
4811 if (desc < 0)
4813 int open_errno = errno;
4814 #ifdef CLASH_DETECTION
4815 if (file_locked)
4816 unlock_file (lockname);
4817 #endif /* CLASH_DETECTION */
4818 UNGCPRO;
4819 report_file_errno ("Opening output file", filename, open_errno);
4822 count1 = SPECPDL_INDEX ();
4823 record_unwind_protect_int (close_file_unwind, desc);
4826 if (NUMBERP (append))
4828 off_t ret = lseek (desc, offset, SEEK_SET);
4829 if (ret < 0)
4831 int lseek_errno = errno;
4832 #ifdef CLASH_DETECTION
4833 if (file_locked)
4834 unlock_file (lockname);
4835 #endif /* CLASH_DETECTION */
4836 UNGCPRO;
4837 report_file_errno ("Lseek error", filename, lseek_errno);
4841 UNGCPRO;
4843 immediate_quit = 1;
4845 if (STRINGP (start))
4846 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
4847 else if (XINT (start) != XINT (end))
4848 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4849 &annotations, &coding);
4850 else
4852 /* If file was empty, still need to write the annotations. */
4853 coding.mode |= CODING_MODE_LAST_BLOCK;
4854 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
4856 save_errno = errno;
4858 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4859 && !(coding.mode & CODING_MODE_LAST_BLOCK))
4861 /* We have to flush out a data. */
4862 coding.mode |= CODING_MODE_LAST_BLOCK;
4863 ok = e_write (desc, Qnil, 1, 1, &coding);
4864 save_errno = errno;
4867 immediate_quit = 0;
4869 /* fsync is not crucial for temporary files. Nor for auto-save
4870 files, since they might lose some work anyway. */
4871 if (open_and_close_file && !auto_saving && !write_region_inhibit_fsync)
4873 /* Transfer data and metadata to disk, retrying if interrupted.
4874 fsync can report a write failure here, e.g., due to disk full
4875 under NFS. But ignore EINVAL, which means fsync is not
4876 supported on this file. */
4877 while (fsync (desc) != 0)
4878 if (errno != EINTR)
4880 if (errno != EINVAL)
4881 ok = 0, save_errno = errno;
4882 break;
4886 modtime = invalid_timespec ();
4887 if (visiting)
4889 if (fstat (desc, &st) == 0)
4890 modtime = get_stat_mtime (&st);
4891 else
4892 ok = 0, save_errno = errno;
4895 if (open_and_close_file)
4897 /* NFS can report a write failure now. */
4898 if (emacs_close (desc) < 0)
4899 ok = 0, save_errno = errno;
4901 /* Discard the unwind protect for close_file_unwind. */
4902 specpdl_ptr = specpdl + count1;
4905 /* Some file systems have a bug where st_mtime is not updated
4906 properly after a write. For example, CIFS might not see the
4907 st_mtime change until after the file is opened again.
4909 Attempt to detect this file system bug, and update MODTIME to the
4910 newer st_mtime if the bug appears to be present. This introduces
4911 a race condition, so to avoid most instances of the race condition
4912 on non-buggy file systems, skip this check if the most recently
4913 encountered non-buggy file system was the current file system.
4915 A race condition can occur if some other process modifies the
4916 file between the fstat above and the fstat below, but the race is
4917 unlikely and a similar race between the last write and the fstat
4918 above cannot possibly be closed anyway. */
4920 if (timespec_valid_p (modtime)
4921 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
4923 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
4924 if (desc1 >= 0)
4926 struct stat st1;
4927 if (fstat (desc1, &st1) == 0
4928 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
4930 /* Use the heuristic if it appears to be valid. With neither
4931 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4932 file, the time stamp won't change. Also, some non-POSIX
4933 systems don't update an empty file's time stamp when
4934 truncating it. Finally, file systems with 100 ns or worse
4935 resolution sometimes seem to have bugs: on a system with ns
4936 resolution, checking ns % 100 incorrectly avoids the heuristic
4937 1% of the time, but the problem should be temporary as we will
4938 try again on the next time stamp. */
4939 bool use_heuristic
4940 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
4941 && st.st_size != 0
4942 && modtime.tv_nsec % 100 != 0);
4944 struct timespec modtime1 = get_stat_mtime (&st1);
4945 if (use_heuristic
4946 && timespec_cmp (modtime, modtime1) == 0
4947 && st.st_size == st1.st_size)
4949 timestamp_file_system = st.st_dev;
4950 valid_timestamp_file_system = 1;
4952 else
4954 st.st_size = st1.st_size;
4955 modtime = modtime1;
4958 emacs_close (desc1);
4962 /* Call write-region-post-annotation-function. */
4963 while (CONSP (Vwrite_region_annotation_buffers))
4965 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
4966 if (!NILP (Fbuffer_live_p (buf)))
4968 Fset_buffer (buf);
4969 if (FUNCTIONP (Vwrite_region_post_annotation_function))
4970 call0 (Vwrite_region_post_annotation_function);
4972 Vwrite_region_annotation_buffers
4973 = XCDR (Vwrite_region_annotation_buffers);
4976 unbind_to (count, Qnil);
4978 #ifdef CLASH_DETECTION
4979 if (file_locked)
4980 unlock_file (lockname);
4981 #endif /* CLASH_DETECTION */
4983 /* Do this before reporting IO error
4984 to avoid a "file has changed on disk" warning on
4985 next attempt to save. */
4986 if (timespec_valid_p (modtime))
4988 current_buffer->modtime = modtime;
4989 current_buffer->modtime_size = st.st_size;
4992 if (! ok)
4993 report_file_errno ("Write error", filename, save_errno);
4995 if (visiting)
4997 SAVE_MODIFF = MODIFF;
4998 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
4999 bset_filename (current_buffer, visit_file);
5000 update_mode_lines = 14;
5002 else if (quietly)
5004 if (auto_saving
5005 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5006 BVAR (current_buffer, auto_save_file_name))))
5007 SAVE_MODIFF = MODIFF;
5009 return Qnil;
5012 if (!auto_saving)
5013 message_with_string ((NUMBERP (append)
5014 ? "Updated %s"
5015 : ! NILP (append)
5016 ? "Added to %s"
5017 : "Wrote %s"),
5018 visit_file, 1);
5020 return Qnil;
5023 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5024 doc: /* Return t if (car A) is numerically less than (car B). */)
5025 (Lisp_Object a, Lisp_Object b)
5027 Lisp_Object args[2] = { Fcar (a), Fcar (b), };
5028 return Flss (2, args);
5031 /* Build the complete list of annotations appropriate for writing out
5032 the text between START and END, by calling all the functions in
5033 write-region-annotate-functions and merging the lists they return.
5034 If one of these functions switches to a different buffer, we assume
5035 that buffer contains altered text. Therefore, the caller must
5036 make sure to restore the current buffer in all cases,
5037 as save-excursion would do. */
5039 static Lisp_Object
5040 build_annotations (Lisp_Object start, Lisp_Object end)
5042 Lisp_Object annotations;
5043 Lisp_Object p, res;
5044 struct gcpro gcpro1, gcpro2;
5045 Lisp_Object original_buffer;
5046 int i;
5047 bool used_global = 0;
5049 XSETBUFFER (original_buffer, current_buffer);
5051 annotations = Qnil;
5052 p = Vwrite_region_annotate_functions;
5053 GCPRO2 (annotations, p);
5054 while (CONSP (p))
5056 struct buffer *given_buffer = current_buffer;
5057 if (EQ (Qt, XCAR (p)) && !used_global)
5058 { /* Use the global value of the hook. */
5059 Lisp_Object arg[2];
5060 used_global = 1;
5061 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
5062 arg[1] = XCDR (p);
5063 p = Fappend (2, arg);
5064 continue;
5066 Vwrite_region_annotations_so_far = annotations;
5067 res = call2 (XCAR (p), start, end);
5068 /* If the function makes a different buffer current,
5069 assume that means this buffer contains altered text to be output.
5070 Reset START and END from the buffer bounds
5071 and discard all previous annotations because they should have
5072 been dealt with by this function. */
5073 if (current_buffer != given_buffer)
5075 Vwrite_region_annotation_buffers
5076 = Fcons (Fcurrent_buffer (),
5077 Vwrite_region_annotation_buffers);
5078 XSETFASTINT (start, BEGV);
5079 XSETFASTINT (end, ZV);
5080 annotations = Qnil;
5082 Flength (res); /* Check basic validity of return value */
5083 annotations = merge (annotations, res, Qcar_less_than_car);
5084 p = XCDR (p);
5087 /* Now do the same for annotation functions implied by the file-format */
5088 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5089 p = BVAR (current_buffer, auto_save_file_format);
5090 else
5091 p = BVAR (current_buffer, file_format);
5092 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5094 struct buffer *given_buffer = current_buffer;
5096 Vwrite_region_annotations_so_far = annotations;
5098 /* Value is either a list of annotations or nil if the function
5099 has written annotations to a temporary buffer, which is now
5100 current. */
5101 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5102 original_buffer, make_number (i));
5103 if (current_buffer != given_buffer)
5105 XSETFASTINT (start, BEGV);
5106 XSETFASTINT (end, ZV);
5107 annotations = Qnil;
5110 if (CONSP (res))
5111 annotations = merge (annotations, res, Qcar_less_than_car);
5114 UNGCPRO;
5115 return annotations;
5119 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5120 If STRING is nil, POS is the character position in the current buffer.
5121 Intersperse with them the annotations from *ANNOT
5122 which fall within the range of POS to POS + NCHARS,
5123 each at its appropriate position.
5125 We modify *ANNOT by discarding elements as we use them up.
5127 Return true if successful. */
5129 static bool
5130 a_write (int desc, Lisp_Object string, ptrdiff_t pos,
5131 ptrdiff_t nchars, Lisp_Object *annot,
5132 struct coding_system *coding)
5134 Lisp_Object tem;
5135 ptrdiff_t nextpos;
5136 ptrdiff_t lastpos = pos + nchars;
5138 while (NILP (*annot) || CONSP (*annot))
5140 tem = Fcar_safe (Fcar (*annot));
5141 nextpos = pos - 1;
5142 if (INTEGERP (tem))
5143 nextpos = XFASTINT (tem);
5145 /* If there are no more annotations in this range,
5146 output the rest of the range all at once. */
5147 if (! (nextpos >= pos && nextpos <= lastpos))
5148 return e_write (desc, string, pos, lastpos, coding);
5150 /* Output buffer text up to the next annotation's position. */
5151 if (nextpos > pos)
5153 if (!e_write (desc, string, pos, nextpos, coding))
5154 return 0;
5155 pos = nextpos;
5157 /* Output the annotation. */
5158 tem = Fcdr (Fcar (*annot));
5159 if (STRINGP (tem))
5161 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5162 return 0;
5164 *annot = Fcdr (*annot);
5166 return 1;
5169 /* Maximum number of characters that the next
5170 function encodes per one loop iteration. */
5172 enum { E_WRITE_MAX = 8 * 1024 * 1024 };
5174 /* Write text in the range START and END into descriptor DESC,
5175 encoding them with coding system CODING. If STRING is nil, START
5176 and END are character positions of the current buffer, else they
5177 are indexes to the string STRING. Return true if successful. */
5179 static bool
5180 e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
5181 struct coding_system *coding)
5183 if (STRINGP (string))
5185 start = 0;
5186 end = SCHARS (string);
5189 /* We used to have a code for handling selective display here. But,
5190 now it is handled within encode_coding. */
5192 while (start < end)
5194 if (STRINGP (string))
5196 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5197 if (CODING_REQUIRE_ENCODING (coding))
5199 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5201 /* Avoid creating huge Lisp string in encode_coding_object. */
5202 if (nchars == E_WRITE_MAX)
5203 coding->raw_destination = 1;
5205 encode_coding_object
5206 (coding, string, start, string_char_to_byte (string, start),
5207 start + nchars, string_char_to_byte (string, start + nchars),
5208 Qt);
5210 else
5212 coding->dst_object = string;
5213 coding->consumed_char = SCHARS (string);
5214 coding->produced = SBYTES (string);
5217 else
5219 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5220 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
5222 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5223 if (CODING_REQUIRE_ENCODING (coding))
5225 ptrdiff_t nchars = min (end - start, E_WRITE_MAX);
5227 /* Likewise. */
5228 if (nchars == E_WRITE_MAX)
5229 coding->raw_destination = 1;
5231 encode_coding_object
5232 (coding, Fcurrent_buffer (), start, start_byte,
5233 start + nchars, CHAR_TO_BYTE (start + nchars), Qt);
5235 else
5237 coding->dst_object = Qnil;
5238 coding->dst_pos_byte = start_byte;
5239 if (start >= GPT || end <= GPT)
5241 coding->consumed_char = end - start;
5242 coding->produced = end_byte - start_byte;
5244 else
5246 coding->consumed_char = GPT - start;
5247 coding->produced = GPT_BYTE - start_byte;
5252 if (coding->produced > 0)
5254 char *buf = (coding->raw_destination ? (char *) coding->destination
5255 : (STRINGP (coding->dst_object)
5256 ? SSDATA (coding->dst_object)
5257 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte)));
5258 coding->produced -= emacs_write_sig (desc, buf, coding->produced);
5260 if (coding->raw_destination)
5262 /* We're responsible for freeing this, see
5263 encode_coding_object to check why. */
5264 xfree (coding->destination);
5265 coding->raw_destination = 0;
5267 if (coding->produced)
5268 return 0;
5270 start += coding->consumed_char;
5273 return 1;
5276 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5277 Sverify_visited_file_modtime, 0, 1, 0,
5278 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5279 This means that the file has not been changed since it was visited or saved.
5280 If BUF is omitted or nil, it defaults to the current buffer.
5281 See Info node `(elisp)Modification Time' for more details. */)
5282 (Lisp_Object buf)
5284 struct buffer *b;
5285 struct stat st;
5286 Lisp_Object handler;
5287 Lisp_Object filename;
5288 struct timespec mtime;
5290 if (NILP (buf))
5291 b = current_buffer;
5292 else
5294 CHECK_BUFFER (buf);
5295 b = XBUFFER (buf);
5298 if (!STRINGP (BVAR (b, filename))) return Qt;
5299 if (b->modtime.tv_nsec == UNKNOWN_MODTIME_NSECS) return Qt;
5301 /* If the file name has special constructs in it,
5302 call the corresponding file handler. */
5303 handler = Ffind_file_name_handler (BVAR (b, filename),
5304 Qverify_visited_file_modtime);
5305 if (!NILP (handler))
5306 return call2 (handler, Qverify_visited_file_modtime, buf);
5308 filename = ENCODE_FILE (BVAR (b, filename));
5310 mtime = (stat (SSDATA (filename), &st) == 0
5311 ? get_stat_mtime (&st)
5312 : time_error_value (errno));
5313 if (timespec_cmp (mtime, b->modtime) == 0
5314 && (b->modtime_size < 0
5315 || st.st_size == b->modtime_size))
5316 return Qt;
5317 return Qnil;
5320 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5321 Svisited_file_modtime, 0, 0, 0,
5322 doc: /* Return the current buffer's recorded visited file modification time.
5323 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5324 `file-attributes' returns. If the current buffer has no recorded file
5325 modification time, this function returns 0. If the visited file
5326 doesn't exist, return -1.
5327 See Info node `(elisp)Modification Time' for more details. */)
5328 (void)
5330 int ns = current_buffer->modtime.tv_nsec;
5331 if (ns < 0)
5332 return make_number (UNKNOWN_MODTIME_NSECS - ns);
5333 return make_lisp_time (current_buffer->modtime);
5336 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5337 Sset_visited_file_modtime, 0, 1, 0,
5338 doc: /* Update buffer's recorded modification time from the visited file's time.
5339 Useful if the buffer was not read from the file normally
5340 or if the file itself has been changed for some known benign reason.
5341 An argument specifies the modification time value to use
5342 \(instead of that of the visited file), in the form of a list
5343 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5344 `visited-file-modtime'. */)
5345 (Lisp_Object time_flag)
5347 if (!NILP (time_flag))
5349 struct timespec mtime;
5350 if (INTEGERP (time_flag))
5352 CHECK_RANGED_INTEGER (time_flag, -1, 0);
5353 mtime = make_timespec (0, UNKNOWN_MODTIME_NSECS - XINT (time_flag));
5355 else
5356 mtime = lisp_time_argument (time_flag);
5358 current_buffer->modtime = mtime;
5359 current_buffer->modtime_size = -1;
5361 else
5363 register Lisp_Object filename;
5364 struct stat st;
5365 Lisp_Object handler;
5367 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
5369 /* If the file name has special constructs in it,
5370 call the corresponding file handler. */
5371 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5372 if (!NILP (handler))
5373 /* The handler can find the file name the same way we did. */
5374 return call2 (handler, Qset_visited_file_modtime, Qnil);
5376 filename = ENCODE_FILE (filename);
5378 if (stat (SSDATA (filename), &st) >= 0)
5380 current_buffer->modtime = get_stat_mtime (&st);
5381 current_buffer->modtime_size = st.st_size;
5385 return Qnil;
5388 static Lisp_Object
5389 auto_save_error (Lisp_Object error_val)
5391 Lisp_Object args[3], msg;
5392 int i;
5393 struct gcpro gcpro1;
5395 auto_save_error_occurred = 1;
5397 ring_bell (XFRAME (selected_frame));
5399 args[0] = build_string ("Auto-saving %s: %s");
5400 args[1] = BVAR (current_buffer, name);
5401 args[2] = Ferror_message_string (error_val);
5402 msg = Fformat (3, args);
5403 GCPRO1 (msg);
5405 for (i = 0; i < 3; ++i)
5407 if (i == 0)
5408 message3 (msg);
5409 else
5410 message3_nolog (msg);
5411 Fsleep_for (make_number (1), Qnil);
5414 UNGCPRO;
5415 return Qnil;
5418 static Lisp_Object
5419 auto_save_1 (void)
5421 struct stat st;
5422 Lisp_Object modes;
5424 auto_save_mode_bits = 0666;
5426 /* Get visited file's mode to become the auto save file's mode. */
5427 if (! NILP (BVAR (current_buffer, filename)))
5429 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5430 /* But make sure we can overwrite it later! */
5431 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5432 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5433 INTEGERP (modes))
5434 /* Remote files don't cooperate with stat. */
5435 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5438 return
5439 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
5440 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5441 Qnil, Qnil);
5444 struct auto_save_unwind
5446 FILE *stream;
5447 bool auto_raise;
5450 static void
5451 do_auto_save_unwind (void *arg)
5453 struct auto_save_unwind *p = arg;
5454 FILE *stream = p->stream;
5455 minibuffer_auto_raise = p->auto_raise;
5456 auto_saving = 0;
5457 if (stream != NULL)
5459 block_input ();
5460 fclose (stream);
5461 unblock_input ();
5465 static Lisp_Object
5466 do_auto_save_make_dir (Lisp_Object dir)
5468 Lisp_Object result;
5470 auto_saving_dir_umask = 077;
5471 result = call2 (Qmake_directory, dir, Qt);
5472 auto_saving_dir_umask = 0;
5473 return result;
5476 static Lisp_Object
5477 do_auto_save_eh (Lisp_Object ignore)
5479 auto_saving_dir_umask = 0;
5480 return Qnil;
5483 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5484 doc: /* Auto-save all buffers that need it.
5485 This is all buffers that have auto-saving enabled
5486 and are changed since last auto-saved.
5487 Auto-saving writes the buffer into a file
5488 so that your editing is not lost if the system crashes.
5489 This file is not the file you visited; that changes only when you save.
5490 Normally we run the normal hook `auto-save-hook' before saving.
5492 A non-nil NO-MESSAGE argument means do not print any message if successful.
5493 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5494 (Lisp_Object no_message, Lisp_Object current_only)
5496 struct buffer *old = current_buffer, *b;
5497 Lisp_Object tail, buf, hook;
5498 bool auto_saved = 0;
5499 int do_handled_files;
5500 Lisp_Object oquit;
5501 FILE *stream = NULL;
5502 ptrdiff_t count = SPECPDL_INDEX ();
5503 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
5504 bool old_message_p = 0;
5505 struct auto_save_unwind auto_save_unwind;
5506 struct gcpro gcpro1, gcpro2;
5508 if (max_specpdl_size < specpdl_size + 40)
5509 max_specpdl_size = specpdl_size + 40;
5511 if (minibuf_level)
5512 no_message = Qt;
5514 if (NILP (no_message))
5516 old_message_p = push_message ();
5517 record_unwind_protect_void (pop_message_unwind);
5520 /* Ordinarily don't quit within this function,
5521 but don't make it impossible to quit (in case we get hung in I/O). */
5522 oquit = Vquit_flag;
5523 Vquit_flag = Qnil;
5525 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5526 point to non-strings reached from Vbuffer_alist. */
5528 hook = intern ("auto-save-hook");
5529 safe_run_hooks (hook);
5531 if (STRINGP (Vauto_save_list_file_name))
5533 Lisp_Object listfile;
5535 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5537 /* Don't try to create the directory when shutting down Emacs,
5538 because creating the directory might signal an error, and
5539 that would leave Emacs in a strange state. */
5540 if (!NILP (Vrun_hooks))
5542 Lisp_Object dir;
5543 dir = Qnil;
5544 GCPRO2 (dir, listfile);
5545 dir = Ffile_name_directory (listfile);
5546 if (NILP (Ffile_directory_p (dir)))
5547 internal_condition_case_1 (do_auto_save_make_dir,
5548 dir, Qt,
5549 do_auto_save_eh);
5550 UNGCPRO;
5553 stream = emacs_fopen (SSDATA (listfile), "w");
5556 auto_save_unwind.stream = stream;
5557 auto_save_unwind.auto_raise = minibuffer_auto_raise;
5558 record_unwind_protect_ptr (do_auto_save_unwind, &auto_save_unwind);
5559 minibuffer_auto_raise = 0;
5560 auto_saving = 1;
5561 auto_save_error_occurred = 0;
5563 /* On first pass, save all files that don't have handlers.
5564 On second pass, save all files that do have handlers.
5566 If Emacs is crashing, the handlers may tweak what is causing
5567 Emacs to crash in the first place, and it would be a shame if
5568 Emacs failed to autosave perfectly ordinary files because it
5569 couldn't handle some ange-ftp'd file. */
5571 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5572 FOR_EACH_LIVE_BUFFER (tail, buf)
5574 b = XBUFFER (buf);
5576 /* Record all the buffers that have auto save mode
5577 in the special file that lists them. For each of these buffers,
5578 Record visited name (if any) and auto save name. */
5579 if (STRINGP (BVAR (b, auto_save_file_name))
5580 && stream != NULL && do_handled_files == 0)
5582 block_input ();
5583 if (!NILP (BVAR (b, filename)))
5585 fwrite (SDATA (BVAR (b, filename)), 1,
5586 SBYTES (BVAR (b, filename)), stream);
5588 putc ('\n', stream);
5589 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5590 SBYTES (BVAR (b, auto_save_file_name)), stream);
5591 putc ('\n', stream);
5592 unblock_input ();
5595 if (!NILP (current_only)
5596 && b != current_buffer)
5597 continue;
5599 /* Don't auto-save indirect buffers.
5600 The base buffer takes care of it. */
5601 if (b->base_buffer)
5602 continue;
5604 /* Check for auto save enabled
5605 and file changed since last auto save
5606 and file changed since last real save. */
5607 if (STRINGP (BVAR (b, auto_save_file_name))
5608 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5609 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
5610 /* -1 means we've turned off autosaving for a while--see below. */
5611 && XINT (BVAR (b, save_length)) >= 0
5612 && (do_handled_files
5613 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
5614 Qwrite_region))))
5616 struct timespec before_time = current_timespec ();
5617 struct timespec after_time;
5619 /* If we had a failure, don't try again for 20 minutes. */
5620 if (b->auto_save_failure_time > 0
5621 && before_time.tv_sec - b->auto_save_failure_time < 1200)
5622 continue;
5624 set_buffer_internal (b);
5625 if (NILP (Vauto_save_include_big_deletions)
5626 && (XFASTINT (BVAR (b, save_length)) * 10
5627 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5628 /* A short file is likely to change a large fraction;
5629 spare the user annoying messages. */
5630 && XFASTINT (BVAR (b, save_length)) > 5000
5631 /* These messages are frequent and annoying for `*mail*'. */
5632 && !EQ (BVAR (b, filename), Qnil)
5633 && NILP (no_message))
5635 /* It has shrunk too much; turn off auto-saving here. */
5636 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5637 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5638 BVAR (b, name), 1);
5639 minibuffer_auto_raise = 0;
5640 /* Turn off auto-saving until there's a real save,
5641 and prevent any more warnings. */
5642 XSETINT (BVAR (b, save_length), -1);
5643 Fsleep_for (make_number (1), Qnil);
5644 continue;
5646 if (!auto_saved && NILP (no_message))
5647 message1 ("Auto-saving...");
5648 internal_condition_case (auto_save_1, Qt, auto_save_error);
5649 auto_saved = 1;
5650 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
5651 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5652 set_buffer_internal (old);
5654 after_time = current_timespec ();
5656 /* If auto-save took more than 60 seconds,
5657 assume it was an NFS failure that got a timeout. */
5658 if (after_time.tv_sec - before_time.tv_sec > 60)
5659 b->auto_save_failure_time = after_time.tv_sec;
5663 /* Prevent another auto save till enough input events come in. */
5664 record_auto_save ();
5666 if (auto_saved && NILP (no_message))
5668 if (old_message_p)
5670 /* If we are going to restore an old message,
5671 give time to read ours. */
5672 sit_for (make_number (1), 0, 0);
5673 restore_message ();
5675 else if (!auto_save_error_occurred)
5676 /* Don't overwrite the error message if an error occurred.
5677 If we displayed a message and then restored a state
5678 with no message, leave a "done" message on the screen. */
5679 message1 ("Auto-saving...done");
5682 Vquit_flag = oquit;
5684 /* This restores the message-stack status. */
5685 unbind_to (count, Qnil);
5686 return Qnil;
5689 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5690 Sset_buffer_auto_saved, 0, 0, 0,
5691 doc: /* Mark current buffer as auto-saved with its current text.
5692 No auto-save file will be written until the buffer changes again. */)
5693 (void)
5695 /* FIXME: This should not be called in indirect buffers, since
5696 they're not autosaved. */
5697 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
5698 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
5699 current_buffer->auto_save_failure_time = 0;
5700 return Qnil;
5703 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5704 Sclear_buffer_auto_save_failure, 0, 0, 0,
5705 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5706 (void)
5708 current_buffer->auto_save_failure_time = 0;
5709 return Qnil;
5712 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5713 0, 0, 0,
5714 doc: /* Return t if current buffer has been auto-saved recently.
5715 More precisely, if it has been auto-saved since last read from or saved
5716 in the visited file. If the buffer has no visited file,
5717 then any auto-save counts as "recent". */)
5718 (void)
5720 /* FIXME: maybe we should return nil for indirect buffers since
5721 they're never autosaved. */
5722 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
5725 /* Reading and completing file names */
5727 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5728 Snext_read_file_uses_dialog_p, 0, 0, 0,
5729 doc: /* Return t if a call to `read-file-name' will use a dialog.
5730 The return value is only relevant for a call to `read-file-name' that happens
5731 before any other event (mouse or keypress) is handled. */)
5732 (void)
5734 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) \
5735 || defined (HAVE_NS)
5736 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5737 && use_dialog_box
5738 && use_file_dialog
5739 && window_system_available (SELECTED_FRAME ()))
5740 return Qt;
5741 #endif
5742 return Qnil;
5745 Lisp_Object
5746 Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
5748 struct gcpro gcpro1;
5749 Lisp_Object args[7];
5751 GCPRO1 (default_filename);
5752 args[0] = intern ("read-file-name");
5753 args[1] = prompt;
5754 args[2] = dir;
5755 args[3] = default_filename;
5756 args[4] = mustmatch;
5757 args[5] = initial;
5758 args[6] = predicate;
5759 RETURN_UNGCPRO (Ffuncall (7, args));
5763 void
5764 init_fileio (void)
5766 valid_timestamp_file_system = 0;
5769 void
5770 syms_of_fileio (void)
5772 DEFSYM (Qoperations, "operations");
5773 DEFSYM (Qexpand_file_name, "expand-file-name");
5774 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5775 DEFSYM (Qdirectory_file_name, "directory-file-name");
5776 DEFSYM (Qfile_name_directory, "file-name-directory");
5777 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5778 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5779 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5780 DEFSYM (Qcopy_file, "copy-file");
5781 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5782 DEFSYM (Qmake_directory, "make-directory");
5783 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5784 DEFSYM (Qdelete_file, "delete-file");
5785 DEFSYM (Qrename_file, "rename-file");
5786 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5787 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5788 DEFSYM (Qfile_exists_p, "file-exists-p");
5789 DEFSYM (Qfile_executable_p, "file-executable-p");
5790 DEFSYM (Qfile_readable_p, "file-readable-p");
5791 DEFSYM (Qfile_writable_p, "file-writable-p");
5792 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5793 DEFSYM (Qaccess_file, "access-file");
5794 DEFSYM (Qfile_directory_p, "file-directory-p");
5795 DEFSYM (Qfile_regular_p, "file-regular-p");
5796 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5797 DEFSYM (Qfile_modes, "file-modes");
5798 DEFSYM (Qset_file_modes, "set-file-modes");
5799 DEFSYM (Qset_file_times, "set-file-times");
5800 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5801 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
5802 DEFSYM (Qfile_acl, "file-acl");
5803 DEFSYM (Qset_file_acl, "set-file-acl");
5804 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5805 DEFSYM (Qinsert_file_contents, "insert-file-contents");
5806 DEFSYM (Qchoose_write_coding_system, "choose-write-coding-system");
5807 DEFSYM (Qwrite_region, "write-region");
5808 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5809 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5810 DEFSYM (Qauto_save_coding, "auto-save-coding");
5812 DEFSYM (Qfile_name_history, "file-name-history");
5813 Fset (Qfile_name_history, Qnil);
5815 DEFSYM (Qfile_error, "file-error");
5816 DEFSYM (Qfile_already_exists, "file-already-exists");
5817 DEFSYM (Qfile_date_error, "file-date-error");
5818 DEFSYM (Qfile_notify_error, "file-notify-error");
5819 DEFSYM (Qexcl, "excl");
5821 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
5822 doc: /* Coding system for encoding file names.
5823 If it is nil, `default-file-name-coding-system' (which see) is used. */);
5824 Vfile_name_coding_system = Qnil;
5826 DEFVAR_LISP ("default-file-name-coding-system",
5827 Vdefault_file_name_coding_system,
5828 doc: /* Default coding system for encoding file names.
5829 This variable is used only when `file-name-coding-system' is nil.
5831 This variable is set/changed by the command `set-language-environment'.
5832 User should not set this variable manually,
5833 instead use `file-name-coding-system' to get a constant encoding
5834 of file names regardless of the current language environment. */);
5835 Vdefault_file_name_coding_system = Qnil;
5837 DEFSYM (Qformat_decode, "format-decode");
5838 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5839 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5840 DEFSYM (Qcar_less_than_car, "car-less-than-car");
5842 Fput (Qfile_error, Qerror_conditions,
5843 Fpurecopy (list2 (Qfile_error, Qerror)));
5844 Fput (Qfile_error, Qerror_message,
5845 build_pure_c_string ("File error"));
5847 Fput (Qfile_already_exists, Qerror_conditions,
5848 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
5849 Fput (Qfile_already_exists, Qerror_message,
5850 build_pure_c_string ("File already exists"));
5852 Fput (Qfile_date_error, Qerror_conditions,
5853 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
5854 Fput (Qfile_date_error, Qerror_message,
5855 build_pure_c_string ("Cannot set file date"));
5857 Fput (Qfile_notify_error, Qerror_conditions,
5858 Fpurecopy (list3 (Qfile_notify_error, Qfile_error, Qerror)));
5859 Fput (Qfile_notify_error, Qerror_message,
5860 build_pure_c_string ("File notification error"));
5862 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
5863 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5864 If a file name matches REGEXP, all I/O on that file is done by calling
5865 HANDLER. If a file name matches more than one handler, the handler
5866 whose match starts last in the file name gets precedence. The
5867 function `find-file-name-handler' checks this list for a handler for
5868 its argument.
5870 HANDLER should be a function. The first argument given to it is the
5871 name of the I/O primitive to be handled; the remaining arguments are
5872 the arguments that were passed to that primitive. For example, if you
5873 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5874 HANDLER is called like this:
5876 (funcall HANDLER 'file-exists-p FILENAME)
5878 Note that HANDLER must be able to handle all I/O primitives; if it has
5879 nothing special to do for a primitive, it should reinvoke the
5880 primitive to handle the operation \"the usual way\".
5881 See Info node `(elisp)Magic File Names' for more details. */);
5882 Vfile_name_handler_alist = Qnil;
5884 DEFVAR_LISP ("set-auto-coding-function",
5885 Vset_auto_coding_function,
5886 doc: /* If non-nil, a function to call to decide a coding system of file.
5887 Two arguments are passed to this function: the file name
5888 and the length of a file contents following the point.
5889 This function should return a coding system to decode the file contents.
5890 It should check the file name against `auto-coding-alist'.
5891 If no coding system is decided, it should check a coding system
5892 specified in the heading lines with the format:
5893 -*- ... coding: CODING-SYSTEM; ... -*-
5894 or local variable spec of the tailing lines with `coding:' tag. */);
5895 Vset_auto_coding_function = Qnil;
5897 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
5898 doc: /* A list of functions to be called at the end of `insert-file-contents'.
5899 Each is passed one argument, the number of characters inserted,
5900 with point at the start of the inserted text. Each function
5901 should leave point the same, and return the new character count.
5902 If `insert-file-contents' is intercepted by a handler from
5903 `file-name-handler-alist', that handler is responsible for calling the
5904 functions in `after-insert-file-functions' if appropriate. */);
5905 Vafter_insert_file_functions = Qnil;
5907 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
5908 doc: /* A list of functions to be called at the start of `write-region'.
5909 Each is passed two arguments, START and END as for `write-region'.
5910 These are usually two numbers but not always; see the documentation
5911 for `write-region'. The function should return a list of pairs
5912 of the form (POSITION . STRING), consisting of strings to be effectively
5913 inserted at the specified positions of the file being written (1 means to
5914 insert before the first byte written). The POSITIONs must be sorted into
5915 increasing order.
5917 If there are several annotation functions, the lists returned by these
5918 functions are merged destructively. As each annotation function runs,
5919 the variable `write-region-annotations-so-far' contains a list of all
5920 annotations returned by previous annotation functions.
5922 An annotation function can return with a different buffer current.
5923 Doing so removes the annotations returned by previous functions, and
5924 resets START and END to `point-min' and `point-max' of the new buffer.
5926 After `write-region' completes, Emacs calls the function stored in
5927 `write-region-post-annotation-function', once for each buffer that was
5928 current when building the annotations (i.e., at least once), with that
5929 buffer current. */);
5930 Vwrite_region_annotate_functions = Qnil;
5931 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
5933 DEFVAR_LISP ("write-region-post-annotation-function",
5934 Vwrite_region_post_annotation_function,
5935 doc: /* Function to call after `write-region' completes.
5936 The function is called with no arguments. If one or more of the
5937 annotation functions in `write-region-annotate-functions' changed the
5938 current buffer, the function stored in this variable is called for
5939 each of those additional buffers as well, in addition to the original
5940 buffer. The relevant buffer is current during each function call. */);
5941 Vwrite_region_post_annotation_function = Qnil;
5942 staticpro (&Vwrite_region_annotation_buffers);
5944 DEFVAR_LISP ("write-region-annotations-so-far",
5945 Vwrite_region_annotations_so_far,
5946 doc: /* When an annotation function is called, this holds the previous annotations.
5947 These are the annotations made by other annotation functions
5948 that were already called. See also `write-region-annotate-functions'. */);
5949 Vwrite_region_annotations_so_far = Qnil;
5951 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
5952 doc: /* A list of file name handlers that temporarily should not be used.
5953 This applies only to the operation `inhibit-file-name-operation'. */);
5954 Vinhibit_file_name_handlers = Qnil;
5956 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
5957 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5958 Vinhibit_file_name_operation = Qnil;
5960 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
5961 doc: /* File name in which we write a list of all auto save file names.
5962 This variable is initialized automatically from `auto-save-list-file-prefix'
5963 shortly after Emacs reads your init file, if you have not yet given it
5964 a non-nil value. */);
5965 Vauto_save_list_file_name = Qnil;
5967 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
5968 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5969 Normally auto-save files are written under other names. */);
5970 Vauto_save_visited_file_name = Qnil;
5972 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
5973 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
5974 If nil, deleting a substantial portion of the text disables auto-save
5975 in the buffer; this is the default behavior, because the auto-save
5976 file is usually more useful if it contains the deleted text. */);
5977 Vauto_save_include_big_deletions = Qnil;
5979 /* fsync can be a significant performance hit. Often it doesn't
5980 suffice to make the file-save operation survive a crash. For
5981 batch scripts, which are typically part of larger shell commands
5982 that don't fsync other files, its effect on performance can be
5983 significant so its utility is particularly questionable.
5984 Hence, for now by default fsync is used only when interactive.
5986 For more on why fsync often fails to work on today's hardware, see:
5987 Zheng M et al. Understanding the robustness of SSDs under power fault.
5988 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5989 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5991 For more on why fsync does not suffice even if it works properly, see:
5992 Roche X. Necessary step(s) to synchronize filename operations on disk.
5993 Austin Group Defect 672, 2013-03-19
5994 http://austingroupbugs.net/view.php?id=672 */
5995 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
5996 doc: /* Non-nil means don't call fsync in `write-region'.
5997 This variable affects calls to `write-region' as well as save commands.
5998 Setting this to nil may avoid data loss if the system loses power or
5999 the operating system crashes. */);
6000 write_region_inhibit_fsync = noninteractive;
6002 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6003 doc: /* Specifies whether to use the system's trash can.
6004 When non-nil, certain file deletion commands use the function
6005 `move-file-to-trash' instead of deleting files outright.
6006 This includes interactive calls to `delete-file' and
6007 `delete-directory' and the Dired deletion commands. */);
6008 delete_by_moving_to_trash = 0;
6009 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
6011 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6012 DEFSYM (Qcopy_directory, "copy-directory");
6013 DEFSYM (Qdelete_directory, "delete-directory");
6014 DEFSYM (Qsubstitute_env_in_file_name, "substitute-env-in-file-name");
6016 defsubr (&Sfind_file_name_handler);
6017 defsubr (&Sfile_name_directory);
6018 defsubr (&Sfile_name_nondirectory);
6019 defsubr (&Sunhandled_file_name_directory);
6020 defsubr (&Sfile_name_as_directory);
6021 defsubr (&Sdirectory_file_name);
6022 defsubr (&Smake_temp_name);
6023 defsubr (&Sexpand_file_name);
6024 defsubr (&Ssubstitute_in_file_name);
6025 defsubr (&Scopy_file);
6026 defsubr (&Smake_directory_internal);
6027 defsubr (&Sdelete_directory_internal);
6028 defsubr (&Sdelete_file);
6029 defsubr (&Srename_file);
6030 defsubr (&Sadd_name_to_file);
6031 defsubr (&Smake_symbolic_link);
6032 defsubr (&Sfile_name_absolute_p);
6033 defsubr (&Sfile_exists_p);
6034 defsubr (&Sfile_executable_p);
6035 defsubr (&Sfile_readable_p);
6036 defsubr (&Sfile_writable_p);
6037 defsubr (&Saccess_file);
6038 defsubr (&Sfile_symlink_p);
6039 defsubr (&Sfile_directory_p);
6040 defsubr (&Sfile_accessible_directory_p);
6041 defsubr (&Sfile_regular_p);
6042 defsubr (&Sfile_modes);
6043 defsubr (&Sset_file_modes);
6044 defsubr (&Sset_file_times);
6045 defsubr (&Sfile_selinux_context);
6046 defsubr (&Sfile_acl);
6047 defsubr (&Sset_file_acl);
6048 defsubr (&Sset_file_selinux_context);
6049 defsubr (&Sset_default_file_modes);
6050 defsubr (&Sdefault_file_modes);
6051 defsubr (&Sfile_newer_than_file_p);
6052 defsubr (&Sinsert_file_contents);
6053 defsubr (&Schoose_write_coding_system);
6054 defsubr (&Swrite_region);
6055 defsubr (&Scar_less_than_car);
6056 defsubr (&Sverify_visited_file_modtime);
6057 defsubr (&Svisited_file_modtime);
6058 defsubr (&Sset_visited_file_modtime);
6059 defsubr (&Sdo_auto_save);
6060 defsubr (&Sset_buffer_auto_saved);
6061 defsubr (&Sclear_buffer_auto_save_failure);
6062 defsubr (&Srecent_auto_save_p);
6064 defsubr (&Snext_read_file_uses_dialog_p);
6066 #ifdef HAVE_SYNC
6067 defsubr (&Sunix_sync);
6068 #endif