1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2018 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 <https://www.gnu.org/licenses/>. */
24 #include <sys/types.h>
38 #ifdef HAVE_LIBSELINUX
39 #include <selinux/selinux.h>
40 #include <selinux/context.h>
43 #if USE_ACL && defined HAVE_ACL_SET_FILE
50 #include "composite.h"
51 #include "character.h"
55 #include "blockinput.h"
56 #include "region-cache.h"
59 #ifdef HAVE_LINUX_FS_H
60 # include <sys/ioctl.h>
61 # include <linux/fs.h>
67 /* The redundant #ifdef is to avoid compiler warning about unused macro. */
73 #endif /* not WINDOWSNT */
77 #include <sys/param.h>
81 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
82 redirector allows the six letters between 'Z' and 'a' as well. */
84 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
87 #define IS_DRIVE(x) c_isalpha (x)
89 /* Need to lower-case the drive letter, or else expanded
90 filenames will sometimes compare unequal, because
91 `expand-file-name' doesn't always down-case the drive letter. */
92 #define DRIVE_LETTER(x) c_tolower (x)
97 #include <allocator.h>
98 #include <careadlinkat.h>
100 #include <stat-time.h>
101 #include <tempname.h>
103 #include <binary-io.h>
109 #include "commands.h"
111 /* True during writing of auto-save files. */
112 static bool auto_saving
;
114 /* Emacs's real umask. */
115 static mode_t realmask
;
117 /* Nonzero umask during creation of auto-save directories. */
118 static mode_t auto_saving_dir_umask
;
120 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
121 a new file with the same mode as the original. */
122 static mode_t auto_save_mode_bits
;
124 /* Set by auto_save_1 if an error occurred during the last auto-save. */
125 static bool auto_save_error_occurred
;
127 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
128 number of a file system where time stamps were observed to work. */
129 static bool valid_timestamp_file_system
;
130 static dev_t timestamp_file_system
;
132 /* Each time an annotation function changes the buffer, the new buffer
134 static Lisp_Object Vwrite_region_annotation_buffers
;
136 static bool a_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
137 Lisp_Object
*, struct coding_system
*);
138 static bool e_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
139 struct coding_system
*);
142 /* Return true if FILENAME exists, otherwise return false and set errno. */
145 check_existing (const char *filename
)
147 return faccessat (AT_FDCWD
, filename
, F_OK
, AT_EACCESS
) == 0;
150 /* Return true if file FILENAME exists and can be executed. */
153 check_executable (char *filename
)
155 return faccessat (AT_FDCWD
, filename
, X_OK
, AT_EACCESS
) == 0;
158 /* Return true if file FILENAME exists and can be accessed
159 according to AMODE, which should include W_OK.
160 On failure, return false and set errno. */
163 check_writable (const char *filename
, int amode
)
166 /* FIXME: an faccessat implementation should be added to the
167 DOS/Windows ports and this #ifdef branch should be removed. */
169 if (stat (filename
, &st
) < 0)
172 return (st
.st_mode
& S_IWRITE
|| S_ISDIR (st
.st_mode
));
173 #else /* not MSDOS */
174 bool res
= faccessat (AT_FDCWD
, filename
, amode
, AT_EACCESS
) == 0;
176 /* faccessat may have returned failure because Cygwin couldn't
177 determine the file's UID or GID; if so, we return success. */
180 int faccessat_errno
= errno
;
182 if (stat (filename
, &st
) < 0)
184 res
= (st
.st_uid
== -1 || st
.st_gid
== -1);
185 errno
= faccessat_errno
;
189 #endif /* not MSDOS */
192 /* Signal a file-access failure. STRING describes the failure,
193 NAME the file involved, and ERRORNO the errno value.
195 If NAME is neither null nor a pair, package it up as a singleton
196 list before reporting it; this saves report_file_errno's caller the
197 trouble of preserving errno before calling list1. */
200 report_file_errno (char const *string
, Lisp_Object name
, int errorno
)
202 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
203 char *str
= emacs_strerror (errorno
);
204 AUTO_STRING (unibyte_str
, str
);
205 Lisp_Object errstring
206 = code_convert_string_norecord (unibyte_str
, Vlocale_coding_system
, 0);
207 Lisp_Object errdata
= Fcons (errstring
, data
);
209 if (errorno
== EEXIST
)
210 xsignal (Qfile_already_exists
, errdata
);
212 xsignal (errorno
== ENOENT
? Qfile_missing
: Qfile_error
,
213 Fcons (build_string (string
), errdata
));
216 /* Signal a file-access failure that set errno. STRING describes the
217 failure, NAME the file involved. When invoking this function, take
218 care to not use arguments such as build_string ("foo") that involve
219 side effects that may set errno. */
222 report_file_error (char const *string
, Lisp_Object name
)
224 report_file_errno (string
, name
, errno
);
227 #ifdef USE_FILE_NOTIFY
228 /* Like report_file_error, but reports a file-notify-error instead. */
231 report_file_notify_error (const char *string
, Lisp_Object name
)
233 char *str
= emacs_strerror (errno
);
234 AUTO_STRING (unibyte_str
, str
);
235 Lisp_Object errstring
236 = code_convert_string_norecord (unibyte_str
, Vlocale_coding_system
, 0);
237 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
238 Lisp_Object errdata
= Fcons (errstring
, data
);
240 xsignal (Qfile_notify_error
, Fcons (build_string (string
), errdata
));
245 close_file_unwind (int fd
)
251 fclose_unwind (void *arg
)
257 /* Restore point, having saved it as a marker. */
260 restore_point_unwind (Lisp_Object location
)
262 Fgoto_char (location
);
263 unchain_marker (XMARKER (location
));
267 DEFUN ("find-file-name-handler", Ffind_file_name_handler
,
268 Sfind_file_name_handler
, 2, 2, 0,
269 doc
: /* Return FILENAME's handler function for OPERATION, if it has one.
270 Otherwise, return nil.
271 A file name is handled if one of the regular expressions in
272 `file-name-handler-alist' matches it.
274 If OPERATION equals `inhibit-file-name-operation', then ignore
275 any handlers that are members of `inhibit-file-name-handlers',
276 but still do run any other handlers. This lets handlers
277 use the standard functions without calling themselves recursively. */)
278 (Lisp_Object filename
, Lisp_Object operation
)
280 /* This function must not munge the match data. */
281 Lisp_Object chain
, inhibited_handlers
, result
;
285 CHECK_STRING (filename
);
287 if (EQ (operation
, Vinhibit_file_name_operation
))
288 inhibited_handlers
= Vinhibit_file_name_handlers
;
290 inhibited_handlers
= Qnil
;
292 for (chain
= Vfile_name_handler_alist
; CONSP (chain
);
293 chain
= XCDR (chain
))
299 Lisp_Object string
= XCAR (elt
);
301 Lisp_Object handler
= XCDR (elt
);
302 Lisp_Object operations
= Qnil
;
304 if (SYMBOLP (handler
))
305 operations
= Fget (handler
, Qoperations
);
308 && (match_pos
= fast_string_match (string
, filename
)) > pos
309 && (NILP (operations
) || ! NILP (Fmemq (operation
, operations
))))
313 handler
= XCDR (elt
);
314 tem
= Fmemq (handler
, inhibited_handlers
);
328 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
330 doc
: /* Return the directory component in file name FILENAME.
331 Return nil if FILENAME does not include a directory.
332 Otherwise return a directory name.
333 Given a Unix syntax file name, returns a string ending in slash. */)
334 (Lisp_Object filename
)
338 CHECK_STRING (filename
);
340 /* If the file name has special constructs in it,
341 call the corresponding file handler. */
342 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
345 Lisp_Object handled_name
= call2 (handler
, Qfile_name_directory
,
347 return STRINGP (handled_name
) ? handled_name
: Qnil
;
350 char *beg
= SSDATA (filename
);
351 char const *p
= beg
+ SBYTES (filename
);
353 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
355 /* only recognize drive specifier at the beginning */
357 /* handle the "/:d:foo" and "/:foo" cases correctly */
358 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
359 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
366 /* Expansion of "c:" to drive and default directory. */
369 SAFE_ALLOCA_STRING (beg
, filename
);
370 p
= beg
+ (p
- SSDATA (filename
));
374 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
375 char *res
= alloca (MAXPATHLEN
+ 1);
378 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
380 memcpy (res
, beg
, 2);
385 if (getdefdir (c_toupper (*beg
) - 'A' + 1, r
))
387 size_t l
= strlen (res
);
389 if (l
> 3 || !IS_DIRECTORY_SEP (res
[l
- 1]))
392 p
= beg
+ strlen (beg
);
393 dostounix_filename (beg
);
394 tem_fn
= make_specified_string (beg
, -1, p
- beg
,
395 STRING_MULTIBYTE (filename
));
398 tem_fn
= make_specified_string (beg
- 2, -1, p
- beg
+ 2,
399 STRING_MULTIBYTE (filename
));
401 else if (STRING_MULTIBYTE (filename
))
403 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 1);
404 dostounix_filename (SSDATA (tem_fn
));
406 if (!NILP (Vw32_downcase_file_names
))
407 tem_fn
= Fdowncase (tem_fn
);
412 dostounix_filename (beg
);
413 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 0);
418 return make_specified_string (beg
, -1, p
- beg
, STRING_MULTIBYTE (filename
));
422 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
423 Sfile_name_nondirectory
, 1, 1, 0,
424 doc
: /* Return file name FILENAME sans its directory.
425 For example, in a Unix-syntax file name,
426 this is everything after the last slash,
427 or the entire name if it contains no slash. */)
428 (Lisp_Object filename
)
430 register const char *beg
, *p
, *end
;
433 CHECK_STRING (filename
);
435 /* If the file name has special constructs in it,
436 call the corresponding file handler. */
437 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
440 Lisp_Object handled_name
= call2 (handler
, Qfile_name_nondirectory
,
442 if (STRINGP (handled_name
))
444 error ("Invalid handler in `file-name-handler-alist'");
447 beg
= SSDATA (filename
);
448 end
= p
= beg
+ SBYTES (filename
);
450 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
452 /* only recognize drive specifier at beginning */
454 /* handle the "/:d:foo" case correctly */
455 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
460 return make_specified_string (p
, -1, end
- p
, STRING_MULTIBYTE (filename
));
463 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
464 Sunhandled_file_name_directory
, 1, 1, 0,
465 doc
: /* Return a directly usable directory name somehow associated with FILENAME.
466 A `directly usable' directory name is one that may be used without the
467 intervention of any file handler.
468 If FILENAME is a directly usable file itself, return
469 \(file-name-as-directory FILENAME).
470 If FILENAME refers to a file which is not accessible from a local process,
471 then this should return nil.
472 The `call-process' and `start-process' functions use this function to
473 get a current directory to run processes in. */)
474 (Lisp_Object filename
)
478 /* If the file name has special constructs in it,
479 call the corresponding file handler. */
480 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
483 Lisp_Object handled_name
= call2 (handler
, Qunhandled_file_name_directory
,
485 return STRINGP (handled_name
) ? handled_name
: Qnil
;
488 return Ffile_name_as_directory (filename
);
491 /* Maximum number of bytes that DST will be longer than SRC
492 in file_name_as_directory. This occurs when SRCLEN == 0. */
493 enum { file_name_as_directory_slop
= 2 };
495 /* Convert from file name SRC of length SRCLEN to directory name in
496 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
497 string. On UNIX, just make sure there is a terminating /. Return
498 the length of DST in bytes. */
501 file_name_as_directory (char *dst
, const char *src
, ptrdiff_t srclen
,
512 memcpy (dst
, src
, srclen
);
513 if (!IS_DIRECTORY_SEP (dst
[srclen
- 1]))
514 dst
[srclen
++] = DIRECTORY_SEP
;
517 dostounix_filename (dst
);
522 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
523 Sfile_name_as_directory
, 1, 1, 0,
524 doc
: /* Return a string representing the file name FILE interpreted as a directory.
525 This operation exists because a directory is also a file, but its name as
526 a directory is different from its name as a file.
527 The result can be used as the value of `default-directory'
528 or passed as second argument to `expand-file-name'.
529 For a Unix-syntax file name, just appends a slash unless a trailing slash
530 is already present. */)
535 Lisp_Object handler
, val
;
540 /* If the file name has special constructs in it,
541 call the corresponding file handler. */
542 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
545 Lisp_Object handled_name
= call2 (handler
, Qfile_name_as_directory
,
547 if (STRINGP (handled_name
))
549 error ("Invalid handler in `file-name-handler-alist'");
553 if (!NILP (Vw32_downcase_file_names
))
554 file
= Fdowncase (file
);
556 buf
= SAFE_ALLOCA (SBYTES (file
) + file_name_as_directory_slop
+ 1);
557 length
= file_name_as_directory (buf
, SSDATA (file
), SBYTES (file
),
558 STRING_MULTIBYTE (file
));
559 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (file
));
564 /* Convert from directory name SRC of length SRCLEN to file name in
565 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
566 string. On UNIX, just make sure there isn't a terminating /.
567 Return the length of DST in bytes. */
570 directory_file_name (char *dst
, char *src
, ptrdiff_t srclen
, bool multibyte
)
572 /* In Unix-like systems, just remove any final slashes. However, if
573 they are all slashes, leave "/" and "//" alone, and treat "///"
574 and longer as if they were "/". */
575 if (! (srclen
== 2 && IS_DIRECTORY_SEP (src
[0])))
578 && !(srclen
> 2 && IS_DEVICE_SEP (src
[srclen
- 2]))
580 && IS_DIRECTORY_SEP (src
[srclen
- 1]))
583 memcpy (dst
, src
, srclen
);
586 dostounix_filename (dst
);
591 DEFUN ("directory-name-p", Fdirectory_name_p
, Sdirectory_name_p
, 1, 1, 0,
592 doc
: /* Return non-nil if NAME ends with a directory separator character. */)
596 ptrdiff_t namelen
= SBYTES (name
);
597 unsigned char c
= namelen
? SREF (name
, namelen
- 1) : 0;
598 return IS_DIRECTORY_SEP (c
) ? Qt
: Qnil
;
601 /* Return the expansion of NEWNAME, except that if NEWNAME is a
602 directory name then return the expansion of FILE's basename under
603 NEWNAME. This resembles how 'cp FILE NEWNAME' works, except that
604 it requires NEWNAME to be a directory name (typically, by ending in
608 expand_cp_target (Lisp_Object file
, Lisp_Object newname
)
610 return (!NILP (Fdirectory_name_p (newname
))
611 ? Fexpand_file_name (Ffile_name_nondirectory (file
), newname
)
612 : Fexpand_file_name (newname
, Qnil
));
615 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
617 doc
: /* Returns the file name of the directory named DIRECTORY.
618 This is the name of the file that holds the data for the directory DIRECTORY.
619 This operation exists because a directory is also a file, but its name as
620 a directory is different from its name as a file.
621 In Unix-syntax, this function just removes the final slash. */)
622 (Lisp_Object directory
)
626 Lisp_Object handler
, val
;
629 CHECK_STRING (directory
);
631 /* If the file name has special constructs in it,
632 call the corresponding file handler. */
633 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
636 Lisp_Object handled_name
= call2 (handler
, Qdirectory_file_name
,
638 if (STRINGP (handled_name
))
640 error ("Invalid handler in `file-name-handler-alist'");
644 if (!NILP (Vw32_downcase_file_names
))
645 directory
= Fdowncase (directory
);
647 buf
= SAFE_ALLOCA (SBYTES (directory
) + 1);
648 length
= directory_file_name (buf
, SSDATA (directory
), SBYTES (directory
),
649 STRING_MULTIBYTE (directory
));
650 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (directory
));
655 DEFUN ("make-temp-file-internal", Fmake_temp_file_internal
,
656 Smake_temp_file_internal
, 4, 4, 0,
657 doc
: /* Generate a new file whose name starts with PREFIX, a string.
658 Return the name of the generated file. If DIR-FLAG is zero, do not
659 create the file, just its name. Otherwise, if DIR-FLAG is non-nil,
660 create an empty directory. The file name should end in SUFFIX.
661 Do not expand PREFIX; a non-absolute PREFIX is relative to the Emacs
662 working directory. If TEXT is a string, insert it into the newly
665 Signal an error if the file could not be created.
667 This function does not grok magic file names. */)
668 (Lisp_Object prefix
, Lisp_Object dir_flag
, Lisp_Object suffix
,
671 CHECK_STRING (prefix
);
672 CHECK_STRING (suffix
);
673 Lisp_Object encoded_prefix
= ENCODE_FILE (prefix
);
674 Lisp_Object encoded_suffix
= ENCODE_FILE (suffix
);
675 ptrdiff_t prefix_len
= SBYTES (encoded_prefix
);
676 ptrdiff_t suffix_len
= SBYTES (encoded_suffix
);
677 if (INT_MAX
< suffix_len
)
678 args_out_of_range (prefix
, suffix
);
680 Lisp_Object val
= make_uninit_string (prefix_len
+ nX
+ suffix_len
);
681 char *data
= SSDATA (val
);
682 memcpy (data
, SSDATA (encoded_prefix
), prefix_len
);
683 memset (data
+ prefix_len
, 'X', nX
);
684 memcpy (data
+ prefix_len
+ nX
, SSDATA (encoded_suffix
), suffix_len
);
685 int kind
= (NILP (dir_flag
) ? GT_FILE
686 : EQ (dir_flag
, make_number (0)) ? GT_NOCREATE
688 int fd
= gen_tempname (data
, suffix_len
, O_BINARY
| O_CLOEXEC
, kind
);
689 bool failed
= fd
< 0;
692 ptrdiff_t count
= SPECPDL_INDEX ();
693 record_unwind_protect_int (close_file_unwind
, fd
);
694 val
= DECODE_FILE (val
);
695 if (STRINGP (text
) && SBYTES (text
) != 0)
696 write_region (text
, Qnil
, val
, Qnil
, Qnil
, Qnil
, Qnil
, fd
);
697 failed
= NILP (dir_flag
) && emacs_close (fd
) != 0;
698 /* Discard the unwind protect. */
699 specpdl_ptr
= specpdl
+ count
;
703 static char const kind_message
[][32] =
705 [GT_FILE
] = "Creating file with prefix",
706 [GT_DIR
] = "Creating directory with prefix",
707 [GT_NOCREATE
] = "Creating file name with prefix"
709 report_file_error (kind_message
[kind
], prefix
);
715 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
716 doc
: /* Generate temporary file name (string) starting with PREFIX (a string).
718 This function tries to choose a name that has no existing file.
719 For this to work, PREFIX should be an absolute file name, and PREFIX
720 and the returned string should both be non-magic.
722 There is a race condition between calling `make-temp-name' and
723 later creating the file, which opens all kinds of security holes.
724 For that reason, you should normally use `make-temp-file' instead. */)
727 return Fmake_temp_file_internal (prefix
, make_number (0),
728 empty_unibyte_string
, Qnil
);
731 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
732 doc
: /* Convert filename NAME to absolute, and canonicalize it.
733 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
734 \(does not start with slash or tilde); both the directory name and
735 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
736 missing, the current buffer's value of `default-directory' is used.
737 NAME should be a string that is a valid file name for the underlying
739 File name components that are `.' are removed, and
740 so are file name components followed by `..', along with the `..' itself;
741 note that these simplifications are done without checking the resulting
742 file names in the file system.
743 Multiple consecutive slashes are collapsed into a single slash,
744 except at the beginning of the file name when they are significant (e.g.,
745 UNC file names on MS-Windows.)
746 An initial `~/' expands to your home directory.
747 An initial `~USER/' expands to USER's home directory.
748 See also the function `substitute-in-file-name'.
750 For technical reasons, this function can return correct but
751 non-intuitive results for the root directory; for instance,
752 \(expand-file-name ".." "/") returns "/..". For this reason, use
753 \(directory-file-name (file-name-directory dirname)) to traverse a
754 filesystem tree, not (expand-file-name ".." dirname). Note: make
755 sure DIRNAME in this example doesn't end in a slash, unless it's
756 the root directory. */)
757 (Lisp_Object name
, Lisp_Object default_directory
)
759 /* These point to SDATA and need to be careful with string-relocation
760 during GC (via DECODE_FILE). */
764 const char *newdirlim
;
765 /* This should only point to alloca'd data. */
772 bool collapse_newdir
= true;
775 ptrdiff_t length
, nbytes
;
776 Lisp_Object handler
, result
, handled_name
;
783 /* If the file name has special constructs in it,
784 call the corresponding file handler. */
785 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
788 handled_name
= call3 (handler
, Qexpand_file_name
,
789 name
, default_directory
);
790 if (STRINGP (handled_name
))
792 error ("Invalid handler in `file-name-handler-alist'");
796 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
797 if (NILP (default_directory
))
798 default_directory
= BVAR (current_buffer
, directory
);
799 if (! STRINGP (default_directory
))
802 /* "/" is not considered a root directory on DOS_NT, so using "/"
803 here causes an infinite recursion in, e.g., the following:
805 (let (default-directory)
806 (expand-file-name "a"))
808 To avoid this, we set default_directory to the root of the
810 default_directory
= build_string (emacs_root_dir ());
812 default_directory
= build_string ("/");
816 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
819 handled_name
= call3 (handler
, Qexpand_file_name
,
820 name
, default_directory
);
821 if (STRINGP (handled_name
))
823 error ("Invalid handler in `file-name-handler-alist'");
827 char *o
= SSDATA (default_directory
);
829 /* Make sure DEFAULT_DIRECTORY is properly expanded.
830 It would be better to do this down below where we actually use
831 default_directory. Unfortunately, calling Fexpand_file_name recursively
832 could invoke GC, and the strings might be relocated. This would
833 be annoying because we have pointers into strings lying around
834 that would need adjusting, and people would add new pointers to
835 the code and forget to adjust them, resulting in intermittent bugs.
836 Putting this call here avoids all that crud.
838 The EQ test avoids infinite recursion. */
839 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
840 /* Save time in some common cases - as long as default_directory
841 is not relative, it can be canonicalized with name below (if it
842 is needed at all) without requiring it to be expanded now. */
844 /* Detect MSDOS file names with drive specifiers. */
845 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1])
846 && IS_DIRECTORY_SEP (o
[2]))
847 /* Detect escaped file names without drive spec after "/:".
848 These should not be recursively expanded, to avoid
849 including the default directory twice in the expanded
851 && ! (o
[0] == '/' && o
[1] == ':')
853 /* Detect Windows file names in UNC format. */
854 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
856 #else /* not DOS_NT */
857 /* Detect Unix absolute file names (/... alone is not absolute on
859 && ! (IS_DIRECTORY_SEP (o
[0]))
860 #endif /* not DOS_NT */
863 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
866 multibyte
= STRING_MULTIBYTE (name
);
867 bool defdir_multibyte
= STRING_MULTIBYTE (default_directory
);
868 if (multibyte
!= defdir_multibyte
)
870 /* We want to make both NAME and DEFAULT_DIRECTORY have the same
871 multibyteness. Strategy:
872 . If either NAME or DEFAULT_DIRECTORY is pure-ASCII, they
873 can be converted to the multibyteness of the other one
874 while keeping the same byte sequence.
875 . If both are non-ASCII, the only safe conversion is to
876 convert the multibyte one to be unibyte, because the
877 reverse conversion potentially adds bytes while raw bytes
878 are converted to their multibyte forms, which we will be
879 unable to account for, since the information about the
880 original multibyteness is lost. If those additional bytes
881 later leak to system APIs because they are not encoded or
882 because they are converted to unibyte strings by keeping
883 the data, file APIs will fail.
885 Note: One could argue that if we see a multibyte string, it
886 is evidence that file-name decoding was already set up, and
887 we could convert unibyte strings to multibyte using
888 DECODE_FILE. However, this is risky, because the likes of
889 string_to_multibyte are able of creating multibyte strings
890 without any decoding. */
893 bool name_ascii_p
= SCHARS (name
) == SBYTES (name
);
894 unsigned char *p
= SDATA (default_directory
);
897 while (*p
&& ASCII_CHAR_P (*p
))
899 if (name_ascii_p
|| *p
!= '\0')
901 /* DEFAULT_DIRECTORY is unibyte and possibly non-ASCII.
902 Make a unibyte string out of NAME, and arrange for
903 the result of this function to be a unibyte string.
904 This is needed during bootstrapping and dumping, when
905 Emacs cannot decode file names, because the locale
906 environment is not set up. */
907 name
= make_unibyte_string (SSDATA (name
), SBYTES (name
));
912 /* NAME is non-ASCII and multibyte, and
913 DEFAULT_DIRECTORY is unibyte and pure-ASCII: make a
914 multibyte string out of DEFAULT_DIRECTORY's data. */
916 make_multibyte_string (SSDATA (default_directory
),
917 SCHARS (default_directory
),
918 SCHARS (default_directory
));
923 unsigned char *p
= SDATA (name
);
925 while (*p
&& ASCII_CHAR_P (*p
))
929 /* DEFAULT_DIRECTORY is multibyte and NAME is unibyte
930 and pure-ASCII. Make a multibyte string out of
932 name
= make_multibyte_string (SSDATA (name
),
933 SCHARS (name
), SCHARS (name
));
937 default_directory
= make_unibyte_string (SSDATA (default_directory
),
938 SBYTES (default_directory
));
943 if (!NILP (Vw32_downcase_file_names
))
944 default_directory
= Fdowncase (default_directory
);
947 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
948 SAFE_ALLOCA_STRING (nm
, name
);
949 nmlim
= nm
+ SBYTES (name
);
952 /* Note if special escape prefix is present, but remove for now. */
953 if (nm
[0] == '/' && nm
[1] == ':')
959 /* Find and remove drive specifier if present; this makes nm absolute
960 even if the rest of the name appears to be relative. Only look for
961 drive specifier at the beginning. */
962 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
964 drive
= (unsigned char) nm
[0];
969 /* If we see "c://somedir", we want to strip the first slash after the
970 colon when stripping the drive letter. Otherwise, this expands to
972 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
975 /* Discard any previous drive specifier if nm is now in UNC format. */
976 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
977 && !IS_DIRECTORY_SEP (nm
[2]))
979 #endif /* WINDOWSNT */
982 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
983 none are found, we can probably return right away. We will avoid
984 allocating a new string if name is already fully expanded. */
986 IS_DIRECTORY_SEP (nm
[0])
988 && drive
&& !is_escaped
991 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
995 /* If it turns out that the filename we want to return is just a
996 suffix of FILENAME, we don't need to go through and edit
997 things; we just need to construct a new string using data
998 starting at the middle of FILENAME. If we set LOSE, that
999 means we've discovered that we can't do that cool trick. */
1005 /* Since we know the name is absolute, we can assume that each
1006 element starts with a "/". */
1008 /* "." and ".." are hairy. */
1009 if (IS_DIRECTORY_SEP (p
[0])
1011 && (IS_DIRECTORY_SEP (p
[2])
1013 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
1016 /* Replace multiple slashes with a single one, except
1017 leave leading "//" alone. */
1018 else if (IS_DIRECTORY_SEP (p
[0])
1019 && IS_DIRECTORY_SEP (p
[1])
1020 && (p
!= nm
|| IS_DIRECTORY_SEP (p
[2])))
1027 /* Make sure directories are all separated with /, but
1028 avoid allocation of a new string when not required. */
1029 dostounix_filename (nm
);
1031 if (IS_DIRECTORY_SEP (nm
[1]))
1033 if (strcmp (nm
, SSDATA (name
)) != 0)
1034 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1038 /* Drive must be set, so this is okay. */
1039 if (strcmp (nm
- 2, SSDATA (name
)) != 0)
1041 name
= make_specified_string (nm
, -1, p
- nm
, multibyte
);
1042 char temp
[] = { DRIVE_LETTER (drive
), ':', 0 };
1043 AUTO_STRING_WITH_LEN (drive_prefix
, temp
, 2);
1044 name
= concat2 (drive_prefix
, name
);
1047 if (!NILP (Vw32_downcase_file_names
))
1048 name
= Fdowncase (name
);
1050 #else /* not DOS_NT */
1051 if (strcmp (nm
, SSDATA (name
)) != 0)
1052 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1053 #endif /* not DOS_NT */
1059 /* At this point, nm might or might not be an absolute file name. We
1060 need to expand ~ or ~user if present, otherwise prefix nm with
1061 default_directory if nm is not absolute, and finally collapse /./
1062 and /foo/../ sequences.
1064 We set newdir to be the appropriate prefix if one is needed:
1065 - the relevant user directory if nm starts with ~ or ~user
1066 - the specified drive's working dir (DOS/NT only) if nm does not
1068 - the value of default_directory.
1070 Note that these prefixes are not guaranteed to be absolute (except
1071 for the working dir of a drive). Therefore, to ensure we always
1072 return an absolute name, if the final prefix is not absolute we
1073 append it to the current working directory. */
1075 newdir
= newdirlim
= 0;
1077 if (nm
[0] == '~' /* prefix ~ */
1079 && !is_escaped
/* don't expand ~ in escaped file names */
1083 if (IS_DIRECTORY_SEP (nm
[1])
1084 || nm
[1] == 0) /* ~ by itself */
1088 if (!(newdir
= egetenv ("HOME")))
1089 newdir
= newdirlim
= "";
1094 char newdir_utf8
[MAX_UTF8_PATH
];
1096 filename_from_ansi (newdir
, newdir_utf8
);
1097 tem
= make_unibyte_string (newdir_utf8
, strlen (newdir_utf8
));
1098 newdir
= SSDATA (tem
);
1102 tem
= build_string (newdir
);
1103 newdirlim
= newdir
+ SBYTES (tem
);
1104 /* `egetenv' may return a unibyte string, which will bite us
1105 if we expect the directory to be multibyte. */
1106 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1108 hdir
= DECODE_FILE (tem
);
1109 newdir
= SSDATA (hdir
);
1110 newdirlim
= newdir
+ SBYTES (hdir
);
1113 collapse_newdir
= false;
1116 else /* ~user/filename */
1119 for (p
= nm
; *p
&& !IS_DIRECTORY_SEP (*p
); p
++)
1121 o
= SAFE_ALLOCA (p
- nm
+ 1);
1122 memcpy (o
, nm
, p
- nm
);
1126 pw
= getpwnam (o
+ 1);
1132 newdir
= pw
->pw_dir
;
1133 /* `getpwnam' may return a unibyte string, which will
1134 bite us when we expect the directory to be multibyte. */
1135 tem
= make_unibyte_string (newdir
, strlen (newdir
));
1136 newdirlim
= newdir
+ SBYTES (tem
);
1137 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1139 hdir
= DECODE_FILE (tem
);
1140 newdir
= SSDATA (hdir
);
1141 newdirlim
= newdir
+ SBYTES (hdir
);
1145 collapse_newdir
= false;
1149 /* If we don't find a user of that name, leave the name
1150 unchanged; don't move nm forward to p. */
1155 /* On DOS and Windows, nm is absolute if a drive name was specified;
1156 use the drive's current directory as the prefix if needed. */
1157 if (!newdir
&& drive
)
1159 /* Get default directory if needed to make nm absolute. */
1161 if (!IS_DIRECTORY_SEP (nm
[0]))
1163 adir
= alloca (MAXPATHLEN
+ 1);
1164 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1168 Lisp_Object tem
= build_string (adir
);
1170 tem
= DECODE_FILE (tem
);
1171 newdirlim
= adir
+ SBYTES (tem
);
1172 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1175 newdirlim
= adir
+ strlen (adir
);
1179 /* Either nm starts with /, or drive isn't mounted. */
1181 adir
[0] = DRIVE_LETTER (drive
);
1185 newdirlim
= adir
+ 3;
1191 /* Finally, if no prefix has been specified and nm is not absolute,
1192 then it must be expanded relative to default_directory. */
1196 /* /... alone is not absolute on DOS and Windows. */
1197 && !IS_DIRECTORY_SEP (nm
[0])
1200 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
1201 && !IS_DIRECTORY_SEP (nm
[2]))
1205 newdir
= SSDATA (default_directory
);
1206 newdirlim
= newdir
+ SBYTES (default_directory
);
1208 /* Note if special escape prefix is present, but remove for now. */
1209 if (newdir
[0] == '/' && newdir
[1] == ':')
1220 /* First ensure newdir is an absolute name. */
1222 /* Detect MSDOS file names with drive specifiers. */
1223 ! (IS_DRIVE (newdir
[0])
1224 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1226 /* Detect Windows file names in UNC format. */
1227 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1228 && !IS_DIRECTORY_SEP (newdir
[2]))
1232 /* Effectively, let newdir be (expand-file-name newdir cwd).
1233 Because of the admonition against calling expand-file-name
1234 when we have pointers into lisp strings, we accomplish this
1235 indirectly by prepending newdir to nm if necessary, and using
1236 cwd (or the wd of newdir's drive) as the new newdir. */
1239 const int adir_size
= MAX_UTF8_PATH
;
1241 const int adir_size
= MAXPATHLEN
+ 1;
1244 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1246 drive
= (unsigned char) newdir
[0];
1249 if (!IS_DIRECTORY_SEP (nm
[0]))
1251 ptrdiff_t nmlen
= nmlim
- nm
;
1252 ptrdiff_t newdirlen
= newdirlim
- newdir
;
1253 char *tmp
= alloca (newdirlen
+ file_name_as_directory_slop
1255 ptrdiff_t dlen
= file_name_as_directory (tmp
, newdir
, newdirlen
,
1257 memcpy (tmp
+ dlen
, nm
, nmlen
+ 1);
1259 nmlim
= nm
+ dlen
+ nmlen
;
1261 adir
= alloca (adir_size
);
1264 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1268 getcwd (adir
, adir_size
);
1271 Lisp_Object tem
= build_string (adir
);
1273 tem
= DECODE_FILE (tem
);
1274 newdirlim
= adir
+ SBYTES (tem
);
1275 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1278 newdirlim
= adir
+ strlen (adir
);
1282 /* Strip off drive name from prefix, if present. */
1283 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1289 /* Keep only a prefix from newdir if nm starts with slash
1290 (//server/share for UNC, nothing otherwise). */
1291 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1294 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1295 && !IS_DIRECTORY_SEP (newdir
[2]))
1297 char *adir
= strcpy (alloca (newdirlim
- newdir
+ 1), newdir
);
1299 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1301 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1304 newdirlim
= newdir
+ strlen (adir
);
1308 newdir
= newdirlim
= "";
1313 /* Ignore any slash at the end of newdir, unless newdir is
1314 just "/" or "//". */
1315 length
= newdirlim
- newdir
;
1316 while (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1317 && ! (length
== 2 && IS_DIRECTORY_SEP (newdir
[0])))
1320 /* Now concatenate the directory and name to new space in the stack frame. */
1321 tlen
= length
+ file_name_as_directory_slop
+ (nmlim
- nm
) + 1;
1322 eassert (tlen
> file_name_as_directory_slop
+ 1);
1324 /* Reserve space for drive specifier and escape prefix, since either
1325 or both may need to be inserted. (The Microsoft x86 compiler
1326 produces incorrect code if the following two lines are combined.) */
1327 target
= alloca (tlen
+ 4);
1329 #else /* not DOS_NT */
1330 target
= SAFE_ALLOCA (tlen
);
1331 #endif /* not DOS_NT */
1337 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1340 /* If newdir is effectively "C:/", then the drive letter will have
1341 been stripped and newdir will be "/". Concatenating with an
1342 absolute directory in nm produces "//", which will then be
1343 incorrectly treated as a network share. Ignore newdir in
1344 this case (keeping the drive letter). */
1345 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1346 && newdir
[1] == '\0'))
1349 memcpy (target
, newdir
, length
);
1355 nbytes
= file_name_as_directory (target
, newdir
, length
, multibyte
);
1358 memcpy (target
+ nbytes
, nm
, nmlim
- nm
+ 1);
1360 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1368 if (!IS_DIRECTORY_SEP (*p
))
1372 else if (p
[1] == '.'
1373 && (IS_DIRECTORY_SEP (p
[2])
1376 /* If "/." is the entire filename, keep the "/". Otherwise,
1377 just delete the whole "/.". */
1378 if (o
== target
&& p
[2] == '\0')
1382 else if (p
[1] == '.' && p
[2] == '.'
1383 /* `/../' is the "superroot" on certain file systems.
1384 Turned off on DOS_NT systems because they have no
1385 "superroot" and because this causes us to produce
1386 file names like "d:/../foo" which fail file-related
1387 functions of the underlying OS. (To reproduce, try a
1388 long series of "../../" in default_directory, longer
1389 than the number of levels from the root.) */
1393 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1398 while (o
!= target
&& (--o
, !IS_DIRECTORY_SEP (*o
)))
1401 /* Don't go below server level in UNC filenames. */
1402 if (o
== target
+ 1 && IS_DIRECTORY_SEP (*o
)
1403 && IS_DIRECTORY_SEP (*target
))
1407 /* Keep initial / only if this is the whole name. */
1408 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1412 else if (IS_DIRECTORY_SEP (p
[1])
1413 && (p
!= target
|| IS_DIRECTORY_SEP (p
[2])))
1414 /* Collapse multiple "/", except leave leading "//" alone. */
1423 /* At last, set drive name. */
1425 /* Except for network file name. */
1426 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1427 #endif /* WINDOWSNT */
1429 if (!drive
) emacs_abort ();
1431 target
[0] = DRIVE_LETTER (drive
);
1434 /* Reinsert the escape prefix if required. */
1441 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1442 dostounix_filename (SSDATA (result
));
1444 if (!NILP (Vw32_downcase_file_names
))
1445 result
= Fdowncase (result
);
1448 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1449 #endif /* !DOS_NT */
1452 /* Again look to see if the file name has special constructs in it
1453 and perhaps call the corresponding file handler. This is needed
1454 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1455 the ".." component gives us "/user@host:/bar/../baz" which needs
1456 to be expanded again. */
1457 handler
= Ffind_file_name_handler (result
, Qexpand_file_name
);
1458 if (!NILP (handler
))
1460 handled_name
= call3 (handler
, Qexpand_file_name
,
1461 result
, default_directory
);
1462 if (! STRINGP (handled_name
))
1463 error ("Invalid handler in `file-name-handler-alist'");
1464 result
= handled_name
;
1472 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1473 This is the old version of expand-file-name, before it was thoroughly
1474 rewritten for Emacs 10.31. We leave this version here commented-out,
1475 because the code is very complex and likely to have subtle bugs. If
1476 bugs _are_ found, it might be of interest to look at the old code and
1477 see what did it do in the relevant situation.
1479 Don't remove this code: it's true that it will be accessible
1480 from the repository, but a few years from deletion, people will
1481 forget it is there. */
1483 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1484 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1485 "Convert FILENAME to absolute, and canonicalize it.\n\
1486 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1487 \(does not start with slash); if DEFAULT is nil or missing,\n\
1488 the current buffer's value of default-directory is used.\n\
1489 Filenames containing `.' or `..' as components are simplified;\n\
1490 initial `~/' expands to your home directory.\n\
1491 See also the function `substitute-in-file-name'.")
1493 Lisp_Object name
, defalt
;
1497 register unsigned char *newdir
, *p
, *o
;
1499 unsigned char *target
;
1502 CHECK_STRING (name
);
1505 /* If nm is absolute, flush ...// and detect /./ and /../.
1506 If no /./ or /../ we can return right away. */
1513 if (p
[0] == '/' && p
[1] == '/')
1515 if (p
[0] == '/' && p
[1] == '~')
1516 nm
= p
+ 1, lose
= 1;
1517 if (p
[0] == '/' && p
[1] == '.'
1518 && (p
[2] == '/' || p
[2] == 0
1519 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1525 if (nm
== SDATA (name
))
1527 return build_string (nm
);
1531 /* Now determine directory to start with and put it in NEWDIR. */
1535 if (nm
[0] == '~') /* prefix ~ */
1536 if (nm
[1] == '/' || nm
[1] == 0)/* ~/filename */
1538 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1539 newdir
= (unsigned char *) "";
1542 else /* ~user/filename */
1544 /* Get past ~ to user. */
1545 unsigned char *user
= nm
+ 1;
1546 /* Find end of name. */
1547 unsigned char *ptr
= (unsigned char *) strchr (user
, '/');
1548 ptrdiff_t len
= ptr
? ptr
- user
: strlen (user
);
1549 /* Copy the user name into temp storage. */
1550 o
= alloca (len
+ 1);
1551 memcpy (o
, user
, len
);
1554 /* Look up the user name. */
1556 pw
= (struct passwd
*) getpwnam (o
+ 1);
1559 error ("\"%s\" isn't a registered user", o
+ 1);
1561 newdir
= (unsigned char *) pw
->pw_dir
;
1563 /* Discard the user name from NM. */
1567 if (nm
[0] != '/' && !newdir
)
1570 defalt
= current_buffer
->directory
;
1571 CHECK_STRING (defalt
);
1572 newdir
= SDATA (defalt
);
1575 /* Now concatenate the directory and name to new space in the stack frame. */
1577 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1578 target
= alloca (tlen
);
1583 if (nm
[0] == 0 || nm
[0] == '/')
1584 strcpy (target
, newdir
);
1586 file_name_as_directory (target
, newdir
);
1589 strcat (target
, nm
);
1591 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1602 else if (!strncmp (p
, "//", 2)
1608 else if (p
[0] == '/' && p
[1] == '.'
1609 && (p
[2] == '/' || p
[2] == 0))
1611 else if (!strncmp (p
, "/..", 3)
1612 /* `/../' is the "superroot" on certain file systems. */
1614 && (p
[3] == '/' || p
[3] == 0))
1616 while (o
!= target
&& *--o
!= '/')
1618 if (o
== target
&& *o
== '/')
1628 return make_string (target
, o
- target
);
1632 /* If /~ or // appears, discard everything through first slash. */
1634 file_name_absolute_p (const char *filename
)
1637 (IS_DIRECTORY_SEP (*filename
) || *filename
== '~'
1639 || (IS_DRIVE (*filename
) && IS_DEVICE_SEP (filename
[1])
1640 && IS_DIRECTORY_SEP (filename
[2]))
1646 search_embedded_absfilename (char *nm
, char *endp
)
1650 for (p
= nm
+ 1; p
< endp
; p
++)
1652 if (IS_DIRECTORY_SEP (p
[-1])
1653 && file_name_absolute_p (p
)
1654 #if defined (WINDOWSNT) || defined (CYGWIN)
1655 /* // at start of file name is meaningful in Apollo,
1656 WindowsNT and Cygwin systems. */
1657 && !(IS_DIRECTORY_SEP (p
[0]) && p
- 1 == nm
)
1658 #endif /* not (WINDOWSNT || CYGWIN) */
1661 for (s
= p
; *s
&& !IS_DIRECTORY_SEP (*s
); s
++);
1662 if (p
[0] == '~' && s
> p
+ 1) /* We've got "/~something/". */
1665 char *o
= SAFE_ALLOCA (s
- p
+ 1);
1667 memcpy (o
, p
, s
- p
);
1670 /* If we have ~user and `user' exists, discard
1671 everything up to ~. But if `user' does not exist, leave
1672 ~user alone, it might be a literal file name. */
1674 pw
= getpwnam (o
+ 1);
1687 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
1688 Ssubstitute_in_file_name
, 1, 1, 0,
1689 doc
: /* Substitute environment variables referred to in FILENAME.
1690 `$FOO' where FOO is an environment variable name means to substitute
1691 the value of that variable. The variable name should be terminated
1692 with a character not a letter, digit or underscore; otherwise, enclose
1693 the entire variable name in braces.
1695 If `/~' appears, all of FILENAME through that `/' is discarded.
1696 If `//' appears, everything up to and including the first of
1697 those `/' is discarded. */)
1698 (Lisp_Object filename
)
1700 char *nm
, *p
, *x
, *endp
;
1701 bool substituted
= false;
1704 Lisp_Object handler
;
1706 CHECK_STRING (filename
);
1708 multibyte
= STRING_MULTIBYTE (filename
);
1710 /* If the file name has special constructs in it,
1711 call the corresponding file handler. */
1712 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
1713 if (!NILP (handler
))
1715 Lisp_Object handled_name
= call2 (handler
, Qsubstitute_in_file_name
,
1717 if (STRINGP (handled_name
))
1718 return handled_name
;
1719 error ("Invalid handler in `file-name-handler-alist'");
1722 /* Always work on a copy of the string, in case GC happens during
1723 decode of environment variables, causing the original Lisp_String
1724 data to be relocated. */
1726 SAFE_ALLOCA_STRING (nm
, filename
);
1729 dostounix_filename (nm
);
1730 substituted
= (memcmp (nm
, SDATA (filename
), SBYTES (filename
)) != 0);
1732 endp
= nm
+ SBYTES (filename
);
1734 /* If /~ or // appears, discard everything through first slash. */
1735 p
= search_embedded_absfilename (nm
, endp
);
1737 /* Start over with the new string, so we check the file-name-handler
1738 again. Important with filenames like "/home/foo//:/hello///there"
1739 which would substitute to "/:/hello///there" rather than "/there". */
1742 = (Fsubstitute_in_file_name
1743 (make_specified_string (p
, -1, endp
- p
, multibyte
)));
1748 /* See if any variables are substituted into the string. */
1750 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name
)))
1753 = (!substituted
? filename
1754 : make_specified_string (nm
, -1, endp
- nm
, multibyte
));
1755 Lisp_Object tmp
= call1 (Qsubstitute_env_in_file_name
, name
);
1757 if (!EQ (tmp
, name
))
1765 if (!NILP (Vw32_downcase_file_names
))
1766 filename
= Fdowncase (filename
);
1772 xnm
= SSDATA (filename
);
1773 x
= xnm
+ SBYTES (filename
);
1775 /* If /~ or // appears, discard everything through first slash. */
1776 while ((p
= search_embedded_absfilename (xnm
, x
)) != NULL
)
1777 /* This time we do not start over because we've already expanded envvars
1778 and replaced $$ with $. Maybe we should start over as well, but we'd
1779 need to quote some $ to $$ first. */
1783 if (!NILP (Vw32_downcase_file_names
))
1785 Lisp_Object xname
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1787 filename
= Fdowncase (xname
);
1791 if (xnm
!= SSDATA (filename
))
1792 filename
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1797 /* A slightly faster and more convenient way to get
1798 (directory-file-name (expand-file-name FOO)). */
1801 expand_and_dir_to_file (Lisp_Object filename
)
1803 Lisp_Object absname
= Fexpand_file_name (filename
, Qnil
);
1805 /* Remove final slash, if any (unless this is the root dir).
1806 stat behaves differently depending! */
1807 if (SCHARS (absname
) > 1
1808 && IS_DIRECTORY_SEP (SREF (absname
, SBYTES (absname
) - 1))
1809 && !IS_DEVICE_SEP (SREF (absname
, SBYTES (absname
) - 2)))
1810 /* We cannot take shortcuts; they might be wrong for magic file names. */
1811 absname
= Fdirectory_file_name (absname
);
1815 /* Signal an error if the file ABSNAME already exists.
1816 If KNOWN_TO_EXIST, the file is known to exist.
1817 QUERYSTRING is a name for the action that is being considered
1819 If INTERACTIVE, ask the user whether to proceed,
1820 and bypass the error if the user says to go ahead.
1821 If QUICK, ask for y or n, not yes or no. */
1824 barf_or_query_if_file_exists (Lisp_Object absname
, bool known_to_exist
,
1825 const char *querystring
, bool interactive
,
1828 Lisp_Object tem
, encoded_filename
;
1829 struct stat statbuf
;
1831 encoded_filename
= ENCODE_FILE (absname
);
1833 if (! known_to_exist
&& lstat (SSDATA (encoded_filename
), &statbuf
) == 0)
1835 if (S_ISDIR (statbuf
.st_mode
))
1836 xsignal2 (Qfile_error
,
1837 build_string ("File is a directory"), absname
);
1838 known_to_exist
= true;
1844 xsignal2 (Qfile_already_exists
,
1845 build_string ("File already exists"), absname
);
1846 AUTO_STRING (format
, "File %s already exists; %s anyway? ");
1847 tem
= CALLN (Fformat
, format
, absname
, build_string (querystring
));
1849 tem
= call1 (intern ("y-or-n-p"), tem
);
1851 tem
= do_yes_or_no_p (tem
);
1853 xsignal2 (Qfile_already_exists
,
1854 build_string ("File already exists"), absname
);
1859 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1861 clone_file (int dest
, int source
)
1864 return ioctl (dest
, FICLONE
, source
) == 0;
1870 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 6,
1871 "fCopy file: \nGCopy %s to file: \np\nP",
1872 doc
: /* Copy FILE to NEWNAME. Both args must be strings.
1873 If NEWNAME is a directory name, copy FILE to a like-named file under
1874 NEWNAME. For NEWNAME to be recognized as a directory name, it should
1877 This function always sets the file modes of the output file to match
1880 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1881 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1882 signal a `file-already-exists' error without overwriting. If
1883 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1884 about overwriting; this is what happens in interactive use with M-x.
1885 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1888 Fourth arg KEEP-TIME non-nil means give the output file the same
1889 last-modified time as the old one. (This works on only some systems.)
1891 A prefix arg makes KEEP-TIME non-nil.
1893 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1896 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1897 this includes the file modes, along with ACL entries and SELinux
1898 context if present. Otherwise, if NEWNAME is created its file
1899 permission bits are those of FILE, masked by the default file
1901 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
,
1902 Lisp_Object keep_time
, Lisp_Object preserve_uid_gid
,
1903 Lisp_Object preserve_permissions
)
1905 Lisp_Object handler
;
1906 ptrdiff_t count
= SPECPDL_INDEX ();
1907 Lisp_Object encoded_file
, encoded_newname
;
1909 security_context_t con
;
1915 bool already_exists
= false;
1921 file
= Fexpand_file_name (file
, Qnil
);
1922 newname
= expand_cp_target (file
, newname
);
1924 /* If the input file name has special constructs in it,
1925 call the corresponding file handler. */
1926 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
1927 /* Likewise for output file name. */
1929 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
1930 if (!NILP (handler
))
1931 return call7 (handler
, Qcopy_file
, file
, newname
,
1932 ok_if_already_exists
, keep_time
, preserve_uid_gid
,
1933 preserve_permissions
);
1935 encoded_file
= ENCODE_FILE (file
);
1936 encoded_newname
= ENCODE_FILE (newname
);
1939 if (NILP (ok_if_already_exists
)
1940 || INTEGERP (ok_if_already_exists
))
1941 barf_or_query_if_file_exists (newname
, false, "copy to it",
1942 INTEGERP (ok_if_already_exists
), false);
1944 result
= w32_copy_file (SSDATA (encoded_file
), SSDATA (encoded_newname
),
1945 !NILP (keep_time
), !NILP (preserve_uid_gid
),
1946 !NILP (preserve_permissions
));
1950 report_file_error ("Copying file", list2 (file
, newname
));
1952 report_file_error ("Copying permissions from", file
);
1954 xsignal2 (Qfile_date_error
,
1955 build_string ("Resetting file times"), newname
);
1957 report_file_error ("Copying permissions to", newname
);
1959 #else /* not WINDOWSNT */
1960 ifd
= emacs_open (SSDATA (encoded_file
), O_RDONLY
, 0);
1963 report_file_error ("Opening input file", file
);
1965 record_unwind_protect_int (close_file_unwind
, ifd
);
1967 if (fstat (ifd
, &st
) != 0)
1968 report_file_error ("Input file status", file
);
1970 if (!NILP (preserve_permissions
))
1973 if (is_selinux_enabled ())
1975 conlength
= fgetfilecon (ifd
, &con
);
1976 if (conlength
== -1)
1977 report_file_error ("Doing fgetfilecon", file
);
1982 /* We can copy only regular files. */
1983 if (!S_ISREG (st
.st_mode
))
1984 report_file_errno ("Non-regular file", file
,
1985 S_ISDIR (st
.st_mode
) ? EISDIR
: EINVAL
);
1988 new_mask
= st
.st_mode
& (!NILP (preserve_uid_gid
) ? 0700 : 0777);
1990 new_mask
= S_IREAD
| S_IWRITE
;
1993 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
| O_CREAT
| O_EXCL
,
1995 if (ofd
< 0 && errno
== EEXIST
)
1997 if (NILP (ok_if_already_exists
) || INTEGERP (ok_if_already_exists
))
1998 barf_or_query_if_file_exists (newname
, true, "copy to it",
1999 INTEGERP (ok_if_already_exists
), false);
2000 already_exists
= true;
2001 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
, 0);
2004 report_file_error ("Opening output file", newname
);
2006 record_unwind_protect_int (close_file_unwind
, ofd
);
2008 off_t oldsize
= 0, newsize
;
2013 if (fstat (ofd
, &out_st
) != 0)
2014 report_file_error ("Output file status", newname
);
2015 if (st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
2016 report_file_errno ("Input and output files are the same",
2017 list2 (file
, newname
), 0);
2018 if (S_ISREG (out_st
.st_mode
))
2019 oldsize
= out_st
.st_size
;
2024 if (clone_file (ofd
, ifd
))
2025 newsize
= st
.st_size
;
2028 char buf
[MAX_ALLOCA
];
2030 for (newsize
= 0; 0 < (n
= emacs_read_quit (ifd
, buf
, sizeof buf
));
2032 if (emacs_write_quit (ofd
, buf
, n
) != n
)
2033 report_file_error ("Write error", newname
);
2035 report_file_error ("Read error", file
);
2038 /* Truncate any existing output file after writing the data. This
2039 is more likely to work than truncation before writing, if the
2040 file system is out of space or the user is over disk quota. */
2041 if (newsize
< oldsize
&& ftruncate (ofd
, newsize
) != 0)
2042 report_file_error ("Truncating output file", newname
);
2045 /* Preserve the original file permissions, and if requested, also its
2048 mode_t preserved_permissions
= st
.st_mode
& 07777;
2049 mode_t default_permissions
= st
.st_mode
& 0777 & ~realmask
;
2050 if (!NILP (preserve_uid_gid
))
2052 /* Attempt to change owner and group. If that doesn't work
2053 attempt to change just the group, as that is sometimes allowed.
2054 Adjust the mode mask to eliminate setuid or setgid bits
2055 or group permissions bits that are inappropriate if the
2056 owner or group are wrong. */
2057 if (fchown (ofd
, st
.st_uid
, st
.st_gid
) != 0)
2059 if (fchown (ofd
, -1, st
.st_gid
) == 0)
2060 preserved_permissions
&= ~04000;
2063 preserved_permissions
&= ~06000;
2065 /* Copy the other bits to the group bits, since the
2067 preserved_permissions
&= ~070;
2068 preserved_permissions
|= (preserved_permissions
& 7) << 3;
2069 default_permissions
&= ~070;
2070 default_permissions
|= (default_permissions
& 7) << 3;
2075 switch (!NILP (preserve_permissions
)
2076 ? qcopy_acl (SSDATA (encoded_file
), ifd
,
2077 SSDATA (encoded_newname
), ofd
,
2078 preserved_permissions
)
2080 || (new_mask
& ~realmask
) == default_permissions
)
2082 : fchmod (ofd
, default_permissions
))
2084 case -2: report_file_error ("Copying permissions from", file
);
2085 case -1: report_file_error ("Copying permissions to", newname
);
2088 #endif /* not MSDOS */
2093 /* Set the modified context back to the file. */
2094 bool fail
= fsetfilecon (ofd
, con
) != 0;
2095 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
2096 if (fail
&& errno
!= ENOTSUP
)
2097 report_file_error ("Doing fsetfilecon", newname
);
2103 if (!NILP (keep_time
))
2105 struct timespec atime
= get_stat_atime (&st
);
2106 struct timespec mtime
= get_stat_mtime (&st
);
2107 if (set_file_times (ofd
, SSDATA (encoded_newname
), atime
, mtime
) != 0)
2108 xsignal2 (Qfile_date_error
,
2109 build_string ("Cannot set file date"), newname
);
2112 if (emacs_close (ofd
) < 0)
2113 report_file_error ("Write error", newname
);
2118 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2119 and if it can't, it tells so. Otherwise, under MSDOS we usually
2120 get only the READ bit, which will make the copied file read-only,
2121 so it's better not to chmod at all. */
2122 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2123 chmod (SDATA (encoded_newname
), st
.st_mode
& 07777);
2125 #endif /* not WINDOWSNT */
2127 /* Discard the unwind protects. */
2128 specpdl_ptr
= specpdl
+ count
;
2133 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2134 Smake_directory_internal
, 1, 1, 0,
2135 doc
: /* Create a new directory named DIRECTORY. */)
2136 (Lisp_Object directory
)
2139 Lisp_Object handler
;
2140 Lisp_Object encoded_dir
;
2142 CHECK_STRING (directory
);
2143 directory
= Fexpand_file_name (directory
, Qnil
);
2145 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2146 if (!NILP (handler
))
2147 return call2 (handler
, Qmake_directory_internal
, directory
);
2149 encoded_dir
= ENCODE_FILE (directory
);
2151 dir
= SSDATA (encoded_dir
);
2153 if (mkdir (dir
, 0777 & ~auto_saving_dir_umask
) != 0)
2154 report_file_error ("Creating directory", directory
);
2159 DEFUN ("delete-directory-internal", Fdelete_directory_internal
,
2160 Sdelete_directory_internal
, 1, 1, 0,
2161 doc
: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2162 (Lisp_Object directory
)
2165 Lisp_Object encoded_dir
;
2167 CHECK_STRING (directory
);
2168 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2169 encoded_dir
= ENCODE_FILE (directory
);
2170 dir
= SSDATA (encoded_dir
);
2172 if (rmdir (dir
) != 0)
2173 report_file_error ("Removing directory", directory
);
2178 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 2,
2179 "(list (read-file-name \
2180 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2181 \"Move file to trash: \" \"Delete file: \") \
2182 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2183 (null current-prefix-arg))",
2184 doc
: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2185 If file has multiple names, it continues to exist with the other names.
2186 TRASH non-nil means to trash the file instead of deleting, provided
2187 `delete-by-moving-to-trash' is non-nil.
2189 When called interactively, TRASH is t if no prefix argument is given.
2190 With a prefix argument, TRASH is nil. */)
2191 (Lisp_Object filename
, Lisp_Object trash
)
2193 Lisp_Object handler
;
2194 Lisp_Object encoded_file
;
2196 if (!NILP (Ffile_directory_p (filename
))
2197 && NILP (Ffile_symlink_p (filename
)))
2198 xsignal2 (Qfile_error
,
2199 build_string ("Removing old name: is a directory"),
2201 filename
= Fexpand_file_name (filename
, Qnil
);
2203 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2204 if (!NILP (handler
))
2205 return call3 (handler
, Qdelete_file
, filename
, trash
);
2207 if (delete_by_moving_to_trash
&& !NILP (trash
))
2208 return call1 (Qmove_file_to_trash
, filename
);
2210 encoded_file
= ENCODE_FILE (filename
);
2212 if (unlink (SSDATA (encoded_file
)) != 0 && errno
!= ENOENT
)
2213 report_file_error ("Removing old name", filename
);
2218 internal_delete_file_1 (Lisp_Object ignore
)
2223 /* Delete file FILENAME, returning true if successful.
2224 This ignores `delete-by-moving-to-trash'. */
2227 internal_delete_file (Lisp_Object filename
)
2231 tem
= internal_condition_case_2 (Fdelete_file
, filename
, Qnil
,
2232 Qt
, internal_delete_file_1
);
2236 /* Filesystems are case-sensitive on all supported systems except
2237 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2238 case-insensitive on the first two, but they may or may not be
2239 case-insensitive on Cygwin and OS X. The following function
2240 attempts to provide a runtime test on those two systems. If the
2241 test is not conclusive, we assume case-insensitivity on Cygwin and
2242 case-sensitivity on Mac OS X.
2244 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2245 NFS-mounted Windows volumes, might be case-insensitive. Can we
2249 file_name_case_insensitive_p (const char *filename
)
2251 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2252 those flags are available. As of this writing (2017-05-20),
2253 Cygwin is the only platform known to support the former (starting
2254 with Cygwin-2.6.1), and macOS is the only platform known to
2255 support the latter. */
2257 #ifdef _PC_CASE_INSENSITIVE
2258 int res
= pathconf (filename
, _PC_CASE_INSENSITIVE
);
2261 #elif defined _PC_CASE_SENSITIVE
2262 int res
= pathconf (filename
, _PC_CASE_SENSITIVE
);
2267 #if defined CYGWIN || defined DOS_NT
2274 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p
,
2275 Sfile_name_case_insensitive_p
, 1, 1, 0,
2276 doc
: /* Return t if file FILENAME is on a case-insensitive filesystem.
2277 The arg must be a string. */)
2278 (Lisp_Object filename
)
2280 Lisp_Object handler
;
2282 CHECK_STRING (filename
);
2283 filename
= Fexpand_file_name (filename
, Qnil
);
2285 /* If the file name has special constructs in it,
2286 call the corresponding file handler. */
2287 handler
= Ffind_file_name_handler (filename
, Qfile_name_case_insensitive_p
);
2288 if (!NILP (handler
))
2289 return call2 (handler
, Qfile_name_case_insensitive_p
, filename
);
2291 filename
= ENCODE_FILE (filename
);
2292 return file_name_case_insensitive_p (SSDATA (filename
)) ? Qt
: Qnil
;
2295 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2296 "fRename file: \nGRename %s to file: \np",
2297 doc
: /* Rename FILE as NEWNAME. Both args must be strings.
2298 If file has names other than FILE, it continues to have those names.
2299 If NEWNAME is a directory name, rename FILE to a like-named file under
2300 NEWNAME. For NEWNAME to be recognized as a directory name, it should
2303 Signal a `file-already-exists' error if a file NEWNAME already exists
2304 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2305 An integer third arg means request confirmation if NEWNAME already exists.
2306 This is what happens in interactive use with M-x. */)
2307 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2309 Lisp_Object handler
;
2310 Lisp_Object encoded_file
, encoded_newname
;
2312 file
= Fexpand_file_name (file
, Qnil
);
2314 /* If the filesystem is case-insensitive and the file names are
2315 identical but for case, treat it as a change-case request, and do
2316 not worry whether NEWNAME exists or whether it is a directory, as
2317 it is already another name for FILE. */
2318 bool case_only_rename
= false;
2319 #if defined CYGWIN || defined DOS_NT
2320 if (!NILP (Ffile_name_case_insensitive_p (file
)))
2322 newname
= Fexpand_file_name (newname
, Qnil
);
2323 case_only_rename
= !NILP (Fstring_equal (Fdowncase (file
),
2324 Fdowncase (newname
)));
2328 if (!case_only_rename
)
2329 newname
= expand_cp_target (Fdirectory_file_name (file
), newname
);
2331 /* If the file name has special constructs in it,
2332 call the corresponding file handler. */
2333 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2335 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2336 if (!NILP (handler
))
2337 return call4 (handler
, Qrename_file
,
2338 file
, newname
, ok_if_already_exists
);
2340 encoded_file
= ENCODE_FILE (file
);
2341 encoded_newname
= ENCODE_FILE (newname
);
2343 bool plain_rename
= (case_only_rename
2344 || (!NILP (ok_if_already_exists
)
2345 && !INTEGERP (ok_if_already_exists
)));
2346 int rename_errno UNINIT
;
2349 if (renameat_noreplace (AT_FDCWD
, SSDATA (encoded_file
),
2350 AT_FDCWD
, SSDATA (encoded_newname
))
2354 rename_errno
= errno
;
2355 switch (rename_errno
)
2357 case EEXIST
: case EINVAL
: case ENOSYS
:
2358 #if ENOSYS != ENOTSUP
2361 barf_or_query_if_file_exists (newname
, rename_errno
== EEXIST
,
2363 INTEGERP (ok_if_already_exists
),
2365 plain_rename
= true;
2372 if (rename (SSDATA (encoded_file
), SSDATA (encoded_newname
)) == 0)
2374 rename_errno
= errno
;
2375 /* Don't prompt again. */
2376 ok_if_already_exists
= Qt
;
2378 else if (!NILP (ok_if_already_exists
))
2379 ok_if_already_exists
= Qt
;
2381 if (rename_errno
!= EXDEV
)
2382 report_file_errno ("Renaming", list2 (file
, newname
), rename_errno
);
2384 struct stat file_st
;
2385 bool dirp
= !NILP (Fdirectory_name_p (file
));
2388 if (lstat (SSDATA (encoded_file
), &file_st
) != 0)
2389 report_file_error ("Renaming", list2 (file
, newname
));
2390 dirp
= S_ISDIR (file_st
.st_mode
) != 0;
2393 call4 (Qcopy_directory
, file
, newname
, Qt
, Qnil
);
2396 Lisp_Object symlink_target
2397 = (S_ISLNK (file_st
.st_mode
)
2398 ? emacs_readlinkat (AT_FDCWD
, SSDATA (encoded_file
))
2400 if (!NILP (symlink_target
))
2401 Fmake_symbolic_link (symlink_target
, newname
, ok_if_already_exists
);
2403 Fcopy_file (file
, newname
, ok_if_already_exists
, Qt
, Qt
, Qt
);
2406 ptrdiff_t count
= SPECPDL_INDEX ();
2407 specbind (Qdelete_by_moving_to_trash
, Qnil
);
2409 call2 (Qdelete_directory
, file
, Qt
);
2411 Fdelete_file (file
, Qnil
);
2412 return unbind_to (count
, Qnil
);
2415 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2416 "fAdd name to file: \nGName to add to %s: \np",
2417 doc
: /* Give FILE additional name NEWNAME. Both args must be strings.
2418 If NEWNAME is a directory name, give FILE a like-named new name under
2421 Signal a `file-already-exists' error if a file NEWNAME already exists
2422 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2423 An integer third arg means request confirmation if NEWNAME already exists.
2424 This is what happens in interactive use with M-x. */)
2425 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2427 Lisp_Object handler
;
2428 Lisp_Object encoded_file
, encoded_newname
;
2430 file
= Fexpand_file_name (file
, Qnil
);
2431 newname
= expand_cp_target (file
, newname
);
2433 /* If the file name has special constructs in it,
2434 call the corresponding file handler. */
2435 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2436 if (!NILP (handler
))
2437 return call4 (handler
, Qadd_name_to_file
, file
,
2438 newname
, ok_if_already_exists
);
2440 /* If the new name has special constructs in it,
2441 call the corresponding file handler. */
2442 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2443 if (!NILP (handler
))
2444 return call4 (handler
, Qadd_name_to_file
, file
,
2445 newname
, ok_if_already_exists
);
2447 encoded_file
= ENCODE_FILE (file
);
2448 encoded_newname
= ENCODE_FILE (newname
);
2450 if (link (SSDATA (encoded_file
), SSDATA (encoded_newname
)) == 0)
2453 if (errno
== EEXIST
)
2455 if (NILP (ok_if_already_exists
)
2456 || INTEGERP (ok_if_already_exists
))
2457 barf_or_query_if_file_exists (newname
, true, "make it a new name",
2458 INTEGERP (ok_if_already_exists
), false);
2459 unlink (SSDATA (newname
));
2460 if (link (SSDATA (encoded_file
), SSDATA (encoded_newname
)) == 0)
2464 report_file_error ("Adding new name", list2 (file
, newname
));
2467 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2468 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2469 doc
: /* Make a symbolic link to TARGET, named NEWNAME.
2470 If NEWNAME is a directory name, make a like-named symbolic link under
2473 Signal a `file-already-exists' error if a file NEWNAME already exists
2474 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2475 An integer third arg means request confirmation if NEWNAME already
2476 exists, and expand leading "~" or strip leading "/:" in TARGET.
2477 This happens for interactive use with M-x. */)
2478 (Lisp_Object target
, Lisp_Object linkname
, Lisp_Object ok_if_already_exists
)
2480 Lisp_Object handler
;
2481 Lisp_Object encoded_target
, encoded_linkname
;
2483 CHECK_STRING (target
);
2484 if (INTEGERP (ok_if_already_exists
))
2486 if (SREF (target
, 0) == '~')
2487 target
= Fexpand_file_name (target
, Qnil
);
2488 else if (SREF (target
, 0) == '/' && SREF (target
, 1) == ':')
2489 target
= Fsubstring_no_properties (target
, make_number (2), Qnil
);
2491 linkname
= expand_cp_target (target
, linkname
);
2493 /* If the new link name has special constructs in it,
2494 call the corresponding file handler. */
2495 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2496 if (!NILP (handler
))
2497 return call4 (handler
, Qmake_symbolic_link
, target
,
2498 linkname
, ok_if_already_exists
);
2500 encoded_target
= ENCODE_FILE (target
);
2501 encoded_linkname
= ENCODE_FILE (linkname
);
2503 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
)) == 0)
2506 if (errno
== ENOSYS
)
2507 xsignal1 (Qfile_error
,
2508 build_string ("Symbolic links are not supported"));
2510 if (errno
== EEXIST
)
2512 if (NILP (ok_if_already_exists
)
2513 || INTEGERP (ok_if_already_exists
))
2514 barf_or_query_if_file_exists (linkname
, true, "make it a link",
2515 INTEGERP (ok_if_already_exists
), false);
2516 unlink (SSDATA (encoded_linkname
));
2517 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
)) == 0)
2521 report_file_error ("Making symbolic link", list2 (target
, linkname
));
2525 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2527 doc
: /* Return t if FILENAME is an absolute file name or starts with `~'.
2528 On Unix, absolute file names start with `/'. */)
2529 (Lisp_Object filename
)
2531 CHECK_STRING (filename
);
2532 return file_name_absolute_p (SSDATA (filename
)) ? Qt
: Qnil
;
2535 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2536 doc
: /* Return t if file FILENAME exists (whether or not you can read it.)
2537 See also `file-readable-p' and `file-attributes'.
2538 This returns nil for a symlink to a nonexistent file.
2539 Use `file-symlink-p' to test for such links. */)
2540 (Lisp_Object filename
)
2542 Lisp_Object absname
;
2543 Lisp_Object handler
;
2545 CHECK_STRING (filename
);
2546 absname
= Fexpand_file_name (filename
, Qnil
);
2548 /* If the file name has special constructs in it,
2549 call the corresponding file handler. */
2550 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2551 if (!NILP (handler
))
2553 Lisp_Object result
= call2 (handler
, Qfile_exists_p
, absname
);
2558 absname
= ENCODE_FILE (absname
);
2560 return check_existing (SSDATA (absname
)) ? Qt
: Qnil
;
2563 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2564 doc
: /* Return t if FILENAME can be executed by you.
2565 For a directory, this means you can access files in that directory.
2566 \(It is generally better to use `file-accessible-directory-p' for that
2567 purpose, though.) */)
2568 (Lisp_Object filename
)
2570 Lisp_Object absname
;
2571 Lisp_Object handler
;
2573 CHECK_STRING (filename
);
2574 absname
= Fexpand_file_name (filename
, Qnil
);
2576 /* If the file name has special constructs in it,
2577 call the corresponding file handler. */
2578 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
2579 if (!NILP (handler
))
2580 return call2 (handler
, Qfile_executable_p
, absname
);
2582 absname
= ENCODE_FILE (absname
);
2584 return (check_executable (SSDATA (absname
)) ? Qt
: Qnil
);
2587 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
2588 doc
: /* Return t if file FILENAME exists and you can read it.
2589 See also `file-exists-p' and `file-attributes'. */)
2590 (Lisp_Object filename
)
2592 Lisp_Object absname
;
2593 Lisp_Object handler
;
2595 CHECK_STRING (filename
);
2596 absname
= Fexpand_file_name (filename
, Qnil
);
2598 /* If the file name has special constructs in it,
2599 call the corresponding file handler. */
2600 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
2601 if (!NILP (handler
))
2602 return call2 (handler
, Qfile_readable_p
, absname
);
2604 absname
= ENCODE_FILE (absname
);
2605 return (faccessat (AT_FDCWD
, SSDATA (absname
), R_OK
, AT_EACCESS
) == 0
2609 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
2610 doc
: /* Return t if file FILENAME can be written or created by you. */)
2611 (Lisp_Object filename
)
2613 Lisp_Object absname
, dir
, encoded
;
2614 Lisp_Object handler
;
2616 CHECK_STRING (filename
);
2617 absname
= Fexpand_file_name (filename
, Qnil
);
2619 /* If the file name has special constructs in it,
2620 call the corresponding file handler. */
2621 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
2622 if (!NILP (handler
))
2623 return call2 (handler
, Qfile_writable_p
, absname
);
2625 encoded
= ENCODE_FILE (absname
);
2626 if (check_writable (SSDATA (encoded
), W_OK
))
2628 if (errno
!= ENOENT
)
2631 dir
= Ffile_name_directory (absname
);
2632 eassert (!NILP (dir
));
2634 dir
= Fdirectory_file_name (dir
);
2637 dir
= ENCODE_FILE (dir
);
2639 /* The read-only attribute of the parent directory doesn't affect
2640 whether a file or directory can be created within it. Some day we
2641 should check ACLs though, which do affect this. */
2642 return file_directory_p (dir
) ? Qt
: Qnil
;
2644 return check_writable (SSDATA (dir
), W_OK
| X_OK
) ? Qt
: Qnil
;
2648 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
2649 doc
: /* Access file FILENAME, and get an error if that does not work.
2650 The second argument STRING is prepended to the error message.
2651 If there is no error, returns nil. */)
2652 (Lisp_Object filename
, Lisp_Object string
)
2654 Lisp_Object handler
, encoded_filename
, absname
;
2656 CHECK_STRING (filename
);
2657 absname
= Fexpand_file_name (filename
, Qnil
);
2659 CHECK_STRING (string
);
2661 /* If the file name has special constructs in it,
2662 call the corresponding file handler. */
2663 handler
= Ffind_file_name_handler (absname
, Qaccess_file
);
2664 if (!NILP (handler
))
2665 return call3 (handler
, Qaccess_file
, absname
, string
);
2667 encoded_filename
= ENCODE_FILE (absname
);
2669 if (faccessat (AT_FDCWD
, SSDATA (encoded_filename
), R_OK
, AT_EACCESS
) != 0)
2670 report_file_error (SSDATA (string
), filename
);
2675 /* Relative to directory FD, return the symbolic link value of FILENAME.
2676 On failure, return nil. */
2678 emacs_readlinkat (int fd
, char const *filename
)
2680 static struct allocator
const emacs_norealloc_allocator
=
2681 { xmalloc
, NULL
, xfree
, memory_full
};
2683 char readlink_buf
[1024];
2684 char *buf
= careadlinkat (fd
, filename
, readlink_buf
, sizeof readlink_buf
,
2685 &emacs_norealloc_allocator
, readlinkat
);
2689 val
= build_unibyte_string (buf
);
2690 if (buf
!= readlink_buf
)
2692 val
= DECODE_FILE (val
);
2696 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
2697 doc
: /* Return non-nil if file FILENAME is the name of a symbolic link.
2698 The value is the link target, as a string.
2699 Otherwise it returns nil.
2701 This function does not check whether the link target exists. */)
2702 (Lisp_Object filename
)
2704 Lisp_Object handler
;
2706 CHECK_STRING (filename
);
2707 filename
= Fexpand_file_name (filename
, Qnil
);
2709 /* If the file name has special constructs in it,
2710 call the corresponding file handler. */
2711 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
2712 if (!NILP (handler
))
2713 return call2 (handler
, Qfile_symlink_p
, filename
);
2715 filename
= ENCODE_FILE (filename
);
2717 return emacs_readlinkat (AT_FDCWD
, SSDATA (filename
));
2720 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
2721 doc
: /* Return t if FILENAME names an existing directory.
2722 Symbolic links to directories count as directories.
2723 See `file-symlink-p' to distinguish symlinks. */)
2724 (Lisp_Object filename
)
2726 Lisp_Object absname
= expand_and_dir_to_file (filename
);
2728 /* If the file name has special constructs in it,
2729 call the corresponding file handler. */
2730 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
2731 if (!NILP (handler
))
2732 return call2 (handler
, Qfile_directory_p
, absname
);
2734 absname
= ENCODE_FILE (absname
);
2736 return file_directory_p (absname
) ? Qt
: Qnil
;
2739 /* Return true if FILE is a directory or a symlink to a directory.
2740 Otherwise return false and set errno. */
2742 file_directory_p (Lisp_Object file
)
2745 /* This is cheaper than 'stat'. */
2746 return faccessat (AT_FDCWD
, SSDATA (file
), D_OK
, AT_EACCESS
) == 0;
2749 /* Use O_PATH if available, as it avoids races and EOVERFLOW issues. */
2750 int fd
= openat (AT_FDCWD
, SSDATA (file
), O_PATH
| O_CLOEXEC
| O_DIRECTORY
);
2756 if (errno
!= EINVAL
)
2758 /* O_PATH is defined but evidently this Linux kernel predates 2.6.39.
2759 Fall back on generic POSIX code. */
2761 /* Use file_accessible_directory, as it avoids stat EOVERFLOW
2762 problems and could be cheaper. However, if it fails because FILE
2763 is inaccessible, fall back on stat; if the latter fails with
2764 EOVERFLOW then FILE must have been a directory unless a race
2765 condition occurred (a problem hard to work around portably). */
2766 if (file_accessible_directory_p (file
))
2768 if (errno
!= EACCES
)
2771 if (stat (SSDATA (file
), &st
) != 0)
2772 return errno
== EOVERFLOW
;
2773 if (S_ISDIR (st
.st_mode
))
2780 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
,
2781 Sfile_accessible_directory_p
, 1, 1, 0,
2782 doc
: /* Return t if FILENAME names a directory you can open.
2783 For the value to be t, FILENAME must specify the name of a directory
2784 as a file, and the directory must allow you to open files in it. In
2785 order to use a directory as a buffer's current directory, this
2786 predicate must return true. A directory name spec may be given
2787 instead; then the value is t if the directory so specified exists and
2788 really is a readable and searchable directory. */)
2789 (Lisp_Object filename
)
2791 Lisp_Object absname
;
2792 Lisp_Object handler
;
2794 CHECK_STRING (filename
);
2795 absname
= Fexpand_file_name (filename
, Qnil
);
2797 /* If the file name has special constructs in it,
2798 call the corresponding file handler. */
2799 handler
= Ffind_file_name_handler (absname
, Qfile_accessible_directory_p
);
2800 if (!NILP (handler
))
2802 Lisp_Object r
= call2 (handler
, Qfile_accessible_directory_p
, absname
);
2804 /* Set errno in case the handler failed. EACCES might be a lie
2805 (e.g., the directory might not exist, or be a regular file),
2806 but at least it does TRT in the "usual" case of an existing
2807 directory that is not accessible by the current user, and
2808 avoids reporting "Success" for a failed operation. Perhaps
2809 someday we can fix this in a better way, by improving
2810 file-accessible-directory-p's API; see Bug#25419. */
2817 absname
= ENCODE_FILE (absname
);
2818 return file_accessible_directory_p (absname
) ? Qt
: Qnil
;
2821 /* If FILE is a searchable directory or a symlink to a
2822 searchable directory, return true. Otherwise return
2823 false and set errno to an error number. */
2825 file_accessible_directory_p (Lisp_Object file
)
2829 /* We need a special-purpose test because (a) NTFS security data is
2830 not reflected in Posix-style mode bits, and (b) the trick with
2831 accessing "DIR/.", used below on Posix hosts, doesn't work on
2832 Windows, because "DIR/." is normalized to just "DIR" before
2833 hitting the disk. */
2834 return (SBYTES (file
) == 0
2835 || w32_accessible_directory_p (SSDATA (file
), SBYTES (file
)));
2837 return file_directory_p (file
);
2840 /* On POSIXish platforms, use just one system call; this avoids a
2841 race and is typically faster. */
2842 const char *data
= SSDATA (file
);
2843 ptrdiff_t len
= SBYTES (file
);
2849 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2850 There are three exceptions: "", "/", and "//". Leave "" alone,
2851 as it's invalid. Append only "." to the other two exceptions as
2852 "/" and "//" are distinct on some platforms, whereas "/", "///",
2853 "////", etc. are all equivalent. */
2858 /* Just check for trailing '/' when deciding whether append '/'
2859 before appending '.'. That's simpler than testing the two
2860 special cases "/" and "//", and it's a safe optimization
2861 here. After appending '.', append another '/' to work around
2862 a macOS bug (Bug#30350). */
2863 static char const appended
[] = "/./";
2864 char *buf
= SAFE_ALLOCA (len
+ sizeof appended
);
2865 memcpy (buf
, data
, len
);
2866 strcpy (buf
+ len
, &appended
[data
[len
- 1] == '/']);
2870 ok
= check_existing (dir
);
2871 saved_errno
= errno
;
2873 errno
= saved_errno
;
2875 #endif /* !DOS_NT */
2878 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
2879 doc
: /* Return t if FILENAME names a regular file.
2880 This is the sort of file that holds an ordinary stream of data bytes.
2881 Symbolic links to regular files count as regular files.
2882 See `file-symlink-p' to distinguish symlinks. */)
2883 (Lisp_Object filename
)
2886 Lisp_Object absname
= expand_and_dir_to_file (filename
);
2888 /* If the file name has special constructs in it,
2889 call the corresponding file handler. */
2890 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
2891 if (!NILP (handler
))
2892 return call2 (handler
, Qfile_regular_p
, absname
);
2894 absname
= ENCODE_FILE (absname
);
2899 Lisp_Object tem
= Vw32_get_true_file_attributes
;
2901 /* Tell stat to use expensive method to get accurate info. */
2902 Vw32_get_true_file_attributes
= Qt
;
2903 result
= stat (SSDATA (absname
), &st
);
2904 Vw32_get_true_file_attributes
= tem
;
2908 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2911 if (stat (SSDATA (absname
), &st
) < 0)
2913 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2917 DEFUN ("file-selinux-context", Ffile_selinux_context
,
2918 Sfile_selinux_context
, 1, 1, 0,
2919 doc
: /* Return SELinux context of file named FILENAME.
2920 The return value is a list (USER ROLE TYPE RANGE), where the list
2921 elements are strings naming the user, role, type, and range of the
2922 file's SELinux security context.
2924 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2925 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2926 (Lisp_Object filename
)
2928 Lisp_Object user
= Qnil
, role
= Qnil
, type
= Qnil
, range
= Qnil
;
2929 Lisp_Object absname
= expand_and_dir_to_file (filename
);
2931 /* If the file name has special constructs in it,
2932 call the corresponding file handler. */
2933 Lisp_Object handler
= Ffind_file_name_handler (absname
,
2934 Qfile_selinux_context
);
2935 if (!NILP (handler
))
2936 return call2 (handler
, Qfile_selinux_context
, absname
);
2938 absname
= ENCODE_FILE (absname
);
2941 if (is_selinux_enabled ())
2943 security_context_t con
;
2944 int conlength
= lgetfilecon (SSDATA (absname
), &con
);
2947 context_t context
= context_new (con
);
2948 if (context_user_get (context
))
2949 user
= build_string (context_user_get (context
));
2950 if (context_role_get (context
))
2951 role
= build_string (context_role_get (context
));
2952 if (context_type_get (context
))
2953 type
= build_string (context_type_get (context
));
2954 if (context_range_get (context
))
2955 range
= build_string (context_range_get (context
));
2956 context_free (context
);
2962 return list4 (user
, role
, type
, range
);
2965 DEFUN ("set-file-selinux-context", Fset_file_selinux_context
,
2966 Sset_file_selinux_context
, 2, 2, 0,
2967 doc
: /* Set SELinux context of file named FILENAME to CONTEXT.
2968 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2969 elements are strings naming the components of a SELinux context.
2971 Value is t if setting of SELinux context was successful, nil otherwise.
2973 This function does nothing and returns nil if SELinux is disabled,
2974 or if Emacs was not compiled with SELinux support. */)
2975 (Lisp_Object filename
, Lisp_Object context
)
2977 Lisp_Object absname
;
2978 Lisp_Object handler
;
2980 Lisp_Object encoded_absname
;
2981 Lisp_Object user
= CAR_SAFE (context
);
2982 Lisp_Object role
= CAR_SAFE (CDR_SAFE (context
));
2983 Lisp_Object type
= CAR_SAFE (CDR_SAFE (CDR_SAFE (context
)));
2984 Lisp_Object range
= CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context
))));
2985 security_context_t con
;
2988 context_t parsed_con
;
2991 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2993 /* If the file name has special constructs in it,
2994 call the corresponding file handler. */
2995 handler
= Ffind_file_name_handler (absname
, Qset_file_selinux_context
);
2996 if (!NILP (handler
))
2997 return call3 (handler
, Qset_file_selinux_context
, absname
, context
);
3000 if (is_selinux_enabled ())
3002 /* Get current file context. */
3003 encoded_absname
= ENCODE_FILE (absname
);
3004 conlength
= lgetfilecon (SSDATA (encoded_absname
), &con
);
3007 parsed_con
= context_new (con
);
3008 /* Change the parts defined in the parameter.*/
3011 if (context_user_set (parsed_con
, SSDATA (user
)))
3012 error ("Doing context_user_set");
3016 if (context_role_set (parsed_con
, SSDATA (role
)))
3017 error ("Doing context_role_set");
3021 if (context_type_set (parsed_con
, SSDATA (type
)))
3022 error ("Doing context_type_set");
3024 if (STRINGP (range
))
3026 if (context_range_set (parsed_con
, SSDATA (range
)))
3027 error ("Doing context_range_set");
3030 /* Set the modified context back to the file. */
3031 fail
= (lsetfilecon (SSDATA (encoded_absname
),
3032 context_str (parsed_con
))
3034 /* See https://debbugs.gnu.org/11245 for ENOTSUP. */
3035 if (fail
&& errno
!= ENOTSUP
)
3036 report_file_error ("Doing lsetfilecon", absname
);
3038 context_free (parsed_con
);
3040 return fail
? Qnil
: Qt
;
3043 report_file_error ("Doing lgetfilecon", absname
);
3050 DEFUN ("file-acl", Ffile_acl
, Sfile_acl
, 1, 1, 0,
3051 doc
: /* Return ACL entries of file named FILENAME.
3052 The entries are returned in a format suitable for use in `set-file-acl'
3053 but is otherwise undocumented and subject to change.
3054 Return nil if file does not exist or is not accessible, or if Emacs
3055 was unable to determine the ACL entries. */)
3056 (Lisp_Object filename
)
3058 Lisp_Object acl_string
= Qnil
;
3061 Lisp_Object absname
= expand_and_dir_to_file (filename
);
3063 /* If the file name has special constructs in it,
3064 call the corresponding file handler. */
3065 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_acl
);
3066 if (!NILP (handler
))
3067 return call2 (handler
, Qfile_acl
, absname
);
3069 # ifdef HAVE_ACL_SET_FILE
3070 absname
= ENCODE_FILE (absname
);
3072 # ifndef HAVE_ACL_TYPE_EXTENDED
3073 acl_type_t ACL_TYPE_EXTENDED
= ACL_TYPE_ACCESS
;
3075 acl_t acl
= acl_get_file (SSDATA (absname
), ACL_TYPE_EXTENDED
);
3079 char *str
= acl_to_text (acl
, NULL
);
3086 acl_string
= build_string (str
);
3095 DEFUN ("set-file-acl", Fset_file_acl
, Sset_file_acl
,
3097 doc
: /* Set ACL of file named FILENAME to ACL-STRING.
3098 ACL-STRING should contain the textual representation of the ACL
3099 entries in a format suitable for the platform.
3101 Value is t if setting of ACL was successful, nil otherwise.
3103 Setting ACL for local files requires Emacs to be built with ACL
3105 (Lisp_Object filename
, Lisp_Object acl_string
)
3108 Lisp_Object absname
;
3109 Lisp_Object handler
;
3110 # ifdef HAVE_ACL_SET_FILE
3111 Lisp_Object encoded_absname
;
3116 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3118 /* If the file name has special constructs in it,
3119 call the corresponding file handler. */
3120 handler
= Ffind_file_name_handler (absname
, Qset_file_acl
);
3121 if (!NILP (handler
))
3122 return call3 (handler
, Qset_file_acl
, absname
, acl_string
);
3124 # ifdef HAVE_ACL_SET_FILE
3125 if (STRINGP (acl_string
))
3127 acl
= acl_from_text (SSDATA (acl_string
));
3130 if (acl_errno_valid (errno
))
3131 report_file_error ("Converting ACL", absname
);
3135 encoded_absname
= ENCODE_FILE (absname
);
3137 fail
= (acl_set_file (SSDATA (encoded_absname
), ACL_TYPE_ACCESS
,
3140 if (fail
&& acl_errno_valid (errno
))
3141 report_file_error ("Setting ACL", absname
);
3144 return fail
? Qnil
: Qt
;
3152 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
3153 doc
: /* Return mode bits of file named FILENAME, as an integer.
3154 Return nil, if file does not exist or is not accessible. */)
3155 (Lisp_Object filename
)
3158 Lisp_Object absname
= expand_and_dir_to_file (filename
);
3160 /* If the file name has special constructs in it,
3161 call the corresponding file handler. */
3162 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
3163 if (!NILP (handler
))
3164 return call2 (handler
, Qfile_modes
, absname
);
3166 absname
= ENCODE_FILE (absname
);
3168 if (stat (SSDATA (absname
), &st
) < 0)
3171 return make_number (st
.st_mode
& 07777);
3174 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2,
3175 "(let ((file (read-file-name \"File: \"))) \
3176 (list file (read-file-modes nil file)))",
3177 doc
: /* Set mode bits of file named FILENAME to MODE (an integer).
3178 Only the 12 low bits of MODE are used.
3180 Interactively, mode bits are read by `read-file-modes', which accepts
3181 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3182 (Lisp_Object filename
, Lisp_Object mode
)
3184 Lisp_Object absname
, encoded_absname
;
3185 Lisp_Object handler
;
3187 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3188 CHECK_NUMBER (mode
);
3190 /* If the file name has special constructs in it,
3191 call the corresponding file handler. */
3192 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
3193 if (!NILP (handler
))
3194 return call3 (handler
, Qset_file_modes
, absname
, mode
);
3196 encoded_absname
= ENCODE_FILE (absname
);
3198 if (chmod (SSDATA (encoded_absname
), XINT (mode
) & 07777) < 0)
3199 report_file_error ("Doing chmod", absname
);
3204 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
3205 doc
: /* Set the file permission bits for newly created files.
3206 The argument MODE should be an integer; only the low 9 bits are used.
3207 On Posix hosts, this setting is inherited by subprocesses.
3209 This function works by setting the Emacs's file mode creation mask.
3210 Each bit that is set in the mask means that the corresponding bit
3211 in the permissions of newly created files will be disabled.
3213 Note that when `write-region' creates a file, it resets the
3214 execute bit, even if the mask set by this function allows that bit
3215 by having the corresponding bit in the mask reset. */)
3218 mode_t oldrealmask
, oldumask
, newumask
;
3219 CHECK_NUMBER (mode
);
3220 oldrealmask
= realmask
;
3221 newumask
= ~ XINT (mode
) & 0777;
3224 realmask
= newumask
;
3225 oldumask
= umask (newumask
);
3228 eassert (oldumask
== oldrealmask
);
3232 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
3233 doc
: /* Return the default file protection for created files.
3234 The value is an integer. */)
3238 XSETINT (value
, (~ realmask
) & 0777);
3243 DEFUN ("set-file-times", Fset_file_times
, Sset_file_times
, 1, 2, 0,
3244 doc
: /* Set times of file FILENAME to TIMESTAMP.
3245 Set both access and modification times.
3246 Return t on success, else nil.
3247 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3249 (Lisp_Object filename
, Lisp_Object timestamp
)
3251 Lisp_Object absname
, encoded_absname
;
3252 Lisp_Object handler
;
3253 struct timespec t
= lisp_time_argument (timestamp
);
3255 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3257 /* If the file name has special constructs in it,
3258 call the corresponding file handler. */
3259 handler
= Ffind_file_name_handler (absname
, Qset_file_times
);
3260 if (!NILP (handler
))
3261 return call3 (handler
, Qset_file_times
, absname
, timestamp
);
3263 encoded_absname
= ENCODE_FILE (absname
);
3266 if (set_file_times (-1, SSDATA (encoded_absname
), t
, t
) != 0)
3269 /* Setting times on a directory always fails. */
3270 if (file_directory_p (encoded_absname
))
3273 report_file_error ("Setting file times", absname
);
3281 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3282 doc
: /* Tell Unix to finish all pending disk updates. */)
3289 #endif /* HAVE_SYNC */
3291 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3292 doc
: /* Return t if file FILE1 is newer than file FILE2.
3293 If FILE1 does not exist, the answer is nil;
3294 otherwise, if FILE2 does not exist, the answer is t. */)
3295 (Lisp_Object file1
, Lisp_Object file2
)
3297 struct stat st1
, st2
;
3299 CHECK_STRING (file1
);
3300 CHECK_STRING (file2
);
3302 Lisp_Object absname1
= expand_and_dir_to_file (file1
);
3303 Lisp_Object absname2
= expand_and_dir_to_file (file2
);
3305 /* If the file name has special constructs in it,
3306 call the corresponding file handler. */
3307 Lisp_Object handler
= Ffind_file_name_handler (absname1
,
3308 Qfile_newer_than_file_p
);
3310 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3311 if (!NILP (handler
))
3312 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3314 absname1
= ENCODE_FILE (absname1
);
3315 absname2
= ENCODE_FILE (absname2
);
3317 if (stat (SSDATA (absname1
), &st1
) < 0)
3320 if (stat (SSDATA (absname2
), &st2
) < 0)
3323 return (timespec_cmp (get_stat_mtime (&st2
), get_stat_mtime (&st1
)) < 0
3327 enum { READ_BUF_SIZE
= MAX_ALLOCA
};
3329 /* This function is called after Lisp functions to decide a coding
3330 system are called, or when they cause an error. Before they are
3331 called, the current buffer is set unibyte and it contains only a
3332 newly inserted text (thus the buffer was empty before the
3335 The functions may set markers, overlays, text properties, or even
3336 alter the buffer contents, change the current buffer.
3338 Here, we reset all those changes by:
3339 o set back the current buffer.
3340 o move all markers and overlays to BEG.
3341 o remove all text properties.
3342 o set back the buffer multibyteness. */
3345 decide_coding_unwind (Lisp_Object unwind_data
)
3347 Lisp_Object multibyte
, undo_list
, buffer
;
3349 multibyte
= XCAR (unwind_data
);
3350 unwind_data
= XCDR (unwind_data
);
3351 undo_list
= XCAR (unwind_data
);
3352 buffer
= XCDR (unwind_data
);
3354 set_buffer_internal (XBUFFER (buffer
));
3355 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3356 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3357 set_buffer_intervals (current_buffer
, NULL
);
3358 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3360 /* Now we are safe to change the buffer's multibyteness directly. */
3361 bset_enable_multibyte_characters (current_buffer
, multibyte
);
3362 bset_undo_list (current_buffer
, undo_list
);
3365 /* Read from a non-regular file. Return the number of bytes read. */
3367 union read_non_regular
3372 ptrdiff_t inserted
, trytry
;
3376 verify (alignof (union read_non_regular
) % GCALIGNMENT
== 0);
3379 read_non_regular (Lisp_Object state
)
3381 union read_non_regular
*data
= XINTPTR (state
);
3382 int nbytes
= emacs_read_quit (data
->s
.fd
,
3383 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
3384 + data
->s
.inserted
),
3386 return make_number (nbytes
);
3390 /* Condition-case handler used when reading from non-regular files
3391 in insert-file-contents. */
3394 read_non_regular_quit (Lisp_Object ignore
)
3399 /* Return the file offset that VAL represents, checking for type
3400 errors and overflow. */
3402 file_offset (Lisp_Object val
)
3404 if (RANGED_INTEGERP (0, val
, TYPE_MAXIMUM (off_t
)))
3409 double v
= XFLOAT_DATA (val
);
3410 if (0 <= v
&& v
< 1.0 + TYPE_MAXIMUM (off_t
))
3418 wrong_type_argument (intern ("file-offset"), val
);
3421 /* Return a special time value indicating the error number ERRNUM. */
3422 static struct timespec
3423 time_error_value (int errnum
)
3425 int ns
= (errnum
== ENOENT
|| errnum
== EACCES
|| errnum
== ENOTDIR
3426 ? NONEXISTENT_MODTIME_NSECS
3427 : UNKNOWN_MODTIME_NSECS
);
3428 return make_timespec (0, ns
);
3432 get_window_points_and_markers (void)
3434 Lisp_Object pt_marker
= Fpoint_marker ();
3436 = call3 (Qget_buffer_window_list
, Fcurrent_buffer (), Qnil
, Qt
);
3437 Lisp_Object window_markers
= windows
;
3438 /* Window markers (and point) are handled specially: rather than move to
3439 just before or just after the modified text, we try to keep the
3440 markers at the same distance (bug#19161).
3441 In general, this is wrong, but for window-markers, this should be harmless
3442 and is convenient for the end user when most of the file is unmodified,
3443 except for a few minor details near the beginning and near the end. */
3444 for (; CONSP (windows
); windows
= XCDR (windows
))
3445 if (WINDOWP (XCAR (windows
)))
3447 Lisp_Object window_marker
= XWINDOW (XCAR (windows
))->pointm
;
3449 Fcons (window_marker
, Fmarker_position (window_marker
)));
3451 return Fcons (Fcons (pt_marker
, Fpoint ()), window_markers
);
3455 restore_window_points (Lisp_Object window_markers
, ptrdiff_t inserted
,
3456 ptrdiff_t same_at_start
, ptrdiff_t same_at_end
)
3458 for (; CONSP (window_markers
); window_markers
= XCDR (window_markers
))
3459 if (CONSP (XCAR (window_markers
)))
3461 Lisp_Object car
= XCAR (window_markers
);
3462 Lisp_Object marker
= XCAR (car
);
3463 Lisp_Object oldpos
= XCDR (car
);
3464 if (MARKERP (marker
) && INTEGERP (oldpos
)
3465 && XINT (oldpos
) > same_at_start
3466 && XINT (oldpos
) < same_at_end
)
3468 ptrdiff_t oldsize
= same_at_end
- same_at_start
;
3469 ptrdiff_t newsize
= inserted
;
3470 double growth
= newsize
/ (double)oldsize
;
3472 = same_at_start
+ growth
* (XINT (oldpos
) - same_at_start
);
3473 Fset_marker (marker
, make_number (newpos
), Qnil
);
3478 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3479 text as a linear C char array. */
3481 maybe_move_gap (struct buffer
*b
)
3483 if (BUF_GPT_BYTE (b
) != BUF_Z_BYTE (b
))
3485 struct buffer
*cb
= current_buffer
;
3487 set_buffer_internal (b
);
3488 move_gap_both (Z
, Z_BYTE
);
3489 set_buffer_internal (cb
);
3493 /* FIXME: insert-file-contents should be split with the top-level moved to
3494 Elisp and only the core kept in C. */
3496 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3498 doc
: /* Insert contents of file FILENAME after point.
3499 Returns list of absolute file name and number of characters inserted.
3500 If second argument VISIT is non-nil, the buffer's visited filename and
3501 last save file modtime are set, and it is marked unmodified. If
3502 visiting and the file does not exist, visiting is completed before the
3505 The optional third and fourth arguments BEG and END specify what portion
3506 of the file to insert. These arguments count bytes in the file, not
3507 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3509 If optional fifth argument REPLACE is non-nil, replace the current
3510 buffer contents (in the accessible portion) with the file contents.
3511 This is better than simply deleting and inserting the whole thing
3512 because (1) it preserves some marker positions and (2) it puts less data
3513 in the undo list. When REPLACE is non-nil, the second return value is
3514 the number of characters that replace previous buffer contents.
3516 This function does code conversion according to the value of
3517 `coding-system-for-read' or `file-coding-system-alist', and sets the
3518 variable `last-coding-system-used' to the coding system actually used.
3520 In addition, this function decodes the inserted text from known formats
3521 by calling `format-decode', which see. */)
3522 (Lisp_Object filename
, Lisp_Object visit
, Lisp_Object beg
, Lisp_Object end
, Lisp_Object replace
)
3525 struct timespec mtime
;
3527 ptrdiff_t inserted
= 0;
3529 off_t beg_offset
, end_offset
;
3531 ptrdiff_t count
= SPECPDL_INDEX ();
3532 Lisp_Object handler
, val
, insval
, orig_filename
, old_undo
;
3534 ptrdiff_t total
= 0;
3535 bool not_regular
= 0;
3537 char read_buf
[READ_BUF_SIZE
];
3538 struct coding_system coding
;
3539 bool replace_handled
= false;
3540 bool set_coding_system
= false;
3541 Lisp_Object coding_system
;
3542 bool read_quit
= false;
3543 /* If the undo log only contains the insertion, there's no point
3544 keeping it. It's typically when we first fill a file-buffer. */
3545 bool empty_undo_list_p
3546 = (!NILP (visit
) && NILP (BVAR (current_buffer
, undo_list
))
3548 Lisp_Object old_Vdeactivate_mark
= Vdeactivate_mark
;
3549 bool we_locked_file
= false;
3551 Lisp_Object window_markers
= Qnil
;
3552 /* same_at_start and same_at_end count bytes, because file access counts
3553 bytes and BEG and END count bytes. */
3554 ptrdiff_t same_at_start
= BEGV_BYTE
;
3555 ptrdiff_t same_at_end
= ZV_BYTE
;
3556 /* SAME_AT_END_CHARPOS counts characters, because
3557 restore_window_points needs the old character count. */
3558 ptrdiff_t same_at_end_charpos
= ZV
;
3560 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3561 error ("Cannot do file visiting in an indirect buffer");
3563 if (!NILP (BVAR (current_buffer
, read_only
)))
3564 Fbarf_if_buffer_read_only (Qnil
);
3568 orig_filename
= Qnil
;
3571 CHECK_STRING (filename
);
3572 filename
= Fexpand_file_name (filename
, Qnil
);
3574 /* The value Qnil means that the coding system is not yet
3576 coding_system
= Qnil
;
3578 /* If the file name has special constructs in it,
3579 call the corresponding file handler. */
3580 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3581 if (!NILP (handler
))
3583 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3584 visit
, beg
, end
, replace
);
3585 if (CONSP (val
) && CONSP (XCDR (val
))
3586 && RANGED_INTEGERP (0, XCAR (XCDR (val
)), ZV
- PT
))
3587 inserted
= XINT (XCAR (XCDR (val
)));
3591 orig_filename
= filename
;
3592 filename
= ENCODE_FILE (filename
);
3594 fd
= emacs_open (SSDATA (filename
), O_RDONLY
, 0);
3599 report_file_error ("Opening input file", orig_filename
);
3600 mtime
= time_error_value (save_errno
);
3602 if (!NILP (Vcoding_system_for_read
))
3604 /* Don't let invalid values into buffer-file-coding-system. */
3605 CHECK_CODING_SYSTEM (Vcoding_system_for_read
);
3606 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3611 fd_index
= SPECPDL_INDEX ();
3612 record_unwind_protect_int (close_file_unwind
, fd
);
3614 /* Replacement should preserve point as it preserves markers. */
3615 if (!NILP (replace
))
3617 window_markers
= get_window_points_and_markers ();
3618 record_unwind_protect (restore_point_unwind
,
3619 XCAR (XCAR (window_markers
)));
3622 if (fstat (fd
, &st
) != 0)
3623 report_file_error ("Input file status", orig_filename
);
3624 mtime
= get_stat_mtime (&st
);
3626 /* This code will need to be changed in order to work on named
3627 pipes, and it's probably just not worth it. So we should at
3628 least signal an error. */
3629 if (!S_ISREG (st
.st_mode
))
3636 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3637 xsignal2 (Qfile_error
,
3638 build_string ("not a regular file"), orig_filename
);
3643 if (!NILP (beg
) || !NILP (end
))
3644 error ("Attempt to visit less than an entire file");
3645 if (BEG
< Z
&& NILP (replace
))
3646 error ("Cannot do file visiting in a non-empty buffer");
3650 beg_offset
= file_offset (beg
);
3655 end_offset
= file_offset (end
);
3659 end_offset
= TYPE_MAXIMUM (off_t
);
3662 end_offset
= st
.st_size
;
3664 /* A negative size can happen on a platform that allows file
3665 sizes greater than the maximum off_t value. */
3669 /* The file size returned from stat may be zero, but data
3670 may be readable nonetheless, for example when this is a
3671 file in the /proc filesystem. */
3672 if (end_offset
== 0)
3673 end_offset
= READ_BUF_SIZE
;
3677 /* Check now whether the buffer will become too large,
3678 in the likely case where the file's length is not changing.
3679 This saves a lot of needless work before a buffer overflow. */
3682 /* The likely offset where we will stop reading. We could read
3683 more (or less), if the file grows (or shrinks) as we read it. */
3684 off_t likely_end
= min (end_offset
, st
.st_size
);
3686 if (beg_offset
< likely_end
)
3689 = Z_BYTE
- (!NILP (replace
) ? ZV_BYTE
- BEGV_BYTE
: 0);
3690 ptrdiff_t buf_growth_max
= BUF_BYTES_MAX
- buf_bytes
;
3691 off_t likely_growth
= likely_end
- beg_offset
;
3692 if (buf_growth_max
< likely_growth
)
3697 /* Prevent redisplay optimizations. */
3698 current_buffer
->clip_changed
= true;
3700 if (EQ (Vcoding_system_for_read
, Qauto_save_coding
))
3702 coding_system
= coding_inherit_eol_type (Qutf_8_emacs
, Qunix
);
3703 setup_coding_system (coding_system
, &coding
);
3704 /* Ensure we set Vlast_coding_system_used. */
3705 set_coding_system
= true;
3709 /* Decide the coding system to use for reading the file now
3710 because we can't use an optimized method for handling
3711 `coding:' tag if the current buffer is not empty. */
3712 if (!NILP (Vcoding_system_for_read
))
3713 coding_system
= Vcoding_system_for_read
;
3716 /* Don't try looking inside a file for a coding system
3717 specification if it is not seekable. */
3718 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3720 /* Find a coding system specified in the heading two
3721 lines or in the tailing several lines of the file.
3722 We assume that the 1K-byte and 3K-byte for heading
3723 and tailing respectively are sufficient for this
3727 if (st
.st_size
<= (1024 * 4))
3728 nread
= emacs_read_quit (fd
, read_buf
, 1024 * 4);
3731 nread
= emacs_read_quit (fd
, read_buf
, 1024);
3735 if (lseek (fd
, - (1024 * 3), SEEK_END
) < 0)
3736 report_file_error ("Setting file position",
3738 ntail
= emacs_read_quit (fd
, read_buf
+ nread
, 1024 * 3);
3739 nread
= ntail
< 0 ? ntail
: nread
+ ntail
;
3744 report_file_error ("Read error", orig_filename
);
3747 AUTO_STRING (name
, " *code-converting-work*");
3748 struct buffer
*prev
= current_buffer
;
3749 Lisp_Object workbuf
;
3752 record_unwind_current_buffer ();
3754 workbuf
= Fget_buffer_create (name
);
3755 buf
= XBUFFER (workbuf
);
3757 delete_all_overlays (buf
);
3758 bset_directory (buf
, BVAR (current_buffer
, directory
));
3759 bset_read_only (buf
, Qnil
);
3760 bset_filename (buf
, Qnil
);
3761 bset_undo_list (buf
, Qt
);
3762 eassert (buf
->overlays_before
== NULL
);
3763 eassert (buf
->overlays_after
== NULL
);
3765 set_buffer_internal (buf
);
3767 bset_enable_multibyte_characters (buf
, Qnil
);
3769 insert_1_both ((char *) read_buf
, nread
, nread
, 0, 0, 0);
3770 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3771 coding_system
= call2 (Vset_auto_coding_function
,
3772 filename
, make_number (nread
));
3773 set_buffer_internal (prev
);
3775 /* Discard the unwind protect for recovering the
3779 /* Rewind the file for the actual read done later. */
3780 if (lseek (fd
, 0, SEEK_SET
) < 0)
3781 report_file_error ("Setting file position", orig_filename
);
3785 if (NILP (coding_system
))
3787 /* If we have not yet decided a coding system, check
3788 file-coding-system-alist. */
3789 coding_system
= CALLN (Ffind_operation_coding_system
,
3790 Qinsert_file_contents
, orig_filename
,
3791 visit
, beg
, end
, replace
);
3792 if (CONSP (coding_system
))
3793 coding_system
= XCAR (coding_system
);
3797 if (NILP (coding_system
))
3798 coding_system
= Qundecided
;
3800 CHECK_CODING_SYSTEM (coding_system
);
3802 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3803 /* We must suppress all character code conversion except for
3804 end-of-line conversion. */
3805 coding_system
= raw_text_coding_system (coding_system
);
3807 setup_coding_system (coding_system
, &coding
);
3808 /* Ensure we set Vlast_coding_system_used. */
3809 set_coding_system
= true;
3812 /* If requested, replace the accessible part of the buffer
3813 with the file contents. Avoid replacing text at the
3814 beginning or end of the buffer that matches the file contents;
3815 that preserves markers pointing to the unchanged parts.
3817 Here we implement this feature in an optimized way
3818 for the case where code conversion is NOT needed.
3819 The following if-statement handles the case of conversion
3820 in a less optimal way.
3822 If the code conversion is "automatic" then we try using this
3823 method and hope for the best.
3824 But if we discover the need for conversion, we give up on this method
3825 and let the following if-statement handle the replace job. */
3828 && (NILP (coding_system
)
3829 || ! CODING_REQUIRE_DECODING (&coding
)))
3832 /* There is still a possibility we will find the need to do code
3833 conversion. If that happens, set this variable to
3834 give up on handling REPLACE in the optimized way. */
3835 bool giveup_match_end
= false;
3837 if (beg_offset
!= 0)
3839 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3840 report_file_error ("Setting file position", orig_filename
);
3843 /* Count how many chars at the start of the file
3844 match the text at the beginning of the buffer. */
3847 int nread
= emacs_read_quit (fd
, read_buf
, sizeof read_buf
);
3849 report_file_error ("Read error", orig_filename
);
3850 else if (nread
== 0)
3853 if (CODING_REQUIRE_DETECTION (&coding
))
3855 coding_system
= detect_coding_system ((unsigned char *) read_buf
,
3858 setup_coding_system (coding_system
, &coding
);
3861 if (CODING_REQUIRE_DECODING (&coding
))
3862 /* We found that the file should be decoded somehow.
3863 Let's give up here. */
3865 giveup_match_end
= true;
3870 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3871 && FETCH_BYTE (same_at_start
) == read_buf
[bufpos
])
3872 same_at_start
++, bufpos
++;
3873 /* If we found a discrepancy, stop the scan.
3874 Otherwise loop around and scan the next bufferful. */
3875 if (bufpos
!= nread
)
3878 /* If the file matches the buffer completely,
3879 there's no need to replace anything. */
3880 if (same_at_start
- BEGV_BYTE
== end_offset
- beg_offset
)
3883 clear_unwind_protect (fd_index
);
3885 /* Truncate the buffer to the size of the file. */
3886 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3890 /* Count how many chars at the end of the file
3891 match the text at the end of the buffer. But, if we have
3892 already found that decoding is necessary, don't waste time. */
3893 while (!giveup_match_end
)
3895 int total_read
, nread
, bufpos
, trial
;
3898 /* At what file position are we now scanning? */
3899 curpos
= end_offset
- (ZV_BYTE
- same_at_end
);
3900 /* If the entire file matches the buffer tail, stop the scan. */
3903 /* How much can we scan in the next step? */
3904 trial
= min (curpos
, sizeof read_buf
);
3905 if (lseek (fd
, curpos
- trial
, SEEK_SET
) < 0)
3906 report_file_error ("Setting file position", orig_filename
);
3908 total_read
= nread
= 0;
3909 while (total_read
< trial
)
3911 nread
= emacs_read_quit (fd
, read_buf
+ total_read
,
3912 trial
- total_read
);
3914 report_file_error ("Read error", orig_filename
);
3915 else if (nread
== 0)
3917 total_read
+= nread
;
3920 /* Scan this bufferful from the end, comparing with
3921 the Emacs buffer. */
3922 bufpos
= total_read
;
3924 /* Compare with same_at_start to avoid counting some buffer text
3925 as matching both at the file's beginning and at the end. */
3926 while (bufpos
> 0 && same_at_end
> same_at_start
3927 && FETCH_BYTE (same_at_end
- 1) == read_buf
[bufpos
- 1])
3928 same_at_end
--, bufpos
--;
3930 /* If we found a discrepancy, stop the scan.
3931 Otherwise loop around and scan the preceding bufferful. */
3934 /* If this discrepancy is because of code conversion,
3935 we cannot use this method; giveup and try the other. */
3936 if (same_at_end
> same_at_start
3937 && FETCH_BYTE (same_at_end
- 1) >= 0200
3938 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
))
3939 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3940 giveup_match_end
= true;
3948 if (! giveup_match_end
)
3951 ptrdiff_t this_count
= SPECPDL_INDEX ();
3953 /* We win! We can handle REPLACE the optimized way. */
3955 /* Extend the start of non-matching text area to multibyte
3956 character boundary. */
3957 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3958 while (same_at_start
> BEGV_BYTE
3959 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3962 /* Extend the end of non-matching text area to multibyte
3963 character boundary. */
3964 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3965 while (same_at_end
< ZV_BYTE
3966 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3969 /* Don't try to reuse the same piece of text twice. */
3970 overlap
= (same_at_start
- BEGV_BYTE
3972 + (! NILP (end
) ? end_offset
: st
.st_size
) - ZV_BYTE
));
3974 same_at_end
+= overlap
;
3975 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
3977 /* Arrange to read only the nonmatching middle part of the file. */
3978 beg_offset
+= same_at_start
- BEGV_BYTE
;
3979 end_offset
-= ZV_BYTE
- same_at_end
;
3981 /* This binding is to avoid ask-user-about-supersession-threat
3982 being called in insert_from_buffer or del_range_bytes (via
3983 prepare_to_modify_buffer).
3984 AFAICT we could avoid ask-user-about-supersession-threat by setting
3985 current_buffer->modtime earlier, but we could still end up calling
3986 ask-user-about-supersession-threat if the file is modified while
3987 we read it, so we bind buffer-file-name instead. */
3988 specbind (intern ("buffer-file-name"), Qnil
);
3989 del_range_byte (same_at_start
, same_at_end
);
3990 /* Insert from the file at the proper position. */
3991 temp
= BYTE_TO_CHAR (same_at_start
);
3992 SET_PT_BOTH (temp
, same_at_start
);
3993 unbind_to (this_count
, Qnil
);
3995 /* If display currently starts at beginning of line,
3996 keep it that way. */
3997 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
3998 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
4000 replace_handled
= true;
4004 /* If requested, replace the accessible part of the buffer
4005 with the file contents. Avoid replacing text at the
4006 beginning or end of the buffer that matches the file contents;
4007 that preserves markers pointing to the unchanged parts.
4009 Here we implement this feature for the case where code conversion
4010 is needed, in a simple way that needs a lot of memory.
4011 The preceding if-statement handles the case of no conversion
4012 in a more optimized way. */
4013 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
4015 ptrdiff_t same_at_start_charpos
;
4016 ptrdiff_t inserted_chars
;
4019 unsigned char *decoded
;
4022 ptrdiff_t this_count
= SPECPDL_INDEX ();
4024 = ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
4025 Lisp_Object conversion_buffer
;
4027 conversion_buffer
= code_conversion_save (1, multibyte
);
4029 /* First read the whole file, performing code conversion into
4030 CONVERSION_BUFFER. */
4032 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
4033 report_file_error ("Setting file position", orig_filename
);
4035 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
4036 unprocessed
= 0; /* Bytes not processed in previous loop. */
4040 /* Read at most READ_BUF_SIZE bytes at a time, to allow
4041 quitting while reading a huge file. */
4043 this = emacs_read_quit (fd
, read_buf
+ unprocessed
,
4044 READ_BUF_SIZE
- unprocessed
);
4048 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer
),
4049 BUF_Z (XBUFFER (conversion_buffer
)));
4050 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
4051 unprocessed
+ this, conversion_buffer
);
4052 unprocessed
= coding
.carryover_bytes
;
4053 if (coding
.carryover_bytes
> 0)
4054 memcpy (read_buf
, coding
.carryover
, unprocessed
);
4058 report_file_error ("Read error", orig_filename
);
4060 clear_unwind_protect (fd_index
);
4062 if (unprocessed
> 0)
4064 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4065 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
4066 unprocessed
, conversion_buffer
);
4067 coding
.mode
&= ~CODING_MODE_LAST_BLOCK
;
4070 coding_system
= CODING_ID_NAME (coding
.id
);
4071 set_coding_system
= true;
4072 maybe_move_gap (XBUFFER (conversion_buffer
));
4073 decoded
= BUF_BEG_ADDR (XBUFFER (conversion_buffer
));
4074 inserted
= (BUF_Z_BYTE (XBUFFER (conversion_buffer
))
4075 - BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4077 /* Compare the beginning of the converted string with the buffer
4081 while (bufpos
< inserted
&& same_at_start
< same_at_end
4082 && FETCH_BYTE (same_at_start
) == decoded
[bufpos
])
4083 same_at_start
++, bufpos
++;
4085 /* If the file matches the head of buffer completely,
4086 there's no need to replace anything. */
4088 if (bufpos
== inserted
)
4090 /* Truncate the buffer to the size of the file. */
4091 if (same_at_start
!= same_at_end
)
4093 /* See previous specbind for the reason behind this. */
4094 specbind (intern ("buffer-file-name"), Qnil
);
4095 del_range_byte (same_at_start
, same_at_end
);
4099 unbind_to (this_count
, Qnil
);
4103 /* Extend the start of non-matching text area to the previous
4104 multibyte character boundary. */
4105 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4106 while (same_at_start
> BEGV_BYTE
4107 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
4110 /* Scan this bufferful from the end, comparing with
4111 the Emacs buffer. */
4114 /* Compare with same_at_start to avoid counting some buffer text
4115 as matching both at the file's beginning and at the end. */
4116 while (bufpos
> 0 && same_at_end
> same_at_start
4117 && FETCH_BYTE (same_at_end
- 1) == decoded
[bufpos
- 1])
4118 same_at_end
--, bufpos
--;
4120 /* Extend the end of non-matching text area to the next
4121 multibyte character boundary. */
4122 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4123 while (same_at_end
< ZV_BYTE
4124 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
4127 /* Don't try to reuse the same piece of text twice. */
4128 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
4130 same_at_end
+= overlap
;
4131 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
4133 /* If display currently starts at beginning of line,
4134 keep it that way. */
4135 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
4136 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
4138 /* Replace the chars that we need to replace,
4139 and update INSERTED to equal the number of bytes
4140 we are taking from the decoded string. */
4141 inserted
-= (ZV_BYTE
- same_at_end
) + (same_at_start
- BEGV_BYTE
);
4143 /* See previous specbind for the reason behind this. */
4144 specbind (intern ("buffer-file-name"), Qnil
);
4145 if (same_at_end
!= same_at_start
)
4147 del_range_byte (same_at_start
, same_at_end
);
4149 eassert (same_at_start
== GPT_BYTE
);
4150 same_at_start
= GPT_BYTE
;
4154 temp
= same_at_end_charpos
;
4156 /* Insert from the file at the proper position. */
4157 SET_PT_BOTH (temp
, same_at_start
);
4158 same_at_start_charpos
4159 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4160 same_at_start
- BEGV_BYTE
4161 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4162 eassert (same_at_start_charpos
== temp
- (BEGV
- BEG
));
4164 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4165 same_at_start
+ inserted
- BEGV_BYTE
4166 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)))
4167 - same_at_start_charpos
);
4168 insert_from_buffer (XBUFFER (conversion_buffer
),
4169 same_at_start_charpos
, inserted_chars
, 0);
4170 /* Set `inserted' to the number of inserted characters. */
4171 inserted
= PT
- temp
;
4172 /* Set point before the inserted characters. */
4173 SET_PT_BOTH (temp
, same_at_start
);
4175 unbind_to (this_count
, Qnil
);
4181 total
= end_offset
- beg_offset
;
4183 /* For a special file, all we can do is guess. */
4184 total
= READ_BUF_SIZE
;
4186 if (NILP (visit
) && total
> 0)
4188 if (!NILP (BVAR (current_buffer
, file_truename
))
4189 /* Make binding buffer-file-name to nil effective. */
4190 && !NILP (BVAR (current_buffer
, filename
))
4191 && SAVE_MODIFF
>= MODIFF
)
4192 we_locked_file
= true;
4193 prepare_to_modify_buffer (PT
, PT
, NULL
);
4196 move_gap_both (PT
, PT_BYTE
);
4197 if (GAP_SIZE
< total
)
4198 make_gap (total
- GAP_SIZE
);
4200 if (beg_offset
!= 0 || !NILP (replace
))
4202 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
4203 report_file_error ("Setting file position", orig_filename
);
4206 /* In the following loop, HOW_MUCH contains the total bytes read so
4207 far for a regular file, and not changed for a special file. But,
4208 before exiting the loop, it is set to a negative value if I/O
4212 /* Total bytes inserted. */
4215 /* Here, we don't do code conversion in the loop. It is done by
4216 decode_coding_gap after all data are read into the buffer. */
4218 ptrdiff_t gap_size
= GAP_SIZE
;
4220 while (how_much
< total
)
4222 /* `try' is reserved in some compilers (Microsoft C). */
4223 ptrdiff_t trytry
= min (total
- how_much
, READ_BUF_SIZE
);
4230 /* Maybe make more room. */
4231 if (gap_size
< trytry
)
4233 make_gap (trytry
- gap_size
);
4234 gap_size
= GAP_SIZE
- inserted
;
4237 /* Read from the file, capturing `quit'. When an
4238 error occurs, end the loop, and arrange for a quit
4239 to be signaled after decoding the text we read. */
4240 union read_non_regular data
= {{fd
, inserted
, trytry
}};
4241 nbytes
= internal_condition_case_1
4242 (read_non_regular
, make_pointer_integer (&data
),
4243 Qerror
, read_non_regular_quit
);
4251 this = XINT (nbytes
);
4255 /* Allow quitting out of the actual I/O. We don't make text
4256 part of the buffer until all the reading is done, so a C-g
4257 here doesn't do any harm. */
4258 this = emacs_read_quit (fd
,
4259 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
4272 /* For a regular file, where TOTAL is the real size,
4273 count HOW_MUCH to compare with it.
4274 For a special file, where TOTAL is just a buffer size,
4275 so don't bother counting in HOW_MUCH.
4276 (INSERTED is where we count the number of characters inserted.) */
4283 /* Now we have either read all the file data into the gap,
4284 or stop reading on I/O error or quit. If nothing was
4285 read, undo marking the buffer modified. */
4290 unlock_file (BVAR (current_buffer
, file_truename
));
4291 Vdeactivate_mark
= old_Vdeactivate_mark
;
4294 Fset (Qdeactivate_mark
, Qt
);
4297 clear_unwind_protect (fd_index
);
4300 report_file_error ("Read error", orig_filename
);
4302 /* Make the text read part of the buffer. */
4303 GAP_SIZE
-= inserted
;
4305 GPT_BYTE
+= inserted
;
4307 ZV_BYTE
+= inserted
;
4312 /* Put an anchor to ensure multi-byte form ends at gap. */
4317 if (NILP (coding_system
))
4319 /* The coding system is not yet decided. Decide it by an
4320 optimized method for handling `coding:' tag.
4322 Note that we can get here only if the buffer was empty
4323 before the insertion. */
4325 if (!NILP (Vcoding_system_for_read
))
4326 coding_system
= Vcoding_system_for_read
;
4329 /* Since we are sure that the current buffer was empty
4330 before the insertion, we can toggle
4331 enable-multibyte-characters directly here without taking
4332 care of marker adjustment. By this way, we can run Lisp
4333 program safely before decoding the inserted text. */
4334 Lisp_Object unwind_data
;
4335 ptrdiff_t count1
= SPECPDL_INDEX ();
4337 unwind_data
= Fcons (BVAR (current_buffer
, enable_multibyte_characters
),
4338 Fcons (BVAR (current_buffer
, undo_list
),
4339 Fcurrent_buffer ()));
4340 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4341 bset_undo_list (current_buffer
, Qt
);
4342 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4344 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4346 coding_system
= call2 (Vset_auto_coding_function
,
4347 filename
, make_number (inserted
));
4350 if (NILP (coding_system
))
4352 /* If the coding system is not yet decided, check
4353 file-coding-system-alist. */
4354 coding_system
= CALLN (Ffind_operation_coding_system
,
4355 Qinsert_file_contents
, orig_filename
,
4356 visit
, beg
, end
, Qnil
);
4357 if (CONSP (coding_system
))
4358 coding_system
= XCAR (coding_system
);
4360 unbind_to (count1
, Qnil
);
4361 inserted
= Z_BYTE
- BEG_BYTE
;
4364 if (NILP (coding_system
))
4365 coding_system
= Qundecided
;
4367 CHECK_CODING_SYSTEM (coding_system
);
4369 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4370 /* We must suppress all character code conversion except for
4371 end-of-line conversion. */
4372 coding_system
= raw_text_coding_system (coding_system
);
4373 setup_coding_system (coding_system
, &coding
);
4374 /* Ensure we set Vlast_coding_system_used. */
4375 set_coding_system
= true;
4380 /* When we visit a file by raw-text, we change the buffer to
4382 if (CODING_FOR_UNIBYTE (&coding
)
4383 /* Can't do this if part of the buffer might be preserved. */
4386 /* Visiting a file with these coding system makes the buffer
4389 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4391 Fset_buffer_multibyte (Qnil
);
4395 coding
.dst_multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
4396 if (CODING_MAY_REQUIRE_DECODING (&coding
)
4397 && (inserted
> 0 || CODING_REQUIRE_FLUSHING (&coding
)))
4399 move_gap_both (PT
, PT_BYTE
);
4400 GAP_SIZE
+= inserted
;
4401 ZV_BYTE
-= inserted
;
4405 decode_coding_gap (&coding
, inserted
, inserted
);
4406 inserted
= coding
.produced_char
;
4407 coding_system
= CODING_ID_NAME (coding
.id
);
4409 else if (inserted
> 0)
4411 invalidate_buffer_caches (current_buffer
, PT
, PT
+ inserted
);
4412 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4416 /* Call after-change hooks for the inserted text, aside from the case
4417 of normal visiting (not with REPLACE), which is done in a new buffer
4418 "before" the buffer is changed. */
4419 if (inserted
> 0 && total
> 0
4420 && (NILP (visit
) || !NILP (replace
)))
4422 signal_after_change (PT
, 0, inserted
);
4423 update_compositions (PT
, PT
, CHECK_BORDER
);
4426 /* Now INSERTED is measured in characters. */
4431 restore_window_points (window_markers
, inserted
,
4432 BYTE_TO_CHAR (same_at_start
),
4433 same_at_end_charpos
);
4437 if (empty_undo_list_p
)
4438 bset_undo_list (current_buffer
, Qnil
);
4442 current_buffer
->modtime
= mtime
;
4443 current_buffer
->modtime_size
= st
.st_size
;
4444 bset_filename (current_buffer
, orig_filename
);
4447 SAVE_MODIFF
= MODIFF
;
4448 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
4449 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4452 if (!NILP (BVAR (current_buffer
, file_truename
)))
4453 unlock_file (BVAR (current_buffer
, file_truename
));
4454 unlock_file (filename
);
4457 xsignal2 (Qfile_error
,
4458 build_string ("not a regular file"), orig_filename
);
4461 if (set_coding_system
)
4462 Vlast_coding_system_used
= coding_system
;
4464 if (! NILP (Ffboundp (Qafter_insert_file_set_coding
)))
4466 insval
= call2 (Qafter_insert_file_set_coding
, make_number (inserted
),
4468 if (! NILP (insval
))
4470 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4471 wrong_type_argument (intern ("inserted-chars"), insval
);
4472 inserted
= XFASTINT (insval
);
4476 /* Decode file format. */
4479 /* Don't run point motion or modification hooks when decoding. */
4480 ptrdiff_t count1
= SPECPDL_INDEX ();
4481 ptrdiff_t old_inserted
= inserted
;
4482 specbind (Qinhibit_point_motion_hooks
, Qt
);
4483 specbind (Qinhibit_modification_hooks
, Qt
);
4485 /* Save old undo list and don't record undo for decoding. */
4486 old_undo
= BVAR (current_buffer
, undo_list
);
4487 bset_undo_list (current_buffer
, Qt
);
4491 insval
= call3 (Qformat_decode
,
4492 Qnil
, make_number (inserted
), visit
);
4493 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4494 wrong_type_argument (intern ("inserted-chars"), insval
);
4495 inserted
= XFASTINT (insval
);
4499 /* If REPLACE is non-nil and we succeeded in not replacing the
4500 beginning or end of the buffer text with the file's contents,
4501 call format-decode with `point' positioned at the beginning
4502 of the buffer and `inserted' equaling the number of
4503 characters in the buffer. Otherwise, format-decode might
4504 fail to correctly analyze the beginning or end of the buffer.
4505 Hence we temporarily save `point' and `inserted' here and
4506 restore `point' iff format-decode did not insert or delete
4507 any text. Otherwise we leave `point' at point-min. */
4508 ptrdiff_t opoint
= PT
;
4509 ptrdiff_t opoint_byte
= PT_BYTE
;
4510 ptrdiff_t oinserted
= ZV
- BEGV
;
4511 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4513 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4514 insval
= call3 (Qformat_decode
,
4515 Qnil
, make_number (oinserted
), visit
);
4516 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4517 wrong_type_argument (intern ("inserted-chars"), insval
);
4518 if (ochars_modiff
== CHARS_MODIFF
)
4519 /* format_decode didn't modify buffer's characters => move
4520 point back to position before inserted text and leave
4521 value of inserted alone. */
4522 SET_PT_BOTH (opoint
, opoint_byte
);
4524 /* format_decode modified buffer's characters => consider
4525 entire buffer changed and leave point at point-min. */
4526 inserted
= XFASTINT (insval
);
4529 /* For consistency with format-decode call these now iff inserted > 0
4530 (martin 2007-06-28). */
4531 p
= Vafter_insert_file_functions
;
4536 insval
= call1 (XCAR (p
), make_number (inserted
));
4539 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4540 wrong_type_argument (intern ("inserted-chars"), insval
);
4541 inserted
= XFASTINT (insval
);
4546 /* For the rationale of this see the comment on
4547 format-decode above. */
4548 ptrdiff_t opoint
= PT
;
4549 ptrdiff_t opoint_byte
= PT_BYTE
;
4550 ptrdiff_t oinserted
= ZV
- BEGV
;
4551 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4553 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4554 insval
= call1 (XCAR (p
), make_number (oinserted
));
4557 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4558 wrong_type_argument (intern ("inserted-chars"), insval
);
4559 if (ochars_modiff
== CHARS_MODIFF
)
4560 /* after_insert_file_functions didn't modify
4561 buffer's characters => move point back to
4562 position before inserted text and leave value of
4564 SET_PT_BOTH (opoint
, opoint_byte
);
4566 /* after_insert_file_functions did modify buffer's
4567 characters => consider entire buffer changed and
4568 leave point at point-min. */
4569 inserted
= XFASTINT (insval
);
4577 if (!empty_undo_list_p
)
4579 bset_undo_list (current_buffer
, old_undo
);
4580 if (CONSP (old_undo
) && inserted
!= old_inserted
)
4582 /* Adjust the last undo record for the size change during
4583 the format conversion. */
4584 Lisp_Object tem
= XCAR (old_undo
);
4585 if (CONSP (tem
) && INTEGERP (XCAR (tem
))
4586 && INTEGERP (XCDR (tem
))
4587 && XFASTINT (XCDR (tem
)) == PT
+ old_inserted
)
4588 XSETCDR (tem
, make_number (PT
+ inserted
));
4592 /* If undo_list was Qt before, keep it that way.
4593 Otherwise start with an empty undo_list. */
4594 bset_undo_list (current_buffer
, EQ (old_undo
, Qt
) ? Qt
: Qnil
);
4596 unbind_to (count1
, Qnil
);
4600 && current_buffer
->modtime
.tv_nsec
== NONEXISTENT_MODTIME_NSECS
)
4602 /* If visiting nonexistent file, return nil. */
4603 report_file_errno ("Opening input file", orig_filename
, save_errno
);
4606 /* We made a lot of deletions and insertions above, so invalidate
4607 the newline cache for the entire region of the inserted
4609 if (current_buffer
->base_buffer
&& current_buffer
->base_buffer
->newline_cache
)
4610 invalidate_region_cache (current_buffer
->base_buffer
,
4611 current_buffer
->base_buffer
->newline_cache
,
4612 PT
- BEG
, Z
- PT
- inserted
);
4613 else if (current_buffer
->newline_cache
)
4614 invalidate_region_cache (current_buffer
,
4615 current_buffer
->newline_cache
,
4616 PT
- BEG
, Z
- PT
- inserted
);
4621 /* Retval needs to be dealt with in all cases consistently. */
4623 val
= list2 (orig_filename
, make_number (inserted
));
4625 return unbind_to (count
, val
);
4628 static Lisp_Object
build_annotations (Lisp_Object
, Lisp_Object
);
4631 build_annotations_unwind (Lisp_Object arg
)
4633 Vwrite_region_annotation_buffers
= arg
;
4636 /* Decide the coding-system to encode the data with. */
4639 choose_write_coding_system (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4640 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4641 struct coding_system
*coding
)
4644 Lisp_Object eol_parent
= Qnil
;
4647 && NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4648 BVAR (current_buffer
, auto_save_file_name
))))
4653 else if (!NILP (Vcoding_system_for_write
))
4655 val
= Vcoding_system_for_write
;
4656 if (coding_system_require_warning
4657 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4658 /* Confirm that VAL can surely encode the current region. */
4659 val
= call5 (Vselect_safe_coding_system_function
,
4660 start
, end
, list2 (Qt
, val
),
4665 /* If the variable `buffer-file-coding-system' is set locally,
4666 it means that the file was read with some kind of code
4667 conversion or the variable is explicitly set by users. We
4668 had better write it out with the same coding system even if
4669 `enable-multibyte-characters' is nil.
4671 If it is not set locally, we anyway have to convert EOL
4672 format if the default value of `buffer-file-coding-system'
4673 tells that it is not Unix-like (LF only) format. */
4674 bool using_default_coding
= 0;
4675 bool force_raw_text
= 0;
4677 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4679 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4682 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4688 /* Check file-coding-system-alist. */
4689 Lisp_Object coding_systems
4690 = CALLN (Ffind_operation_coding_system
, Qwrite_region
, start
, end
,
4691 filename
, append
, visit
, lockname
);
4692 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4693 val
= XCDR (coding_systems
);
4698 /* If we still have not decided a coding system, use the
4699 current buffer's value of buffer-file-coding-system. */
4700 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4701 using_default_coding
= 1;
4704 if (! NILP (val
) && ! force_raw_text
)
4706 Lisp_Object spec
, attrs
;
4708 CHECK_CODING_SYSTEM (val
);
4709 CHECK_CODING_SYSTEM_GET_SPEC (val
, spec
);
4710 attrs
= AREF (spec
, 0);
4711 if (EQ (CODING_ATTR_TYPE (attrs
), Qraw_text
))
4716 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4718 /* Confirm that VAL can surely encode the current region. */
4719 val
= call5 (Vselect_safe_coding_system_function
,
4720 start
, end
, val
, Qnil
, filename
);
4721 /* As the function specified by select-safe-coding-system-function
4722 is out of our control, make sure we are not fed by bogus
4725 CHECK_CODING_SYSTEM (val
);
4728 /* If the decided coding-system doesn't specify end-of-line
4729 format, we use that of `buffer-file-coding-system'. */
4730 if (! using_default_coding
)
4732 Lisp_Object dflt
= BVAR (&buffer_defaults
, buffer_file_coding_system
);
4735 val
= coding_inherit_eol_type (val
, dflt
);
4738 /* If we decide not to encode text, use `raw-text' or one of its
4741 val
= raw_text_coding_system (val
);
4744 val
= coding_inherit_eol_type (val
, eol_parent
);
4745 setup_coding_system (val
, coding
);
4747 if (!STRINGP (start
) && !NILP (BVAR (current_buffer
, selective_display
)))
4748 coding
->mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4752 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4753 "r\nFWrite region to file: \ni\ni\ni\np",
4754 doc
: /* Write current region into specified file.
4755 When called from a program, requires three arguments:
4756 START, END and FILENAME. START and END are normally buffer positions
4757 specifying the part of the buffer to write.
4758 If START is nil, that means to use the entire buffer contents; END is
4760 If START is a string, then output that string to the file
4761 instead of any buffer contents; END is ignored.
4763 Optional fourth argument APPEND if non-nil means
4764 append to existing file contents (if any). If it is a number,
4765 seek to that offset in the file before writing.
4766 Optional fifth argument VISIT, if t or a string, means
4767 set the last-save-file-modtime of buffer to this file's modtime
4768 and mark buffer not modified.
4769 If VISIT is a string, it is a second file name;
4770 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4771 VISIT is also the file name to lock and unlock for clash detection.
4772 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4773 do not display the \"Wrote file\" message.
4774 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4775 use for locking and unlocking, overriding FILENAME and VISIT.
4776 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4777 for an existing file with the same name. If MUSTBENEW is `excl',
4778 that means to get an error if the file already exists; never overwrite.
4779 If MUSTBENEW is neither nil nor `excl', that means ask for
4780 confirmation before overwriting, but do go ahead and overwrite the file
4781 if the user confirms.
4783 This does code conversion according to the value of
4784 `coding-system-for-write', `buffer-file-coding-system', or
4785 `file-coding-system-alist', and sets the variable
4786 `last-coding-system-used' to the coding system actually used.
4788 This calls `write-region-annotate-functions' at the start, and
4789 `write-region-post-annotation-function' at the end. */)
4790 (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
, Lisp_Object append
,
4791 Lisp_Object visit
, Lisp_Object lockname
, Lisp_Object mustbenew
)
4793 return write_region (start
, end
, filename
, append
, visit
, lockname
, mustbenew
,
4797 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4798 descriptor for FILENAME, so do not open or close FILENAME. */
4801 write_region (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4802 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4803 Lisp_Object mustbenew
, int desc
)
4807 off_t offset UNINIT
;
4808 bool open_and_close_file
= desc
< 0;
4813 struct timespec modtime
;
4814 ptrdiff_t count
= SPECPDL_INDEX ();
4815 ptrdiff_t count1 UNINIT
;
4816 Lisp_Object handler
;
4817 Lisp_Object visit_file
;
4818 Lisp_Object annotations
;
4819 Lisp_Object encoded_filename
;
4820 bool visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4821 bool quietly
= !NILP (visit
);
4822 bool file_locked
= 0;
4823 struct buffer
*given_buffer
;
4824 struct coding_system coding
;
4826 if (current_buffer
->base_buffer
&& visiting
)
4827 error ("Cannot do file visiting in an indirect buffer");
4829 if (!NILP (start
) && !STRINGP (start
))
4830 validate_region (&start
, &end
);
4834 filename
= Fexpand_file_name (filename
, Qnil
);
4836 if (!NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4837 barf_or_query_if_file_exists (filename
, false, "overwrite", true, true);
4839 if (STRINGP (visit
))
4840 visit_file
= Fexpand_file_name (visit
, Qnil
);
4842 visit_file
= filename
;
4844 if (NILP (lockname
))
4845 lockname
= visit_file
;
4849 /* If the file name has special constructs in it,
4850 call the corresponding file handler. */
4851 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4852 /* If FILENAME has no handler, see if VISIT has one. */
4853 if (NILP (handler
) && STRINGP (visit
))
4854 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4856 if (!NILP (handler
))
4859 val
= call8 (handler
, Qwrite_region
, start
, end
,
4860 filename
, append
, visit
, lockname
, mustbenew
);
4864 SAVE_MODIFF
= MODIFF
;
4865 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4866 bset_filename (current_buffer
, visit_file
);
4872 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
4874 /* Special kludge to simplify auto-saving. */
4877 /* Do it later, so write-region-annotate-function can work differently
4878 if we save "the buffer" vs "a region".
4879 This is useful in tar-mode. --Stef
4880 XSETFASTINT (start, BEG);
4881 XSETFASTINT (end, Z); */
4885 record_unwind_protect (build_annotations_unwind
,
4886 Vwrite_region_annotation_buffers
);
4887 Vwrite_region_annotation_buffers
= list1 (Fcurrent_buffer ());
4889 given_buffer
= current_buffer
;
4891 if (!STRINGP (start
))
4893 annotations
= build_annotations (start
, end
);
4895 if (current_buffer
!= given_buffer
)
4897 XSETFASTINT (start
, BEGV
);
4898 XSETFASTINT (end
, ZV
);
4904 XSETFASTINT (start
, BEGV
);
4905 XSETFASTINT (end
, ZV
);
4908 /* Decide the coding-system to encode the data with.
4909 We used to make this choice before calling build_annotations, but that
4910 leads to problems when a write-annotate-function takes care of
4911 unsavable chars (as was the case with X-Symbol). */
4912 Vlast_coding_system_used
4913 = choose_write_coding_system (start
, end
, filename
,
4914 append
, visit
, lockname
, &coding
);
4916 if (open_and_close_file
&& !auto_saving
)
4918 lock_file (lockname
);
4922 encoded_filename
= ENCODE_FILE (filename
);
4923 fn
= SSDATA (encoded_filename
);
4924 open_flags
= O_WRONLY
| O_CREAT
;
4925 open_flags
|= EQ (mustbenew
, Qexcl
) ? O_EXCL
: !NILP (append
) ? 0 : O_TRUNC
;
4926 if (NUMBERP (append
))
4927 offset
= file_offset (append
);
4928 else if (!NILP (append
))
4929 open_flags
|= O_APPEND
;
4931 mode
= S_IREAD
| S_IWRITE
;
4933 mode
= auto_saving
? auto_save_mode_bits
: 0666;
4936 if (open_and_close_file
)
4938 desc
= emacs_open (fn
, open_flags
, mode
);
4941 int open_errno
= errno
;
4943 unlock_file (lockname
);
4944 report_file_errno ("Opening output file", filename
, open_errno
);
4947 count1
= SPECPDL_INDEX ();
4948 record_unwind_protect_int (close_file_unwind
, desc
);
4951 if (NUMBERP (append
))
4953 off_t ret
= lseek (desc
, offset
, SEEK_SET
);
4956 int lseek_errno
= errno
;
4958 unlock_file (lockname
);
4959 report_file_errno ("Lseek error", filename
, lseek_errno
);
4963 if (STRINGP (start
))
4964 ok
= a_write (desc
, start
, 0, SCHARS (start
), &annotations
, &coding
);
4965 else if (XINT (start
) != XINT (end
))
4966 ok
= a_write (desc
, Qnil
, XINT (start
), XINT (end
) - XINT (start
),
4967 &annotations
, &coding
);
4970 /* If file was empty, still need to write the annotations. */
4971 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4972 ok
= a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4976 if (ok
&& CODING_REQUIRE_FLUSHING (&coding
)
4977 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
))
4979 /* We have to flush out a data. */
4980 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4981 ok
= e_write (desc
, Qnil
, 1, 1, &coding
);
4985 /* fsync is not crucial for temporary files. Nor for auto-save
4986 files, since they might lose some work anyway. */
4987 if (open_and_close_file
&& !auto_saving
&& !write_region_inhibit_fsync
)
4989 /* Transfer data and metadata to disk, retrying if interrupted.
4990 fsync can report a write failure here, e.g., due to disk full
4991 under NFS. But ignore EINVAL, which means fsync is not
4992 supported on this file. */
4993 while (fsync (desc
) != 0)
4996 if (errno
!= EINVAL
)
4997 ok
= 0, save_errno
= errno
;
5002 modtime
= invalid_timespec ();
5005 if (fstat (desc
, &st
) == 0)
5006 modtime
= get_stat_mtime (&st
);
5008 ok
= 0, save_errno
= errno
;
5011 if (open_and_close_file
)
5013 /* NFS can report a write failure now. */
5014 if (emacs_close (desc
) < 0)
5015 ok
= 0, save_errno
= errno
;
5017 /* Discard the unwind protect for close_file_unwind. */
5018 specpdl_ptr
= specpdl
+ count1
;
5021 /* Some file systems have a bug where st_mtime is not updated
5022 properly after a write. For example, CIFS might not see the
5023 st_mtime change until after the file is opened again.
5025 Attempt to detect this file system bug, and update MODTIME to the
5026 newer st_mtime if the bug appears to be present. This introduces
5027 a race condition, so to avoid most instances of the race condition
5028 on non-buggy file systems, skip this check if the most recently
5029 encountered non-buggy file system was the current file system.
5031 A race condition can occur if some other process modifies the
5032 file between the fstat above and the fstat below, but the race is
5033 unlikely and a similar race between the last write and the fstat
5034 above cannot possibly be closed anyway. */
5036 if (timespec_valid_p (modtime
)
5037 && ! (valid_timestamp_file_system
&& st
.st_dev
== timestamp_file_system
))
5039 int desc1
= emacs_open (fn
, O_WRONLY
, 0);
5043 if (fstat (desc1
, &st1
) == 0
5044 && st
.st_dev
== st1
.st_dev
&& st
.st_ino
== st1
.st_ino
)
5046 /* Use the heuristic if it appears to be valid. With neither
5047 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
5048 file, the time stamp won't change. Also, some non-POSIX
5049 systems don't update an empty file's time stamp when
5050 truncating it. Finally, file systems with 100 ns or worse
5051 resolution sometimes seem to have bugs: on a system with ns
5052 resolution, checking ns % 100 incorrectly avoids the heuristic
5053 1% of the time, but the problem should be temporary as we will
5054 try again on the next time stamp. */
5056 = ((open_flags
& (O_EXCL
| O_TRUNC
)) != 0
5058 && modtime
.tv_nsec
% 100 != 0);
5060 struct timespec modtime1
= get_stat_mtime (&st1
);
5062 && timespec_cmp (modtime
, modtime1
) == 0
5063 && st
.st_size
== st1
.st_size
)
5065 timestamp_file_system
= st
.st_dev
;
5066 valid_timestamp_file_system
= 1;
5070 st
.st_size
= st1
.st_size
;
5074 emacs_close (desc1
);
5078 /* Call write-region-post-annotation-function. */
5079 while (CONSP (Vwrite_region_annotation_buffers
))
5081 Lisp_Object buf
= XCAR (Vwrite_region_annotation_buffers
);
5082 if (!NILP (Fbuffer_live_p (buf
)))
5085 if (FUNCTIONP (Vwrite_region_post_annotation_function
))
5086 call0 (Vwrite_region_post_annotation_function
);
5088 Vwrite_region_annotation_buffers
5089 = XCDR (Vwrite_region_annotation_buffers
);
5092 unbind_to (count
, Qnil
);
5095 unlock_file (lockname
);
5097 /* Do this before reporting IO error
5098 to avoid a "file has changed on disk" warning on
5099 next attempt to save. */
5100 if (timespec_valid_p (modtime
))
5102 current_buffer
->modtime
= modtime
;
5103 current_buffer
->modtime_size
= st
.st_size
;
5107 report_file_errno ("Write error", filename
, save_errno
);
5109 bool auto_saving_into_visited_file
=
5111 && ! NILP (Fstring_equal (BVAR (current_buffer
, filename
),
5112 BVAR (current_buffer
, auto_save_file_name
)));
5115 SAVE_MODIFF
= MODIFF
;
5116 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5117 bset_filename (current_buffer
, visit_file
);
5118 update_mode_lines
= 14;
5119 if (auto_saving_into_visited_file
)
5120 unlock_file (lockname
);
5124 if (auto_saving_into_visited_file
)
5126 SAVE_MODIFF
= MODIFF
;
5127 unlock_file (lockname
);
5133 if (!auto_saving
&& !noninteractive
)
5134 message_with_string ((NUMBERP (append
)
5144 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
5145 doc
: /* Return t if (car A) is numerically less than (car B). */)
5146 (Lisp_Object a
, Lisp_Object b
)
5148 return arithcompare (Fcar (a
), Fcar (b
), ARITH_LESS
);
5151 /* Build the complete list of annotations appropriate for writing out
5152 the text between START and END, by calling all the functions in
5153 write-region-annotate-functions and merging the lists they return.
5154 If one of these functions switches to a different buffer, we assume
5155 that buffer contains altered text. Therefore, the caller must
5156 make sure to restore the current buffer in all cases,
5157 as save-excursion would do. */
5160 build_annotations (Lisp_Object start
, Lisp_Object end
)
5162 Lisp_Object annotations
;
5164 Lisp_Object original_buffer
;
5166 bool used_global
= false;
5168 XSETBUFFER (original_buffer
, current_buffer
);
5171 p
= Vwrite_region_annotate_functions
;
5174 struct buffer
*given_buffer
= current_buffer
;
5175 if (EQ (Qt
, XCAR (p
)) && !used_global
)
5176 { /* Use the global value of the hook. */
5179 Fdefault_value (Qwrite_region_annotate_functions
),
5183 Vwrite_region_annotations_so_far
= annotations
;
5184 res
= call2 (XCAR (p
), start
, end
);
5185 /* If the function makes a different buffer current,
5186 assume that means this buffer contains altered text to be output.
5187 Reset START and END from the buffer bounds
5188 and discard all previous annotations because they should have
5189 been dealt with by this function. */
5190 if (current_buffer
!= given_buffer
)
5192 Vwrite_region_annotation_buffers
5193 = Fcons (Fcurrent_buffer (),
5194 Vwrite_region_annotation_buffers
);
5195 XSETFASTINT (start
, BEGV
);
5196 XSETFASTINT (end
, ZV
);
5199 Flength (res
); /* Check basic validity of return value */
5200 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5204 /* Now do the same for annotation functions implied by the file-format */
5205 if (auto_saving
&& (!EQ (BVAR (current_buffer
, auto_save_file_format
), Qt
)))
5206 p
= BVAR (current_buffer
, auto_save_file_format
);
5208 p
= BVAR (current_buffer
, file_format
);
5209 for (i
= 0; CONSP (p
); p
= XCDR (p
), ++i
)
5211 struct buffer
*given_buffer
= current_buffer
;
5213 Vwrite_region_annotations_so_far
= annotations
;
5215 /* Value is either a list of annotations or nil if the function
5216 has written annotations to a temporary buffer, which is now
5218 res
= call5 (Qformat_annotate_function
, XCAR (p
), start
, end
,
5219 original_buffer
, make_number (i
));
5220 if (current_buffer
!= given_buffer
)
5222 XSETFASTINT (start
, BEGV
);
5223 XSETFASTINT (end
, ZV
);
5228 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5235 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5236 If STRING is nil, POS is the character position in the current buffer.
5237 Intersperse with them the annotations from *ANNOT
5238 which fall within the range of POS to POS + NCHARS,
5239 each at its appropriate position.
5241 We modify *ANNOT by discarding elements as we use them up.
5243 Return true if successful. */
5246 a_write (int desc
, Lisp_Object string
, ptrdiff_t pos
,
5247 ptrdiff_t nchars
, Lisp_Object
*annot
,
5248 struct coding_system
*coding
)
5252 ptrdiff_t lastpos
= pos
+ nchars
;
5254 while (NILP (*annot
) || CONSP (*annot
))
5256 tem
= Fcar_safe (Fcar (*annot
));
5259 nextpos
= XFASTINT (tem
);
5261 /* If there are no more annotations in this range,
5262 output the rest of the range all at once. */
5263 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
5264 return e_write (desc
, string
, pos
, lastpos
, coding
);
5266 /* Output buffer text up to the next annotation's position. */
5269 if (!e_write (desc
, string
, pos
, nextpos
, coding
))
5273 /* Output the annotation. */
5274 tem
= Fcdr (Fcar (*annot
));
5277 if (!e_write (desc
, tem
, 0, SCHARS (tem
), coding
))
5280 *annot
= Fcdr (*annot
);
5285 /* Maximum number of characters that the next
5286 function encodes per one loop iteration. */
5288 enum { E_WRITE_MAX
= 8 * 1024 * 1024 };
5290 /* Write text in the range START and END into descriptor DESC,
5291 encoding them with coding system CODING. If STRING is nil, START
5292 and END are character positions of the current buffer, else they
5293 are indexes to the string STRING. Return true if successful. */
5296 e_write (int desc
, Lisp_Object string
, ptrdiff_t start
, ptrdiff_t end
,
5297 struct coding_system
*coding
)
5299 if (STRINGP (string
))
5302 end
= SCHARS (string
);
5305 /* We used to have a code for handling selective display here. But,
5306 now it is handled within encode_coding. */
5310 if (STRINGP (string
))
5312 coding
->src_multibyte
= SCHARS (string
) < SBYTES (string
);
5313 if (CODING_REQUIRE_ENCODING (coding
))
5315 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5317 /* Avoid creating huge Lisp string in encode_coding_object. */
5318 if (nchars
== E_WRITE_MAX
)
5319 coding
->raw_destination
= 1;
5321 encode_coding_object
5322 (coding
, string
, start
, string_char_to_byte (string
, start
),
5323 start
+ nchars
, string_char_to_byte (string
, start
+ nchars
),
5328 coding
->dst_object
= string
;
5329 coding
->consumed_char
= SCHARS (string
);
5330 coding
->produced
= SBYTES (string
);
5335 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
5336 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
5338 coding
->src_multibyte
= (end
- start
) < (end_byte
- start_byte
);
5339 if (CODING_REQUIRE_ENCODING (coding
))
5341 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5344 if (nchars
== E_WRITE_MAX
)
5345 coding
->raw_destination
= 1;
5347 encode_coding_object
5348 (coding
, Fcurrent_buffer (), start
, start_byte
,
5349 start
+ nchars
, CHAR_TO_BYTE (start
+ nchars
), Qt
);
5353 coding
->dst_object
= Qnil
;
5354 coding
->dst_pos_byte
= start_byte
;
5355 if (start
>= GPT
|| end
<= GPT
)
5357 coding
->consumed_char
= end
- start
;
5358 coding
->produced
= end_byte
- start_byte
;
5362 coding
->consumed_char
= GPT
- start
;
5363 coding
->produced
= GPT_BYTE
- start_byte
;
5368 if (coding
->produced
> 0)
5370 char *buf
= (coding
->raw_destination
? (char *) coding
->destination
5371 : (STRINGP (coding
->dst_object
)
5372 ? SSDATA (coding
->dst_object
)
5373 : (char *) BYTE_POS_ADDR (coding
->dst_pos_byte
)));
5374 coding
->produced
-= emacs_write_quit (desc
, buf
, coding
->produced
);
5376 if (coding
->raw_destination
)
5378 /* We're responsible for freeing this, see
5379 encode_coding_object to check why. */
5380 xfree (coding
->destination
);
5381 coding
->raw_destination
= 0;
5383 if (coding
->produced
)
5386 start
+= coding
->consumed_char
;
5392 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5393 Sverify_visited_file_modtime
, 0, 1, 0,
5394 doc
: /* Return t if last mod time of BUF's visited file matches what BUF records.
5395 This means that the file has not been changed since it was visited or saved.
5396 If BUF is omitted or nil, it defaults to the current buffer.
5397 See Info node `(elisp)Modification Time' for more details. */)
5400 struct buffer
*b
= decode_buffer (buf
);
5402 Lisp_Object handler
;
5403 Lisp_Object filename
;
5404 struct timespec mtime
;
5406 if (!STRINGP (BVAR (b
, filename
))) return Qt
;
5407 if (b
->modtime
.tv_nsec
== UNKNOWN_MODTIME_NSECS
) return Qt
;
5409 /* If the file name has special constructs in it,
5410 call the corresponding file handler. */
5411 handler
= Ffind_file_name_handler (BVAR (b
, filename
),
5412 Qverify_visited_file_modtime
);
5413 if (!NILP (handler
))
5414 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5416 filename
= ENCODE_FILE (BVAR (b
, filename
));
5418 mtime
= (stat (SSDATA (filename
), &st
) == 0
5419 ? get_stat_mtime (&st
)
5420 : time_error_value (errno
));
5421 if (timespec_cmp (mtime
, b
->modtime
) == 0
5422 && (b
->modtime_size
< 0
5423 || st
.st_size
== b
->modtime_size
))
5428 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5429 Svisited_file_modtime
, 0, 0, 0,
5430 doc
: /* Return the current buffer's recorded visited file modification time.
5431 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5432 `file-attributes' returns. If the current buffer has no recorded file
5433 modification time, this function returns 0. If the visited file
5434 doesn't exist, return -1.
5435 See Info node `(elisp)Modification Time' for more details. */)
5438 int ns
= current_buffer
->modtime
.tv_nsec
;
5440 return make_number (UNKNOWN_MODTIME_NSECS
- ns
);
5441 return make_lisp_time (current_buffer
->modtime
);
5444 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5445 Sset_visited_file_modtime
, 0, 1, 0,
5446 doc
: /* Update buffer's recorded modification time from the visited file's time.
5447 Useful if the buffer was not read from the file normally
5448 or if the file itself has been changed for some known benign reason.
5449 An argument specifies the modification time value to use
5450 \(instead of that of the visited file), in the form of a list
5451 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5452 `visited-file-modtime'. */)
5453 (Lisp_Object time_flag
)
5455 if (!NILP (time_flag
))
5457 struct timespec mtime
;
5458 if (INTEGERP (time_flag
))
5460 CHECK_RANGED_INTEGER (time_flag
, -1, 0);
5461 mtime
= make_timespec (0, UNKNOWN_MODTIME_NSECS
- XINT (time_flag
));
5464 mtime
= lisp_time_argument (time_flag
);
5466 current_buffer
->modtime
= mtime
;
5467 current_buffer
->modtime_size
= -1;
5471 register Lisp_Object filename
;
5473 Lisp_Object handler
;
5475 filename
= Fexpand_file_name (BVAR (current_buffer
, filename
), Qnil
);
5477 /* If the file name has special constructs in it,
5478 call the corresponding file handler. */
5479 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5480 if (!NILP (handler
))
5481 /* The handler can find the file name the same way we did. */
5482 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5484 filename
= ENCODE_FILE (filename
);
5486 if (stat (SSDATA (filename
), &st
) >= 0)
5488 current_buffer
->modtime
= get_stat_mtime (&st
);
5489 current_buffer
->modtime_size
= st
.st_size
;
5497 auto_save_error (Lisp_Object error_val
)
5499 auto_save_error_occurred
= 1;
5501 ring_bell (XFRAME (selected_frame
));
5503 AUTO_STRING (format
, "Auto-saving %s: %s");
5504 Lisp_Object msg
= CALLN (Fformat
, format
, BVAR (current_buffer
, name
),
5505 Ferror_message_string (error_val
));
5506 call3 (intern ("display-warning"),
5507 intern ("auto-save"), msg
, intern ("error"));
5518 auto_save_mode_bits
= 0666;
5520 /* Get visited file's mode to become the auto save file's mode. */
5521 if (! NILP (BVAR (current_buffer
, filename
)))
5523 if (stat (SSDATA (BVAR (current_buffer
, filename
)), &st
) >= 0)
5524 /* But make sure we can overwrite it later! */
5525 auto_save_mode_bits
= (st
.st_mode
| 0600) & 0777;
5526 else if (modes
= Ffile_modes (BVAR (current_buffer
, filename
)),
5528 /* Remote files don't cooperate with stat. */
5529 auto_save_mode_bits
= (XINT (modes
) | 0600) & 0777;
5533 Fwrite_region (Qnil
, Qnil
, BVAR (current_buffer
, auto_save_file_name
), Qnil
,
5534 NILP (Vauto_save_visited_file_name
) ? Qlambda
: Qt
,
5538 struct auto_save_unwind
5545 do_auto_save_unwind (void *arg
)
5547 struct auto_save_unwind
*p
= arg
;
5548 FILE *stream
= p
->stream
;
5549 minibuffer_auto_raise
= p
->auto_raise
;
5560 do_auto_save_make_dir (Lisp_Object dir
)
5564 auto_saving_dir_umask
= 077;
5565 result
= call2 (Qmake_directory
, dir
, Qt
);
5566 auto_saving_dir_umask
= 0;
5571 do_auto_save_eh (Lisp_Object ignore
)
5573 auto_saving_dir_umask
= 0;
5577 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5578 doc
: /* Auto-save all buffers that need it.
5579 This is all buffers that have auto-saving enabled
5580 and are changed since last auto-saved.
5581 Auto-saving writes the buffer into a file
5582 so that your editing is not lost if the system crashes.
5583 This file is not the file you visited; that changes only when you save.
5584 Normally, run the normal hook `auto-save-hook' before saving.
5586 A non-nil NO-MESSAGE argument means do not print any message if successful.
5587 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5588 (Lisp_Object no_message
, Lisp_Object current_only
)
5590 struct buffer
*old
= current_buffer
, *b
;
5591 Lisp_Object tail
, buf
, hook
;
5592 bool auto_saved
= 0;
5593 int do_handled_files
;
5595 FILE *stream
= NULL
;
5596 ptrdiff_t count
= SPECPDL_INDEX ();
5597 bool orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5598 bool old_message_p
= 0;
5599 struct auto_save_unwind auto_save_unwind
;
5601 if (max_specpdl_size
< specpdl_size
+ 40)
5602 max_specpdl_size
= specpdl_size
+ 40;
5607 if (NILP (no_message
))
5609 old_message_p
= push_message ();
5610 record_unwind_protect_void (pop_message_unwind
);
5613 /* Ordinarily don't quit within this function,
5614 but don't make it impossible to quit (in case we get hung in I/O). */
5618 hook
= intern ("auto-save-hook");
5619 safe_run_hooks (hook
);
5621 if (STRINGP (Vauto_save_list_file_name
))
5623 Lisp_Object listfile
;
5625 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5627 /* Don't try to create the directory when shutting down Emacs,
5628 because creating the directory might signal an error, and
5629 that would leave Emacs in a strange state. */
5630 if (!NILP (Vrun_hooks
))
5633 dir
= Ffile_name_directory (listfile
);
5634 if (NILP (Ffile_directory_p (dir
)))
5635 internal_condition_case_1 (do_auto_save_make_dir
,
5640 stream
= emacs_fopen (SSDATA (listfile
), "w");
5643 auto_save_unwind
.stream
= stream
;
5644 auto_save_unwind
.auto_raise
= minibuffer_auto_raise
;
5645 record_unwind_protect_ptr (do_auto_save_unwind
, &auto_save_unwind
);
5646 minibuffer_auto_raise
= 0;
5648 auto_save_error_occurred
= 0;
5650 /* On first pass, save all files that don't have handlers.
5651 On second pass, save all files that do have handlers.
5653 If Emacs is crashing, the handlers may tweak what is causing
5654 Emacs to crash in the first place, and it would be a shame if
5655 Emacs failed to autosave perfectly ordinary files because it
5656 couldn't handle some ange-ftp'd file. */
5658 for (do_handled_files
= 0; do_handled_files
< 2; do_handled_files
++)
5659 FOR_EACH_LIVE_BUFFER (tail
, buf
)
5663 /* Record all the buffers that have auto save mode
5664 in the special file that lists them. For each of these buffers,
5665 Record visited name (if any) and auto save name. */
5666 if (STRINGP (BVAR (b
, auto_save_file_name
))
5667 && stream
!= NULL
&& do_handled_files
== 0)
5670 if (!NILP (BVAR (b
, filename
)))
5671 fwrite_unlocked (SDATA (BVAR (b
, filename
)), 1,
5672 SBYTES (BVAR (b
, filename
)), stream
);
5673 putc_unlocked ('\n', stream
);
5674 fwrite_unlocked (SDATA (BVAR (b
, auto_save_file_name
)), 1,
5675 SBYTES (BVAR (b
, auto_save_file_name
)), stream
);
5676 putc_unlocked ('\n', stream
);
5680 if (!NILP (current_only
)
5681 && b
!= current_buffer
)
5684 /* Don't auto-save indirect buffers.
5685 The base buffer takes care of it. */
5689 /* Check for auto save enabled
5690 and file changed since last auto save
5691 and file changed since last real save. */
5692 if (STRINGP (BVAR (b
, auto_save_file_name
))
5693 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
)
5694 && BUF_AUTOSAVE_MODIFF (b
) < BUF_MODIFF (b
)
5695 /* -1 means we've turned off autosaving for a while--see below. */
5696 && XINT (BVAR (b
, save_length
)) >= 0
5697 && (do_handled_files
5698 || NILP (Ffind_file_name_handler (BVAR (b
, auto_save_file_name
),
5701 struct timespec before_time
= current_timespec ();
5702 struct timespec after_time
;
5704 /* If we had a failure, don't try again for 20 minutes. */
5705 if (b
->auto_save_failure_time
> 0
5706 && before_time
.tv_sec
- b
->auto_save_failure_time
< 1200)
5709 set_buffer_internal (b
);
5710 if (NILP (Vauto_save_include_big_deletions
)
5711 && (XFASTINT (BVAR (b
, save_length
)) * 10
5712 > (BUF_Z (b
) - BUF_BEG (b
)) * 13)
5713 /* A short file is likely to change a large fraction;
5714 spare the user annoying messages. */
5715 && XFASTINT (BVAR (b
, save_length
)) > 5000
5716 /* These messages are frequent and annoying for `*mail*'. */
5717 && !EQ (BVAR (b
, filename
), Qnil
)
5718 && NILP (no_message
))
5720 /* It has shrunk too much; turn off auto-saving here. */
5721 minibuffer_auto_raise
= orig_minibuffer_auto_raise
;
5722 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5724 minibuffer_auto_raise
= 0;
5725 /* Turn off auto-saving until there's a real save,
5726 and prevent any more warnings. */
5727 XSETINT (BVAR (b
, save_length
), -1);
5728 Fsleep_for (make_number (1), Qnil
);
5731 if (!auto_saved
&& NILP (no_message
))
5732 message1 ("Auto-saving...");
5733 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
5735 BUF_AUTOSAVE_MODIFF (b
) = BUF_MODIFF (b
);
5736 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5737 set_buffer_internal (old
);
5739 after_time
= current_timespec ();
5741 /* If auto-save took more than 60 seconds,
5742 assume it was an NFS failure that got a timeout. */
5743 if (after_time
.tv_sec
- before_time
.tv_sec
> 60)
5744 b
->auto_save_failure_time
= after_time
.tv_sec
;
5748 /* Prevent another auto save till enough input events come in. */
5749 record_auto_save ();
5751 if (auto_saved
&& NILP (no_message
))
5755 /* If we are going to restore an old message,
5756 give time to read ours. */
5757 sit_for (make_number (1), 0, 0);
5760 else if (!auto_save_error_occurred
)
5761 /* Don't overwrite the error message if an error occurred.
5762 If we displayed a message and then restored a state
5763 with no message, leave a "done" message on the screen. */
5764 message1 ("Auto-saving...done");
5769 /* This restores the message-stack status. */
5770 unbind_to (count
, Qnil
);
5774 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved
,
5775 Sset_buffer_auto_saved
, 0, 0, 0,
5776 doc
: /* Mark current buffer as auto-saved with its current text.
5777 No auto-save file will be written until the buffer changes again. */)
5780 /* FIXME: This should not be called in indirect buffers, since
5781 they're not autosaved. */
5782 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
5783 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5784 current_buffer
->auto_save_failure_time
= 0;
5788 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure
,
5789 Sclear_buffer_auto_save_failure
, 0, 0, 0,
5790 doc
: /* Clear any record of a recent auto-save failure in the current buffer. */)
5793 current_buffer
->auto_save_failure_time
= 0;
5797 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
5799 doc
: /* Return t if current buffer has been auto-saved recently.
5800 More precisely, if it has been auto-saved since last read from or saved
5801 in the visited file. If the buffer has no visited file,
5802 then any auto-save counts as "recent". */)
5805 /* FIXME: maybe we should return nil for indirect buffers since
5806 they're never autosaved. */
5807 return (SAVE_MODIFF
< BUF_AUTOSAVE_MODIFF (current_buffer
) ? Qt
: Qnil
);
5810 /* Reading and completing file names. */
5812 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p
,
5813 Snext_read_file_uses_dialog_p
, 0, 0, 0,
5814 doc
: /* Return t if a call to `read-file-name' will use a dialog.
5815 The return value is only relevant for a call to `read-file-name' that happens
5816 before any other event (mouse or keypress) is handled. */)
5819 #if (defined USE_GTK || defined USE_MOTIF \
5820 || defined HAVE_NS || defined HAVE_NTGUI)
5821 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5824 && window_system_available (SELECTED_FRAME ()))
5831 DEFUN ("set-binary-mode", Fset_binary_mode
, Sset_binary_mode
, 2, 2, 0,
5832 doc
: /* Switch STREAM to binary I/O mode or text I/O mode.
5833 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5834 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5837 As a side effect, this function flushes any pending STREAM's data.
5839 Value is the previous value of STREAM's I/O mode, nil for text mode,
5840 non-nil for binary mode.
5842 On MS-Windows and MS-DOS, binary mode is needed to read or write
5843 arbitrary binary data, and for disabling translation between CR-LF
5844 pairs and a single newline character. Examples include generation
5845 of text files with Unix-style end-of-line format using `princ' in
5846 batch mode, with standard output redirected to a file.
5848 On Posix systems, this function always returns non-nil, and has no
5849 effect except for flushing STREAM's data. */)
5850 (Lisp_Object stream
, Lisp_Object mode
)
5855 CHECK_SYMBOL (stream
);
5856 if (EQ (stream
, Qstdin
))
5858 else if (EQ (stream
, Qstdout
))
5860 else if (EQ (stream
, Qstderr
))
5863 xsignal2 (Qerror
, build_string ("unsupported stream"), stream
);
5865 binmode
= NILP (mode
) ? O_TEXT
: O_BINARY
;
5867 fflush_unlocked (fp
);
5869 return (set_binary_mode (fileno (fp
), binmode
) == O_BINARY
) ? Qt
: Qnil
;
5874 /* Yield a Lisp float as close as possible to BLOCKSIZE * BLOCKS, with
5875 the result negated if NEGATE. */
5877 blocks_to_bytes (uintmax_t blocksize
, uintmax_t blocks
, bool negate
)
5879 /* On typical platforms the following code is accurate to 53 bits,
5880 which is close enough. BLOCKSIZE is invariably a power of 2, so
5881 converting it to double does not lose information. */
5882 double bs
= blocksize
;
5883 return make_float (negate
? -bs
* -blocks
: bs
* blocks
);
5886 DEFUN ("file-system-info", Ffile_system_info
, Sfile_system_info
, 1, 1, 0,
5887 doc
: /* Return storage information about the file system FILENAME is on.
5888 Value is a list of numbers (TOTAL FREE AVAIL), where TOTAL is the total
5889 storage of the file system, FREE is the free storage, and AVAIL is the
5890 storage available to a non-superuser. All 3 numbers are in bytes.
5891 If the underlying system call fails, value is nil. */)
5892 (Lisp_Object filename
)
5894 Lisp_Object encoded
= ENCODE_FILE (Fexpand_file_name (filename
, Qnil
));
5896 /* If the file name has special constructs in it,
5897 call the corresponding file handler. */
5898 Lisp_Object handler
= Ffind_file_name_handler (encoded
, Qfile_system_info
);
5899 if (!NILP (handler
))
5901 Lisp_Object result
= call2 (handler
, Qfile_system_info
, encoded
);
5902 if (CONSP (result
) || NILP (result
))
5904 error ("Invalid handler in `file-name-handler-alist'");
5908 if (get_fs_usage (SSDATA (encoded
), NULL
, &u
) != 0)
5910 return list3 (blocks_to_bytes (u
.fsu_blocksize
, u
.fsu_blocks
, false),
5911 blocks_to_bytes (u
.fsu_blocksize
, u
.fsu_bfree
, false),
5912 blocks_to_bytes (u
.fsu_blocksize
, u
.fsu_bavail
,
5913 u
.fsu_bavail_top_bit_set
));
5916 #endif /* !DOS_NT */
5921 realmask
= umask (0);
5924 valid_timestamp_file_system
= 0;
5926 /* fsync can be a significant performance hit. Often it doesn't
5927 suffice to make the file-save operation survive a crash. For
5928 batch scripts, which are typically part of larger shell commands
5929 that don't fsync other files, its effect on performance can be
5930 significant so its utility is particularly questionable.
5931 Hence, for now by default fsync is used only when interactive.
5933 For more on why fsync often fails to work on today's hardware, see:
5934 Zheng M et al. Understanding the robustness of SSDs under power fault.
5935 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5936 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5938 For more on why fsync does not suffice even if it works properly, see:
5939 Roche X. Necessary step(s) to synchronize filename operations on disk.
5940 Austin Group Defect 672, 2013-03-19
5941 http://austingroupbugs.net/view.php?id=672 */
5942 write_region_inhibit_fsync
= noninteractive
;
5946 syms_of_fileio (void)
5948 /* Property name of a file name handler,
5949 which gives a list of operations it handles. */
5950 DEFSYM (Qoperations
, "operations");
5952 DEFSYM (Qexpand_file_name
, "expand-file-name");
5953 DEFSYM (Qsubstitute_in_file_name
, "substitute-in-file-name");
5954 DEFSYM (Qdirectory_file_name
, "directory-file-name");
5955 DEFSYM (Qfile_name_directory
, "file-name-directory");
5956 DEFSYM (Qfile_name_nondirectory
, "file-name-nondirectory");
5957 DEFSYM (Qunhandled_file_name_directory
, "unhandled-file-name-directory");
5958 DEFSYM (Qfile_name_as_directory
, "file-name-as-directory");
5959 DEFSYM (Qcopy_file
, "copy-file");
5960 DEFSYM (Qmake_directory_internal
, "make-directory-internal");
5961 DEFSYM (Qmake_directory
, "make-directory");
5962 DEFSYM (Qdelete_file
, "delete-file");
5963 DEFSYM (Qfile_name_case_insensitive_p
, "file-name-case-insensitive-p");
5964 DEFSYM (Qrename_file
, "rename-file");
5965 DEFSYM (Qadd_name_to_file
, "add-name-to-file");
5966 DEFSYM (Qmake_symbolic_link
, "make-symbolic-link");
5967 DEFSYM (Qfile_exists_p
, "file-exists-p");
5968 DEFSYM (Qfile_executable_p
, "file-executable-p");
5969 DEFSYM (Qfile_readable_p
, "file-readable-p");
5970 DEFSYM (Qfile_writable_p
, "file-writable-p");
5971 DEFSYM (Qfile_symlink_p
, "file-symlink-p");
5972 DEFSYM (Qaccess_file
, "access-file");
5973 DEFSYM (Qfile_directory_p
, "file-directory-p");
5974 DEFSYM (Qfile_regular_p
, "file-regular-p");
5975 DEFSYM (Qfile_accessible_directory_p
, "file-accessible-directory-p");
5976 DEFSYM (Qfile_modes
, "file-modes");
5977 DEFSYM (Qset_file_modes
, "set-file-modes");
5978 DEFSYM (Qset_file_times
, "set-file-times");
5979 DEFSYM (Qfile_selinux_context
, "file-selinux-context");
5980 DEFSYM (Qset_file_selinux_context
, "set-file-selinux-context");
5981 DEFSYM (Qfile_acl
, "file-acl");
5982 DEFSYM (Qset_file_acl
, "set-file-acl");
5983 DEFSYM (Qfile_newer_than_file_p
, "file-newer-than-file-p");
5984 DEFSYM (Qinsert_file_contents
, "insert-file-contents");
5985 DEFSYM (Qwrite_region
, "write-region");
5986 DEFSYM (Qverify_visited_file_modtime
, "verify-visited-file-modtime");
5987 DEFSYM (Qset_visited_file_modtime
, "set-visited-file-modtime");
5988 DEFSYM (Qfile_system_info
, "file-system-info");
5990 /* The symbol bound to coding-system-for-read when
5991 insert-file-contents is called for recovering a file. This is not
5992 an actual coding system name, but just an indicator to tell
5993 insert-file-contents to use `emacs-mule' with a special flag for
5994 auto saving and recovering a file. */
5995 DEFSYM (Qauto_save_coding
, "auto-save-coding");
5997 DEFSYM (Qfile_name_history
, "file-name-history");
5998 Fset (Qfile_name_history
, Qnil
);
6000 DEFSYM (Qfile_error
, "file-error");
6001 DEFSYM (Qfile_already_exists
, "file-already-exists");
6002 DEFSYM (Qfile_date_error
, "file-date-error");
6003 DEFSYM (Qfile_missing
, "file-missing");
6004 DEFSYM (Qfile_notify_error
, "file-notify-error");
6005 DEFSYM (Qexcl
, "excl");
6007 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system
,
6008 doc
: /* Coding system for encoding file names.
6009 If it is nil, `default-file-name-coding-system' (which see) is used.
6011 On MS-Windows, the value of this variable is largely ignored if
6012 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
6013 behaves as if file names were encoded in `utf-8'. */);
6014 Vfile_name_coding_system
= Qnil
;
6016 DEFVAR_LISP ("default-file-name-coding-system",
6017 Vdefault_file_name_coding_system
,
6018 doc
: /* Default coding system for encoding file names.
6019 This variable is used only when `file-name-coding-system' is nil.
6021 This variable is set/changed by the command `set-language-environment'.
6022 User should not set this variable manually,
6023 instead use `file-name-coding-system' to get a constant encoding
6024 of file names regardless of the current language environment.
6026 On MS-Windows, the value of this variable is largely ignored if
6027 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
6028 behaves as if file names were encoded in `utf-8'. */);
6029 Vdefault_file_name_coding_system
= Qnil
;
6031 /* Lisp functions for translating file formats. */
6032 DEFSYM (Qformat_decode
, "format-decode");
6033 DEFSYM (Qformat_annotate_function
, "format-annotate-function");
6035 /* Lisp function for setting buffer-file-coding-system and the
6036 multibyteness of the current buffer after inserting a file. */
6037 DEFSYM (Qafter_insert_file_set_coding
, "after-insert-file-set-coding");
6039 DEFSYM (Qcar_less_than_car
, "car-less-than-car");
6041 Fput (Qfile_error
, Qerror_conditions
,
6042 Fpurecopy (list2 (Qfile_error
, Qerror
)));
6043 Fput (Qfile_error
, Qerror_message
,
6044 build_pure_c_string ("File error"));
6046 Fput (Qfile_already_exists
, Qerror_conditions
,
6047 Fpurecopy (list3 (Qfile_already_exists
, Qfile_error
, Qerror
)));
6048 Fput (Qfile_already_exists
, Qerror_message
,
6049 build_pure_c_string ("File already exists"));
6051 Fput (Qfile_date_error
, Qerror_conditions
,
6052 Fpurecopy (list3 (Qfile_date_error
, Qfile_error
, Qerror
)));
6053 Fput (Qfile_date_error
, Qerror_message
,
6054 build_pure_c_string ("Cannot set file date"));
6056 Fput (Qfile_missing
, Qerror_conditions
,
6057 Fpurecopy (list3 (Qfile_missing
, Qfile_error
, Qerror
)));
6058 Fput (Qfile_missing
, Qerror_message
,
6059 build_pure_c_string ("File is missing"));
6061 Fput (Qfile_notify_error
, Qerror_conditions
,
6062 Fpurecopy (list3 (Qfile_notify_error
, Qfile_error
, Qerror
)));
6063 Fput (Qfile_notify_error
, Qerror_message
,
6064 build_pure_c_string ("File notification error"));
6066 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist
,
6067 doc
: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
6068 If a file name matches REGEXP, all I/O on that file is done by calling
6069 HANDLER. If a file name matches more than one handler, the handler
6070 whose match starts last in the file name gets precedence. The
6071 function `find-file-name-handler' checks this list for a handler for
6074 HANDLER should be a function. The first argument given to it is the
6075 name of the I/O primitive to be handled; the remaining arguments are
6076 the arguments that were passed to that primitive. For example, if you
6077 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
6078 HANDLER is called like this:
6080 (funcall HANDLER \\='file-exists-p FILENAME)
6082 Note that HANDLER must be able to handle all I/O primitives; if it has
6083 nothing special to do for a primitive, it should reinvoke the
6084 primitive to handle the operation \"the usual way\".
6085 See Info node `(elisp)Magic File Names' for more details. */);
6086 Vfile_name_handler_alist
= Qnil
;
6088 DEFVAR_LISP ("set-auto-coding-function",
6089 Vset_auto_coding_function
,
6090 doc
: /* If non-nil, a function to call to decide a coding system of file.
6091 Two arguments are passed to this function: the file name
6092 and the length of a file contents following the point.
6093 This function should return a coding system to decode the file contents.
6094 It should check the file name against `auto-coding-alist'.
6095 If no coding system is decided, it should check a coding system
6096 specified in the heading lines with the format:
6097 -*- ... coding: CODING-SYSTEM; ... -*-
6098 or local variable spec of the tailing lines with `coding:' tag. */);
6099 Vset_auto_coding_function
= Qnil
;
6101 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions
,
6102 doc
: /* A list of functions to be called at the end of `insert-file-contents'.
6103 Each is passed one argument, the number of characters inserted,
6104 with point at the start of the inserted text. Each function
6105 should leave point the same, and return the new character count.
6106 If `insert-file-contents' is intercepted by a handler from
6107 `file-name-handler-alist', that handler is responsible for calling the
6108 functions in `after-insert-file-functions' if appropriate. */);
6109 Vafter_insert_file_functions
= Qnil
;
6111 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions
,
6112 doc
: /* A list of functions to be called at the start of `write-region'.
6113 Each is passed two arguments, START and END as for `write-region'.
6114 These are usually two numbers but not always; see the documentation
6115 for `write-region'. The function should return a list of pairs
6116 of the form (POSITION . STRING), consisting of strings to be effectively
6117 inserted at the specified positions of the file being written (1 means to
6118 insert before the first byte written). The POSITIONs must be sorted into
6121 If there are several annotation functions, the lists returned by these
6122 functions are merged destructively. As each annotation function runs,
6123 the variable `write-region-annotations-so-far' contains a list of all
6124 annotations returned by previous annotation functions.
6126 An annotation function can return with a different buffer current.
6127 Doing so removes the annotations returned by previous functions, and
6128 resets START and END to `point-min' and `point-max' of the new buffer.
6130 After `write-region' completes, Emacs calls the function stored in
6131 `write-region-post-annotation-function', once for each buffer that was
6132 current when building the annotations (i.e., at least once), with that
6133 buffer current. */);
6134 Vwrite_region_annotate_functions
= Qnil
;
6135 DEFSYM (Qwrite_region_annotate_functions
, "write-region-annotate-functions");
6137 DEFVAR_LISP ("write-region-post-annotation-function",
6138 Vwrite_region_post_annotation_function
,
6139 doc
: /* Function to call after `write-region' completes.
6140 The function is called with no arguments. If one or more of the
6141 annotation functions in `write-region-annotate-functions' changed the
6142 current buffer, the function stored in this variable is called for
6143 each of those additional buffers as well, in addition to the original
6144 buffer. The relevant buffer is current during each function call. */);
6145 Vwrite_region_post_annotation_function
= Qnil
;
6146 staticpro (&Vwrite_region_annotation_buffers
);
6148 DEFVAR_LISP ("write-region-annotations-so-far",
6149 Vwrite_region_annotations_so_far
,
6150 doc
: /* When an annotation function is called, this holds the previous annotations.
6151 These are the annotations made by other annotation functions
6152 that were already called. See also `write-region-annotate-functions'. */);
6153 Vwrite_region_annotations_so_far
= Qnil
;
6155 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers
,
6156 doc
: /* A list of file name handlers that temporarily should not be used.
6157 This applies only to the operation `inhibit-file-name-operation'. */);
6158 Vinhibit_file_name_handlers
= Qnil
;
6160 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation
,
6161 doc
: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6162 Vinhibit_file_name_operation
= Qnil
;
6164 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name
,
6165 doc
: /* File name in which to write a list of all auto save file names.
6166 This variable is initialized automatically from `auto-save-list-file-prefix'
6167 shortly after Emacs reads your init file, if you have not yet given it
6168 a non-nil value. */);
6169 Vauto_save_list_file_name
= Qnil
;
6171 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name
,
6172 doc
: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6173 Normally auto-save files are written under other names. */);
6174 Vauto_save_visited_file_name
= Qnil
;
6176 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions
,
6177 doc
: /* If non-nil, auto-save even if a large part of the text is deleted.
6178 If nil, deleting a substantial portion of the text disables auto-save
6179 in the buffer; this is the default behavior, because the auto-save
6180 file is usually more useful if it contains the deleted text. */);
6181 Vauto_save_include_big_deletions
= Qnil
;
6183 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync
,
6184 doc
: /* Non-nil means don't call fsync in `write-region'.
6185 This variable affects calls to `write-region' as well as save commands.
6186 Setting this to nil may avoid data loss if the system loses power or
6187 the operating system crashes. By default, it is non-nil in batch mode. */);
6188 write_region_inhibit_fsync
= 0; /* See also `init_fileio' above. */
6190 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash
,
6191 doc
: /* Specifies whether to use the system's trash can.
6192 When non-nil, certain file deletion commands use the function
6193 `move-file-to-trash' instead of deleting files outright.
6194 This includes interactive calls to `delete-file' and
6195 `delete-directory' and the Dired deletion commands. */);
6196 delete_by_moving_to_trash
= 0;
6197 DEFSYM (Qdelete_by_moving_to_trash
, "delete-by-moving-to-trash");
6199 /* Lisp function for moving files to trash. */
6200 DEFSYM (Qmove_file_to_trash
, "move-file-to-trash");
6202 /* Lisp function for recursively copying directories. */
6203 DEFSYM (Qcopy_directory
, "copy-directory");
6205 /* Lisp function for recursively deleting directories. */
6206 DEFSYM (Qdelete_directory
, "delete-directory");
6208 DEFSYM (Qsubstitute_env_in_file_name
, "substitute-env-in-file-name");
6209 DEFSYM (Qget_buffer_window_list
, "get-buffer-window-list");
6211 DEFSYM (Qstdin
, "stdin");
6212 DEFSYM (Qstdout
, "stdout");
6213 DEFSYM (Qstderr
, "stderr");
6215 defsubr (&Sfind_file_name_handler
);
6216 defsubr (&Sfile_name_directory
);
6217 defsubr (&Sfile_name_nondirectory
);
6218 defsubr (&Sunhandled_file_name_directory
);
6219 defsubr (&Sfile_name_as_directory
);
6220 defsubr (&Sdirectory_name_p
);
6221 defsubr (&Sdirectory_file_name
);
6222 defsubr (&Smake_temp_file_internal
);
6223 defsubr (&Smake_temp_name
);
6224 defsubr (&Sexpand_file_name
);
6225 defsubr (&Ssubstitute_in_file_name
);
6226 defsubr (&Scopy_file
);
6227 defsubr (&Smake_directory_internal
);
6228 defsubr (&Sdelete_directory_internal
);
6229 defsubr (&Sdelete_file
);
6230 defsubr (&Sfile_name_case_insensitive_p
);
6231 defsubr (&Srename_file
);
6232 defsubr (&Sadd_name_to_file
);
6233 defsubr (&Smake_symbolic_link
);
6234 defsubr (&Sfile_name_absolute_p
);
6235 defsubr (&Sfile_exists_p
);
6236 defsubr (&Sfile_executable_p
);
6237 defsubr (&Sfile_readable_p
);
6238 defsubr (&Sfile_writable_p
);
6239 defsubr (&Saccess_file
);
6240 defsubr (&Sfile_symlink_p
);
6241 defsubr (&Sfile_directory_p
);
6242 defsubr (&Sfile_accessible_directory_p
);
6243 defsubr (&Sfile_regular_p
);
6244 defsubr (&Sfile_modes
);
6245 defsubr (&Sset_file_modes
);
6246 defsubr (&Sset_file_times
);
6247 defsubr (&Sfile_selinux_context
);
6248 defsubr (&Sfile_acl
);
6249 defsubr (&Sset_file_acl
);
6250 defsubr (&Sset_file_selinux_context
);
6251 defsubr (&Sset_default_file_modes
);
6252 defsubr (&Sdefault_file_modes
);
6253 defsubr (&Sfile_newer_than_file_p
);
6254 defsubr (&Sinsert_file_contents
);
6255 defsubr (&Swrite_region
);
6256 defsubr (&Scar_less_than_car
);
6257 defsubr (&Sverify_visited_file_modtime
);
6258 defsubr (&Svisited_file_modtime
);
6259 defsubr (&Sset_visited_file_modtime
);
6260 defsubr (&Sdo_auto_save
);
6261 defsubr (&Sset_buffer_auto_saved
);
6262 defsubr (&Sclear_buffer_auto_save_failure
);
6263 defsubr (&Srecent_auto_save_p
);
6265 defsubr (&Snext_read_file_uses_dialog_p
);
6267 defsubr (&Sset_binary_mode
);
6270 defsubr (&Sfile_system_info
);
6274 defsubr (&Sunix_sync
);