1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 #include <sys/types.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
39 #if USE_ACL && defined HAVE_ACL_SET_FILE
46 #include "composite.h"
47 #include "character.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
55 #ifdef HAVE_LINUX_FS_H
56 # include <sys/ioctl.h>
57 # include <linux/fs.h>
65 #endif /* not WINDOWSNT */
69 #include <sys/param.h>
73 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
74 redirector allows the six letters between 'Z' and 'a' as well. */
76 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
79 #define IS_DRIVE(x) c_isalpha (x)
81 /* Need to lower-case the drive letter, or else expanded
82 filenames will sometimes compare unequal, because
83 `expand-file-name' doesn't always down-case the drive letter. */
84 #define DRIVE_LETTER(x) c_tolower (x)
89 #include <allocator.h>
90 #include <careadlinkat.h>
91 #include <stat-time.h>
93 #include <binary-io.h>
101 /* True during writing of auto-save files. */
102 static bool auto_saving
;
104 /* Emacs's real umask. */
105 static mode_t realmask
;
107 /* Nonzero umask during creation of auto-save directories. */
108 static mode_t auto_saving_dir_umask
;
110 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
111 a new file with the same mode as the original. */
112 static mode_t auto_save_mode_bits
;
114 /* Set by auto_save_1 if an error occurred during the last auto-save. */
115 static bool auto_save_error_occurred
;
117 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
118 number of a file system where time stamps were observed to to work. */
119 static bool valid_timestamp_file_system
;
120 static dev_t timestamp_file_system
;
122 /* Each time an annotation function changes the buffer, the new buffer
124 static Lisp_Object Vwrite_region_annotation_buffers
;
126 static bool a_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
127 Lisp_Object
*, struct coding_system
*);
128 static bool e_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
129 struct coding_system
*);
132 /* Return true if FILENAME exists. */
135 check_existing (const char *filename
)
137 return faccessat (AT_FDCWD
, filename
, F_OK
, AT_EACCESS
) == 0;
140 /* Return true if file FILENAME exists and can be executed. */
143 check_executable (char *filename
)
145 return faccessat (AT_FDCWD
, filename
, X_OK
, AT_EACCESS
) == 0;
148 /* Return true if file FILENAME exists and can be accessed
149 according to AMODE, which should include W_OK.
150 On failure, return false and set errno. */
153 check_writable (const char *filename
, int amode
)
156 /* FIXME: an faccessat implementation should be added to the
157 DOS/Windows ports and this #ifdef branch should be removed. */
159 if (stat (filename
, &st
) < 0)
162 return (st
.st_mode
& S_IWRITE
|| S_ISDIR (st
.st_mode
));
163 #else /* not MSDOS */
164 bool res
= faccessat (AT_FDCWD
, filename
, amode
, AT_EACCESS
) == 0;
166 /* faccessat may have returned failure because Cygwin couldn't
167 determine the file's UID or GID; if so, we return success. */
170 int faccessat_errno
= errno
;
172 if (stat (filename
, &st
) < 0)
174 res
= (st
.st_uid
== -1 || st
.st_gid
== -1);
175 errno
= faccessat_errno
;
179 #endif /* not MSDOS */
182 /* Signal a file-access failure. STRING describes the failure,
183 NAME the file involved, and ERRORNO the errno value.
185 If NAME is neither null nor a pair, package it up as a singleton
186 list before reporting it; this saves report_file_errno's caller the
187 trouble of preserving errno before calling list1. */
190 report_file_errno (char const *string
, Lisp_Object name
, int errorno
)
192 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
193 char *str
= emacs_strerror (errorno
);
194 AUTO_STRING (unibyte_str
, str
);
195 Lisp_Object errstring
196 = code_convert_string_norecord (unibyte_str
, Vlocale_coding_system
, 0);
197 Lisp_Object errdata
= Fcons (errstring
, data
);
199 if (errorno
== EEXIST
)
200 xsignal (Qfile_already_exists
, errdata
);
202 xsignal (Qfile_error
, Fcons (build_string (string
), errdata
));
205 /* Signal a file-access failure that set errno. STRING describes the
206 failure, NAME the file involved. When invoking this function, take
207 care to not use arguments such as build_string ("foo") that involve
208 side effects that may set errno. */
211 report_file_error (char const *string
, Lisp_Object name
)
213 report_file_errno (string
, name
, errno
);
216 /* Like report_file_error, but reports a file-notify-error instead. */
219 report_file_notify_error (const char *string
, Lisp_Object name
)
221 char *str
= emacs_strerror (errno
);
222 AUTO_STRING (unibyte_str
, str
);
223 Lisp_Object errstring
224 = code_convert_string_norecord (unibyte_str
, Vlocale_coding_system
, 0);
225 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
226 Lisp_Object errdata
= Fcons (errstring
, data
);
228 xsignal (Qfile_notify_error
, Fcons (build_string (string
), errdata
));
232 close_file_unwind (int fd
)
238 fclose_unwind (void *arg
)
244 /* Restore point, having saved it as a marker. */
247 restore_point_unwind (Lisp_Object location
)
249 Fgoto_char (location
);
250 unchain_marker (XMARKER (location
));
254 DEFUN ("find-file-name-handler", Ffind_file_name_handler
,
255 Sfind_file_name_handler
, 2, 2, 0,
256 doc
: /* Return FILENAME's handler function for OPERATION, if it has one.
257 Otherwise, return nil.
258 A file name is handled if one of the regular expressions in
259 `file-name-handler-alist' matches it.
261 If OPERATION equals `inhibit-file-name-operation', then we ignore
262 any handlers that are members of `inhibit-file-name-handlers',
263 but we still do run any other handlers. This lets handlers
264 use the standard functions without calling themselves recursively. */)
265 (Lisp_Object filename
, Lisp_Object operation
)
267 /* This function must not munge the match data. */
268 Lisp_Object chain
, inhibited_handlers
, result
;
272 CHECK_STRING (filename
);
274 if (EQ (operation
, Vinhibit_file_name_operation
))
275 inhibited_handlers
= Vinhibit_file_name_handlers
;
277 inhibited_handlers
= Qnil
;
279 for (chain
= Vfile_name_handler_alist
; CONSP (chain
);
280 chain
= XCDR (chain
))
286 Lisp_Object string
= XCAR (elt
);
288 Lisp_Object handler
= XCDR (elt
);
289 Lisp_Object operations
= Qnil
;
291 if (SYMBOLP (handler
))
292 operations
= Fget (handler
, Qoperations
);
295 && (match_pos
= fast_string_match (string
, filename
)) > pos
296 && (NILP (operations
) || ! NILP (Fmemq (operation
, operations
))))
300 handler
= XCDR (elt
);
301 tem
= Fmemq (handler
, inhibited_handlers
);
315 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
317 doc
: /* Return the directory component in file name FILENAME.
318 Return nil if FILENAME does not include a directory.
319 Otherwise return a directory name.
320 Given a Unix syntax file name, returns a string ending in slash. */)
321 (Lisp_Object filename
)
325 CHECK_STRING (filename
);
327 /* If the file name has special constructs in it,
328 call the corresponding file handler. */
329 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
332 Lisp_Object handled_name
= call2 (handler
, Qfile_name_directory
,
334 return STRINGP (handled_name
) ? handled_name
: Qnil
;
337 char *beg
= SSDATA (filename
);
338 char const *p
= beg
+ SBYTES (filename
);
340 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
342 /* only recognize drive specifier at the beginning */
344 /* handle the "/:d:foo" and "/:foo" cases correctly */
345 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
346 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
353 /* Expansion of "c:" to drive and default directory. */
356 SAFE_ALLOCA_STRING (beg
, filename
);
357 p
= beg
+ (p
- SSDATA (filename
));
361 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
362 char *res
= alloca (MAXPATHLEN
+ 1);
365 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
367 memcpy (res
, beg
, 2);
372 if (getdefdir (c_toupper (*beg
) - 'A' + 1, r
))
374 size_t l
= strlen (res
);
376 if (l
> 3 || !IS_DIRECTORY_SEP (res
[l
- 1]))
379 p
= beg
+ strlen (beg
);
380 dostounix_filename (beg
);
381 tem_fn
= make_specified_string (beg
, -1, p
- beg
,
382 STRING_MULTIBYTE (filename
));
385 tem_fn
= make_specified_string (beg
- 2, -1, p
- beg
+ 2,
386 STRING_MULTIBYTE (filename
));
388 else if (STRING_MULTIBYTE (filename
))
390 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 1);
391 dostounix_filename (SSDATA (tem_fn
));
393 if (!NILP (Vw32_downcase_file_names
))
394 tem_fn
= Fdowncase (tem_fn
);
399 dostounix_filename (beg
);
400 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 0);
405 return make_specified_string (beg
, -1, p
- beg
, STRING_MULTIBYTE (filename
));
409 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
410 Sfile_name_nondirectory
, 1, 1, 0,
411 doc
: /* Return file name FILENAME sans its directory.
412 For example, in a Unix-syntax file name,
413 this is everything after the last slash,
414 or the entire name if it contains no slash. */)
415 (Lisp_Object filename
)
417 register const char *beg
, *p
, *end
;
420 CHECK_STRING (filename
);
422 /* If the file name has special constructs in it,
423 call the corresponding file handler. */
424 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
427 Lisp_Object handled_name
= call2 (handler
, Qfile_name_nondirectory
,
429 if (STRINGP (handled_name
))
431 error ("Invalid handler in `file-name-handler-alist'");
434 beg
= SSDATA (filename
);
435 end
= p
= beg
+ SBYTES (filename
);
437 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
439 /* only recognize drive specifier at beginning */
441 /* handle the "/:d:foo" case correctly */
442 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
447 return make_specified_string (p
, -1, end
- p
, STRING_MULTIBYTE (filename
));
450 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
451 Sunhandled_file_name_directory
, 1, 1, 0,
452 doc
: /* Return a directly usable directory name somehow associated with FILENAME.
453 A `directly usable' directory name is one that may be used without the
454 intervention of any file handler.
455 If FILENAME is a directly usable file itself, return
456 \(file-name-as-directory FILENAME).
457 If FILENAME refers to a file which is not accessible from a local process,
458 then this should return nil.
459 The `call-process' and `start-process' functions use this function to
460 get a current directory to run processes in. */)
461 (Lisp_Object filename
)
465 /* If the file name has special constructs in it,
466 call the corresponding file handler. */
467 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
470 Lisp_Object handled_name
= call2 (handler
, Qunhandled_file_name_directory
,
472 return STRINGP (handled_name
) ? handled_name
: Qnil
;
475 return Ffile_name_as_directory (filename
);
478 /* Maximum number of bytes that DST will be longer than SRC
479 in file_name_as_directory. This occurs when SRCLEN == 0. */
480 enum { file_name_as_directory_slop
= 2 };
482 /* Convert from file name SRC of length SRCLEN to directory name in
483 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
484 string. On UNIX, just make sure there is a terminating /. Return
485 the length of DST in bytes. */
488 file_name_as_directory (char *dst
, const char *src
, ptrdiff_t srclen
,
499 memcpy (dst
, src
, srclen
);
500 if (!IS_DIRECTORY_SEP (dst
[srclen
- 1]))
501 dst
[srclen
++] = DIRECTORY_SEP
;
504 dostounix_filename (dst
);
509 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
510 Sfile_name_as_directory
, 1, 1, 0,
511 doc
: /* Return a string representing the file name FILE interpreted as a directory.
512 This operation exists because a directory is also a file, but its name as
513 a directory is different from its name as a file.
514 The result can be used as the value of `default-directory'
515 or passed as second argument to `expand-file-name'.
516 For a Unix-syntax file name, just appends a slash unless a trailing slash
517 is already present. */)
522 Lisp_Object handler
, val
;
527 /* If the file name has special constructs in it,
528 call the corresponding file handler. */
529 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
532 Lisp_Object handled_name
= call2 (handler
, Qfile_name_as_directory
,
534 if (STRINGP (handled_name
))
536 error ("Invalid handler in `file-name-handler-alist'");
540 if (!NILP (Vw32_downcase_file_names
))
541 file
= Fdowncase (file
);
543 buf
= SAFE_ALLOCA (SBYTES (file
) + file_name_as_directory_slop
+ 1);
544 length
= file_name_as_directory (buf
, SSDATA (file
), SBYTES (file
),
545 STRING_MULTIBYTE (file
));
546 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (file
));
551 /* Convert from directory name SRC of length SRCLEN to file name in
552 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
553 string. On UNIX, just make sure there isn't a terminating /.
554 Return the length of DST in bytes. */
557 directory_file_name (char *dst
, char *src
, ptrdiff_t srclen
, bool multibyte
)
559 /* Process as Unix format: just remove any final slash.
560 But leave "/" and "//" unchanged. */
563 && !IS_ANY_SEP (src
[srclen
- 2])
565 && IS_DIRECTORY_SEP (src
[srclen
- 1])
566 && ! (srclen
== 2 && IS_DIRECTORY_SEP (src
[0])))
569 memcpy (dst
, src
, srclen
);
572 dostounix_filename (dst
);
577 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
579 doc
: /* Returns the file name of the directory named DIRECTORY.
580 This is the name of the file that holds the data for the directory DIRECTORY.
581 This operation exists because a directory is also a file, but its name as
582 a directory is different from its name as a file.
583 In Unix-syntax, this function just removes the final slash. */)
584 (Lisp_Object directory
)
588 Lisp_Object handler
, val
;
591 CHECK_STRING (directory
);
593 /* If the file name has special constructs in it,
594 call the corresponding file handler. */
595 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
598 Lisp_Object handled_name
= call2 (handler
, Qdirectory_file_name
,
600 if (STRINGP (handled_name
))
602 error ("Invalid handler in `file-name-handler-alist'");
606 if (!NILP (Vw32_downcase_file_names
))
607 directory
= Fdowncase (directory
);
609 buf
= SAFE_ALLOCA (SBYTES (directory
) + 1);
610 length
= directory_file_name (buf
, SSDATA (directory
), SBYTES (directory
),
611 STRING_MULTIBYTE (directory
));
612 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (directory
));
617 static const char make_temp_name_tbl
[64] =
619 'A','B','C','D','E','F','G','H',
620 'I','J','K','L','M','N','O','P',
621 'Q','R','S','T','U','V','W','X',
622 'Y','Z','a','b','c','d','e','f',
623 'g','h','i','j','k','l','m','n',
624 'o','p','q','r','s','t','u','v',
625 'w','x','y','z','0','1','2','3',
626 '4','5','6','7','8','9','-','_'
629 static unsigned make_temp_name_count
, make_temp_name_count_initialized_p
;
631 /* Value is a temporary file name starting with PREFIX, a string.
633 The Emacs process number forms part of the result, so there is
634 no danger of generating a name being used by another process.
635 In addition, this function makes an attempt to choose a name
636 which has no existing file. To make this work, PREFIX should be
637 an absolute file name.
639 BASE64_P means add the pid as 3 characters in base64
640 encoding. In this case, 6 characters will be added to PREFIX to
641 form the file name. Otherwise, if Emacs is running on a system
642 with long file names, add the pid as a decimal number.
644 This function signals an error if no unique file name could be
648 make_temp_name (Lisp_Object prefix
, bool base64_p
)
650 Lisp_Object val
, encoded_prefix
;
654 char pidbuf
[INT_BUFSIZE_BOUND (printmax_t
)];
657 CHECK_STRING (prefix
);
659 /* VAL is created by adding 6 characters to PREFIX. The first
660 three are the PID of this process, in base 64, and the second
661 three are incremented if the file already exists. This ensures
662 262144 unique file names per PID per PREFIX. */
668 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
669 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
670 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
675 #ifdef HAVE_LONG_FILE_NAMES
676 pidlen
= sprintf (pidbuf
, "%"pMd
, pid
);
678 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
679 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
680 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
685 encoded_prefix
= ENCODE_FILE (prefix
);
686 len
= SBYTES (encoded_prefix
);
687 val
= make_uninit_string (len
+ 3 + pidlen
);
689 memcpy (data
, SSDATA (encoded_prefix
), len
);
692 memcpy (p
, pidbuf
, pidlen
);
695 /* Here we try to minimize useless stat'ing when this function is
696 invoked many times successively with the same PREFIX. We achieve
697 this by initializing count to a random value, and incrementing it
700 We don't want make-temp-name to be called while dumping,
701 because then make_temp_name_count_initialized_p would get set
702 and then make_temp_name_count would not be set when Emacs starts. */
704 if (!make_temp_name_count_initialized_p
)
706 make_temp_name_count
= time (NULL
);
707 make_temp_name_count_initialized_p
= 1;
712 unsigned num
= make_temp_name_count
;
714 p
[0] = make_temp_name_tbl
[num
& 63], num
>>= 6;
715 p
[1] = make_temp_name_tbl
[num
& 63], num
>>= 6;
716 p
[2] = make_temp_name_tbl
[num
& 63], num
>>= 6;
718 /* Poor man's congruential RN generator. Replace with
719 ++make_temp_name_count for debugging. */
720 make_temp_name_count
+= 25229;
721 make_temp_name_count
%= 225307;
723 if (!check_existing (data
))
725 /* We want to return only if errno is ENOENT. */
727 return DECODE_FILE (val
);
729 /* The error here is dubious, but there is little else we
730 can do. The alternatives are to return nil, which is
731 as bad as (and in many cases worse than) throwing the
732 error, or to ignore the error, which will likely result
733 in looping through 225307 stat's, which is not only
734 dog-slow, but also useless since eventually nil would
735 have to be returned anyway. */
736 report_file_error ("Cannot create temporary name for prefix",
744 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
745 doc
: /* Generate temporary file name (string) starting with PREFIX (a string).
746 The Emacs process number forms part of the result, so there is no
747 danger of generating a name being used by another Emacs process
748 \(so long as only a single host can access the containing directory...).
750 This function tries to choose a name that has no existing file.
751 For this to work, PREFIX should be an absolute file name.
753 There is a race condition between calling `make-temp-name' and creating the
754 file, which opens all kinds of security holes. For that reason, you should
755 normally use `make-temp-file' instead. */)
758 return make_temp_name (prefix
, 0);
761 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
762 doc
: /* Convert filename NAME to absolute, and canonicalize it.
763 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
764 \(does not start with slash or tilde); both the directory name and
765 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
766 missing, the current buffer's value of `default-directory' is used.
767 NAME should be a string that is a valid file name for the underlying
769 File name components that are `.' are removed, and
770 so are file name components followed by `..', along with the `..' itself;
771 note that these simplifications are done without checking the resulting
772 file names in the file system.
773 Multiple consecutive slashes are collapsed into a single slash,
774 except at the beginning of the file name when they are significant (e.g.,
775 UNC file names on MS-Windows.)
776 An initial `~/' expands to your home directory.
777 An initial `~USER/' expands to USER's home directory.
778 See also the function `substitute-in-file-name'.
780 For technical reasons, this function can return correct but
781 non-intuitive results for the root directory; for instance,
782 \(expand-file-name ".." "/") returns "/..". For this reason, use
783 \(directory-file-name (file-name-directory dirname)) to traverse a
784 filesystem tree, not (expand-file-name ".." dirname). */)
785 (Lisp_Object name
, Lisp_Object default_directory
)
787 /* These point to SDATA and need to be careful with string-relocation
788 during GC (via DECODE_FILE). */
792 const char *newdirlim
;
793 /* This should only point to alloca'd data. */
800 bool collapse_newdir
= true;
803 ptrdiff_t length
, nbytes
;
804 Lisp_Object handler
, result
, handled_name
;
811 /* If the file name has special constructs in it,
812 call the corresponding file handler. */
813 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
816 handled_name
= call3 (handler
, Qexpand_file_name
,
817 name
, default_directory
);
818 if (STRINGP (handled_name
))
820 error ("Invalid handler in `file-name-handler-alist'");
824 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
825 if (NILP (default_directory
))
826 default_directory
= BVAR (current_buffer
, directory
);
827 if (! STRINGP (default_directory
))
830 /* "/" is not considered a root directory on DOS_NT, so using "/"
831 here causes an infinite recursion in, e.g., the following:
833 (let (default-directory)
834 (expand-file-name "a"))
836 To avoid this, we set default_directory to the root of the
838 default_directory
= build_string (emacs_root_dir ());
840 default_directory
= build_string ("/");
844 if (!NILP (default_directory
))
846 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
849 handled_name
= call3 (handler
, Qexpand_file_name
,
850 name
, default_directory
);
851 if (STRINGP (handled_name
))
853 error ("Invalid handler in `file-name-handler-alist'");
858 char *o
= SSDATA (default_directory
);
860 /* Make sure DEFAULT_DIRECTORY is properly expanded.
861 It would be better to do this down below where we actually use
862 default_directory. Unfortunately, calling Fexpand_file_name recursively
863 could invoke GC, and the strings might be relocated. This would
864 be annoying because we have pointers into strings lying around
865 that would need adjusting, and people would add new pointers to
866 the code and forget to adjust them, resulting in intermittent bugs.
867 Putting this call here avoids all that crud.
869 The EQ test avoids infinite recursion. */
870 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
871 /* Save time in some common cases - as long as default_directory
872 is not relative, it can be canonicalized with name below (if it
873 is needed at all) without requiring it to be expanded now. */
875 /* Detect MSDOS file names with drive specifiers. */
876 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1])
877 && IS_DIRECTORY_SEP (o
[2]))
879 /* Detect Windows file names in UNC format. */
880 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
882 #else /* not DOS_NT */
883 /* Detect Unix absolute file names (/... alone is not absolute on
885 && ! (IS_DIRECTORY_SEP (o
[0]))
886 #endif /* not DOS_NT */
889 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
892 multibyte
= STRING_MULTIBYTE (name
);
893 if (multibyte
!= STRING_MULTIBYTE (default_directory
))
897 unsigned char *p
= SDATA (name
);
899 while (*p
&& ASCII_CHAR_P (*p
))
903 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
904 unibyte. Do not convert DEFAULT_DIRECTORY to
905 multibyte; instead, convert NAME to a unibyte string,
906 so that the result of this function is also a unibyte
907 string. This is needed during bootstrapping and
908 dumping, when Emacs cannot decode file names, because
909 the locale environment is not set up. */
910 name
= make_unibyte_string (SSDATA (name
), SBYTES (name
));
914 default_directory
= string_to_multibyte (default_directory
);
918 name
= string_to_multibyte (name
);
924 if (!NILP (Vw32_downcase_file_names
))
925 default_directory
= Fdowncase (default_directory
);
928 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
929 SAFE_ALLOCA_STRING (nm
, name
);
930 nmlim
= nm
+ SBYTES (name
);
933 /* Note if special escape prefix is present, but remove for now. */
934 if (nm
[0] == '/' && nm
[1] == ':')
940 /* Find and remove drive specifier if present; this makes nm absolute
941 even if the rest of the name appears to be relative. Only look for
942 drive specifier at the beginning. */
943 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
945 drive
= (unsigned char) nm
[0];
950 /* If we see "c://somedir", we want to strip the first slash after the
951 colon when stripping the drive letter. Otherwise, this expands to
953 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
956 /* Discard any previous drive specifier if nm is now in UNC format. */
957 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
958 && !IS_DIRECTORY_SEP (nm
[2]))
960 #endif /* WINDOWSNT */
963 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
964 none are found, we can probably return right away. We will avoid
965 allocating a new string if name is already fully expanded. */
967 IS_DIRECTORY_SEP (nm
[0])
969 && drive
&& !is_escaped
972 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
976 /* If it turns out that the filename we want to return is just a
977 suffix of FILENAME, we don't need to go through and edit
978 things; we just need to construct a new string using data
979 starting at the middle of FILENAME. If we set LOSE, that
980 means we've discovered that we can't do that cool trick. */
986 /* Since we know the name is absolute, we can assume that each
987 element starts with a "/". */
989 /* "." and ".." are hairy. */
990 if (IS_DIRECTORY_SEP (p
[0])
992 && (IS_DIRECTORY_SEP (p
[2])
994 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
997 /* Replace multiple slashes with a single one, except
998 leave leading "//" alone. */
999 else if (IS_DIRECTORY_SEP (p
[0])
1000 && IS_DIRECTORY_SEP (p
[1])
1001 && (p
!= nm
|| IS_DIRECTORY_SEP (p
[2])))
1008 /* Make sure directories are all separated with /, but
1009 avoid allocation of a new string when not required. */
1010 dostounix_filename (nm
);
1012 if (IS_DIRECTORY_SEP (nm
[1]))
1014 if (strcmp (nm
, SSDATA (name
)) != 0)
1015 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1019 /* Drive must be set, so this is okay. */
1020 if (strcmp (nm
- 2, SSDATA (name
)) != 0)
1022 name
= make_specified_string (nm
, -1, p
- nm
, multibyte
);
1023 char temp
[] = { DRIVE_LETTER (drive
), ':', 0 };
1024 AUTO_STRING_WITH_LEN (drive_prefix
, temp
, 2);
1025 name
= concat2 (drive_prefix
, name
);
1028 if (!NILP (Vw32_downcase_file_names
))
1029 name
= Fdowncase (name
);
1031 #else /* not DOS_NT */
1032 if (strcmp (nm
, SSDATA (name
)) != 0)
1033 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1034 #endif /* not DOS_NT */
1040 /* At this point, nm might or might not be an absolute file name. We
1041 need to expand ~ or ~user if present, otherwise prefix nm with
1042 default_directory if nm is not absolute, and finally collapse /./
1043 and /foo/../ sequences.
1045 We set newdir to be the appropriate prefix if one is needed:
1046 - the relevant user directory if nm starts with ~ or ~user
1047 - the specified drive's working dir (DOS/NT only) if nm does not
1049 - the value of default_directory.
1051 Note that these prefixes are not guaranteed to be absolute (except
1052 for the working dir of a drive). Therefore, to ensure we always
1053 return an absolute name, if the final prefix is not absolute we
1054 append it to the current working directory. */
1056 newdir
= newdirlim
= 0;
1058 if (nm
[0] == '~') /* prefix ~ */
1060 if (IS_DIRECTORY_SEP (nm
[1])
1061 || nm
[1] == 0) /* ~ by itself */
1065 if (!(newdir
= egetenv ("HOME")))
1066 newdir
= newdirlim
= "";
1068 /* `egetenv' may return a unibyte string, which will bite us since
1069 we expect the directory to be multibyte. */
1073 char newdir_utf8
[MAX_UTF8_PATH
];
1075 filename_from_ansi (newdir
, newdir_utf8
);
1076 tem
= make_unibyte_string (newdir_utf8
, strlen (newdir_utf8
));
1080 tem
= build_string (newdir
);
1081 newdirlim
= newdir
+ SBYTES (tem
);
1082 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1084 hdir
= DECODE_FILE (tem
);
1085 newdir
= SSDATA (hdir
);
1086 newdirlim
= newdir
+ SBYTES (hdir
);
1089 collapse_newdir
= false;
1092 else /* ~user/filename */
1095 for (p
= nm
; *p
&& !IS_DIRECTORY_SEP (*p
); p
++)
1097 o
= SAFE_ALLOCA (p
- nm
+ 1);
1098 memcpy (o
, nm
, p
- nm
);
1102 pw
= getpwnam (o
+ 1);
1108 newdir
= pw
->pw_dir
;
1109 /* `getpwnam' may return a unibyte string, which will
1110 bite us since we expect the directory to be
1112 tem
= make_unibyte_string (newdir
, strlen (newdir
));
1113 newdirlim
= newdir
+ SBYTES (tem
);
1114 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1116 hdir
= DECODE_FILE (tem
);
1117 newdir
= SSDATA (hdir
);
1118 newdirlim
= newdir
+ SBYTES (hdir
);
1122 collapse_newdir
= false;
1126 /* If we don't find a user of that name, leave the name
1127 unchanged; don't move nm forward to p. */
1132 /* On DOS and Windows, nm is absolute if a drive name was specified;
1133 use the drive's current directory as the prefix if needed. */
1134 if (!newdir
&& drive
)
1136 /* Get default directory if needed to make nm absolute. */
1138 if (!IS_DIRECTORY_SEP (nm
[0]))
1140 adir
= alloca (MAXPATHLEN
+ 1);
1141 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1145 Lisp_Object tem
= build_string (adir
);
1147 tem
= DECODE_FILE (tem
);
1148 newdirlim
= adir
+ SBYTES (tem
);
1149 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1152 newdirlim
= adir
+ strlen (adir
);
1156 /* Either nm starts with /, or drive isn't mounted. */
1158 adir
[0] = DRIVE_LETTER (drive
);
1162 newdirlim
= adir
+ 3;
1168 /* Finally, if no prefix has been specified and nm is not absolute,
1169 then it must be expanded relative to default_directory. */
1173 /* /... alone is not absolute on DOS and Windows. */
1174 && !IS_DIRECTORY_SEP (nm
[0])
1177 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
1178 && !IS_DIRECTORY_SEP (nm
[2]))
1182 newdir
= SSDATA (default_directory
);
1183 newdirlim
= newdir
+ SBYTES (default_directory
);
1185 /* Note if special escape prefix is present, but remove for now. */
1186 if (newdir
[0] == '/' && newdir
[1] == ':')
1197 /* First ensure newdir is an absolute name. */
1199 /* Detect MSDOS file names with drive specifiers. */
1200 ! (IS_DRIVE (newdir
[0])
1201 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1203 /* Detect Windows file names in UNC format. */
1204 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1205 && !IS_DIRECTORY_SEP (newdir
[2]))
1209 /* Effectively, let newdir be (expand-file-name newdir cwd).
1210 Because of the admonition against calling expand-file-name
1211 when we have pointers into lisp strings, we accomplish this
1212 indirectly by prepending newdir to nm if necessary, and using
1213 cwd (or the wd of newdir's drive) as the new newdir. */
1216 const int adir_size
= MAX_UTF8_PATH
;
1218 const int adir_size
= MAXPATHLEN
+ 1;
1221 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1223 drive
= (unsigned char) newdir
[0];
1226 if (!IS_DIRECTORY_SEP (nm
[0]))
1228 ptrdiff_t nmlen
= nmlim
- nm
;
1229 ptrdiff_t newdirlen
= newdirlim
- newdir
;
1230 char *tmp
= alloca (newdirlen
+ file_name_as_directory_slop
1232 ptrdiff_t dlen
= file_name_as_directory (tmp
, newdir
, newdirlen
,
1234 memcpy (tmp
+ dlen
, nm
, nmlen
+ 1);
1236 nmlim
= nm
+ dlen
+ nmlen
;
1238 adir
= alloca (adir_size
);
1241 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1245 getcwd (adir
, adir_size
);
1248 Lisp_Object tem
= build_string (adir
);
1250 tem
= DECODE_FILE (tem
);
1251 newdirlim
= adir
+ SBYTES (tem
);
1252 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1255 newdirlim
= adir
+ strlen (adir
);
1259 /* Strip off drive name from prefix, if present. */
1260 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1266 /* Keep only a prefix from newdir if nm starts with slash
1267 (//server/share for UNC, nothing otherwise). */
1268 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1271 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1272 && !IS_DIRECTORY_SEP (newdir
[2]))
1274 char *adir
= strcpy (alloca (newdirlim
- newdir
+ 1), newdir
);
1276 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1278 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1281 newdirlim
= newdir
+ strlen (adir
);
1285 newdir
= newdirlim
= "";
1290 /* Ignore any slash at the end of newdir, unless newdir is
1291 just "/" or "//". */
1292 length
= newdirlim
- newdir
;
1293 while (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1294 && ! (length
== 2 && IS_DIRECTORY_SEP (newdir
[0])))
1297 /* Now concatenate the directory and name to new space in the stack frame. */
1298 tlen
= length
+ file_name_as_directory_slop
+ (nmlim
- nm
) + 1;
1299 eassert (tlen
> file_name_as_directory_slop
+ 1);
1301 /* Reserve space for drive specifier and escape prefix, since either
1302 or both may need to be inserted. (The Microsoft x86 compiler
1303 produces incorrect code if the following two lines are combined.) */
1304 target
= alloca (tlen
+ 4);
1306 #else /* not DOS_NT */
1307 target
= SAFE_ALLOCA (tlen
);
1308 #endif /* not DOS_NT */
1314 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1317 /* If newdir is effectively "C:/", then the drive letter will have
1318 been stripped and newdir will be "/". Concatenating with an
1319 absolute directory in nm produces "//", which will then be
1320 incorrectly treated as a network share. Ignore newdir in
1321 this case (keeping the drive letter). */
1322 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1323 && newdir
[1] == '\0'))
1326 memcpy (target
, newdir
, length
);
1332 nbytes
= file_name_as_directory (target
, newdir
, length
, multibyte
);
1335 memcpy (target
+ nbytes
, nm
, nmlim
- nm
+ 1);
1337 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1345 if (!IS_DIRECTORY_SEP (*p
))
1349 else if (p
[1] == '.'
1350 && (IS_DIRECTORY_SEP (p
[2])
1353 /* If "/." is the entire filename, keep the "/". Otherwise,
1354 just delete the whole "/.". */
1355 if (o
== target
&& p
[2] == '\0')
1359 else if (p
[1] == '.' && p
[2] == '.'
1360 /* `/../' is the "superroot" on certain file systems.
1361 Turned off on DOS_NT systems because they have no
1362 "superroot" and because this causes us to produce
1363 file names like "d:/../foo" which fail file-related
1364 functions of the underlying OS. (To reproduce, try a
1365 long series of "../../" in default_directory, longer
1366 than the number of levels from the root.) */
1370 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1375 while (o
!= target
&& (--o
, !IS_DIRECTORY_SEP (*o
)))
1378 /* Don't go below server level in UNC filenames. */
1379 if (o
== target
+ 1 && IS_DIRECTORY_SEP (*o
)
1380 && IS_DIRECTORY_SEP (*target
))
1384 /* Keep initial / only if this is the whole name. */
1385 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1389 else if (IS_DIRECTORY_SEP (p
[1])
1390 && (p
!= target
|| IS_DIRECTORY_SEP (p
[2])))
1391 /* Collapse multiple "/", except leave leading "//" alone. */
1400 /* At last, set drive name. */
1402 /* Except for network file name. */
1403 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1404 #endif /* WINDOWSNT */
1406 if (!drive
) emacs_abort ();
1408 target
[0] = DRIVE_LETTER (drive
);
1411 /* Reinsert the escape prefix if required. */
1418 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1419 dostounix_filename (SSDATA (result
));
1421 if (!NILP (Vw32_downcase_file_names
))
1422 result
= Fdowncase (result
);
1425 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1426 #endif /* !DOS_NT */
1429 /* Again look to see if the file name has special constructs in it
1430 and perhaps call the corresponding file handler. This is needed
1431 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1432 the ".." component gives us "/user@host:/bar/../baz" which needs
1433 to be expanded again. */
1434 handler
= Ffind_file_name_handler (result
, Qexpand_file_name
);
1435 if (!NILP (handler
))
1437 handled_name
= call3 (handler
, Qexpand_file_name
,
1438 result
, default_directory
);
1439 if (! STRINGP (handled_name
))
1440 error ("Invalid handler in `file-name-handler-alist'");
1441 result
= handled_name
;
1449 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1450 This is the old version of expand-file-name, before it was thoroughly
1451 rewritten for Emacs 10.31. We leave this version here commented-out,
1452 because the code is very complex and likely to have subtle bugs. If
1453 bugs _are_ found, it might be of interest to look at the old code and
1454 see what did it do in the relevant situation.
1456 Don't remove this code: it's true that it will be accessible
1457 from the repository, but a few years from deletion, people will
1458 forget it is there. */
1460 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1461 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1462 "Convert FILENAME to absolute, and canonicalize it.\n\
1463 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1464 \(does not start with slash); if DEFAULT is nil or missing,\n\
1465 the current buffer's value of default-directory is used.\n\
1466 Filenames containing `.' or `..' as components are simplified;\n\
1467 initial `~/' expands to your home directory.\n\
1468 See also the function `substitute-in-file-name'.")
1470 Lisp_Object name
, defalt
;
1474 register unsigned char *newdir
, *p
, *o
;
1476 unsigned char *target
;
1479 CHECK_STRING (name
);
1482 /* If nm is absolute, flush ...// and detect /./ and /../.
1483 If no /./ or /../ we can return right away. */
1490 if (p
[0] == '/' && p
[1] == '/')
1492 if (p
[0] == '/' && p
[1] == '~')
1493 nm
= p
+ 1, lose
= 1;
1494 if (p
[0] == '/' && p
[1] == '.'
1495 && (p
[2] == '/' || p
[2] == 0
1496 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1502 if (nm
== SDATA (name
))
1504 return build_string (nm
);
1508 /* Now determine directory to start with and put it in NEWDIR. */
1512 if (nm
[0] == '~') /* prefix ~ */
1513 if (nm
[1] == '/' || nm
[1] == 0)/* ~/filename */
1515 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1516 newdir
= (unsigned char *) "";
1519 else /* ~user/filename */
1521 /* Get past ~ to user. */
1522 unsigned char *user
= nm
+ 1;
1523 /* Find end of name. */
1524 unsigned char *ptr
= (unsigned char *) strchr (user
, '/');
1525 ptrdiff_t len
= ptr
? ptr
- user
: strlen (user
);
1526 /* Copy the user name into temp storage. */
1527 o
= alloca (len
+ 1);
1528 memcpy (o
, user
, len
);
1531 /* Look up the user name. */
1533 pw
= (struct passwd
*) getpwnam (o
+ 1);
1536 error ("\"%s\" isn't a registered user", o
+ 1);
1538 newdir
= (unsigned char *) pw
->pw_dir
;
1540 /* Discard the user name from NM. */
1544 if (nm
[0] != '/' && !newdir
)
1547 defalt
= current_buffer
->directory
;
1548 CHECK_STRING (defalt
);
1549 newdir
= SDATA (defalt
);
1552 /* Now concatenate the directory and name to new space in the stack frame. */
1554 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1555 target
= alloca (tlen
);
1560 if (nm
[0] == 0 || nm
[0] == '/')
1561 strcpy (target
, newdir
);
1563 file_name_as_directory (target
, newdir
);
1566 strcat (target
, nm
);
1568 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1579 else if (!strncmp (p
, "//", 2)
1585 else if (p
[0] == '/' && p
[1] == '.'
1586 && (p
[2] == '/' || p
[2] == 0))
1588 else if (!strncmp (p
, "/..", 3)
1589 /* `/../' is the "superroot" on certain file systems. */
1591 && (p
[3] == '/' || p
[3] == 0))
1593 while (o
!= target
&& *--o
!= '/')
1595 if (o
== target
&& *o
== '/')
1605 return make_string (target
, o
- target
);
1609 /* If /~ or // appears, discard everything through first slash. */
1611 file_name_absolute_p (const char *filename
)
1614 (IS_DIRECTORY_SEP (*filename
) || *filename
== '~'
1616 || (IS_DRIVE (*filename
) && IS_DEVICE_SEP (filename
[1])
1617 && IS_DIRECTORY_SEP (filename
[2]))
1623 search_embedded_absfilename (char *nm
, char *endp
)
1627 for (p
= nm
+ 1; p
< endp
; p
++)
1629 if (IS_DIRECTORY_SEP (p
[-1])
1630 && file_name_absolute_p (p
)
1631 #if defined (WINDOWSNT) || defined (CYGWIN)
1632 /* // at start of file name is meaningful in Apollo,
1633 WindowsNT and Cygwin systems. */
1634 && !(IS_DIRECTORY_SEP (p
[0]) && p
- 1 == nm
)
1635 #endif /* not (WINDOWSNT || CYGWIN) */
1638 for (s
= p
; *s
&& !IS_DIRECTORY_SEP (*s
); s
++);
1639 if (p
[0] == '~' && s
> p
+ 1) /* We've got "/~something/". */
1642 char *o
= SAFE_ALLOCA (s
- p
+ 1);
1644 memcpy (o
, p
, s
- p
);
1647 /* If we have ~user and `user' exists, discard
1648 everything up to ~. But if `user' does not exist, leave
1649 ~user alone, it might be a literal file name. */
1651 pw
= getpwnam (o
+ 1);
1664 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
1665 Ssubstitute_in_file_name
, 1, 1, 0,
1666 doc
: /* Substitute environment variables referred to in FILENAME.
1667 `$FOO' where FOO is an environment variable name means to substitute
1668 the value of that variable. The variable name should be terminated
1669 with a character not a letter, digit or underscore; otherwise, enclose
1670 the entire variable name in braces.
1672 If `/~' appears, all of FILENAME through that `/' is discarded.
1673 If `//' appears, everything up to and including the first of
1674 those `/' is discarded. */)
1675 (Lisp_Object filename
)
1677 char *nm
, *p
, *x
, *endp
;
1678 bool substituted
= false;
1681 Lisp_Object handler
;
1683 CHECK_STRING (filename
);
1685 multibyte
= STRING_MULTIBYTE (filename
);
1687 /* If the file name has special constructs in it,
1688 call the corresponding file handler. */
1689 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
1690 if (!NILP (handler
))
1692 Lisp_Object handled_name
= call2 (handler
, Qsubstitute_in_file_name
,
1694 if (STRINGP (handled_name
))
1695 return handled_name
;
1696 error ("Invalid handler in `file-name-handler-alist'");
1699 /* Always work on a copy of the string, in case GC happens during
1700 decode of environment variables, causing the original Lisp_String
1701 data to be relocated. */
1703 SAFE_ALLOCA_STRING (nm
, filename
);
1706 dostounix_filename (nm
);
1707 substituted
= (memcmp (nm
, SDATA (filename
), SBYTES (filename
)) != 0);
1709 endp
= nm
+ SBYTES (filename
);
1711 /* If /~ or // appears, discard everything through first slash. */
1712 p
= search_embedded_absfilename (nm
, endp
);
1714 /* Start over with the new string, so we check the file-name-handler
1715 again. Important with filenames like "/home/foo//:/hello///there"
1716 which would substitute to "/:/hello///there" rather than "/there". */
1719 = (Fsubstitute_in_file_name
1720 (make_specified_string (p
, -1, endp
- p
, multibyte
)));
1725 /* See if any variables are substituted into the string. */
1727 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name
)))
1730 = (!substituted
? filename
1731 : make_specified_string (nm
, -1, endp
- nm
, multibyte
));
1732 Lisp_Object tmp
= call1 (Qsubstitute_env_in_file_name
, name
);
1734 if (!EQ (tmp
, name
))
1742 if (!NILP (Vw32_downcase_file_names
))
1743 filename
= Fdowncase (filename
);
1749 xnm
= SSDATA (filename
);
1750 x
= xnm
+ SBYTES (filename
);
1752 /* If /~ or // appears, discard everything through first slash. */
1753 while ((p
= search_embedded_absfilename (xnm
, x
)) != NULL
)
1754 /* This time we do not start over because we've already expanded envvars
1755 and replaced $$ with $. Maybe we should start over as well, but we'd
1756 need to quote some $ to $$ first. */
1760 if (!NILP (Vw32_downcase_file_names
))
1762 Lisp_Object xname
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1764 filename
= Fdowncase (xname
);
1768 if (xnm
!= SSDATA (filename
))
1769 filename
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1774 /* A slightly faster and more convenient way to get
1775 (directory-file-name (expand-file-name FOO)). */
1778 expand_and_dir_to_file (Lisp_Object filename
, Lisp_Object defdir
)
1780 register Lisp_Object absname
;
1782 absname
= Fexpand_file_name (filename
, defdir
);
1784 /* Remove final slash, if any (unless this is the root dir).
1785 stat behaves differently depending! */
1786 if (SCHARS (absname
) > 1
1787 && IS_DIRECTORY_SEP (SREF (absname
, SBYTES (absname
) - 1))
1788 && !IS_DEVICE_SEP (SREF (absname
, SBYTES (absname
) - 2)))
1789 /* We cannot take shortcuts; they might be wrong for magic file names. */
1790 absname
= Fdirectory_file_name (absname
);
1794 /* Signal an error if the file ABSNAME already exists.
1795 If KNOWN_TO_EXIST, the file is known to exist.
1796 QUERYSTRING is a name for the action that is being considered
1798 If INTERACTIVE, ask the user whether to proceed,
1799 and bypass the error if the user says to go ahead.
1800 If QUICK, ask for y or n, not yes or no. */
1803 barf_or_query_if_file_exists (Lisp_Object absname
, bool known_to_exist
,
1804 const char *querystring
, bool interactive
,
1807 Lisp_Object tem
, encoded_filename
;
1808 struct stat statbuf
;
1810 encoded_filename
= ENCODE_FILE (absname
);
1812 if (! known_to_exist
&& lstat (SSDATA (encoded_filename
), &statbuf
) == 0)
1814 if (S_ISDIR (statbuf
.st_mode
))
1815 xsignal2 (Qfile_error
,
1816 build_string ("File is a directory"), absname
);
1817 known_to_exist
= true;
1823 xsignal2 (Qfile_already_exists
,
1824 build_string ("File already exists"), absname
);
1825 AUTO_STRING (format
, "File %s already exists; %s anyway? ");
1826 tem
= CALLN (Fformat
, format
, absname
, build_string (querystring
));
1828 tem
= call1 (intern ("y-or-n-p"), tem
);
1830 tem
= do_yes_or_no_p (tem
);
1832 xsignal2 (Qfile_already_exists
,
1833 build_string ("File already exists"), absname
);
1837 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1839 clone_file (int dest
, int source
)
1842 return ioctl (dest
, FICLONE
, source
) == 0;
1847 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 6,
1848 "fCopy file: \nGCopy %s to file: \np\nP",
1849 doc
: /* Copy FILE to NEWNAME. Both args must be strings.
1850 If NEWNAME names a directory, copy FILE there.
1852 This function always sets the file modes of the output file to match
1855 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1856 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1857 signal a `file-already-exists' error without overwriting. If
1858 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1859 about overwriting; this is what happens in interactive use with M-x.
1860 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1863 Fourth arg KEEP-TIME non-nil means give the output file the same
1864 last-modified time as the old one. (This works on only some systems.)
1866 A prefix arg makes KEEP-TIME non-nil.
1868 If PRESERVE-UID-GID is non-nil, we try to transfer the
1869 uid and gid of FILE to NEWNAME.
1871 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1872 this includes the file modes, along with ACL entries and SELinux
1873 context if present. Otherwise, if NEWNAME is created its file
1874 permission bits are those of FILE, masked by the default file
1876 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
,
1877 Lisp_Object keep_time
, Lisp_Object preserve_uid_gid
,
1878 Lisp_Object preserve_permissions
)
1880 Lisp_Object handler
;
1881 ptrdiff_t count
= SPECPDL_INDEX ();
1882 Lisp_Object encoded_file
, encoded_newname
;
1884 security_context_t con
;
1890 bool already_exists
= false;
1896 encoded_file
= encoded_newname
= Qnil
;
1897 CHECK_STRING (file
);
1898 CHECK_STRING (newname
);
1900 if (!NILP (Ffile_directory_p (newname
)))
1901 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
1903 newname
= Fexpand_file_name (newname
, Qnil
);
1905 file
= Fexpand_file_name (file
, Qnil
);
1907 /* If the input file name has special constructs in it,
1908 call the corresponding file handler. */
1909 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
1910 /* Likewise for output file name. */
1912 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
1913 if (!NILP (handler
))
1914 return call7 (handler
, Qcopy_file
, file
, newname
,
1915 ok_if_already_exists
, keep_time
, preserve_uid_gid
,
1916 preserve_permissions
);
1918 encoded_file
= ENCODE_FILE (file
);
1919 encoded_newname
= ENCODE_FILE (newname
);
1922 if (NILP (ok_if_already_exists
)
1923 || INTEGERP (ok_if_already_exists
))
1924 barf_or_query_if_file_exists (newname
, false, "copy to it",
1925 INTEGERP (ok_if_already_exists
), false);
1927 result
= w32_copy_file (SSDATA (encoded_file
), SSDATA (encoded_newname
),
1928 !NILP (keep_time
), !NILP (preserve_uid_gid
),
1929 !NILP (preserve_permissions
));
1933 report_file_error ("Copying file", list2 (file
, newname
));
1935 report_file_error ("Copying permissions from", file
);
1937 xsignal2 (Qfile_date_error
,
1938 build_string ("Resetting file times"), newname
);
1940 report_file_error ("Copying permissions to", newname
);
1942 #else /* not WINDOWSNT */
1944 ifd
= emacs_open (SSDATA (encoded_file
), O_RDONLY
, 0);
1948 report_file_error ("Opening input file", file
);
1950 record_unwind_protect_int (close_file_unwind
, ifd
);
1952 if (fstat (ifd
, &st
) != 0)
1953 report_file_error ("Input file status", file
);
1955 if (!NILP (preserve_permissions
))
1958 if (is_selinux_enabled ())
1960 conlength
= fgetfilecon (ifd
, &con
);
1961 if (conlength
== -1)
1962 report_file_error ("Doing fgetfilecon", file
);
1967 /* We can copy only regular files. */
1968 if (!S_ISREG (st
.st_mode
))
1969 report_file_errno ("Non-regular file", file
,
1970 S_ISDIR (st
.st_mode
) ? EISDIR
: EINVAL
);
1973 new_mask
= st
.st_mode
& (!NILP (preserve_uid_gid
) ? 0700 : 0777);
1975 new_mask
= S_IREAD
| S_IWRITE
;
1978 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
| O_CREAT
| O_EXCL
,
1980 if (ofd
< 0 && errno
== EEXIST
)
1982 if (NILP (ok_if_already_exists
) || INTEGERP (ok_if_already_exists
))
1983 barf_or_query_if_file_exists (newname
, true, "copy to it",
1984 INTEGERP (ok_if_already_exists
), false);
1985 already_exists
= true;
1986 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
, 0);
1989 report_file_error ("Opening output file", newname
);
1991 record_unwind_protect_int (close_file_unwind
, ofd
);
1993 off_t oldsize
= 0, newsize
;
1998 if (fstat (ofd
, &out_st
) != 0)
1999 report_file_error ("Output file status", newname
);
2000 if (st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
2001 report_file_errno ("Input and output files are the same",
2002 list2 (file
, newname
), 0);
2003 if (S_ISREG (out_st
.st_mode
))
2004 oldsize
= out_st
.st_size
;
2010 if (clone_file (ofd
, ifd
))
2011 newsize
= st
.st_size
;
2014 char buf
[MAX_ALLOCA
];
2016 for (newsize
= 0; 0 < (n
= emacs_read (ifd
, buf
, sizeof buf
));
2018 if (emacs_write_sig (ofd
, buf
, n
) != n
)
2019 report_file_error ("Write error", newname
);
2021 report_file_error ("Read error", file
);
2024 /* Truncate any existing output file after writing the data. This
2025 is more likely to work than truncation before writing, if the
2026 file system is out of space or the user is over disk quota. */
2027 if (newsize
< oldsize
&& ftruncate (ofd
, newsize
) != 0)
2028 report_file_error ("Truncating output file", newname
);
2033 /* Preserve the original file permissions, and if requested, also its
2036 mode_t preserved_permissions
= st
.st_mode
& 07777;
2037 mode_t default_permissions
= st
.st_mode
& 0777 & ~realmask
;
2038 if (!NILP (preserve_uid_gid
))
2040 /* Attempt to change owner and group. If that doesn't work
2041 attempt to change just the group, as that is sometimes allowed.
2042 Adjust the mode mask to eliminate setuid or setgid bits
2043 or group permissions bits that are inappropriate if the
2044 owner or group are wrong. */
2045 if (fchown (ofd
, st
.st_uid
, st
.st_gid
) != 0)
2047 if (fchown (ofd
, -1, st
.st_gid
) == 0)
2048 preserved_permissions
&= ~04000;
2051 preserved_permissions
&= ~06000;
2053 /* Copy the other bits to the group bits, since the
2055 preserved_permissions
&= ~070;
2056 preserved_permissions
|= (preserved_permissions
& 7) << 3;
2057 default_permissions
&= ~070;
2058 default_permissions
|= (default_permissions
& 7) << 3;
2063 switch (!NILP (preserve_permissions
)
2064 ? qcopy_acl (SSDATA (encoded_file
), ifd
,
2065 SSDATA (encoded_newname
), ofd
,
2066 preserved_permissions
)
2068 || (new_mask
& ~realmask
) == default_permissions
)
2070 : fchmod (ofd
, default_permissions
))
2072 case -2: report_file_error ("Copying permissions from", file
);
2073 case -1: report_file_error ("Copying permissions to", newname
);
2076 #endif /* not MSDOS */
2081 /* Set the modified context back to the file. */
2082 bool fail
= fsetfilecon (ofd
, con
) != 0;
2083 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2084 if (fail
&& errno
!= ENOTSUP
)
2085 report_file_error ("Doing fsetfilecon", newname
);
2091 if (!NILP (keep_time
))
2093 struct timespec atime
= get_stat_atime (&st
);
2094 struct timespec mtime
= get_stat_mtime (&st
);
2095 if (set_file_times (ofd
, SSDATA (encoded_newname
), atime
, mtime
) != 0)
2096 xsignal2 (Qfile_date_error
,
2097 build_string ("Cannot set file date"), newname
);
2100 if (emacs_close (ofd
) < 0)
2101 report_file_error ("Write error", newname
);
2106 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2107 and if it can't, it tells so. Otherwise, under MSDOS we usually
2108 get only the READ bit, which will make the copied file read-only,
2109 so it's better not to chmod at all. */
2110 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2111 chmod (SDATA (encoded_newname
), st
.st_mode
& 07777);
2113 #endif /* not WINDOWSNT */
2115 /* Discard the unwind protects. */
2116 specpdl_ptr
= specpdl
+ count
;
2121 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2122 Smake_directory_internal
, 1, 1, 0,
2123 doc
: /* Create a new directory named DIRECTORY. */)
2124 (Lisp_Object directory
)
2127 Lisp_Object handler
;
2128 Lisp_Object encoded_dir
;
2130 CHECK_STRING (directory
);
2131 directory
= Fexpand_file_name (directory
, Qnil
);
2133 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2134 if (!NILP (handler
))
2135 return call2 (handler
, Qmake_directory_internal
, directory
);
2137 encoded_dir
= ENCODE_FILE (directory
);
2139 dir
= SSDATA (encoded_dir
);
2142 if (mkdir (dir
) != 0)
2144 if (mkdir (dir
, 0777 & ~auto_saving_dir_umask
) != 0)
2146 report_file_error ("Creating directory", directory
);
2151 DEFUN ("delete-directory-internal", Fdelete_directory_internal
,
2152 Sdelete_directory_internal
, 1, 1, 0,
2153 doc
: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2154 (Lisp_Object directory
)
2157 Lisp_Object encoded_dir
;
2159 CHECK_STRING (directory
);
2160 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2161 encoded_dir
= ENCODE_FILE (directory
);
2162 dir
= SSDATA (encoded_dir
);
2164 if (rmdir (dir
) != 0)
2165 report_file_error ("Removing directory", directory
);
2170 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 2,
2171 "(list (read-file-name \
2172 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2173 \"Move file to trash: \" \"Delete file: \") \
2174 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2175 (null current-prefix-arg))",
2176 doc
: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2177 If file has multiple names, it continues to exist with the other names.
2178 TRASH non-nil means to trash the file instead of deleting, provided
2179 `delete-by-moving-to-trash' is non-nil.
2181 When called interactively, TRASH is t if no prefix argument is given.
2182 With a prefix argument, TRASH is nil. */)
2183 (Lisp_Object filename
, Lisp_Object trash
)
2185 Lisp_Object handler
;
2186 Lisp_Object encoded_file
;
2188 if (!NILP (Ffile_directory_p (filename
))
2189 && NILP (Ffile_symlink_p (filename
)))
2190 xsignal2 (Qfile_error
,
2191 build_string ("Removing old name: is a directory"),
2193 filename
= Fexpand_file_name (filename
, Qnil
);
2195 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2196 if (!NILP (handler
))
2197 return call3 (handler
, Qdelete_file
, filename
, trash
);
2199 if (delete_by_moving_to_trash
&& !NILP (trash
))
2200 return call1 (Qmove_file_to_trash
, filename
);
2202 encoded_file
= ENCODE_FILE (filename
);
2204 if (unlink (SSDATA (encoded_file
)) < 0)
2205 report_file_error ("Removing old name", filename
);
2210 internal_delete_file_1 (Lisp_Object ignore
)
2215 /* Delete file FILENAME, returning true if successful.
2216 This ignores `delete-by-moving-to-trash'. */
2219 internal_delete_file (Lisp_Object filename
)
2223 tem
= internal_condition_case_2 (Fdelete_file
, filename
, Qnil
,
2224 Qt
, internal_delete_file_1
);
2228 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2229 "fRename file: \nGRename %s to file: \np",
2230 doc
: /* Rename FILE as NEWNAME. Both args must be strings.
2231 If file has names other than FILE, it continues to have those names.
2232 Signals a `file-already-exists' error if a file NEWNAME already exists
2233 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2234 A number as third arg means request confirmation if NEWNAME already exists.
2235 This is what happens in interactive use with M-x. */)
2236 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2238 Lisp_Object handler
;
2239 Lisp_Object encoded_file
, encoded_newname
, symlink_target
;
2241 symlink_target
= encoded_file
= encoded_newname
= Qnil
;
2242 CHECK_STRING (file
);
2243 CHECK_STRING (newname
);
2244 file
= Fexpand_file_name (file
, Qnil
);
2246 if ((!NILP (Ffile_directory_p (newname
)))
2248 /* If the file names are identical but for the case,
2249 don't attempt to move directory to itself. */
2250 && (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2254 Lisp_Object fname
= (NILP (Ffile_directory_p (file
))
2255 ? file
: Fdirectory_file_name (file
));
2256 newname
= Fexpand_file_name (Ffile_name_nondirectory (fname
), newname
);
2259 newname
= Fexpand_file_name (newname
, Qnil
);
2261 /* If the file name has special constructs in it,
2262 call the corresponding file handler. */
2263 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2265 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2266 if (!NILP (handler
))
2267 return call4 (handler
, Qrename_file
,
2268 file
, newname
, ok_if_already_exists
);
2270 encoded_file
= ENCODE_FILE (file
);
2271 encoded_newname
= ENCODE_FILE (newname
);
2274 /* If the file names are identical but for the case, don't ask for
2275 confirmation: they simply want to change the letter-case of the
2277 if (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2279 if (NILP (ok_if_already_exists
)
2280 || INTEGERP (ok_if_already_exists
))
2281 barf_or_query_if_file_exists (newname
, false, "rename to it",
2282 INTEGERP (ok_if_already_exists
), false);
2283 if (rename (SSDATA (encoded_file
), SSDATA (encoded_newname
)) < 0)
2285 int rename_errno
= errno
;
2286 if (rename_errno
== EXDEV
)
2289 symlink_target
= Ffile_symlink_p (file
);
2290 if (! NILP (symlink_target
))
2291 Fmake_symbolic_link (symlink_target
, newname
,
2292 NILP (ok_if_already_exists
) ? Qnil
: Qt
);
2293 else if (!NILP (Ffile_directory_p (file
)))
2294 call4 (Qcopy_directory
, file
, newname
, Qt
, Qnil
);
2296 /* We have already prompted if it was an integer, so don't
2297 have copy-file prompt again. */
2298 Fcopy_file (file
, newname
,
2299 NILP (ok_if_already_exists
) ? Qnil
: Qt
,
2302 count
= SPECPDL_INDEX ();
2303 specbind (Qdelete_by_moving_to_trash
, Qnil
);
2305 if (!NILP (Ffile_directory_p (file
)) && NILP (symlink_target
))
2306 call2 (Qdelete_directory
, file
, Qt
);
2308 Fdelete_file (file
, Qnil
);
2309 unbind_to (count
, Qnil
);
2312 report_file_errno ("Renaming", list2 (file
, newname
), rename_errno
);
2318 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2319 "fAdd name to file: \nGName to add to %s: \np",
2320 doc
: /* Give FILE additional name NEWNAME. Both args must be strings.
2321 Signals a `file-already-exists' error if a file NEWNAME already exists
2322 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2323 A number as third arg means request confirmation if NEWNAME already exists.
2324 This is what happens in interactive use with M-x. */)
2325 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2327 Lisp_Object handler
;
2328 Lisp_Object encoded_file
, encoded_newname
;
2330 encoded_file
= encoded_newname
= Qnil
;
2331 CHECK_STRING (file
);
2332 CHECK_STRING (newname
);
2333 file
= Fexpand_file_name (file
, Qnil
);
2335 if (!NILP (Ffile_directory_p (newname
)))
2336 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
2338 newname
= Fexpand_file_name (newname
, Qnil
);
2340 /* If the file name has special constructs in it,
2341 call the corresponding file handler. */
2342 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2343 if (!NILP (handler
))
2344 return call4 (handler
, Qadd_name_to_file
, file
,
2345 newname
, ok_if_already_exists
);
2347 /* If the new name has special constructs in it,
2348 call the corresponding file handler. */
2349 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2350 if (!NILP (handler
))
2351 return call4 (handler
, Qadd_name_to_file
, file
,
2352 newname
, ok_if_already_exists
);
2354 encoded_file
= ENCODE_FILE (file
);
2355 encoded_newname
= ENCODE_FILE (newname
);
2357 if (NILP (ok_if_already_exists
)
2358 || INTEGERP (ok_if_already_exists
))
2359 barf_or_query_if_file_exists (newname
, false, "make it a new name",
2360 INTEGERP (ok_if_already_exists
), false);
2362 unlink (SSDATA (newname
));
2363 if (link (SSDATA (encoded_file
), SSDATA (encoded_newname
)) < 0)
2365 int link_errno
= errno
;
2366 report_file_errno ("Adding new name", list2 (file
, newname
), link_errno
);
2372 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2373 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2374 doc
: /* Make a symbolic link to TARGET, named LINKNAME.
2375 Both args must be strings.
2376 Signals a `file-already-exists' error if a file LINKNAME already exists
2377 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2378 A number as third arg means request confirmation if LINKNAME already exists.
2379 This happens for interactive use with M-x. */)
2380 (Lisp_Object target
, Lisp_Object linkname
, Lisp_Object ok_if_already_exists
)
2382 Lisp_Object handler
;
2383 Lisp_Object encoded_target
, encoded_linkname
;
2385 encoded_target
= encoded_linkname
= Qnil
;
2386 CHECK_STRING (target
);
2387 CHECK_STRING (linkname
);
2388 /* If the link target has a ~, we must expand it to get
2389 a truly valid file name. Otherwise, do not expand;
2390 we want to permit links to relative file names. */
2391 if (SREF (target
, 0) == '~')
2392 target
= Fexpand_file_name (target
, Qnil
);
2394 if (!NILP (Ffile_directory_p (linkname
)))
2395 linkname
= Fexpand_file_name (Ffile_name_nondirectory (target
), linkname
);
2397 linkname
= Fexpand_file_name (linkname
, Qnil
);
2399 /* If the file name has special constructs in it,
2400 call the corresponding file handler. */
2401 handler
= Ffind_file_name_handler (target
, Qmake_symbolic_link
);
2402 if (!NILP (handler
))
2403 return call4 (handler
, Qmake_symbolic_link
, target
,
2404 linkname
, ok_if_already_exists
);
2406 /* If the new link name has special constructs in it,
2407 call the corresponding file handler. */
2408 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2409 if (!NILP (handler
))
2410 return call4 (handler
, Qmake_symbolic_link
, target
,
2411 linkname
, ok_if_already_exists
);
2413 encoded_target
= ENCODE_FILE (target
);
2414 encoded_linkname
= ENCODE_FILE (linkname
);
2416 if (NILP (ok_if_already_exists
)
2417 || INTEGERP (ok_if_already_exists
))
2418 barf_or_query_if_file_exists (linkname
, false, "make it a link",
2419 INTEGERP (ok_if_already_exists
), false);
2420 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
)) < 0)
2422 /* If we didn't complain already, silently delete existing file. */
2424 if (errno
== EEXIST
)
2426 unlink (SSDATA (encoded_linkname
));
2427 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
))
2431 if (errno
== ENOSYS
)
2432 xsignal1 (Qfile_error
,
2433 build_string ("Symbolic links are not supported"));
2435 symlink_errno
= errno
;
2436 report_file_errno ("Making symbolic link", list2 (target
, linkname
),
2444 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2446 doc
: /* Return t if file FILENAME specifies an absolute file name.
2447 On Unix, this is a name starting with a `/' or a `~'. */)
2448 (Lisp_Object filename
)
2450 CHECK_STRING (filename
);
2451 return file_name_absolute_p (SSDATA (filename
)) ? Qt
: Qnil
;
2454 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2455 doc
: /* Return t if file FILENAME exists (whether or not you can read it.)
2456 See also `file-readable-p' and `file-attributes'.
2457 This returns nil for a symlink to a nonexistent file.
2458 Use `file-symlink-p' to test for such links. */)
2459 (Lisp_Object filename
)
2461 Lisp_Object absname
;
2462 Lisp_Object handler
;
2464 CHECK_STRING (filename
);
2465 absname
= Fexpand_file_name (filename
, Qnil
);
2467 /* If the file name has special constructs in it,
2468 call the corresponding file handler. */
2469 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2470 if (!NILP (handler
))
2472 Lisp_Object result
= call2 (handler
, Qfile_exists_p
, absname
);
2477 absname
= ENCODE_FILE (absname
);
2479 return check_existing (SSDATA (absname
)) ? Qt
: Qnil
;
2482 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2483 doc
: /* Return t if FILENAME can be executed by you.
2484 For a directory, this means you can access files in that directory.
2485 \(It is generally better to use `file-accessible-directory-p' for that
2486 purpose, though.) */)
2487 (Lisp_Object filename
)
2489 Lisp_Object absname
;
2490 Lisp_Object handler
;
2492 CHECK_STRING (filename
);
2493 absname
= Fexpand_file_name (filename
, Qnil
);
2495 /* If the file name has special constructs in it,
2496 call the corresponding file handler. */
2497 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
2498 if (!NILP (handler
))
2499 return call2 (handler
, Qfile_executable_p
, absname
);
2501 absname
= ENCODE_FILE (absname
);
2503 return (check_executable (SSDATA (absname
)) ? Qt
: Qnil
);
2506 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
2507 doc
: /* Return t if file FILENAME exists and you can read it.
2508 See also `file-exists-p' and `file-attributes'. */)
2509 (Lisp_Object filename
)
2511 Lisp_Object absname
;
2512 Lisp_Object handler
;
2514 CHECK_STRING (filename
);
2515 absname
= Fexpand_file_name (filename
, Qnil
);
2517 /* If the file name has special constructs in it,
2518 call the corresponding file handler. */
2519 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
2520 if (!NILP (handler
))
2521 return call2 (handler
, Qfile_readable_p
, absname
);
2523 absname
= ENCODE_FILE (absname
);
2524 return (faccessat (AT_FDCWD
, SSDATA (absname
), R_OK
, AT_EACCESS
) == 0
2528 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
2529 doc
: /* Return t if file FILENAME can be written or created by you. */)
2530 (Lisp_Object filename
)
2532 Lisp_Object absname
, dir
, encoded
;
2533 Lisp_Object handler
;
2535 CHECK_STRING (filename
);
2536 absname
= Fexpand_file_name (filename
, Qnil
);
2538 /* If the file name has special constructs in it,
2539 call the corresponding file handler. */
2540 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
2541 if (!NILP (handler
))
2542 return call2 (handler
, Qfile_writable_p
, absname
);
2544 encoded
= ENCODE_FILE (absname
);
2545 if (check_writable (SSDATA (encoded
), W_OK
))
2547 if (errno
!= ENOENT
)
2550 dir
= Ffile_name_directory (absname
);
2551 eassert (!NILP (dir
));
2553 dir
= Fdirectory_file_name (dir
);
2556 dir
= ENCODE_FILE (dir
);
2558 /* The read-only attribute of the parent directory doesn't affect
2559 whether a file or directory can be created within it. Some day we
2560 should check ACLs though, which do affect this. */
2561 return file_directory_p (SSDATA (dir
)) ? Qt
: Qnil
;
2563 return check_writable (SSDATA (dir
), W_OK
| X_OK
) ? Qt
: Qnil
;
2567 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
2568 doc
: /* Access file FILENAME, and get an error if that does not work.
2569 The second argument STRING is used in the error message.
2570 If there is no error, returns nil. */)
2571 (Lisp_Object filename
, Lisp_Object string
)
2573 Lisp_Object handler
, encoded_filename
, absname
;
2575 CHECK_STRING (filename
);
2576 absname
= Fexpand_file_name (filename
, Qnil
);
2578 CHECK_STRING (string
);
2580 /* If the file name has special constructs in it,
2581 call the corresponding file handler. */
2582 handler
= Ffind_file_name_handler (absname
, Qaccess_file
);
2583 if (!NILP (handler
))
2584 return call3 (handler
, Qaccess_file
, absname
, string
);
2586 encoded_filename
= ENCODE_FILE (absname
);
2588 if (faccessat (AT_FDCWD
, SSDATA (encoded_filename
), R_OK
, AT_EACCESS
) != 0)
2589 report_file_error (SSDATA (string
), filename
);
2594 /* Relative to directory FD, return the symbolic link value of FILENAME.
2595 On failure, return nil. */
2597 emacs_readlinkat (int fd
, char const *filename
)
2599 static struct allocator
const emacs_norealloc_allocator
=
2600 { xmalloc
, NULL
, xfree
, memory_full
};
2602 char readlink_buf
[1024];
2603 char *buf
= careadlinkat (fd
, filename
, readlink_buf
, sizeof readlink_buf
,
2604 &emacs_norealloc_allocator
, readlinkat
);
2608 val
= build_unibyte_string (buf
);
2609 if (buf
[0] == '/' && strchr (buf
, ':'))
2611 AUTO_STRING (slash_colon
, "/:");
2612 val
= concat2 (slash_colon
, val
);
2614 if (buf
!= readlink_buf
)
2616 val
= DECODE_FILE (val
);
2620 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
2621 doc
: /* Return non-nil if file FILENAME is the name of a symbolic link.
2622 The value is the link target, as a string.
2623 Otherwise it returns nil.
2625 This function does not check whether the link target exists. */)
2626 (Lisp_Object filename
)
2628 Lisp_Object handler
;
2630 CHECK_STRING (filename
);
2631 filename
= Fexpand_file_name (filename
, Qnil
);
2633 /* If the file name has special constructs in it,
2634 call the corresponding file handler. */
2635 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
2636 if (!NILP (handler
))
2637 return call2 (handler
, Qfile_symlink_p
, filename
);
2639 filename
= ENCODE_FILE (filename
);
2641 return emacs_readlinkat (AT_FDCWD
, SSDATA (filename
));
2644 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
2645 doc
: /* Return t if FILENAME names an existing directory.
2646 Symbolic links to directories count as directories.
2647 See `file-symlink-p' to distinguish symlinks. */)
2648 (Lisp_Object filename
)
2650 Lisp_Object absname
;
2651 Lisp_Object handler
;
2653 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2655 /* If the file name has special constructs in it,
2656 call the corresponding file handler. */
2657 handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
2658 if (!NILP (handler
))
2659 return call2 (handler
, Qfile_directory_p
, absname
);
2661 absname
= ENCODE_FILE (absname
);
2663 return file_directory_p (SSDATA (absname
)) ? Qt
: Qnil
;
2666 /* Return true if FILE is a directory or a symlink to a directory. */
2668 file_directory_p (char const *file
)
2671 /* This is cheaper than 'stat'. */
2672 return faccessat (AT_FDCWD
, file
, D_OK
, AT_EACCESS
) == 0;
2675 return stat (file
, &st
) == 0 && S_ISDIR (st
.st_mode
);
2679 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
,
2680 Sfile_accessible_directory_p
, 1, 1, 0,
2681 doc
: /* Return t if FILENAME names a directory you can open.
2682 For the value to be t, FILENAME must specify the name of a directory
2683 as a file, and the directory must allow you to open files in it. In
2684 order to use a directory as a buffer's current directory, this
2685 predicate must return true. A directory name spec may be given
2686 instead; then the value is t if the directory so specified exists and
2687 really is a readable and searchable directory. */)
2688 (Lisp_Object filename
)
2690 Lisp_Object absname
;
2691 Lisp_Object handler
;
2693 CHECK_STRING (filename
);
2694 absname
= Fexpand_file_name (filename
, Qnil
);
2696 /* If the file name has special constructs in it,
2697 call the corresponding file handler. */
2698 handler
= Ffind_file_name_handler (absname
, Qfile_accessible_directory_p
);
2699 if (!NILP (handler
))
2701 Lisp_Object r
= call2 (handler
, Qfile_accessible_directory_p
, absname
);
2706 absname
= ENCODE_FILE (absname
);
2707 return file_accessible_directory_p (absname
) ? Qt
: Qnil
;
2710 /* If FILE is a searchable directory or a symlink to a
2711 searchable directory, return true. Otherwise return
2712 false and set errno to an error number. */
2714 file_accessible_directory_p (Lisp_Object file
)
2718 /* We need a special-purpose test because (a) NTFS security data is
2719 not reflected in Posix-style mode bits, and (b) the trick with
2720 accessing "DIR/.", used below on Posix hosts, doesn't work on
2721 Windows, because "DIR/." is normalized to just "DIR" before
2722 hitting the disk. */
2723 return (SBYTES (file
) == 0
2724 || w32_accessible_directory_p (SSDATA (file
), SBYTES (file
)));
2726 return file_directory_p (SSDATA (file
));
2729 /* On POSIXish platforms, use just one system call; this avoids a
2730 race and is typically faster. */
2731 const char *data
= SSDATA (file
);
2732 ptrdiff_t len
= SBYTES (file
);
2738 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2739 There are three exceptions: "", "/", and "//". Leave "" alone,
2740 as it's invalid. Append only "." to the other two exceptions as
2741 "/" and "//" are distinct on some platforms, whereas "/", "///",
2742 "////", etc. are all equivalent. */
2747 /* Just check for trailing '/' when deciding whether to append '/'.
2748 That's simpler than testing the two special cases "/" and "//",
2749 and it's a safe optimization here. */
2750 char *buf
= SAFE_ALLOCA (len
+ 3);
2751 memcpy (buf
, data
, len
);
2752 strcpy (buf
+ len
, &"/."[data
[len
- 1] == '/']);
2756 ok
= check_existing (dir
);
2757 saved_errno
= errno
;
2759 errno
= saved_errno
;
2761 #endif /* !DOS_NT */
2764 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
2765 doc
: /* Return t if FILENAME names a regular file.
2766 This is the sort of file that holds an ordinary stream of data bytes.
2767 Symbolic links to regular files count as regular files.
2768 See `file-symlink-p' to distinguish symlinks. */)
2769 (Lisp_Object filename
)
2771 register Lisp_Object absname
;
2773 Lisp_Object handler
;
2775 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2777 /* If the file name has special constructs in it,
2778 call the corresponding file handler. */
2779 handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
2780 if (!NILP (handler
))
2781 return call2 (handler
, Qfile_regular_p
, absname
);
2783 absname
= ENCODE_FILE (absname
);
2788 Lisp_Object tem
= Vw32_get_true_file_attributes
;
2790 /* Tell stat to use expensive method to get accurate info. */
2791 Vw32_get_true_file_attributes
= Qt
;
2792 result
= stat (SSDATA (absname
), &st
);
2793 Vw32_get_true_file_attributes
= tem
;
2797 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2800 if (stat (SSDATA (absname
), &st
) < 0)
2802 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2806 DEFUN ("file-selinux-context", Ffile_selinux_context
,
2807 Sfile_selinux_context
, 1, 1, 0,
2808 doc
: /* Return SELinux context of file named FILENAME.
2809 The return value is a list (USER ROLE TYPE RANGE), where the list
2810 elements are strings naming the user, role, type, and range of the
2811 file's SELinux security context.
2813 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2814 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2815 (Lisp_Object filename
)
2817 Lisp_Object absname
;
2818 Lisp_Object user
= Qnil
, role
= Qnil
, type
= Qnil
, range
= Qnil
;
2820 Lisp_Object handler
;
2822 security_context_t con
;
2827 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2829 /* If the file name has special constructs in it,
2830 call the corresponding file handler. */
2831 handler
= Ffind_file_name_handler (absname
, Qfile_selinux_context
);
2832 if (!NILP (handler
))
2833 return call2 (handler
, Qfile_selinux_context
, absname
);
2835 absname
= ENCODE_FILE (absname
);
2838 if (is_selinux_enabled ())
2840 conlength
= lgetfilecon (SSDATA (absname
), &con
);
2843 context
= context_new (con
);
2844 if (context_user_get (context
))
2845 user
= build_string (context_user_get (context
));
2846 if (context_role_get (context
))
2847 role
= build_string (context_role_get (context
));
2848 if (context_type_get (context
))
2849 type
= build_string (context_type_get (context
));
2850 if (context_range_get (context
))
2851 range
= build_string (context_range_get (context
));
2852 context_free (context
);
2858 return list4 (user
, role
, type
, range
);
2861 DEFUN ("set-file-selinux-context", Fset_file_selinux_context
,
2862 Sset_file_selinux_context
, 2, 2, 0,
2863 doc
: /* Set SELinux context of file named FILENAME to CONTEXT.
2864 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2865 elements are strings naming the components of a SELinux context.
2867 Value is t if setting of SELinux context was successful, nil otherwise.
2869 This function does nothing and returns nil if SELinux is disabled,
2870 or if Emacs was not compiled with SELinux support. */)
2871 (Lisp_Object filename
, Lisp_Object context
)
2873 Lisp_Object absname
;
2874 Lisp_Object handler
;
2876 Lisp_Object encoded_absname
;
2877 Lisp_Object user
= CAR_SAFE (context
);
2878 Lisp_Object role
= CAR_SAFE (CDR_SAFE (context
));
2879 Lisp_Object type
= CAR_SAFE (CDR_SAFE (CDR_SAFE (context
)));
2880 Lisp_Object range
= CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context
))));
2881 security_context_t con
;
2884 context_t parsed_con
;
2887 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2889 /* If the file name has special constructs in it,
2890 call the corresponding file handler. */
2891 handler
= Ffind_file_name_handler (absname
, Qset_file_selinux_context
);
2892 if (!NILP (handler
))
2893 return call3 (handler
, Qset_file_selinux_context
, absname
, context
);
2896 if (is_selinux_enabled ())
2898 /* Get current file context. */
2899 encoded_absname
= ENCODE_FILE (absname
);
2900 conlength
= lgetfilecon (SSDATA (encoded_absname
), &con
);
2903 parsed_con
= context_new (con
);
2904 /* Change the parts defined in the parameter.*/
2907 if (context_user_set (parsed_con
, SSDATA (user
)))
2908 error ("Doing context_user_set");
2912 if (context_role_set (parsed_con
, SSDATA (role
)))
2913 error ("Doing context_role_set");
2917 if (context_type_set (parsed_con
, SSDATA (type
)))
2918 error ("Doing context_type_set");
2920 if (STRINGP (range
))
2922 if (context_range_set (parsed_con
, SSDATA (range
)))
2923 error ("Doing context_range_set");
2926 /* Set the modified context back to the file. */
2927 fail
= (lsetfilecon (SSDATA (encoded_absname
),
2928 context_str (parsed_con
))
2930 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2931 if (fail
&& errno
!= ENOTSUP
)
2932 report_file_error ("Doing lsetfilecon", absname
);
2934 context_free (parsed_con
);
2936 return fail
? Qnil
: Qt
;
2939 report_file_error ("Doing lgetfilecon", absname
);
2946 DEFUN ("file-acl", Ffile_acl
, Sfile_acl
, 1, 1, 0,
2947 doc
: /* Return ACL entries of file named FILENAME.
2948 The entries are returned in a format suitable for use in `set-file-acl'
2949 but is otherwise undocumented and subject to change.
2950 Return nil if file does not exist or is not accessible, or if Emacs
2951 was unable to determine the ACL entries. */)
2952 (Lisp_Object filename
)
2955 Lisp_Object absname
;
2956 Lisp_Object handler
;
2957 # ifdef HAVE_ACL_SET_FILE
2959 Lisp_Object acl_string
;
2961 # ifndef HAVE_ACL_TYPE_EXTENDED
2962 acl_type_t ACL_TYPE_EXTENDED
= ACL_TYPE_ACCESS
;
2966 absname
= expand_and_dir_to_file (filename
,
2967 BVAR (current_buffer
, directory
));
2969 /* If the file name has special constructs in it,
2970 call the corresponding file handler. */
2971 handler
= Ffind_file_name_handler (absname
, Qfile_acl
);
2972 if (!NILP (handler
))
2973 return call2 (handler
, Qfile_acl
, absname
);
2975 # ifdef HAVE_ACL_SET_FILE
2976 absname
= ENCODE_FILE (absname
);
2978 acl
= acl_get_file (SSDATA (absname
), ACL_TYPE_EXTENDED
);
2982 str
= acl_to_text (acl
, NULL
);
2989 acl_string
= build_string (str
);
3000 DEFUN ("set-file-acl", Fset_file_acl
, Sset_file_acl
,
3002 doc
: /* Set ACL of file named FILENAME to ACL-STRING.
3003 ACL-STRING should contain the textual representation of the ACL
3004 entries in a format suitable for the platform.
3006 Value is t if setting of ACL was successful, nil otherwise.
3008 Setting ACL for local files requires Emacs to be built with ACL
3010 (Lisp_Object filename
, Lisp_Object acl_string
)
3013 Lisp_Object absname
;
3014 Lisp_Object handler
;
3015 # ifdef HAVE_ACL_SET_FILE
3016 Lisp_Object encoded_absname
;
3021 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3023 /* If the file name has special constructs in it,
3024 call the corresponding file handler. */
3025 handler
= Ffind_file_name_handler (absname
, Qset_file_acl
);
3026 if (!NILP (handler
))
3027 return call3 (handler
, Qset_file_acl
, absname
, acl_string
);
3029 # ifdef HAVE_ACL_SET_FILE
3030 if (STRINGP (acl_string
))
3032 acl
= acl_from_text (SSDATA (acl_string
));
3035 report_file_error ("Converting ACL", absname
);
3039 encoded_absname
= ENCODE_FILE (absname
);
3041 fail
= (acl_set_file (SSDATA (encoded_absname
), ACL_TYPE_ACCESS
,
3044 if (fail
&& acl_errno_valid (errno
))
3045 report_file_error ("Setting ACL", absname
);
3048 return fail
? Qnil
: Qt
;
3056 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
3057 doc
: /* Return mode bits of file named FILENAME, as an integer.
3058 Return nil, if file does not exist or is not accessible. */)
3059 (Lisp_Object filename
)
3061 Lisp_Object absname
;
3063 Lisp_Object handler
;
3065 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
3067 /* If the file name has special constructs in it,
3068 call the corresponding file handler. */
3069 handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
3070 if (!NILP (handler
))
3071 return call2 (handler
, Qfile_modes
, absname
);
3073 absname
= ENCODE_FILE (absname
);
3075 if (stat (SSDATA (absname
), &st
) < 0)
3078 return make_number (st
.st_mode
& 07777);
3081 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2,
3082 "(let ((file (read-file-name \"File: \"))) \
3083 (list file (read-file-modes nil file)))",
3084 doc
: /* Set mode bits of file named FILENAME to MODE (an integer).
3085 Only the 12 low bits of MODE are used.
3087 Interactively, mode bits are read by `read-file-modes', which accepts
3088 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3089 (Lisp_Object filename
, Lisp_Object mode
)
3091 Lisp_Object absname
, encoded_absname
;
3092 Lisp_Object handler
;
3094 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3095 CHECK_NUMBER (mode
);
3097 /* If the file name has special constructs in it,
3098 call the corresponding file handler. */
3099 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
3100 if (!NILP (handler
))
3101 return call3 (handler
, Qset_file_modes
, absname
, mode
);
3103 encoded_absname
= ENCODE_FILE (absname
);
3105 if (chmod (SSDATA (encoded_absname
), XINT (mode
) & 07777) < 0)
3106 report_file_error ("Doing chmod", absname
);
3111 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
3112 doc
: /* Set the file permission bits for newly created files.
3113 The argument MODE should be an integer; only the low 9 bits are used.
3114 This setting is inherited by subprocesses. */)
3117 mode_t oldrealmask
, oldumask
, newumask
;
3118 CHECK_NUMBER (mode
);
3119 oldrealmask
= realmask
;
3120 newumask
= ~ XINT (mode
) & 0777;
3123 realmask
= newumask
;
3124 oldumask
= umask (newumask
);
3127 eassert (oldumask
== oldrealmask
);
3131 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
3132 doc
: /* Return the default file protection for created files.
3133 The value is an integer. */)
3137 XSETINT (value
, (~ realmask
) & 0777);
3142 DEFUN ("set-file-times", Fset_file_times
, Sset_file_times
, 1, 2, 0,
3143 doc
: /* Set times of file FILENAME to TIMESTAMP.
3144 Set both access and modification times.
3145 Return t on success, else nil.
3146 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3148 (Lisp_Object filename
, Lisp_Object timestamp
)
3150 Lisp_Object absname
, encoded_absname
;
3151 Lisp_Object handler
;
3152 struct timespec t
= lisp_time_argument (timestamp
);
3154 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3156 /* If the file name has special constructs in it,
3157 call the corresponding file handler. */
3158 handler
= Ffind_file_name_handler (absname
, Qset_file_times
);
3159 if (!NILP (handler
))
3160 return call3 (handler
, Qset_file_times
, absname
, timestamp
);
3162 encoded_absname
= ENCODE_FILE (absname
);
3165 if (set_file_times (-1, SSDATA (encoded_absname
), t
, t
) != 0)
3168 /* Setting times on a directory always fails. */
3169 if (file_directory_p (SSDATA (encoded_absname
)))
3172 report_file_error ("Setting file times", absname
);
3180 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3181 doc
: /* Tell Unix to finish all pending disk updates. */)
3188 #endif /* HAVE_SYNC */
3190 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3191 doc
: /* Return t if file FILE1 is newer than file FILE2.
3192 If FILE1 does not exist, the answer is nil;
3193 otherwise, if FILE2 does not exist, the answer is t. */)
3194 (Lisp_Object file1
, Lisp_Object file2
)
3196 Lisp_Object absname1
, absname2
;
3197 struct stat st1
, st2
;
3198 Lisp_Object handler
;
3200 CHECK_STRING (file1
);
3201 CHECK_STRING (file2
);
3204 absname1
= expand_and_dir_to_file (file1
, BVAR (current_buffer
, directory
));
3205 absname2
= expand_and_dir_to_file (file2
, BVAR (current_buffer
, directory
));
3207 /* If the file name has special constructs in it,
3208 call the corresponding file handler. */
3209 handler
= Ffind_file_name_handler (absname1
, Qfile_newer_than_file_p
);
3211 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3212 if (!NILP (handler
))
3213 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3215 absname1
= ENCODE_FILE (absname1
);
3216 absname2
= ENCODE_FILE (absname2
);
3218 if (stat (SSDATA (absname1
), &st1
) < 0)
3221 if (stat (SSDATA (absname2
), &st2
) < 0)
3224 return (timespec_cmp (get_stat_mtime (&st2
), get_stat_mtime (&st1
)) < 0
3228 #ifndef READ_BUF_SIZE
3229 #define READ_BUF_SIZE (64 << 10)
3231 /* Some buffer offsets are stored in 'int' variables. */
3232 verify (READ_BUF_SIZE
<= INT_MAX
);
3234 /* This function is called after Lisp functions to decide a coding
3235 system are called, or when they cause an error. Before they are
3236 called, the current buffer is set unibyte and it contains only a
3237 newly inserted text (thus the buffer was empty before the
3240 The functions may set markers, overlays, text properties, or even
3241 alter the buffer contents, change the current buffer.
3243 Here, we reset all those changes by:
3244 o set back the current buffer.
3245 o move all markers and overlays to BEG.
3246 o remove all text properties.
3247 o set back the buffer multibyteness. */
3250 decide_coding_unwind (Lisp_Object unwind_data
)
3252 Lisp_Object multibyte
, undo_list
, buffer
;
3254 multibyte
= XCAR (unwind_data
);
3255 unwind_data
= XCDR (unwind_data
);
3256 undo_list
= XCAR (unwind_data
);
3257 buffer
= XCDR (unwind_data
);
3259 set_buffer_internal (XBUFFER (buffer
));
3260 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3261 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3262 set_buffer_intervals (current_buffer
, NULL
);
3263 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3265 /* Now we are safe to change the buffer's multibyteness directly. */
3266 bset_enable_multibyte_characters (current_buffer
, multibyte
);
3267 bset_undo_list (current_buffer
, undo_list
);
3270 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3271 object where slot 0 is the file descriptor, slot 1 specifies
3272 an offset to put the read bytes, and slot 2 is the maximum
3273 amount of bytes to read. Value is the number of bytes read. */
3276 read_non_regular (Lisp_Object state
)
3282 nbytes
= emacs_read (XSAVE_INTEGER (state
, 0),
3283 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
3284 + XSAVE_INTEGER (state
, 1)),
3285 XSAVE_INTEGER (state
, 2));
3287 /* Fast recycle this object for the likely next call. */
3289 return make_number (nbytes
);
3293 /* Condition-case handler used when reading from non-regular files
3294 in insert-file-contents. */
3297 read_non_regular_quit (Lisp_Object ignore
)
3302 /* Return the file offset that VAL represents, checking for type
3303 errors and overflow. */
3305 file_offset (Lisp_Object val
)
3307 if (RANGED_INTEGERP (0, val
, TYPE_MAXIMUM (off_t
)))
3312 double v
= XFLOAT_DATA (val
);
3314 && (sizeof (off_t
) < sizeof v
3315 ? v
<= TYPE_MAXIMUM (off_t
)
3316 : v
< TYPE_MAXIMUM (off_t
)))
3320 wrong_type_argument (intern ("file-offset"), val
);
3323 /* Return a special time value indicating the error number ERRNUM. */
3324 static struct timespec
3325 time_error_value (int errnum
)
3327 int ns
= (errnum
== ENOENT
|| errnum
== EACCES
|| errnum
== ENOTDIR
3328 ? NONEXISTENT_MODTIME_NSECS
3329 : UNKNOWN_MODTIME_NSECS
);
3330 return make_timespec (0, ns
);
3334 get_window_points_and_markers (void)
3336 Lisp_Object pt_marker
= Fpoint_marker ();
3338 = call3 (Qget_buffer_window_list
, Fcurrent_buffer (), Qnil
, Qt
);
3339 Lisp_Object window_markers
= windows
;
3340 /* Window markers (and point) are handled specially: rather than move to
3341 just before or just after the modified text, we try to keep the
3342 markers at the same distance (bug#19161).
3343 In general, this is wrong, but for window-markers, this should be harmless
3344 and is convenient for the end user when most of the file is unmodified,
3345 except for a few minor details near the beginning and near the end. */
3346 for (; CONSP (windows
); windows
= XCDR (windows
))
3347 if (WINDOWP (XCAR (windows
)))
3349 Lisp_Object window_marker
= XWINDOW (XCAR (windows
))->pointm
;
3351 Fcons (window_marker
, Fmarker_position (window_marker
)));
3353 return Fcons (Fcons (pt_marker
, Fpoint ()), window_markers
);
3357 restore_window_points (Lisp_Object window_markers
, ptrdiff_t inserted
,
3358 ptrdiff_t same_at_start
, ptrdiff_t same_at_end
)
3360 for (; CONSP (window_markers
); window_markers
= XCDR (window_markers
))
3361 if (CONSP (XCAR (window_markers
)))
3363 Lisp_Object car
= XCAR (window_markers
);
3364 Lisp_Object marker
= XCAR (car
);
3365 Lisp_Object oldpos
= XCDR (car
);
3366 if (MARKERP (marker
) && INTEGERP (oldpos
)
3367 && XINT (oldpos
) > same_at_start
3368 && XINT (oldpos
) < same_at_end
)
3370 ptrdiff_t oldsize
= same_at_end
- same_at_start
;
3371 ptrdiff_t newsize
= inserted
;
3372 double growth
= newsize
/ (double)oldsize
;
3374 = same_at_start
+ growth
* (XINT (oldpos
) - same_at_start
);
3375 Fset_marker (marker
, make_number (newpos
), Qnil
);
3380 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3381 text as a linear C char array. */
3383 maybe_move_gap (struct buffer
*b
)
3385 if (BUF_GPT_BYTE (b
) != BUF_Z_BYTE (b
))
3387 struct buffer
*cb
= current_buffer
;
3389 set_buffer_internal (b
);
3390 move_gap_both (Z
, Z_BYTE
);
3391 set_buffer_internal (cb
);
3395 /* FIXME: insert-file-contents should be split with the top-level moved to
3396 Elisp and only the core kept in C. */
3398 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3400 doc
: /* Insert contents of file FILENAME after point.
3401 Returns list of absolute file name and number of characters inserted.
3402 If second argument VISIT is non-nil, the buffer's visited filename and
3403 last save file modtime are set, and it is marked unmodified. If
3404 visiting and the file does not exist, visiting is completed before the
3407 The optional third and fourth arguments BEG and END specify what portion
3408 of the file to insert. These arguments count bytes in the file, not
3409 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3411 If optional fifth argument REPLACE is non-nil, replace the current
3412 buffer contents (in the accessible portion) with the file contents.
3413 This is better than simply deleting and inserting the whole thing
3414 because (1) it preserves some marker positions and (2) it puts less data
3415 in the undo list. When REPLACE is non-nil, the second return value is
3416 the number of characters that replace previous buffer contents.
3418 This function does code conversion according to the value of
3419 `coding-system-for-read' or `file-coding-system-alist', and sets the
3420 variable `last-coding-system-used' to the coding system actually used.
3422 In addition, this function decodes the inserted text from known formats
3423 by calling `format-decode', which see. */)
3424 (Lisp_Object filename
, Lisp_Object visit
, Lisp_Object beg
, Lisp_Object end
, Lisp_Object replace
)
3427 struct timespec mtime
;
3429 ptrdiff_t inserted
= 0;
3431 off_t beg_offset
, end_offset
;
3433 ptrdiff_t count
= SPECPDL_INDEX ();
3434 Lisp_Object handler
, val
, insval
, orig_filename
, old_undo
;
3436 ptrdiff_t total
= 0;
3437 bool not_regular
= 0;
3439 char read_buf
[READ_BUF_SIZE
];
3440 struct coding_system coding
;
3441 bool replace_handled
= false;
3442 bool set_coding_system
= false;
3443 Lisp_Object coding_system
;
3444 bool read_quit
= false;
3445 /* If the undo log only contains the insertion, there's no point
3446 keeping it. It's typically when we first fill a file-buffer. */
3447 bool empty_undo_list_p
3448 = (!NILP (visit
) && NILP (BVAR (current_buffer
, undo_list
))
3450 Lisp_Object old_Vdeactivate_mark
= Vdeactivate_mark
;
3451 bool we_locked_file
= false;
3453 Lisp_Object window_markers
= Qnil
;
3454 /* same_at_start and same_at_end count bytes, because file access counts
3455 bytes and BEG and END count bytes. */
3456 ptrdiff_t same_at_start
= BEGV_BYTE
;
3457 ptrdiff_t same_at_end
= ZV_BYTE
;
3458 /* SAME_AT_END_CHARPOS counts characters, because
3459 restore_window_points needs the old character count. */
3460 ptrdiff_t same_at_end_charpos
= ZV
;
3462 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3463 error ("Cannot do file visiting in an indirect buffer");
3465 if (!NILP (BVAR (current_buffer
, read_only
)))
3466 Fbarf_if_buffer_read_only (Qnil
);
3470 orig_filename
= Qnil
;
3473 CHECK_STRING (filename
);
3474 filename
= Fexpand_file_name (filename
, Qnil
);
3476 /* The value Qnil means that the coding system is not yet
3478 coding_system
= Qnil
;
3480 /* If the file name has special constructs in it,
3481 call the corresponding file handler. */
3482 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3483 if (!NILP (handler
))
3485 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3486 visit
, beg
, end
, replace
);
3487 if (CONSP (val
) && CONSP (XCDR (val
))
3488 && RANGED_INTEGERP (0, XCAR (XCDR (val
)), ZV
- PT
))
3489 inserted
= XINT (XCAR (XCDR (val
)));
3493 orig_filename
= filename
;
3494 filename
= ENCODE_FILE (filename
);
3496 fd
= emacs_open (SSDATA (filename
), O_RDONLY
, 0);
3501 report_file_error ("Opening input file", orig_filename
);
3502 mtime
= time_error_value (save_errno
);
3504 if (!NILP (Vcoding_system_for_read
))
3506 /* Don't let invalid values into buffer-file-coding-system. */
3507 CHECK_CODING_SYSTEM (Vcoding_system_for_read
);
3508 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3513 fd_index
= SPECPDL_INDEX ();
3514 record_unwind_protect_int (close_file_unwind
, fd
);
3516 /* Replacement should preserve point as it preserves markers. */
3517 if (!NILP (replace
))
3519 window_markers
= get_window_points_and_markers ();
3520 record_unwind_protect (restore_point_unwind
,
3521 XCAR (XCAR (window_markers
)));
3524 if (fstat (fd
, &st
) != 0)
3525 report_file_error ("Input file status", orig_filename
);
3526 mtime
= get_stat_mtime (&st
);
3528 /* This code will need to be changed in order to work on named
3529 pipes, and it's probably just not worth it. So we should at
3530 least signal an error. */
3531 if (!S_ISREG (st
.st_mode
))
3538 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3539 xsignal2 (Qfile_error
,
3540 build_string ("not a regular file"), orig_filename
);
3545 if (!NILP (beg
) || !NILP (end
))
3546 error ("Attempt to visit less than an entire file");
3547 if (BEG
< Z
&& NILP (replace
))
3548 error ("Cannot do file visiting in a non-empty buffer");
3552 beg_offset
= file_offset (beg
);
3557 end_offset
= file_offset (end
);
3561 end_offset
= TYPE_MAXIMUM (off_t
);
3564 end_offset
= st
.st_size
;
3566 /* A negative size can happen on a platform that allows file
3567 sizes greater than the maximum off_t value. */
3571 /* The file size returned from stat may be zero, but data
3572 may be readable nonetheless, for example when this is a
3573 file in the /proc filesystem. */
3574 if (end_offset
== 0)
3575 end_offset
= READ_BUF_SIZE
;
3579 /* Check now whether the buffer will become too large,
3580 in the likely case where the file's length is not changing.
3581 This saves a lot of needless work before a buffer overflow. */
3584 /* The likely offset where we will stop reading. We could read
3585 more (or less), if the file grows (or shrinks) as we read it. */
3586 off_t likely_end
= min (end_offset
, st
.st_size
);
3588 if (beg_offset
< likely_end
)
3591 = Z_BYTE
- (!NILP (replace
) ? ZV_BYTE
- BEGV_BYTE
: 0);
3592 ptrdiff_t buf_growth_max
= BUF_BYTES_MAX
- buf_bytes
;
3593 off_t likely_growth
= likely_end
- beg_offset
;
3594 if (buf_growth_max
< likely_growth
)
3599 /* Prevent redisplay optimizations. */
3600 current_buffer
->clip_changed
= true;
3602 if (EQ (Vcoding_system_for_read
, Qauto_save_coding
))
3604 coding_system
= coding_inherit_eol_type (Qutf_8_emacs
, Qunix
);
3605 setup_coding_system (coding_system
, &coding
);
3606 /* Ensure we set Vlast_coding_system_used. */
3607 set_coding_system
= true;
3611 /* Decide the coding system to use for reading the file now
3612 because we can't use an optimized method for handling
3613 `coding:' tag if the current buffer is not empty. */
3614 if (!NILP (Vcoding_system_for_read
))
3615 coding_system
= Vcoding_system_for_read
;
3618 /* Don't try looking inside a file for a coding system
3619 specification if it is not seekable. */
3620 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3622 /* Find a coding system specified in the heading two
3623 lines or in the tailing several lines of the file.
3624 We assume that the 1K-byte and 3K-byte for heading
3625 and tailing respectively are sufficient for this
3629 if (st
.st_size
<= (1024 * 4))
3630 nread
= emacs_read (fd
, read_buf
, 1024 * 4);
3633 nread
= emacs_read (fd
, read_buf
, 1024);
3637 if (lseek (fd
, - (1024 * 3), SEEK_END
) < 0)
3638 report_file_error ("Setting file position",
3640 ntail
= emacs_read (fd
, read_buf
+ nread
, 1024 * 3);
3641 nread
= ntail
< 0 ? ntail
: nread
+ ntail
;
3646 report_file_error ("Read error", orig_filename
);
3649 AUTO_STRING (name
, " *code-converting-work*");
3650 struct buffer
*prev
= current_buffer
;
3651 Lisp_Object workbuf
;
3654 record_unwind_current_buffer ();
3656 workbuf
= Fget_buffer_create (name
);
3657 buf
= XBUFFER (workbuf
);
3659 delete_all_overlays (buf
);
3660 bset_directory (buf
, BVAR (current_buffer
, directory
));
3661 bset_read_only (buf
, Qnil
);
3662 bset_filename (buf
, Qnil
);
3663 bset_undo_list (buf
, Qt
);
3664 eassert (buf
->overlays_before
== NULL
);
3665 eassert (buf
->overlays_after
== NULL
);
3667 set_buffer_internal (buf
);
3669 bset_enable_multibyte_characters (buf
, Qnil
);
3671 insert_1_both ((char *) read_buf
, nread
, nread
, 0, 0, 0);
3672 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3673 coding_system
= call2 (Vset_auto_coding_function
,
3674 filename
, make_number (nread
));
3675 set_buffer_internal (prev
);
3677 /* Discard the unwind protect for recovering the
3681 /* Rewind the file for the actual read done later. */
3682 if (lseek (fd
, 0, SEEK_SET
) < 0)
3683 report_file_error ("Setting file position", orig_filename
);
3687 if (NILP (coding_system
))
3689 /* If we have not yet decided a coding system, check
3690 file-coding-system-alist. */
3691 coding_system
= CALLN (Ffind_operation_coding_system
,
3692 Qinsert_file_contents
, orig_filename
,
3693 visit
, beg
, end
, replace
);
3694 if (CONSP (coding_system
))
3695 coding_system
= XCAR (coding_system
);
3699 if (NILP (coding_system
))
3700 coding_system
= Qundecided
;
3702 CHECK_CODING_SYSTEM (coding_system
);
3704 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3705 /* We must suppress all character code conversion except for
3706 end-of-line conversion. */
3707 coding_system
= raw_text_coding_system (coding_system
);
3709 setup_coding_system (coding_system
, &coding
);
3710 /* Ensure we set Vlast_coding_system_used. */
3711 set_coding_system
= true;
3714 /* If requested, replace the accessible part of the buffer
3715 with the file contents. Avoid replacing text at the
3716 beginning or end of the buffer that matches the file contents;
3717 that preserves markers pointing to the unchanged parts.
3719 Here we implement this feature in an optimized way
3720 for the case where code conversion is NOT needed.
3721 The following if-statement handles the case of conversion
3722 in a less optimal way.
3724 If the code conversion is "automatic" then we try using this
3725 method and hope for the best.
3726 But if we discover the need for conversion, we give up on this method
3727 and let the following if-statement handle the replace job. */
3730 && (NILP (coding_system
)
3731 || ! CODING_REQUIRE_DECODING (&coding
)))
3734 /* There is still a possibility we will find the need to do code
3735 conversion. If that happens, set this variable to
3736 give up on handling REPLACE in the optimized way. */
3737 bool giveup_match_end
= false;
3739 if (beg_offset
!= 0)
3741 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3742 report_file_error ("Setting file position", orig_filename
);
3747 /* Count how many chars at the start of the file
3748 match the text at the beginning of the buffer. */
3753 nread
= emacs_read (fd
, read_buf
, sizeof read_buf
);
3755 report_file_error ("Read error", orig_filename
);
3756 else if (nread
== 0)
3759 if (CODING_REQUIRE_DETECTION (&coding
))
3761 coding_system
= detect_coding_system ((unsigned char *) read_buf
,
3764 setup_coding_system (coding_system
, &coding
);
3767 if (CODING_REQUIRE_DECODING (&coding
))
3768 /* We found that the file should be decoded somehow.
3769 Let's give up here. */
3771 giveup_match_end
= true;
3776 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3777 && FETCH_BYTE (same_at_start
) == read_buf
[bufpos
])
3778 same_at_start
++, bufpos
++;
3779 /* If we found a discrepancy, stop the scan.
3780 Otherwise loop around and scan the next bufferful. */
3781 if (bufpos
!= nread
)
3784 immediate_quit
= false;
3785 /* If the file matches the buffer completely,
3786 there's no need to replace anything. */
3787 if (same_at_start
- BEGV_BYTE
== end_offset
- beg_offset
)
3790 clear_unwind_protect (fd_index
);
3792 /* Truncate the buffer to the size of the file. */
3793 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3796 immediate_quit
= true;
3798 /* Count how many chars at the end of the file
3799 match the text at the end of the buffer. But, if we have
3800 already found that decoding is necessary, don't waste time. */
3801 while (!giveup_match_end
)
3803 int total_read
, nread
, bufpos
, trial
;
3806 /* At what file position are we now scanning? */
3807 curpos
= end_offset
- (ZV_BYTE
- same_at_end
);
3808 /* If the entire file matches the buffer tail, stop the scan. */
3811 /* How much can we scan in the next step? */
3812 trial
= min (curpos
, sizeof read_buf
);
3813 if (lseek (fd
, curpos
- trial
, SEEK_SET
) < 0)
3814 report_file_error ("Setting file position", orig_filename
);
3816 total_read
= nread
= 0;
3817 while (total_read
< trial
)
3819 nread
= emacs_read (fd
, read_buf
+ total_read
, trial
- total_read
);
3821 report_file_error ("Read error", orig_filename
);
3822 else if (nread
== 0)
3824 total_read
+= nread
;
3827 /* Scan this bufferful from the end, comparing with
3828 the Emacs buffer. */
3829 bufpos
= total_read
;
3831 /* Compare with same_at_start to avoid counting some buffer text
3832 as matching both at the file's beginning and at the end. */
3833 while (bufpos
> 0 && same_at_end
> same_at_start
3834 && FETCH_BYTE (same_at_end
- 1) == read_buf
[bufpos
- 1])
3835 same_at_end
--, bufpos
--;
3837 /* If we found a discrepancy, stop the scan.
3838 Otherwise loop around and scan the preceding bufferful. */
3841 /* If this discrepancy is because of code conversion,
3842 we cannot use this method; giveup and try the other. */
3843 if (same_at_end
> same_at_start
3844 && FETCH_BYTE (same_at_end
- 1) >= 0200
3845 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
))
3846 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3847 giveup_match_end
= true;
3856 if (! giveup_match_end
)
3860 /* We win! We can handle REPLACE the optimized way. */
3862 /* Extend the start of non-matching text area to multibyte
3863 character boundary. */
3864 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3865 while (same_at_start
> BEGV_BYTE
3866 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3869 /* Extend the end of non-matching text area to multibyte
3870 character boundary. */
3871 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3872 while (same_at_end
< ZV_BYTE
3873 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3876 /* Don't try to reuse the same piece of text twice. */
3877 overlap
= (same_at_start
- BEGV_BYTE
3879 + (! NILP (end
) ? end_offset
: st
.st_size
) - ZV_BYTE
));
3881 same_at_end
+= overlap
;
3882 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
3884 /* Arrange to read only the nonmatching middle part of the file. */
3885 beg_offset
+= same_at_start
- BEGV_BYTE
;
3886 end_offset
-= ZV_BYTE
- same_at_end
;
3888 invalidate_buffer_caches (current_buffer
,
3889 BYTE_TO_CHAR (same_at_start
),
3890 same_at_end_charpos
);
3891 del_range_byte (same_at_start
, same_at_end
, 0);
3892 /* Insert from the file at the proper position. */
3893 temp
= BYTE_TO_CHAR (same_at_start
);
3894 SET_PT_BOTH (temp
, same_at_start
);
3896 /* If display currently starts at beginning of line,
3897 keep it that way. */
3898 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
3899 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
3901 replace_handled
= true;
3905 /* If requested, replace the accessible part of the buffer
3906 with the file contents. Avoid replacing text at the
3907 beginning or end of the buffer that matches the file contents;
3908 that preserves markers pointing to the unchanged parts.
3910 Here we implement this feature for the case where code conversion
3911 is needed, in a simple way that needs a lot of memory.
3912 The preceding if-statement handles the case of no conversion
3913 in a more optimized way. */
3914 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
3916 ptrdiff_t same_at_start_charpos
;
3917 ptrdiff_t inserted_chars
;
3920 unsigned char *decoded
;
3923 ptrdiff_t this_count
= SPECPDL_INDEX ();
3925 = ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3926 Lisp_Object conversion_buffer
;
3928 conversion_buffer
= code_conversion_save (1, multibyte
);
3930 /* First read the whole file, performing code conversion into
3931 CONVERSION_BUFFER. */
3933 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3934 report_file_error ("Setting file position", orig_filename
);
3936 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
3937 unprocessed
= 0; /* Bytes not processed in previous loop. */
3941 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3942 quitting while reading a huge file. */
3944 /* Allow quitting out of the actual I/O. */
3947 this = emacs_read (fd
, read_buf
+ unprocessed
,
3948 READ_BUF_SIZE
- unprocessed
);
3954 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer
),
3955 BUF_Z (XBUFFER (conversion_buffer
)));
3956 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3957 unprocessed
+ this, conversion_buffer
);
3958 unprocessed
= coding
.carryover_bytes
;
3959 if (coding
.carryover_bytes
> 0)
3960 memcpy (read_buf
, coding
.carryover
, unprocessed
);
3964 report_file_error ("Read error", orig_filename
);
3966 clear_unwind_protect (fd_index
);
3968 if (unprocessed
> 0)
3970 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
3971 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3972 unprocessed
, conversion_buffer
);
3973 coding
.mode
&= ~CODING_MODE_LAST_BLOCK
;
3976 coding_system
= CODING_ID_NAME (coding
.id
);
3977 set_coding_system
= true;
3978 maybe_move_gap (XBUFFER (conversion_buffer
));
3979 decoded
= BUF_BEG_ADDR (XBUFFER (conversion_buffer
));
3980 inserted
= (BUF_Z_BYTE (XBUFFER (conversion_buffer
))
3981 - BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
3983 /* Compare the beginning of the converted string with the buffer
3987 while (bufpos
< inserted
&& same_at_start
< same_at_end
3988 && FETCH_BYTE (same_at_start
) == decoded
[bufpos
])
3989 same_at_start
++, bufpos
++;
3991 /* If the file matches the head of buffer completely,
3992 there's no need to replace anything. */
3994 if (bufpos
== inserted
)
3996 /* Truncate the buffer to the size of the file. */
3997 if (same_at_start
!= same_at_end
)
3999 invalidate_buffer_caches (current_buffer
,
4000 BYTE_TO_CHAR (same_at_start
),
4001 BYTE_TO_CHAR (same_at_end
));
4002 del_range_byte (same_at_start
, same_at_end
, 0);
4006 unbind_to (this_count
, Qnil
);
4010 /* Extend the start of non-matching text area to the previous
4011 multibyte character boundary. */
4012 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4013 while (same_at_start
> BEGV_BYTE
4014 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
4017 /* Scan this bufferful from the end, comparing with
4018 the Emacs buffer. */
4021 /* Compare with same_at_start to avoid counting some buffer text
4022 as matching both at the file's beginning and at the end. */
4023 while (bufpos
> 0 && same_at_end
> same_at_start
4024 && FETCH_BYTE (same_at_end
- 1) == decoded
[bufpos
- 1])
4025 same_at_end
--, bufpos
--;
4027 /* Extend the end of non-matching text area to the next
4028 multibyte character boundary. */
4029 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4030 while (same_at_end
< ZV_BYTE
4031 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
4034 /* Don't try to reuse the same piece of text twice. */
4035 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
4037 same_at_end
+= overlap
;
4038 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
4040 /* If display currently starts at beginning of line,
4041 keep it that way. */
4042 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
4043 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
4045 /* Replace the chars that we need to replace,
4046 and update INSERTED to equal the number of bytes
4047 we are taking from the decoded string. */
4048 inserted
-= (ZV_BYTE
- same_at_end
) + (same_at_start
- BEGV_BYTE
);
4050 if (same_at_end
!= same_at_start
)
4052 invalidate_buffer_caches (current_buffer
,
4053 BYTE_TO_CHAR (same_at_start
),
4054 same_at_end_charpos
);
4055 del_range_byte (same_at_start
, same_at_end
, 0);
4057 eassert (same_at_start
== GPT_BYTE
);
4058 same_at_start
= GPT_BYTE
;
4062 temp
= same_at_end_charpos
;
4064 /* Insert from the file at the proper position. */
4065 SET_PT_BOTH (temp
, same_at_start
);
4066 same_at_start_charpos
4067 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4068 same_at_start
- BEGV_BYTE
4069 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4070 eassert (same_at_start_charpos
== temp
- (BEGV
- BEG
));
4072 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4073 same_at_start
+ inserted
- BEGV_BYTE
4074 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)))
4075 - same_at_start_charpos
);
4076 /* This binding is to avoid ask-user-about-supersession-threat
4077 being called in insert_from_buffer (via in
4078 prepare_to_modify_buffer). */
4079 specbind (intern ("buffer-file-name"), Qnil
);
4080 insert_from_buffer (XBUFFER (conversion_buffer
),
4081 same_at_start_charpos
, inserted_chars
, 0);
4082 /* Set `inserted' to the number of inserted characters. */
4083 inserted
= PT
- temp
;
4084 /* Set point before the inserted characters. */
4085 SET_PT_BOTH (temp
, same_at_start
);
4087 unbind_to (this_count
, Qnil
);
4093 total
= end_offset
- beg_offset
;
4095 /* For a special file, all we can do is guess. */
4096 total
= READ_BUF_SIZE
;
4098 if (NILP (visit
) && total
> 0)
4100 if (!NILP (BVAR (current_buffer
, file_truename
))
4101 /* Make binding buffer-file-name to nil effective. */
4102 && !NILP (BVAR (current_buffer
, filename
))
4103 && SAVE_MODIFF
>= MODIFF
)
4104 we_locked_file
= true;
4105 prepare_to_modify_buffer (PT
, PT
, NULL
);
4108 move_gap_both (PT
, PT_BYTE
);
4109 if (GAP_SIZE
< total
)
4110 make_gap (total
- GAP_SIZE
);
4112 if (beg_offset
!= 0 || !NILP (replace
))
4114 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
4115 report_file_error ("Setting file position", orig_filename
);
4118 /* In the following loop, HOW_MUCH contains the total bytes read so
4119 far for a regular file, and not changed for a special file. But,
4120 before exiting the loop, it is set to a negative value if I/O
4124 /* Total bytes inserted. */
4127 /* Here, we don't do code conversion in the loop. It is done by
4128 decode_coding_gap after all data are read into the buffer. */
4130 ptrdiff_t gap_size
= GAP_SIZE
;
4132 while (how_much
< total
)
4134 /* `try' is reserved in some compilers (Microsoft C). */
4135 ptrdiff_t trytry
= min (total
- how_much
, READ_BUF_SIZE
);
4142 /* Maybe make more room. */
4143 if (gap_size
< trytry
)
4145 make_gap (trytry
- gap_size
);
4146 gap_size
= GAP_SIZE
- inserted
;
4149 /* Read from the file, capturing `quit'. When an
4150 error occurs, end the loop, and arrange for a quit
4151 to be signaled after decoding the text we read. */
4152 nbytes
= internal_condition_case_1
4154 make_save_int_int_int (fd
, inserted
, trytry
),
4155 Qerror
, read_non_regular_quit
);
4163 this = XINT (nbytes
);
4167 /* Allow quitting out of the actual I/O. We don't make text
4168 part of the buffer until all the reading is done, so a C-g
4169 here doesn't do any harm. */
4172 this = emacs_read (fd
,
4173 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
4187 /* For a regular file, where TOTAL is the real size,
4188 count HOW_MUCH to compare with it.
4189 For a special file, where TOTAL is just a buffer size,
4190 so don't bother counting in HOW_MUCH.
4191 (INSERTED is where we count the number of characters inserted.) */
4198 /* Now we have either read all the file data into the gap,
4199 or stop reading on I/O error or quit. If nothing was
4200 read, undo marking the buffer modified. */
4205 unlock_file (BVAR (current_buffer
, file_truename
));
4206 Vdeactivate_mark
= old_Vdeactivate_mark
;
4209 Fset (Qdeactivate_mark
, Qt
);
4212 clear_unwind_protect (fd_index
);
4215 report_file_error ("Read error", orig_filename
);
4217 /* Make the text read part of the buffer. */
4218 GAP_SIZE
-= inserted
;
4220 GPT_BYTE
+= inserted
;
4222 ZV_BYTE
+= inserted
;
4227 /* Put an anchor to ensure multi-byte form ends at gap. */
4232 if (NILP (coding_system
))
4234 /* The coding system is not yet decided. Decide it by an
4235 optimized method for handling `coding:' tag.
4237 Note that we can get here only if the buffer was empty
4238 before the insertion. */
4240 if (!NILP (Vcoding_system_for_read
))
4241 coding_system
= Vcoding_system_for_read
;
4244 /* Since we are sure that the current buffer was empty
4245 before the insertion, we can toggle
4246 enable-multibyte-characters directly here without taking
4247 care of marker adjustment. By this way, we can run Lisp
4248 program safely before decoding the inserted text. */
4249 Lisp_Object unwind_data
;
4250 ptrdiff_t count1
= SPECPDL_INDEX ();
4252 unwind_data
= Fcons (BVAR (current_buffer
, enable_multibyte_characters
),
4253 Fcons (BVAR (current_buffer
, undo_list
),
4254 Fcurrent_buffer ()));
4255 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4256 bset_undo_list (current_buffer
, Qt
);
4257 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4259 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4261 coding_system
= call2 (Vset_auto_coding_function
,
4262 filename
, make_number (inserted
));
4265 if (NILP (coding_system
))
4267 /* If the coding system is not yet decided, check
4268 file-coding-system-alist. */
4269 coding_system
= CALLN (Ffind_operation_coding_system
,
4270 Qinsert_file_contents
, orig_filename
,
4271 visit
, beg
, end
, Qnil
);
4272 if (CONSP (coding_system
))
4273 coding_system
= XCAR (coding_system
);
4275 unbind_to (count1
, Qnil
);
4276 inserted
= Z_BYTE
- BEG_BYTE
;
4279 if (NILP (coding_system
))
4280 coding_system
= Qundecided
;
4282 CHECK_CODING_SYSTEM (coding_system
);
4284 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4285 /* We must suppress all character code conversion except for
4286 end-of-line conversion. */
4287 coding_system
= raw_text_coding_system (coding_system
);
4288 setup_coding_system (coding_system
, &coding
);
4289 /* Ensure we set Vlast_coding_system_used. */
4290 set_coding_system
= true;
4295 /* When we visit a file by raw-text, we change the buffer to
4297 if (CODING_FOR_UNIBYTE (&coding
)
4298 /* Can't do this if part of the buffer might be preserved. */
4301 /* Visiting a file with these coding system makes the buffer
4304 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4306 Fset_buffer_multibyte (Qnil
);
4310 coding
.dst_multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
4311 if (CODING_MAY_REQUIRE_DECODING (&coding
)
4312 && (inserted
> 0 || CODING_REQUIRE_FLUSHING (&coding
)))
4314 move_gap_both (PT
, PT_BYTE
);
4315 GAP_SIZE
+= inserted
;
4316 ZV_BYTE
-= inserted
;
4320 decode_coding_gap (&coding
, inserted
, inserted
);
4321 inserted
= coding
.produced_char
;
4322 coding_system
= CODING_ID_NAME (coding
.id
);
4324 else if (inserted
> 0)
4326 invalidate_buffer_caches (current_buffer
, PT
, PT
+ inserted
);
4327 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4331 /* Call after-change hooks for the inserted text, aside from the case
4332 of normal visiting (not with REPLACE), which is done in a new buffer
4333 "before" the buffer is changed. */
4334 if (inserted
> 0 && total
> 0
4335 && (NILP (visit
) || !NILP (replace
)))
4337 signal_after_change (PT
, 0, inserted
);
4338 update_compositions (PT
, PT
, CHECK_BORDER
);
4341 /* Now INSERTED is measured in characters. */
4346 restore_window_points (window_markers
, inserted
,
4347 BYTE_TO_CHAR (same_at_start
),
4348 same_at_end_charpos
);
4352 if (empty_undo_list_p
)
4353 bset_undo_list (current_buffer
, Qnil
);
4357 current_buffer
->modtime
= mtime
;
4358 current_buffer
->modtime_size
= st
.st_size
;
4359 bset_filename (current_buffer
, orig_filename
);
4362 SAVE_MODIFF
= MODIFF
;
4363 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
4364 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4367 if (!NILP (BVAR (current_buffer
, file_truename
)))
4368 unlock_file (BVAR (current_buffer
, file_truename
));
4369 unlock_file (filename
);
4372 xsignal2 (Qfile_error
,
4373 build_string ("not a regular file"), orig_filename
);
4376 if (set_coding_system
)
4377 Vlast_coding_system_used
= coding_system
;
4379 if (! NILP (Ffboundp (Qafter_insert_file_set_coding
)))
4381 insval
= call2 (Qafter_insert_file_set_coding
, make_number (inserted
),
4383 if (! NILP (insval
))
4385 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4386 wrong_type_argument (intern ("inserted-chars"), insval
);
4387 inserted
= XFASTINT (insval
);
4391 /* Decode file format. */
4394 /* Don't run point motion or modification hooks when decoding. */
4395 ptrdiff_t count1
= SPECPDL_INDEX ();
4396 ptrdiff_t old_inserted
= inserted
;
4397 specbind (Qinhibit_point_motion_hooks
, Qt
);
4398 specbind (Qinhibit_modification_hooks
, Qt
);
4400 /* Save old undo list and don't record undo for decoding. */
4401 old_undo
= BVAR (current_buffer
, undo_list
);
4402 bset_undo_list (current_buffer
, Qt
);
4406 insval
= call3 (Qformat_decode
,
4407 Qnil
, make_number (inserted
), visit
);
4408 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4409 wrong_type_argument (intern ("inserted-chars"), insval
);
4410 inserted
= XFASTINT (insval
);
4414 /* If REPLACE is non-nil and we succeeded in not replacing the
4415 beginning or end of the buffer text with the file's contents,
4416 call format-decode with `point' positioned at the beginning
4417 of the buffer and `inserted' equaling the number of
4418 characters in the buffer. Otherwise, format-decode might
4419 fail to correctly analyze the beginning or end of the buffer.
4420 Hence we temporarily save `point' and `inserted' here and
4421 restore `point' iff format-decode did not insert or delete
4422 any text. Otherwise we leave `point' at point-min. */
4423 ptrdiff_t opoint
= PT
;
4424 ptrdiff_t opoint_byte
= PT_BYTE
;
4425 ptrdiff_t oinserted
= ZV
- BEGV
;
4426 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4428 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4429 insval
= call3 (Qformat_decode
,
4430 Qnil
, make_number (oinserted
), visit
);
4431 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4432 wrong_type_argument (intern ("inserted-chars"), insval
);
4433 if (ochars_modiff
== CHARS_MODIFF
)
4434 /* format_decode didn't modify buffer's characters => move
4435 point back to position before inserted text and leave
4436 value of inserted alone. */
4437 SET_PT_BOTH (opoint
, opoint_byte
);
4439 /* format_decode modified buffer's characters => consider
4440 entire buffer changed and leave point at point-min. */
4441 inserted
= XFASTINT (insval
);
4444 /* For consistency with format-decode call these now iff inserted > 0
4445 (martin 2007-06-28). */
4446 p
= Vafter_insert_file_functions
;
4451 insval
= call1 (XCAR (p
), make_number (inserted
));
4454 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4455 wrong_type_argument (intern ("inserted-chars"), insval
);
4456 inserted
= XFASTINT (insval
);
4461 /* For the rationale of this see the comment on
4462 format-decode above. */
4463 ptrdiff_t opoint
= PT
;
4464 ptrdiff_t opoint_byte
= PT_BYTE
;
4465 ptrdiff_t oinserted
= ZV
- BEGV
;
4466 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4468 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4469 insval
= call1 (XCAR (p
), make_number (oinserted
));
4472 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4473 wrong_type_argument (intern ("inserted-chars"), insval
);
4474 if (ochars_modiff
== CHARS_MODIFF
)
4475 /* after_insert_file_functions didn't modify
4476 buffer's characters => move point back to
4477 position before inserted text and leave value of
4479 SET_PT_BOTH (opoint
, opoint_byte
);
4481 /* after_insert_file_functions did modify buffer's
4482 characters => consider entire buffer changed and
4483 leave point at point-min. */
4484 inserted
= XFASTINT (insval
);
4492 if (!empty_undo_list_p
)
4494 bset_undo_list (current_buffer
, old_undo
);
4495 if (CONSP (old_undo
) && inserted
!= old_inserted
)
4497 /* Adjust the last undo record for the size change during
4498 the format conversion. */
4499 Lisp_Object tem
= XCAR (old_undo
);
4500 if (CONSP (tem
) && INTEGERP (XCAR (tem
))
4501 && INTEGERP (XCDR (tem
))
4502 && XFASTINT (XCDR (tem
)) == PT
+ old_inserted
)
4503 XSETCDR (tem
, make_number (PT
+ inserted
));
4507 /* If undo_list was Qt before, keep it that way.
4508 Otherwise start with an empty undo_list. */
4509 bset_undo_list (current_buffer
, EQ (old_undo
, Qt
) ? Qt
: Qnil
);
4511 unbind_to (count1
, Qnil
);
4515 && current_buffer
->modtime
.tv_nsec
== NONEXISTENT_MODTIME_NSECS
)
4517 /* If visiting nonexistent file, return nil. */
4518 report_file_errno ("Opening input file", orig_filename
, save_errno
);
4521 /* We made a lot of deletions and insertions above, so invalidate
4522 the newline cache for the entire region of the inserted
4524 if (current_buffer
->base_buffer
&& current_buffer
->base_buffer
->newline_cache
)
4525 invalidate_region_cache (current_buffer
->base_buffer
,
4526 current_buffer
->base_buffer
->newline_cache
,
4527 PT
- BEG
, Z
- PT
- inserted
);
4528 else if (current_buffer
->newline_cache
)
4529 invalidate_region_cache (current_buffer
,
4530 current_buffer
->newline_cache
,
4531 PT
- BEG
, Z
- PT
- inserted
);
4536 /* Retval needs to be dealt with in all cases consistently. */
4538 val
= list2 (orig_filename
, make_number (inserted
));
4540 return unbind_to (count
, val
);
4543 static Lisp_Object
build_annotations (Lisp_Object
, Lisp_Object
);
4546 build_annotations_unwind (Lisp_Object arg
)
4548 Vwrite_region_annotation_buffers
= arg
;
4551 /* Decide the coding-system to encode the data with. */
4554 choose_write_coding_system (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4555 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4556 struct coding_system
*coding
)
4559 Lisp_Object eol_parent
= Qnil
;
4562 && NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4563 BVAR (current_buffer
, auto_save_file_name
))))
4568 else if (!NILP (Vcoding_system_for_write
))
4570 val
= Vcoding_system_for_write
;
4571 if (coding_system_require_warning
4572 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4573 /* Confirm that VAL can surely encode the current region. */
4574 val
= call5 (Vselect_safe_coding_system_function
,
4575 start
, end
, list2 (Qt
, val
),
4580 /* If the variable `buffer-file-coding-system' is set locally,
4581 it means that the file was read with some kind of code
4582 conversion or the variable is explicitly set by users. We
4583 had better write it out with the same coding system even if
4584 `enable-multibyte-characters' is nil.
4586 If it is not set locally, we anyway have to convert EOL
4587 format if the default value of `buffer-file-coding-system'
4588 tells that it is not Unix-like (LF only) format. */
4589 bool using_default_coding
= 0;
4590 bool force_raw_text
= 0;
4592 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4594 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4597 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4603 /* Check file-coding-system-alist. */
4604 Lisp_Object coding_systems
4605 = CALLN (Ffind_operation_coding_system
, Qwrite_region
, start
, end
,
4606 filename
, append
, visit
, lockname
);
4607 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4608 val
= XCDR (coding_systems
);
4613 /* If we still have not decided a coding system, use the
4614 current buffer's value of buffer-file-coding-system. */
4615 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4616 using_default_coding
= 1;
4619 if (! NILP (val
) && ! force_raw_text
)
4621 Lisp_Object spec
, attrs
;
4623 CHECK_CODING_SYSTEM (val
);
4624 CHECK_CODING_SYSTEM_GET_SPEC (val
, spec
);
4625 attrs
= AREF (spec
, 0);
4626 if (EQ (CODING_ATTR_TYPE (attrs
), Qraw_text
))
4631 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4633 /* Confirm that VAL can surely encode the current region. */
4634 val
= call5 (Vselect_safe_coding_system_function
,
4635 start
, end
, val
, Qnil
, filename
);
4636 /* As the function specified by select-safe-coding-system-function
4637 is out of our control, make sure we are not fed by bogus
4640 CHECK_CODING_SYSTEM (val
);
4643 /* If the decided coding-system doesn't specify end-of-line
4644 format, we use that of
4645 `default-buffer-file-coding-system'. */
4646 if (! using_default_coding
)
4648 Lisp_Object dflt
= BVAR (&buffer_defaults
, buffer_file_coding_system
);
4651 val
= coding_inherit_eol_type (val
, dflt
);
4654 /* If we decide not to encode text, use `raw-text' or one of its
4657 val
= raw_text_coding_system (val
);
4660 val
= coding_inherit_eol_type (val
, eol_parent
);
4661 setup_coding_system (val
, coding
);
4663 if (!STRINGP (start
) && !NILP (BVAR (current_buffer
, selective_display
)))
4664 coding
->mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4668 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4669 "r\nFWrite region to file: \ni\ni\ni\np",
4670 doc
: /* Write current region into specified file.
4671 When called from a program, requires three arguments:
4672 START, END and FILENAME. START and END are normally buffer positions
4673 specifying the part of the buffer to write.
4674 If START is nil, that means to use the entire buffer contents; END is
4676 If START is a string, then output that string to the file
4677 instead of any buffer contents; END is ignored.
4679 Optional fourth argument APPEND if non-nil means
4680 append to existing file contents (if any). If it is a number,
4681 seek to that offset in the file before writing.
4682 Optional fifth argument VISIT, if t or a string, means
4683 set the last-save-file-modtime of buffer to this file's modtime
4684 and mark buffer not modified.
4685 If VISIT is a string, it is a second file name;
4686 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4687 VISIT is also the file name to lock and unlock for clash detection.
4688 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4689 do not display the \"Wrote file\" message.
4690 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4691 use for locking and unlocking, overriding FILENAME and VISIT.
4692 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4693 for an existing file with the same name. If MUSTBENEW is `excl',
4694 that means to get an error if the file already exists; never overwrite.
4695 If MUSTBENEW is neither nil nor `excl', that means ask for
4696 confirmation before overwriting, but do go ahead and overwrite the file
4697 if the user confirms.
4699 This does code conversion according to the value of
4700 `coding-system-for-write', `buffer-file-coding-system', or
4701 `file-coding-system-alist', and sets the variable
4702 `last-coding-system-used' to the coding system actually used.
4704 This calls `write-region-annotate-functions' at the start, and
4705 `write-region-post-annotation-function' at the end. */)
4706 (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
, Lisp_Object append
,
4707 Lisp_Object visit
, Lisp_Object lockname
, Lisp_Object mustbenew
)
4709 return write_region (start
, end
, filename
, append
, visit
, lockname
, mustbenew
,
4713 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4714 descriptor for FILENAME, so do not open or close FILENAME. */
4717 write_region (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4718 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4719 Lisp_Object mustbenew
, int desc
)
4723 off_t offset UNINIT
;
4724 bool open_and_close_file
= desc
< 0;
4729 struct timespec modtime
;
4730 ptrdiff_t count
= SPECPDL_INDEX ();
4731 ptrdiff_t count1 UNINIT
;
4732 Lisp_Object handler
;
4733 Lisp_Object visit_file
;
4734 Lisp_Object annotations
;
4735 Lisp_Object encoded_filename
;
4736 bool visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4737 bool quietly
= !NILP (visit
);
4738 bool file_locked
= 0;
4739 struct buffer
*given_buffer
;
4740 struct coding_system coding
;
4742 if (current_buffer
->base_buffer
&& visiting
)
4743 error ("Cannot do file visiting in an indirect buffer");
4745 if (!NILP (start
) && !STRINGP (start
))
4746 validate_region (&start
, &end
);
4750 filename
= Fexpand_file_name (filename
, Qnil
);
4752 if (!NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4753 barf_or_query_if_file_exists (filename
, false, "overwrite", true, true);
4755 if (STRINGP (visit
))
4756 visit_file
= Fexpand_file_name (visit
, Qnil
);
4758 visit_file
= filename
;
4760 if (NILP (lockname
))
4761 lockname
= visit_file
;
4765 /* If the file name has special constructs in it,
4766 call the corresponding file handler. */
4767 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4768 /* If FILENAME has no handler, see if VISIT has one. */
4769 if (NILP (handler
) && STRINGP (visit
))
4770 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4772 if (!NILP (handler
))
4775 val
= call6 (handler
, Qwrite_region
, start
, end
,
4776 filename
, append
, visit
);
4780 SAVE_MODIFF
= MODIFF
;
4781 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4782 bset_filename (current_buffer
, visit_file
);
4788 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
4790 /* Special kludge to simplify auto-saving. */
4793 /* Do it later, so write-region-annotate-function can work differently
4794 if we save "the buffer" vs "a region".
4795 This is useful in tar-mode. --Stef
4796 XSETFASTINT (start, BEG);
4797 XSETFASTINT (end, Z); */
4801 record_unwind_protect (build_annotations_unwind
,
4802 Vwrite_region_annotation_buffers
);
4803 Vwrite_region_annotation_buffers
= list1 (Fcurrent_buffer ());
4805 given_buffer
= current_buffer
;
4807 if (!STRINGP (start
))
4809 annotations
= build_annotations (start
, end
);
4811 if (current_buffer
!= given_buffer
)
4813 XSETFASTINT (start
, BEGV
);
4814 XSETFASTINT (end
, ZV
);
4820 XSETFASTINT (start
, BEGV
);
4821 XSETFASTINT (end
, ZV
);
4824 /* Decide the coding-system to encode the data with.
4825 We used to make this choice before calling build_annotations, but that
4826 leads to problems when a write-annotate-function takes care of
4827 unsavable chars (as was the case with X-Symbol). */
4828 Vlast_coding_system_used
4829 = choose_write_coding_system (start
, end
, filename
,
4830 append
, visit
, lockname
, &coding
);
4832 if (open_and_close_file
&& !auto_saving
)
4834 lock_file (lockname
);
4838 encoded_filename
= ENCODE_FILE (filename
);
4839 fn
= SSDATA (encoded_filename
);
4840 open_flags
= O_WRONLY
| O_CREAT
;
4841 open_flags
|= EQ (mustbenew
, Qexcl
) ? O_EXCL
: !NILP (append
) ? 0 : O_TRUNC
;
4842 if (NUMBERP (append
))
4843 offset
= file_offset (append
);
4844 else if (!NILP (append
))
4845 open_flags
|= O_APPEND
;
4847 mode
= S_IREAD
| S_IWRITE
;
4849 mode
= auto_saving
? auto_save_mode_bits
: 0666;
4852 if (open_and_close_file
)
4854 desc
= emacs_open (fn
, open_flags
, mode
);
4857 int open_errno
= errno
;
4859 unlock_file (lockname
);
4860 report_file_errno ("Opening output file", filename
, open_errno
);
4863 count1
= SPECPDL_INDEX ();
4864 record_unwind_protect_int (close_file_unwind
, desc
);
4867 if (NUMBERP (append
))
4869 off_t ret
= lseek (desc
, offset
, SEEK_SET
);
4872 int lseek_errno
= errno
;
4874 unlock_file (lockname
);
4875 report_file_errno ("Lseek error", filename
, lseek_errno
);
4881 if (STRINGP (start
))
4882 ok
= a_write (desc
, start
, 0, SCHARS (start
), &annotations
, &coding
);
4883 else if (XINT (start
) != XINT (end
))
4884 ok
= a_write (desc
, Qnil
, XINT (start
), XINT (end
) - XINT (start
),
4885 &annotations
, &coding
);
4888 /* If file was empty, still need to write the annotations. */
4889 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4890 ok
= a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4894 if (ok
&& CODING_REQUIRE_FLUSHING (&coding
)
4895 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
))
4897 /* We have to flush out a data. */
4898 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4899 ok
= e_write (desc
, Qnil
, 1, 1, &coding
);
4905 /* fsync is not crucial for temporary files. Nor for auto-save
4906 files, since they might lose some work anyway. */
4907 if (open_and_close_file
&& !auto_saving
&& !write_region_inhibit_fsync
)
4909 /* Transfer data and metadata to disk, retrying if interrupted.
4910 fsync can report a write failure here, e.g., due to disk full
4911 under NFS. But ignore EINVAL, which means fsync is not
4912 supported on this file. */
4913 while (fsync (desc
) != 0)
4916 if (errno
!= EINVAL
)
4917 ok
= 0, save_errno
= errno
;
4922 modtime
= invalid_timespec ();
4925 if (fstat (desc
, &st
) == 0)
4926 modtime
= get_stat_mtime (&st
);
4928 ok
= 0, save_errno
= errno
;
4931 if (open_and_close_file
)
4933 /* NFS can report a write failure now. */
4934 if (emacs_close (desc
) < 0)
4935 ok
= 0, save_errno
= errno
;
4937 /* Discard the unwind protect for close_file_unwind. */
4938 specpdl_ptr
= specpdl
+ count1
;
4941 /* Some file systems have a bug where st_mtime is not updated
4942 properly after a write. For example, CIFS might not see the
4943 st_mtime change until after the file is opened again.
4945 Attempt to detect this file system bug, and update MODTIME to the
4946 newer st_mtime if the bug appears to be present. This introduces
4947 a race condition, so to avoid most instances of the race condition
4948 on non-buggy file systems, skip this check if the most recently
4949 encountered non-buggy file system was the current file system.
4951 A race condition can occur if some other process modifies the
4952 file between the fstat above and the fstat below, but the race is
4953 unlikely and a similar race between the last write and the fstat
4954 above cannot possibly be closed anyway. */
4956 if (timespec_valid_p (modtime
)
4957 && ! (valid_timestamp_file_system
&& st
.st_dev
== timestamp_file_system
))
4959 int desc1
= emacs_open (fn
, O_WRONLY
, 0);
4963 if (fstat (desc1
, &st1
) == 0
4964 && st
.st_dev
== st1
.st_dev
&& st
.st_ino
== st1
.st_ino
)
4966 /* Use the heuristic if it appears to be valid. With neither
4967 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4968 file, the time stamp won't change. Also, some non-POSIX
4969 systems don't update an empty file's time stamp when
4970 truncating it. Finally, file systems with 100 ns or worse
4971 resolution sometimes seem to have bugs: on a system with ns
4972 resolution, checking ns % 100 incorrectly avoids the heuristic
4973 1% of the time, but the problem should be temporary as we will
4974 try again on the next time stamp. */
4976 = ((open_flags
& (O_EXCL
| O_TRUNC
)) != 0
4978 && modtime
.tv_nsec
% 100 != 0);
4980 struct timespec modtime1
= get_stat_mtime (&st1
);
4982 && timespec_cmp (modtime
, modtime1
) == 0
4983 && st
.st_size
== st1
.st_size
)
4985 timestamp_file_system
= st
.st_dev
;
4986 valid_timestamp_file_system
= 1;
4990 st
.st_size
= st1
.st_size
;
4994 emacs_close (desc1
);
4998 /* Call write-region-post-annotation-function. */
4999 while (CONSP (Vwrite_region_annotation_buffers
))
5001 Lisp_Object buf
= XCAR (Vwrite_region_annotation_buffers
);
5002 if (!NILP (Fbuffer_live_p (buf
)))
5005 if (FUNCTIONP (Vwrite_region_post_annotation_function
))
5006 call0 (Vwrite_region_post_annotation_function
);
5008 Vwrite_region_annotation_buffers
5009 = XCDR (Vwrite_region_annotation_buffers
);
5012 unbind_to (count
, Qnil
);
5015 unlock_file (lockname
);
5017 /* Do this before reporting IO error
5018 to avoid a "file has changed on disk" warning on
5019 next attempt to save. */
5020 if (timespec_valid_p (modtime
))
5022 current_buffer
->modtime
= modtime
;
5023 current_buffer
->modtime_size
= st
.st_size
;
5027 report_file_errno ("Write error", filename
, save_errno
);
5031 SAVE_MODIFF
= MODIFF
;
5032 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5033 bset_filename (current_buffer
, visit_file
);
5034 update_mode_lines
= 14;
5039 && ! NILP (Fstring_equal (BVAR (current_buffer
, filename
),
5040 BVAR (current_buffer
, auto_save_file_name
))))
5041 SAVE_MODIFF
= MODIFF
;
5046 if (!auto_saving
&& !noninteractive
)
5047 message_with_string ((NUMBERP (append
)
5057 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
5058 doc
: /* Return t if (car A) is numerically less than (car B). */)
5059 (Lisp_Object a
, Lisp_Object b
)
5061 return CALLN (Flss
, Fcar (a
), Fcar (b
));
5064 /* Build the complete list of annotations appropriate for writing out
5065 the text between START and END, by calling all the functions in
5066 write-region-annotate-functions and merging the lists they return.
5067 If one of these functions switches to a different buffer, we assume
5068 that buffer contains altered text. Therefore, the caller must
5069 make sure to restore the current buffer in all cases,
5070 as save-excursion would do. */
5073 build_annotations (Lisp_Object start
, Lisp_Object end
)
5075 Lisp_Object annotations
;
5077 Lisp_Object original_buffer
;
5079 bool used_global
= false;
5081 XSETBUFFER (original_buffer
, current_buffer
);
5084 p
= Vwrite_region_annotate_functions
;
5087 struct buffer
*given_buffer
= current_buffer
;
5088 if (EQ (Qt
, XCAR (p
)) && !used_global
)
5089 { /* Use the global value of the hook. */
5092 Fdefault_value (Qwrite_region_annotate_functions
),
5096 Vwrite_region_annotations_so_far
= annotations
;
5097 res
= call2 (XCAR (p
), start
, end
);
5098 /* If the function makes a different buffer current,
5099 assume that means this buffer contains altered text to be output.
5100 Reset START and END from the buffer bounds
5101 and discard all previous annotations because they should have
5102 been dealt with by this function. */
5103 if (current_buffer
!= given_buffer
)
5105 Vwrite_region_annotation_buffers
5106 = Fcons (Fcurrent_buffer (),
5107 Vwrite_region_annotation_buffers
);
5108 XSETFASTINT (start
, BEGV
);
5109 XSETFASTINT (end
, ZV
);
5112 Flength (res
); /* Check basic validity of return value */
5113 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5117 /* Now do the same for annotation functions implied by the file-format */
5118 if (auto_saving
&& (!EQ (BVAR (current_buffer
, auto_save_file_format
), Qt
)))
5119 p
= BVAR (current_buffer
, auto_save_file_format
);
5121 p
= BVAR (current_buffer
, file_format
);
5122 for (i
= 0; CONSP (p
); p
= XCDR (p
), ++i
)
5124 struct buffer
*given_buffer
= current_buffer
;
5126 Vwrite_region_annotations_so_far
= annotations
;
5128 /* Value is either a list of annotations or nil if the function
5129 has written annotations to a temporary buffer, which is now
5131 res
= call5 (Qformat_annotate_function
, XCAR (p
), start
, end
,
5132 original_buffer
, make_number (i
));
5133 if (current_buffer
!= given_buffer
)
5135 XSETFASTINT (start
, BEGV
);
5136 XSETFASTINT (end
, ZV
);
5141 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5148 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5149 If STRING is nil, POS is the character position in the current buffer.
5150 Intersperse with them the annotations from *ANNOT
5151 which fall within the range of POS to POS + NCHARS,
5152 each at its appropriate position.
5154 We modify *ANNOT by discarding elements as we use them up.
5156 Return true if successful. */
5159 a_write (int desc
, Lisp_Object string
, ptrdiff_t pos
,
5160 ptrdiff_t nchars
, Lisp_Object
*annot
,
5161 struct coding_system
*coding
)
5165 ptrdiff_t lastpos
= pos
+ nchars
;
5167 while (NILP (*annot
) || CONSP (*annot
))
5169 tem
= Fcar_safe (Fcar (*annot
));
5172 nextpos
= XFASTINT (tem
);
5174 /* If there are no more annotations in this range,
5175 output the rest of the range all at once. */
5176 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
5177 return e_write (desc
, string
, pos
, lastpos
, coding
);
5179 /* Output buffer text up to the next annotation's position. */
5182 if (!e_write (desc
, string
, pos
, nextpos
, coding
))
5186 /* Output the annotation. */
5187 tem
= Fcdr (Fcar (*annot
));
5190 if (!e_write (desc
, tem
, 0, SCHARS (tem
), coding
))
5193 *annot
= Fcdr (*annot
);
5198 /* Maximum number of characters that the next
5199 function encodes per one loop iteration. */
5201 enum { E_WRITE_MAX
= 8 * 1024 * 1024 };
5203 /* Write text in the range START and END into descriptor DESC,
5204 encoding them with coding system CODING. If STRING is nil, START
5205 and END are character positions of the current buffer, else they
5206 are indexes to the string STRING. Return true if successful. */
5209 e_write (int desc
, Lisp_Object string
, ptrdiff_t start
, ptrdiff_t end
,
5210 struct coding_system
*coding
)
5212 if (STRINGP (string
))
5215 end
= SCHARS (string
);
5218 /* We used to have a code for handling selective display here. But,
5219 now it is handled within encode_coding. */
5223 if (STRINGP (string
))
5225 coding
->src_multibyte
= SCHARS (string
) < SBYTES (string
);
5226 if (CODING_REQUIRE_ENCODING (coding
))
5228 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5230 /* Avoid creating huge Lisp string in encode_coding_object. */
5231 if (nchars
== E_WRITE_MAX
)
5232 coding
->raw_destination
= 1;
5234 encode_coding_object
5235 (coding
, string
, start
, string_char_to_byte (string
, start
),
5236 start
+ nchars
, string_char_to_byte (string
, start
+ nchars
),
5241 coding
->dst_object
= string
;
5242 coding
->consumed_char
= SCHARS (string
);
5243 coding
->produced
= SBYTES (string
);
5248 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
5249 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
5251 coding
->src_multibyte
= (end
- start
) < (end_byte
- start_byte
);
5252 if (CODING_REQUIRE_ENCODING (coding
))
5254 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5257 if (nchars
== E_WRITE_MAX
)
5258 coding
->raw_destination
= 1;
5260 encode_coding_object
5261 (coding
, Fcurrent_buffer (), start
, start_byte
,
5262 start
+ nchars
, CHAR_TO_BYTE (start
+ nchars
), Qt
);
5266 coding
->dst_object
= Qnil
;
5267 coding
->dst_pos_byte
= start_byte
;
5268 if (start
>= GPT
|| end
<= GPT
)
5270 coding
->consumed_char
= end
- start
;
5271 coding
->produced
= end_byte
- start_byte
;
5275 coding
->consumed_char
= GPT
- start
;
5276 coding
->produced
= GPT_BYTE
- start_byte
;
5281 if (coding
->produced
> 0)
5283 char *buf
= (coding
->raw_destination
? (char *) coding
->destination
5284 : (STRINGP (coding
->dst_object
)
5285 ? SSDATA (coding
->dst_object
)
5286 : (char *) BYTE_POS_ADDR (coding
->dst_pos_byte
)));
5287 coding
->produced
-= emacs_write_sig (desc
, buf
, coding
->produced
);
5289 if (coding
->raw_destination
)
5291 /* We're responsible for freeing this, see
5292 encode_coding_object to check why. */
5293 xfree (coding
->destination
);
5294 coding
->raw_destination
= 0;
5296 if (coding
->produced
)
5299 start
+= coding
->consumed_char
;
5305 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5306 Sverify_visited_file_modtime
, 0, 1, 0,
5307 doc
: /* Return t if last mod time of BUF's visited file matches what BUF records.
5308 This means that the file has not been changed since it was visited or saved.
5309 If BUF is omitted or nil, it defaults to the current buffer.
5310 See Info node `(elisp)Modification Time' for more details. */)
5313 struct buffer
*b
= decode_buffer (buf
);
5315 Lisp_Object handler
;
5316 Lisp_Object filename
;
5317 struct timespec mtime
;
5319 if (!STRINGP (BVAR (b
, filename
))) return Qt
;
5320 if (b
->modtime
.tv_nsec
== UNKNOWN_MODTIME_NSECS
) return Qt
;
5322 /* If the file name has special constructs in it,
5323 call the corresponding file handler. */
5324 handler
= Ffind_file_name_handler (BVAR (b
, filename
),
5325 Qverify_visited_file_modtime
);
5326 if (!NILP (handler
))
5327 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5329 filename
= ENCODE_FILE (BVAR (b
, filename
));
5331 mtime
= (stat (SSDATA (filename
), &st
) == 0
5332 ? get_stat_mtime (&st
)
5333 : time_error_value (errno
));
5334 if (timespec_cmp (mtime
, b
->modtime
) == 0
5335 && (b
->modtime_size
< 0
5336 || st
.st_size
== b
->modtime_size
))
5341 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5342 Svisited_file_modtime
, 0, 0, 0,
5343 doc
: /* Return the current buffer's recorded visited file modification time.
5344 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5345 `file-attributes' returns. If the current buffer has no recorded file
5346 modification time, this function returns 0. If the visited file
5347 doesn't exist, return -1.
5348 See Info node `(elisp)Modification Time' for more details. */)
5351 int ns
= current_buffer
->modtime
.tv_nsec
;
5353 return make_number (UNKNOWN_MODTIME_NSECS
- ns
);
5354 return make_lisp_time (current_buffer
->modtime
);
5357 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5358 Sset_visited_file_modtime
, 0, 1, 0,
5359 doc
: /* Update buffer's recorded modification time from the visited file's time.
5360 Useful if the buffer was not read from the file normally
5361 or if the file itself has been changed for some known benign reason.
5362 An argument specifies the modification time value to use
5363 \(instead of that of the visited file), in the form of a list
5364 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5365 `visited-file-modtime'. */)
5366 (Lisp_Object time_flag
)
5368 if (!NILP (time_flag
))
5370 struct timespec mtime
;
5371 if (INTEGERP (time_flag
))
5373 CHECK_RANGED_INTEGER (time_flag
, -1, 0);
5374 mtime
= make_timespec (0, UNKNOWN_MODTIME_NSECS
- XINT (time_flag
));
5377 mtime
= lisp_time_argument (time_flag
);
5379 current_buffer
->modtime
= mtime
;
5380 current_buffer
->modtime_size
= -1;
5384 register Lisp_Object filename
;
5386 Lisp_Object handler
;
5388 filename
= Fexpand_file_name (BVAR (current_buffer
, filename
), Qnil
);
5390 /* If the file name has special constructs in it,
5391 call the corresponding file handler. */
5392 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5393 if (!NILP (handler
))
5394 /* The handler can find the file name the same way we did. */
5395 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5397 filename
= ENCODE_FILE (filename
);
5399 if (stat (SSDATA (filename
), &st
) >= 0)
5401 current_buffer
->modtime
= get_stat_mtime (&st
);
5402 current_buffer
->modtime_size
= st
.st_size
;
5410 auto_save_error (Lisp_Object error_val
)
5412 auto_save_error_occurred
= 1;
5414 ring_bell (XFRAME (selected_frame
));
5416 AUTO_STRING (format
, "Auto-saving %s: %s");
5417 Lisp_Object msg
= CALLN (Fformat
, format
, BVAR (current_buffer
, name
),
5418 Ferror_message_string (error_val
));
5419 call3 (intern ("display-warning"),
5420 intern ("auto-save"), msg
, intern ("error"));
5431 auto_save_mode_bits
= 0666;
5433 /* Get visited file's mode to become the auto save file's mode. */
5434 if (! NILP (BVAR (current_buffer
, filename
)))
5436 if (stat (SSDATA (BVAR (current_buffer
, filename
)), &st
) >= 0)
5437 /* But make sure we can overwrite it later! */
5438 auto_save_mode_bits
= (st
.st_mode
| 0600) & 0777;
5439 else if (modes
= Ffile_modes (BVAR (current_buffer
, filename
)),
5441 /* Remote files don't cooperate with stat. */
5442 auto_save_mode_bits
= (XINT (modes
) | 0600) & 0777;
5446 Fwrite_region (Qnil
, Qnil
, BVAR (current_buffer
, auto_save_file_name
), Qnil
,
5447 NILP (Vauto_save_visited_file_name
) ? Qlambda
: Qt
,
5451 struct auto_save_unwind
5458 do_auto_save_unwind (void *arg
)
5460 struct auto_save_unwind
*p
= arg
;
5461 FILE *stream
= p
->stream
;
5462 minibuffer_auto_raise
= p
->auto_raise
;
5473 do_auto_save_make_dir (Lisp_Object dir
)
5477 auto_saving_dir_umask
= 077;
5478 result
= call2 (Qmake_directory
, dir
, Qt
);
5479 auto_saving_dir_umask
= 0;
5484 do_auto_save_eh (Lisp_Object ignore
)
5486 auto_saving_dir_umask
= 0;
5490 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5491 doc
: /* Auto-save all buffers that need it.
5492 This is all buffers that have auto-saving enabled
5493 and are changed since last auto-saved.
5494 Auto-saving writes the buffer into a file
5495 so that your editing is not lost if the system crashes.
5496 This file is not the file you visited; that changes only when you save.
5497 Normally we run the normal hook `auto-save-hook' before saving.
5499 A non-nil NO-MESSAGE argument means do not print any message if successful.
5500 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5501 (Lisp_Object no_message
, Lisp_Object current_only
)
5503 struct buffer
*old
= current_buffer
, *b
;
5504 Lisp_Object tail
, buf
, hook
;
5505 bool auto_saved
= 0;
5506 int do_handled_files
;
5508 FILE *stream
= NULL
;
5509 ptrdiff_t count
= SPECPDL_INDEX ();
5510 bool orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5511 bool old_message_p
= 0;
5512 struct auto_save_unwind auto_save_unwind
;
5514 if (max_specpdl_size
< specpdl_size
+ 40)
5515 max_specpdl_size
= specpdl_size
+ 40;
5520 if (NILP (no_message
))
5522 old_message_p
= push_message ();
5523 record_unwind_protect_void (pop_message_unwind
);
5526 /* Ordinarily don't quit within this function,
5527 but don't make it impossible to quit (in case we get hung in I/O). */
5531 hook
= intern ("auto-save-hook");
5532 safe_run_hooks (hook
);
5534 if (STRINGP (Vauto_save_list_file_name
))
5536 Lisp_Object listfile
;
5538 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5540 /* Don't try to create the directory when shutting down Emacs,
5541 because creating the directory might signal an error, and
5542 that would leave Emacs in a strange state. */
5543 if (!NILP (Vrun_hooks
))
5546 dir
= Ffile_name_directory (listfile
);
5547 if (NILP (Ffile_directory_p (dir
)))
5548 internal_condition_case_1 (do_auto_save_make_dir
,
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;
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
)
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)
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
);
5595 if (!NILP (current_only
)
5596 && b
!= current_buffer
)
5599 /* Don't auto-save indirect buffers.
5600 The base buffer takes care of it. */
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
),
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)
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",
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
);
5646 if (!auto_saved
&& NILP (no_message
))
5647 message1 ("Auto-saving...");
5648 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
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
))
5670 /* If we are going to restore an old message,
5671 give time to read ours. */
5672 sit_for (make_number (1), 0, 0);
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");
5684 /* This restores the message-stack status. */
5685 unbind_to (count
, 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. */)
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;
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. */)
5708 current_buffer
->auto_save_failure_time
= 0;
5712 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
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". */)
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. */)
5734 #if (defined USE_GTK || defined USE_MOTIF \
5735 || defined HAVE_NS || defined HAVE_NTGUI)
5736 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5739 && window_system_available (SELECTED_FRAME ()))
5746 DEFUN ("set-binary-mode", Fset_binary_mode
, Sset_binary_mode
, 2, 2, 0,
5747 doc
: /* Switch STREAM to binary I/O mode or text I/O mode.
5748 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5749 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5752 As a side effect, this function flushes any pending STREAM's data.
5754 Value is the previous value of STREAM's I/O mode, nil for text mode,
5755 non-nil for binary mode.
5757 On MS-Windows and MS-DOS, binary mode is needed to read or write
5758 arbitrary binary data, and for disabling translation between CR-LF
5759 pairs and a single newline character. Examples include generation
5760 of text files with Unix-style end-of-line format using `princ' in
5761 batch mode, with standard output redirected to a file.
5763 On Posix systems, this function always returns non-nil, and has no
5764 effect except for flushing STREAM's data. */)
5765 (Lisp_Object stream
, Lisp_Object mode
)
5770 CHECK_SYMBOL (stream
);
5771 if (EQ (stream
, Qstdin
))
5773 else if (EQ (stream
, Qstdout
))
5775 else if (EQ (stream
, Qstderr
))
5778 xsignal2 (Qerror
, build_string ("unsupported stream"), stream
);
5780 binmode
= NILP (mode
) ? O_TEXT
: O_BINARY
;
5784 return (set_binary_mode (fileno (fp
), binmode
) == O_BINARY
) ? Qt
: Qnil
;
5790 realmask
= umask (0);
5793 valid_timestamp_file_system
= 0;
5795 /* fsync can be a significant performance hit. Often it doesn't
5796 suffice to make the file-save operation survive a crash. For
5797 batch scripts, which are typically part of larger shell commands
5798 that don't fsync other files, its effect on performance can be
5799 significant so its utility is particularly questionable.
5800 Hence, for now by default fsync is used only when interactive.
5802 For more on why fsync often fails to work on today's hardware, see:
5803 Zheng M et al. Understanding the robustness of SSDs under power fault.
5804 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5805 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5807 For more on why fsync does not suffice even if it works properly, see:
5808 Roche X. Necessary step(s) to synchronize filename operations on disk.
5809 Austin Group Defect 672, 2013-03-19
5810 http://austingroupbugs.net/view.php?id=672 */
5811 write_region_inhibit_fsync
= noninteractive
;
5815 syms_of_fileio (void)
5817 /* Property name of a file name handler,
5818 which gives a list of operations it handles. */
5819 DEFSYM (Qoperations
, "operations");
5821 DEFSYM (Qexpand_file_name
, "expand-file-name");
5822 DEFSYM (Qsubstitute_in_file_name
, "substitute-in-file-name");
5823 DEFSYM (Qdirectory_file_name
, "directory-file-name");
5824 DEFSYM (Qfile_name_directory
, "file-name-directory");
5825 DEFSYM (Qfile_name_nondirectory
, "file-name-nondirectory");
5826 DEFSYM (Qunhandled_file_name_directory
, "unhandled-file-name-directory");
5827 DEFSYM (Qfile_name_as_directory
, "file-name-as-directory");
5828 DEFSYM (Qcopy_file
, "copy-file");
5829 DEFSYM (Qmake_directory_internal
, "make-directory-internal");
5830 DEFSYM (Qmake_directory
, "make-directory");
5831 DEFSYM (Qdelete_file
, "delete-file");
5832 DEFSYM (Qrename_file
, "rename-file");
5833 DEFSYM (Qadd_name_to_file
, "add-name-to-file");
5834 DEFSYM (Qmake_symbolic_link
, "make-symbolic-link");
5835 DEFSYM (Qfile_exists_p
, "file-exists-p");
5836 DEFSYM (Qfile_executable_p
, "file-executable-p");
5837 DEFSYM (Qfile_readable_p
, "file-readable-p");
5838 DEFSYM (Qfile_writable_p
, "file-writable-p");
5839 DEFSYM (Qfile_symlink_p
, "file-symlink-p");
5840 DEFSYM (Qaccess_file
, "access-file");
5841 DEFSYM (Qfile_directory_p
, "file-directory-p");
5842 DEFSYM (Qfile_regular_p
, "file-regular-p");
5843 DEFSYM (Qfile_accessible_directory_p
, "file-accessible-directory-p");
5844 DEFSYM (Qfile_modes
, "file-modes");
5845 DEFSYM (Qset_file_modes
, "set-file-modes");
5846 DEFSYM (Qset_file_times
, "set-file-times");
5847 DEFSYM (Qfile_selinux_context
, "file-selinux-context");
5848 DEFSYM (Qset_file_selinux_context
, "set-file-selinux-context");
5849 DEFSYM (Qfile_acl
, "file-acl");
5850 DEFSYM (Qset_file_acl
, "set-file-acl");
5851 DEFSYM (Qfile_newer_than_file_p
, "file-newer-than-file-p");
5852 DEFSYM (Qinsert_file_contents
, "insert-file-contents");
5853 DEFSYM (Qwrite_region
, "write-region");
5854 DEFSYM (Qverify_visited_file_modtime
, "verify-visited-file-modtime");
5855 DEFSYM (Qset_visited_file_modtime
, "set-visited-file-modtime");
5857 /* The symbol bound to coding-system-for-read when
5858 insert-file-contents is called for recovering a file. This is not
5859 an actual coding system name, but just an indicator to tell
5860 insert-file-contents to use `emacs-mule' with a special flag for
5861 auto saving and recovering a file. */
5862 DEFSYM (Qauto_save_coding
, "auto-save-coding");
5864 DEFSYM (Qfile_name_history
, "file-name-history");
5865 Fset (Qfile_name_history
, Qnil
);
5867 DEFSYM (Qfile_error
, "file-error");
5868 DEFSYM (Qfile_already_exists
, "file-already-exists");
5869 DEFSYM (Qfile_date_error
, "file-date-error");
5870 DEFSYM (Qfile_notify_error
, "file-notify-error");
5871 DEFSYM (Qexcl
, "excl");
5873 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system
,
5874 doc
: /* Coding system for encoding file names.
5875 If it is nil, `default-file-name-coding-system' (which see) is used.
5877 On MS-Windows, the value of this variable is largely ignored if
5878 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5879 behaves as if file names were encoded in `utf-8'. */);
5880 Vfile_name_coding_system
= Qnil
;
5882 DEFVAR_LISP ("default-file-name-coding-system",
5883 Vdefault_file_name_coding_system
,
5884 doc
: /* Default coding system for encoding file names.
5885 This variable is used only when `file-name-coding-system' is nil.
5887 This variable is set/changed by the command `set-language-environment'.
5888 User should not set this variable manually,
5889 instead use `file-name-coding-system' to get a constant encoding
5890 of file names regardless of the current language environment.
5892 On MS-Windows, the value of this variable is largely ignored if
5893 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5894 behaves as if file names were encoded in `utf-8'. */);
5895 Vdefault_file_name_coding_system
= Qnil
;
5897 /* Lisp functions for translating file formats. */
5898 DEFSYM (Qformat_decode
, "format-decode");
5899 DEFSYM (Qformat_annotate_function
, "format-annotate-function");
5901 /* Lisp function for setting buffer-file-coding-system and the
5902 multibyteness of the current buffer after inserting a file. */
5903 DEFSYM (Qafter_insert_file_set_coding
, "after-insert-file-set-coding");
5905 DEFSYM (Qcar_less_than_car
, "car-less-than-car");
5907 Fput (Qfile_error
, Qerror_conditions
,
5908 Fpurecopy (list2 (Qfile_error
, Qerror
)));
5909 Fput (Qfile_error
, Qerror_message
,
5910 build_pure_c_string ("File error"));
5912 Fput (Qfile_already_exists
, Qerror_conditions
,
5913 Fpurecopy (list3 (Qfile_already_exists
, Qfile_error
, Qerror
)));
5914 Fput (Qfile_already_exists
, Qerror_message
,
5915 build_pure_c_string ("File already exists"));
5917 Fput (Qfile_date_error
, Qerror_conditions
,
5918 Fpurecopy (list3 (Qfile_date_error
, Qfile_error
, Qerror
)));
5919 Fput (Qfile_date_error
, Qerror_message
,
5920 build_pure_c_string ("Cannot set file date"));
5922 Fput (Qfile_notify_error
, Qerror_conditions
,
5923 Fpurecopy (list3 (Qfile_notify_error
, Qfile_error
, Qerror
)));
5924 Fput (Qfile_notify_error
, Qerror_message
,
5925 build_pure_c_string ("File notification error"));
5927 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist
,
5928 doc
: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5929 If a file name matches REGEXP, all I/O on that file is done by calling
5930 HANDLER. If a file name matches more than one handler, the handler
5931 whose match starts last in the file name gets precedence. The
5932 function `find-file-name-handler' checks this list for a handler for
5935 HANDLER should be a function. The first argument given to it is the
5936 name of the I/O primitive to be handled; the remaining arguments are
5937 the arguments that were passed to that primitive. For example, if you
5938 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5939 HANDLER is called like this:
5941 (funcall HANDLER \\='file-exists-p FILENAME)
5943 Note that HANDLER must be able to handle all I/O primitives; if it has
5944 nothing special to do for a primitive, it should reinvoke the
5945 primitive to handle the operation \"the usual way\".
5946 See Info node `(elisp)Magic File Names' for more details. */);
5947 Vfile_name_handler_alist
= Qnil
;
5949 DEFVAR_LISP ("set-auto-coding-function",
5950 Vset_auto_coding_function
,
5951 doc
: /* If non-nil, a function to call to decide a coding system of file.
5952 Two arguments are passed to this function: the file name
5953 and the length of a file contents following the point.
5954 This function should return a coding system to decode the file contents.
5955 It should check the file name against `auto-coding-alist'.
5956 If no coding system is decided, it should check a coding system
5957 specified in the heading lines with the format:
5958 -*- ... coding: CODING-SYSTEM; ... -*-
5959 or local variable spec of the tailing lines with `coding:' tag. */);
5960 Vset_auto_coding_function
= Qnil
;
5962 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions
,
5963 doc
: /* A list of functions to be called at the end of `insert-file-contents'.
5964 Each is passed one argument, the number of characters inserted,
5965 with point at the start of the inserted text. Each function
5966 should leave point the same, and return the new character count.
5967 If `insert-file-contents' is intercepted by a handler from
5968 `file-name-handler-alist', that handler is responsible for calling the
5969 functions in `after-insert-file-functions' if appropriate. */);
5970 Vafter_insert_file_functions
= Qnil
;
5972 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions
,
5973 doc
: /* A list of functions to be called at the start of `write-region'.
5974 Each is passed two arguments, START and END as for `write-region'.
5975 These are usually two numbers but not always; see the documentation
5976 for `write-region'. The function should return a list of pairs
5977 of the form (POSITION . STRING), consisting of strings to be effectively
5978 inserted at the specified positions of the file being written (1 means to
5979 insert before the first byte written). The POSITIONs must be sorted into
5982 If there are several annotation functions, the lists returned by these
5983 functions are merged destructively. As each annotation function runs,
5984 the variable `write-region-annotations-so-far' contains a list of all
5985 annotations returned by previous annotation functions.
5987 An annotation function can return with a different buffer current.
5988 Doing so removes the annotations returned by previous functions, and
5989 resets START and END to `point-min' and `point-max' of the new buffer.
5991 After `write-region' completes, Emacs calls the function stored in
5992 `write-region-post-annotation-function', once for each buffer that was
5993 current when building the annotations (i.e., at least once), with that
5994 buffer current. */);
5995 Vwrite_region_annotate_functions
= Qnil
;
5996 DEFSYM (Qwrite_region_annotate_functions
, "write-region-annotate-functions");
5998 DEFVAR_LISP ("write-region-post-annotation-function",
5999 Vwrite_region_post_annotation_function
,
6000 doc
: /* Function to call after `write-region' completes.
6001 The function is called with no arguments. If one or more of the
6002 annotation functions in `write-region-annotate-functions' changed the
6003 current buffer, the function stored in this variable is called for
6004 each of those additional buffers as well, in addition to the original
6005 buffer. The relevant buffer is current during each function call. */);
6006 Vwrite_region_post_annotation_function
= Qnil
;
6007 staticpro (&Vwrite_region_annotation_buffers
);
6009 DEFVAR_LISP ("write-region-annotations-so-far",
6010 Vwrite_region_annotations_so_far
,
6011 doc
: /* When an annotation function is called, this holds the previous annotations.
6012 These are the annotations made by other annotation functions
6013 that were already called. See also `write-region-annotate-functions'. */);
6014 Vwrite_region_annotations_so_far
= Qnil
;
6016 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers
,
6017 doc
: /* A list of file name handlers that temporarily should not be used.
6018 This applies only to the operation `inhibit-file-name-operation'. */);
6019 Vinhibit_file_name_handlers
= Qnil
;
6021 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation
,
6022 doc
: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6023 Vinhibit_file_name_operation
= Qnil
;
6025 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name
,
6026 doc
: /* File name in which we write a list of all auto save file names.
6027 This variable is initialized automatically from `auto-save-list-file-prefix'
6028 shortly after Emacs reads your init file, if you have not yet given it
6029 a non-nil value. */);
6030 Vauto_save_list_file_name
= Qnil
;
6032 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name
,
6033 doc
: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6034 Normally auto-save files are written under other names. */);
6035 Vauto_save_visited_file_name
= Qnil
;
6037 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions
,
6038 doc
: /* If non-nil, auto-save even if a large part of the text is deleted.
6039 If nil, deleting a substantial portion of the text disables auto-save
6040 in the buffer; this is the default behavior, because the auto-save
6041 file is usually more useful if it contains the deleted text. */);
6042 Vauto_save_include_big_deletions
= Qnil
;
6044 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync
,
6045 doc
: /* Non-nil means don't call fsync in `write-region'.
6046 This variable affects calls to `write-region' as well as save commands.
6047 Setting this to nil may avoid data loss if the system loses power or
6048 the operating system crashes. By default, it is non-nil in batch mode. */);
6049 write_region_inhibit_fsync
= 0; /* See also `init_fileio' above. */
6051 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash
,
6052 doc
: /* Specifies whether to use the system's trash can.
6053 When non-nil, certain file deletion commands use the function
6054 `move-file-to-trash' instead of deleting files outright.
6055 This includes interactive calls to `delete-file' and
6056 `delete-directory' and the Dired deletion commands. */);
6057 delete_by_moving_to_trash
= 0;
6058 DEFSYM (Qdelete_by_moving_to_trash
, "delete-by-moving-to-trash");
6060 /* Lisp function for moving files to trash. */
6061 DEFSYM (Qmove_file_to_trash
, "move-file-to-trash");
6063 /* Lisp function for recursively copying directories. */
6064 DEFSYM (Qcopy_directory
, "copy-directory");
6066 /* Lisp function for recursively deleting directories. */
6067 DEFSYM (Qdelete_directory
, "delete-directory");
6069 DEFSYM (Qsubstitute_env_in_file_name
, "substitute-env-in-file-name");
6070 DEFSYM (Qget_buffer_window_list
, "get-buffer-window-list");
6072 DEFSYM (Qstdin
, "stdin");
6073 DEFSYM (Qstdout
, "stdout");
6074 DEFSYM (Qstderr
, "stderr");
6076 defsubr (&Sfind_file_name_handler
);
6077 defsubr (&Sfile_name_directory
);
6078 defsubr (&Sfile_name_nondirectory
);
6079 defsubr (&Sunhandled_file_name_directory
);
6080 defsubr (&Sfile_name_as_directory
);
6081 defsubr (&Sdirectory_file_name
);
6082 defsubr (&Smake_temp_name
);
6083 defsubr (&Sexpand_file_name
);
6084 defsubr (&Ssubstitute_in_file_name
);
6085 defsubr (&Scopy_file
);
6086 defsubr (&Smake_directory_internal
);
6087 defsubr (&Sdelete_directory_internal
);
6088 defsubr (&Sdelete_file
);
6089 defsubr (&Srename_file
);
6090 defsubr (&Sadd_name_to_file
);
6091 defsubr (&Smake_symbolic_link
);
6092 defsubr (&Sfile_name_absolute_p
);
6093 defsubr (&Sfile_exists_p
);
6094 defsubr (&Sfile_executable_p
);
6095 defsubr (&Sfile_readable_p
);
6096 defsubr (&Sfile_writable_p
);
6097 defsubr (&Saccess_file
);
6098 defsubr (&Sfile_symlink_p
);
6099 defsubr (&Sfile_directory_p
);
6100 defsubr (&Sfile_accessible_directory_p
);
6101 defsubr (&Sfile_regular_p
);
6102 defsubr (&Sfile_modes
);
6103 defsubr (&Sset_file_modes
);
6104 defsubr (&Sset_file_times
);
6105 defsubr (&Sfile_selinux_context
);
6106 defsubr (&Sfile_acl
);
6107 defsubr (&Sset_file_acl
);
6108 defsubr (&Sset_file_selinux_context
);
6109 defsubr (&Sset_default_file_modes
);
6110 defsubr (&Sdefault_file_modes
);
6111 defsubr (&Sfile_newer_than_file_p
);
6112 defsubr (&Sinsert_file_contents
);
6113 defsubr (&Swrite_region
);
6114 defsubr (&Scar_less_than_car
);
6115 defsubr (&Sverify_visited_file_modtime
);
6116 defsubr (&Svisited_file_modtime
);
6117 defsubr (&Sset_visited_file_modtime
);
6118 defsubr (&Sdo_auto_save
);
6119 defsubr (&Sset_buffer_auto_saved
);
6120 defsubr (&Sclear_buffer_auto_save_failure
);
6121 defsubr (&Srecent_auto_save_p
);
6123 defsubr (&Snext_read_file_uses_dialog_p
);
6125 defsubr (&Sset_binary_mode
);
6128 defsubr (&Sunix_sync
);