1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2017 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 #include <sys/types.h>
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>
99 #include <stat-time.h>
100 #include <tempname.h>
102 #include <binary-io.h>
108 #include "commands.h"
110 /* True during writing of auto-save files. */
111 static bool auto_saving
;
113 /* Emacs's real umask. */
114 static mode_t realmask
;
116 /* Nonzero umask during creation of auto-save directories. */
117 static mode_t auto_saving_dir_umask
;
119 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
120 a new file with the same mode as the original. */
121 static mode_t auto_save_mode_bits
;
123 /* Set by auto_save_1 if an error occurred during the last auto-save. */
124 static bool auto_save_error_occurred
;
126 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
127 number of a file system where time stamps were observed to to work. */
128 static bool valid_timestamp_file_system
;
129 static dev_t timestamp_file_system
;
131 /* Each time an annotation function changes the buffer, the new buffer
133 static Lisp_Object Vwrite_region_annotation_buffers
;
135 static bool a_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
136 Lisp_Object
*, struct coding_system
*);
137 static bool e_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
138 struct coding_system
*);
141 /* Return true if FILENAME exists. */
144 check_existing (const char *filename
)
146 return faccessat (AT_FDCWD
, filename
, F_OK
, AT_EACCESS
) == 0;
149 /* Return true if file FILENAME exists and can be executed. */
152 check_executable (char *filename
)
154 return faccessat (AT_FDCWD
, filename
, X_OK
, AT_EACCESS
) == 0;
157 /* Return true if file FILENAME exists and can be accessed
158 according to AMODE, which should include W_OK.
159 On failure, return false and set errno. */
162 check_writable (const char *filename
, int amode
)
165 /* FIXME: an faccessat implementation should be added to the
166 DOS/Windows ports and this #ifdef branch should be removed. */
168 if (stat (filename
, &st
) < 0)
171 return (st
.st_mode
& S_IWRITE
|| S_ISDIR (st
.st_mode
));
172 #else /* not MSDOS */
173 bool res
= faccessat (AT_FDCWD
, filename
, amode
, AT_EACCESS
) == 0;
175 /* faccessat may have returned failure because Cygwin couldn't
176 determine the file's UID or GID; if so, we return success. */
179 int faccessat_errno
= errno
;
181 if (stat (filename
, &st
) < 0)
183 res
= (st
.st_uid
== -1 || st
.st_gid
== -1);
184 errno
= faccessat_errno
;
188 #endif /* not MSDOS */
191 /* Signal a file-access failure. STRING describes the failure,
192 NAME the file involved, and ERRORNO the errno value.
194 If NAME is neither null nor a pair, package it up as a singleton
195 list before reporting it; this saves report_file_errno's caller the
196 trouble of preserving errno before calling list1. */
199 report_file_errno (char const *string
, Lisp_Object name
, int errorno
)
201 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
202 char *str
= emacs_strerror (errorno
);
203 AUTO_STRING (unibyte_str
, str
);
204 Lisp_Object errstring
205 = code_convert_string_norecord (unibyte_str
, Vlocale_coding_system
, 0);
206 Lisp_Object errdata
= Fcons (errstring
, data
);
208 if (errorno
== EEXIST
)
209 xsignal (Qfile_already_exists
, errdata
);
211 xsignal (errorno
== ENOENT
? Qfile_missing
: Qfile_error
,
212 Fcons (build_string (string
), errdata
));
215 /* Signal a file-access failure that set errno. STRING describes the
216 failure, NAME the file involved. When invoking this function, take
217 care to not use arguments such as build_string ("foo") that involve
218 side effects that may set errno. */
221 report_file_error (char const *string
, Lisp_Object name
)
223 report_file_errno (string
, name
, errno
);
226 /* Like report_file_error, but reports a file-notify-error instead. */
229 report_file_notify_error (const char *string
, Lisp_Object name
)
231 char *str
= emacs_strerror (errno
);
232 AUTO_STRING (unibyte_str
, str
);
233 Lisp_Object errstring
234 = code_convert_string_norecord (unibyte_str
, Vlocale_coding_system
, 0);
235 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
236 Lisp_Object errdata
= Fcons (errstring
, data
);
238 xsignal (Qfile_notify_error
, Fcons (build_string (string
), errdata
));
242 close_file_unwind (int fd
)
248 fclose_unwind (void *arg
)
254 /* Restore point, having saved it as a marker. */
257 restore_point_unwind (Lisp_Object location
)
259 Fgoto_char (location
);
260 unchain_marker (XMARKER (location
));
264 DEFUN ("find-file-name-handler", Ffind_file_name_handler
,
265 Sfind_file_name_handler
, 2, 2, 0,
266 doc
: /* Return FILENAME's handler function for OPERATION, if it has one.
267 Otherwise, return nil.
268 A file name is handled if one of the regular expressions in
269 `file-name-handler-alist' matches it.
271 If OPERATION equals `inhibit-file-name-operation', then ignore
272 any handlers that are members of `inhibit-file-name-handlers',
273 but still do run any other handlers. This lets handlers
274 use the standard functions without calling themselves recursively. */)
275 (Lisp_Object filename
, Lisp_Object operation
)
277 /* This function must not munge the match data. */
278 Lisp_Object chain
, inhibited_handlers
, result
;
282 CHECK_STRING (filename
);
284 if (EQ (operation
, Vinhibit_file_name_operation
))
285 inhibited_handlers
= Vinhibit_file_name_handlers
;
287 inhibited_handlers
= Qnil
;
289 for (chain
= Vfile_name_handler_alist
; CONSP (chain
);
290 chain
= XCDR (chain
))
296 Lisp_Object string
= XCAR (elt
);
298 Lisp_Object handler
= XCDR (elt
);
299 Lisp_Object operations
= Qnil
;
301 if (SYMBOLP (handler
))
302 operations
= Fget (handler
, Qoperations
);
305 && (match_pos
= fast_string_match (string
, filename
)) > pos
306 && (NILP (operations
) || ! NILP (Fmemq (operation
, operations
))))
310 handler
= XCDR (elt
);
311 tem
= Fmemq (handler
, inhibited_handlers
);
325 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
327 doc
: /* Return the directory component in file name FILENAME.
328 Return nil if FILENAME does not include a directory.
329 Otherwise return a directory name.
330 Given a Unix syntax file name, returns a string ending in slash. */)
331 (Lisp_Object filename
)
335 CHECK_STRING (filename
);
337 /* If the file name has special constructs in it,
338 call the corresponding file handler. */
339 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
342 Lisp_Object handled_name
= call2 (handler
, Qfile_name_directory
,
344 return STRINGP (handled_name
) ? handled_name
: Qnil
;
347 char *beg
= SSDATA (filename
);
348 char const *p
= beg
+ SBYTES (filename
);
350 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
352 /* only recognize drive specifier at the beginning */
354 /* handle the "/:d:foo" and "/:foo" cases correctly */
355 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
356 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
363 /* Expansion of "c:" to drive and default directory. */
366 SAFE_ALLOCA_STRING (beg
, filename
);
367 p
= beg
+ (p
- SSDATA (filename
));
371 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
372 char *res
= alloca (MAXPATHLEN
+ 1);
375 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
377 memcpy (res
, beg
, 2);
382 if (getdefdir (c_toupper (*beg
) - 'A' + 1, r
))
384 size_t l
= strlen (res
);
386 if (l
> 3 || !IS_DIRECTORY_SEP (res
[l
- 1]))
389 p
= beg
+ strlen (beg
);
390 dostounix_filename (beg
);
391 tem_fn
= make_specified_string (beg
, -1, p
- beg
,
392 STRING_MULTIBYTE (filename
));
395 tem_fn
= make_specified_string (beg
- 2, -1, p
- beg
+ 2,
396 STRING_MULTIBYTE (filename
));
398 else if (STRING_MULTIBYTE (filename
))
400 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 1);
401 dostounix_filename (SSDATA (tem_fn
));
403 if (!NILP (Vw32_downcase_file_names
))
404 tem_fn
= Fdowncase (tem_fn
);
409 dostounix_filename (beg
);
410 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 0);
415 return make_specified_string (beg
, -1, p
- beg
, STRING_MULTIBYTE (filename
));
419 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
420 Sfile_name_nondirectory
, 1, 1, 0,
421 doc
: /* Return file name FILENAME sans its directory.
422 For example, in a Unix-syntax file name,
423 this is everything after the last slash,
424 or the entire name if it contains no slash. */)
425 (Lisp_Object filename
)
427 register const char *beg
, *p
, *end
;
430 CHECK_STRING (filename
);
432 /* If the file name has special constructs in it,
433 call the corresponding file handler. */
434 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
437 Lisp_Object handled_name
= call2 (handler
, Qfile_name_nondirectory
,
439 if (STRINGP (handled_name
))
441 error ("Invalid handler in `file-name-handler-alist'");
444 beg
= SSDATA (filename
);
445 end
= p
= beg
+ SBYTES (filename
);
447 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
449 /* only recognize drive specifier at beginning */
451 /* handle the "/:d:foo" case correctly */
452 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
457 return make_specified_string (p
, -1, end
- p
, STRING_MULTIBYTE (filename
));
460 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
461 Sunhandled_file_name_directory
, 1, 1, 0,
462 doc
: /* Return a directly usable directory name somehow associated with FILENAME.
463 A `directly usable' directory name is one that may be used without the
464 intervention of any file handler.
465 If FILENAME is a directly usable file itself, return
466 \(file-name-as-directory FILENAME).
467 If FILENAME refers to a file which is not accessible from a local process,
468 then this should return nil.
469 The `call-process' and `start-process' functions use this function to
470 get a current directory to run processes in. */)
471 (Lisp_Object filename
)
475 /* If the file name has special constructs in it,
476 call the corresponding file handler. */
477 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
480 Lisp_Object handled_name
= call2 (handler
, Qunhandled_file_name_directory
,
482 return STRINGP (handled_name
) ? handled_name
: Qnil
;
485 return Ffile_name_as_directory (filename
);
488 /* Maximum number of bytes that DST will be longer than SRC
489 in file_name_as_directory. This occurs when SRCLEN == 0. */
490 enum { file_name_as_directory_slop
= 2 };
492 /* Convert from file name SRC of length SRCLEN to directory name in
493 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
494 string. On UNIX, just make sure there is a terminating /. Return
495 the length of DST in bytes. */
498 file_name_as_directory (char *dst
, const char *src
, ptrdiff_t srclen
,
509 memcpy (dst
, src
, srclen
);
510 if (!IS_DIRECTORY_SEP (dst
[srclen
- 1]))
511 dst
[srclen
++] = DIRECTORY_SEP
;
514 dostounix_filename (dst
);
519 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
520 Sfile_name_as_directory
, 1, 1, 0,
521 doc
: /* Return a string representing the file name FILE interpreted as a directory.
522 This operation exists because a directory is also a file, but its name as
523 a directory is different from its name as a file.
524 The result can be used as the value of `default-directory'
525 or passed as second argument to `expand-file-name'.
526 For a Unix-syntax file name, just appends a slash unless a trailing slash
527 is already present. */)
532 Lisp_Object handler
, val
;
537 /* If the file name has special constructs in it,
538 call the corresponding file handler. */
539 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
542 Lisp_Object handled_name
= call2 (handler
, Qfile_name_as_directory
,
544 if (STRINGP (handled_name
))
546 error ("Invalid handler in `file-name-handler-alist'");
550 if (!NILP (Vw32_downcase_file_names
))
551 file
= Fdowncase (file
);
553 buf
= SAFE_ALLOCA (SBYTES (file
) + file_name_as_directory_slop
+ 1);
554 length
= file_name_as_directory (buf
, SSDATA (file
), SBYTES (file
),
555 STRING_MULTIBYTE (file
));
556 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (file
));
561 /* Convert from directory name SRC of length SRCLEN to file name in
562 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
563 string. On UNIX, just make sure there isn't a terminating /.
564 Return the length of DST in bytes. */
567 directory_file_name (char *dst
, char *src
, ptrdiff_t srclen
, bool multibyte
)
569 /* In Unix-like systems, just remove any final slashes. However, if
570 they are all slashes, leave "/" and "//" alone, and treat "///"
571 and longer as if they were "/". */
572 if (! (srclen
== 2 && IS_DIRECTORY_SEP (src
[0])))
575 && !(srclen
> 2 && IS_DEVICE_SEP (src
[srclen
- 2]))
577 && IS_DIRECTORY_SEP (src
[srclen
- 1]))
580 memcpy (dst
, src
, srclen
);
583 dostounix_filename (dst
);
588 DEFUN ("directory-name-p", Fdirectory_name_p
, Sdirectory_name_p
, 1, 1, 0,
589 doc
: /* Return non-nil if NAME ends with a directory separator character. */)
593 ptrdiff_t namelen
= SBYTES (name
);
594 unsigned char c
= namelen
? SREF (name
, namelen
- 1) : 0;
595 return IS_DIRECTORY_SEP (c
) ? Qt
: Qnil
;
598 /* Return true if NAME must be that of a directory if it exists.
599 When NAME is a directory name, this avoids system calls compared to
600 just calling Ffile_directory_p. */
603 directory_like (Lisp_Object name
)
605 return !NILP (Fdirectory_name_p (name
)) || !NILP (Ffile_directory_p (name
));
608 /* Return the expansion of NEWNAME, except that if NEWNAME is like a
609 directory then return the expansion of FILE's basename under
610 NEWNAME. This is like how 'cp FILE NEWNAME' works. */
613 expand_cp_target (Lisp_Object file
, Lisp_Object newname
)
615 return (directory_like (newname
)
616 ? Fexpand_file_name (Ffile_name_nondirectory (file
), newname
)
617 : Fexpand_file_name (newname
, Qnil
));
620 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
622 doc
: /* Returns the file name of the directory named DIRECTORY.
623 This is the name of the file that holds the data for the directory DIRECTORY.
624 This operation exists because a directory is also a file, but its name as
625 a directory is different from its name as a file.
626 In Unix-syntax, this function just removes the final slash. */)
627 (Lisp_Object directory
)
631 Lisp_Object handler
, val
;
634 CHECK_STRING (directory
);
636 /* If the file name has special constructs in it,
637 call the corresponding file handler. */
638 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
641 Lisp_Object handled_name
= call2 (handler
, Qdirectory_file_name
,
643 if (STRINGP (handled_name
))
645 error ("Invalid handler in `file-name-handler-alist'");
649 if (!NILP (Vw32_downcase_file_names
))
650 directory
= Fdowncase (directory
);
652 buf
= SAFE_ALLOCA (SBYTES (directory
) + 1);
653 length
= directory_file_name (buf
, SSDATA (directory
), SBYTES (directory
),
654 STRING_MULTIBYTE (directory
));
655 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (directory
));
660 DEFUN ("make-temp-file-internal", Fmake_temp_file_internal
,
661 Smake_temp_file_internal
, 4, 4, 0,
662 doc
: /* Generate a new file whose name starts with PREFIX, a string.
663 Return the name of the generated file. If DIR-FLAG is zero, do not
664 create the file, just its name. Otherwise, if DIR-FLAG is non-nil,
665 create an empty directory. The file name should end in SUFFIX.
666 Do not expand PREFIX; a non-absolute PREFIX is relative to the Emacs
667 working directory. If TEXT is a string, insert it into the newly
670 Signal an error if the file could not be created.
672 This function does not grok magic file names. */)
673 (Lisp_Object prefix
, Lisp_Object dir_flag
, Lisp_Object suffix
,
676 CHECK_STRING (prefix
);
677 CHECK_STRING (suffix
);
678 Lisp_Object encoded_prefix
= ENCODE_FILE (prefix
);
679 Lisp_Object encoded_suffix
= ENCODE_FILE (suffix
);
680 ptrdiff_t prefix_len
= SBYTES (encoded_prefix
);
681 ptrdiff_t suffix_len
= SBYTES (encoded_suffix
);
682 if (INT_MAX
< suffix_len
)
683 args_out_of_range (prefix
, suffix
);
685 Lisp_Object val
= make_uninit_string (prefix_len
+ nX
+ suffix_len
);
686 char *data
= SSDATA (val
);
687 memcpy (data
, SSDATA (encoded_prefix
), prefix_len
);
688 memset (data
+ prefix_len
, 'X', nX
);
689 memcpy (data
+ prefix_len
+ nX
, SSDATA (encoded_suffix
), suffix_len
);
690 int kind
= (NILP (dir_flag
) ? GT_FILE
691 : EQ (dir_flag
, make_number (0)) ? GT_NOCREATE
693 int fd
= gen_tempname (data
, suffix_len
, O_BINARY
| O_CLOEXEC
, kind
);
694 bool failed
= fd
< 0;
697 ptrdiff_t count
= SPECPDL_INDEX ();
698 record_unwind_protect_int (close_file_unwind
, fd
);
699 val
= DECODE_FILE (val
);
700 if (STRINGP (text
) && SBYTES (text
) != 0)
701 write_region (text
, Qnil
, val
, Qnil
, Qnil
, Qnil
, Qnil
, fd
);
702 failed
= NILP (dir_flag
) && emacs_close (fd
) != 0;
703 /* Discard the unwind protect. */
704 specpdl_ptr
= specpdl
+ count
;
708 static char const kind_message
[][32] =
710 [GT_FILE
] = "Creating file with prefix",
711 [GT_DIR
] = "Creating directory with prefix",
712 [GT_NOCREATE
] = "Creating file name with prefix"
714 report_file_error (kind_message
[kind
], prefix
);
720 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
721 doc
: /* Generate temporary file name (string) starting with PREFIX (a string).
723 This function tries to choose a name that has no existing file.
724 For this to work, PREFIX should be an absolute file name, and PREFIX
725 and the returned string should both be non-magic.
727 There is a race condition between calling `make-temp-name' and
728 later creating the file, which opens all kinds of security holes.
729 For that reason, you should normally use `make-temp-file' instead. */)
732 return Fmake_temp_file_internal (prefix
, make_number (0),
733 empty_unibyte_string
, Qnil
);
736 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
737 doc
: /* Convert filename NAME to absolute, and canonicalize it.
738 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
739 \(does not start with slash or tilde); both the directory name and
740 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
741 missing, the current buffer's value of `default-directory' is used.
742 NAME should be a string that is a valid file name for the underlying
744 File name components that are `.' are removed, and
745 so are file name components followed by `..', along with the `..' itself;
746 note that these simplifications are done without checking the resulting
747 file names in the file system.
748 Multiple consecutive slashes are collapsed into a single slash,
749 except at the beginning of the file name when they are significant (e.g.,
750 UNC file names on MS-Windows.)
751 An initial `~/' expands to your home directory.
752 An initial `~USER/' expands to USER's home directory.
753 See also the function `substitute-in-file-name'.
755 For technical reasons, this function can return correct but
756 non-intuitive results for the root directory; for instance,
757 \(expand-file-name ".." "/") returns "/..". For this reason, use
758 \(directory-file-name (file-name-directory dirname)) to traverse a
759 filesystem tree, not (expand-file-name ".." dirname). Note: make
760 sure DIRNAME in this example doesn't end in a slash, unless it's
761 the root directory. */)
762 (Lisp_Object name
, Lisp_Object default_directory
)
764 /* These point to SDATA and need to be careful with string-relocation
765 during GC (via DECODE_FILE). */
769 const char *newdirlim
;
770 /* This should only point to alloca'd data. */
777 bool collapse_newdir
= true;
780 ptrdiff_t length
, nbytes
;
781 Lisp_Object handler
, result
, handled_name
;
788 /* If the file name has special constructs in it,
789 call the corresponding file handler. */
790 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
793 handled_name
= call3 (handler
, Qexpand_file_name
,
794 name
, default_directory
);
795 if (STRINGP (handled_name
))
797 error ("Invalid handler in `file-name-handler-alist'");
801 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
802 if (NILP (default_directory
))
803 default_directory
= BVAR (current_buffer
, directory
);
804 if (! STRINGP (default_directory
))
807 /* "/" is not considered a root directory on DOS_NT, so using "/"
808 here causes an infinite recursion in, e.g., the following:
810 (let (default-directory)
811 (expand-file-name "a"))
813 To avoid this, we set default_directory to the root of the
815 default_directory
= build_string (emacs_root_dir ());
817 default_directory
= build_string ("/");
821 if (!NILP (default_directory
))
823 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
826 handled_name
= call3 (handler
, Qexpand_file_name
,
827 name
, default_directory
);
828 if (STRINGP (handled_name
))
830 error ("Invalid handler in `file-name-handler-alist'");
835 char *o
= SSDATA (default_directory
);
837 /* Make sure DEFAULT_DIRECTORY is properly expanded.
838 It would be better to do this down below where we actually use
839 default_directory. Unfortunately, calling Fexpand_file_name recursively
840 could invoke GC, and the strings might be relocated. This would
841 be annoying because we have pointers into strings lying around
842 that would need adjusting, and people would add new pointers to
843 the code and forget to adjust them, resulting in intermittent bugs.
844 Putting this call here avoids all that crud.
846 The EQ test avoids infinite recursion. */
847 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
848 /* Save time in some common cases - as long as default_directory
849 is not relative, it can be canonicalized with name below (if it
850 is needed at all) without requiring it to be expanded now. */
852 /* Detect MSDOS file names with drive specifiers. */
853 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1])
854 && IS_DIRECTORY_SEP (o
[2]))
855 /* Detect escaped file names without drive spec after "/:".
856 These should not be recursively expanded, to avoid
857 including the default directory twice in the expanded
859 && ! (o
[0] == '/' && o
[1] == ':')
861 /* Detect Windows file names in UNC format. */
862 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
864 #else /* not DOS_NT */
865 /* Detect Unix absolute file names (/... alone is not absolute on
867 && ! (IS_DIRECTORY_SEP (o
[0]))
868 #endif /* not DOS_NT */
871 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
874 multibyte
= STRING_MULTIBYTE (name
);
875 if (multibyte
!= STRING_MULTIBYTE (default_directory
))
879 unsigned char *p
= SDATA (name
);
881 while (*p
&& ASCII_CHAR_P (*p
))
885 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
886 unibyte. Do not convert DEFAULT_DIRECTORY to
887 multibyte; instead, convert NAME to a unibyte string,
888 so that the result of this function is also a unibyte
889 string. This is needed during bootstrapping and
890 dumping, when Emacs cannot decode file names, because
891 the locale environment is not set up. */
892 name
= make_unibyte_string (SSDATA (name
), SBYTES (name
));
896 default_directory
= string_to_multibyte (default_directory
);
900 name
= string_to_multibyte (name
);
906 if (!NILP (Vw32_downcase_file_names
))
907 default_directory
= Fdowncase (default_directory
);
910 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
911 SAFE_ALLOCA_STRING (nm
, name
);
912 nmlim
= nm
+ SBYTES (name
);
915 /* Note if special escape prefix is present, but remove for now. */
916 if (nm
[0] == '/' && nm
[1] == ':')
922 /* Find and remove drive specifier if present; this makes nm absolute
923 even if the rest of the name appears to be relative. Only look for
924 drive specifier at the beginning. */
925 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
927 drive
= (unsigned char) nm
[0];
932 /* If we see "c://somedir", we want to strip the first slash after the
933 colon when stripping the drive letter. Otherwise, this expands to
935 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
938 /* Discard any previous drive specifier if nm is now in UNC format. */
939 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
940 && !IS_DIRECTORY_SEP (nm
[2]))
942 #endif /* WINDOWSNT */
945 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
946 none are found, we can probably return right away. We will avoid
947 allocating a new string if name is already fully expanded. */
949 IS_DIRECTORY_SEP (nm
[0])
951 && drive
&& !is_escaped
954 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
958 /* If it turns out that the filename we want to return is just a
959 suffix of FILENAME, we don't need to go through and edit
960 things; we just need to construct a new string using data
961 starting at the middle of FILENAME. If we set LOSE, that
962 means we've discovered that we can't do that cool trick. */
968 /* Since we know the name is absolute, we can assume that each
969 element starts with a "/". */
971 /* "." and ".." are hairy. */
972 if (IS_DIRECTORY_SEP (p
[0])
974 && (IS_DIRECTORY_SEP (p
[2])
976 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
979 /* Replace multiple slashes with a single one, except
980 leave leading "//" alone. */
981 else if (IS_DIRECTORY_SEP (p
[0])
982 && IS_DIRECTORY_SEP (p
[1])
983 && (p
!= nm
|| IS_DIRECTORY_SEP (p
[2])))
990 /* Make sure directories are all separated with /, but
991 avoid allocation of a new string when not required. */
992 dostounix_filename (nm
);
994 if (IS_DIRECTORY_SEP (nm
[1]))
996 if (strcmp (nm
, SSDATA (name
)) != 0)
997 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1001 /* Drive must be set, so this is okay. */
1002 if (strcmp (nm
- 2, SSDATA (name
)) != 0)
1004 name
= make_specified_string (nm
, -1, p
- nm
, multibyte
);
1005 char temp
[] = { DRIVE_LETTER (drive
), ':', 0 };
1006 AUTO_STRING_WITH_LEN (drive_prefix
, temp
, 2);
1007 name
= concat2 (drive_prefix
, name
);
1010 if (!NILP (Vw32_downcase_file_names
))
1011 name
= Fdowncase (name
);
1013 #else /* not DOS_NT */
1014 if (strcmp (nm
, SSDATA (name
)) != 0)
1015 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1016 #endif /* not DOS_NT */
1022 /* At this point, nm might or might not be an absolute file name. We
1023 need to expand ~ or ~user if present, otherwise prefix nm with
1024 default_directory if nm is not absolute, and finally collapse /./
1025 and /foo/../ sequences.
1027 We set newdir to be the appropriate prefix if one is needed:
1028 - the relevant user directory if nm starts with ~ or ~user
1029 - the specified drive's working dir (DOS/NT only) if nm does not
1031 - the value of default_directory.
1033 Note that these prefixes are not guaranteed to be absolute (except
1034 for the working dir of a drive). Therefore, to ensure we always
1035 return an absolute name, if the final prefix is not absolute we
1036 append it to the current working directory. */
1038 newdir
= newdirlim
= 0;
1040 if (nm
[0] == '~' /* prefix ~ */
1042 && !is_escaped
/* don't expand ~ in escaped file names */
1046 if (IS_DIRECTORY_SEP (nm
[1])
1047 || nm
[1] == 0) /* ~ by itself */
1051 if (!(newdir
= egetenv ("HOME")))
1052 newdir
= newdirlim
= "";
1057 char newdir_utf8
[MAX_UTF8_PATH
];
1059 filename_from_ansi (newdir
, newdir_utf8
);
1060 tem
= make_unibyte_string (newdir_utf8
, strlen (newdir_utf8
));
1061 newdir
= SSDATA (tem
);
1065 tem
= build_string (newdir
);
1066 newdirlim
= newdir
+ SBYTES (tem
);
1067 /* `egetenv' may return a unibyte string, which will bite us
1068 if we expect the directory to be multibyte. */
1069 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1071 hdir
= DECODE_FILE (tem
);
1072 newdir
= SSDATA (hdir
);
1073 newdirlim
= newdir
+ SBYTES (hdir
);
1076 collapse_newdir
= false;
1079 else /* ~user/filename */
1082 for (p
= nm
; *p
&& !IS_DIRECTORY_SEP (*p
); p
++)
1084 o
= SAFE_ALLOCA (p
- nm
+ 1);
1085 memcpy (o
, nm
, p
- nm
);
1089 pw
= getpwnam (o
+ 1);
1095 newdir
= pw
->pw_dir
;
1096 /* `getpwnam' may return a unibyte string, which will
1097 bite us when we expect the directory to be multibyte. */
1098 tem
= make_unibyte_string (newdir
, strlen (newdir
));
1099 newdirlim
= newdir
+ SBYTES (tem
);
1100 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1102 hdir
= DECODE_FILE (tem
);
1103 newdir
= SSDATA (hdir
);
1104 newdirlim
= newdir
+ SBYTES (hdir
);
1108 collapse_newdir
= false;
1112 /* If we don't find a user of that name, leave the name
1113 unchanged; don't move nm forward to p. */
1118 /* On DOS and Windows, nm is absolute if a drive name was specified;
1119 use the drive's current directory as the prefix if needed. */
1120 if (!newdir
&& drive
)
1122 /* Get default directory if needed to make nm absolute. */
1124 if (!IS_DIRECTORY_SEP (nm
[0]))
1126 adir
= alloca (MAXPATHLEN
+ 1);
1127 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1131 Lisp_Object tem
= build_string (adir
);
1133 tem
= DECODE_FILE (tem
);
1134 newdirlim
= adir
+ SBYTES (tem
);
1135 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1138 newdirlim
= adir
+ strlen (adir
);
1142 /* Either nm starts with /, or drive isn't mounted. */
1144 adir
[0] = DRIVE_LETTER (drive
);
1148 newdirlim
= adir
+ 3;
1154 /* Finally, if no prefix has been specified and nm is not absolute,
1155 then it must be expanded relative to default_directory. */
1159 /* /... alone is not absolute on DOS and Windows. */
1160 && !IS_DIRECTORY_SEP (nm
[0])
1163 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
1164 && !IS_DIRECTORY_SEP (nm
[2]))
1168 newdir
= SSDATA (default_directory
);
1169 newdirlim
= newdir
+ SBYTES (default_directory
);
1171 /* Note if special escape prefix is present, but remove for now. */
1172 if (newdir
[0] == '/' && newdir
[1] == ':')
1183 /* First ensure newdir is an absolute name. */
1185 /* Detect MSDOS file names with drive specifiers. */
1186 ! (IS_DRIVE (newdir
[0])
1187 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1189 /* Detect Windows file names in UNC format. */
1190 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1191 && !IS_DIRECTORY_SEP (newdir
[2]))
1195 /* Effectively, let newdir be (expand-file-name newdir cwd).
1196 Because of the admonition against calling expand-file-name
1197 when we have pointers into lisp strings, we accomplish this
1198 indirectly by prepending newdir to nm if necessary, and using
1199 cwd (or the wd of newdir's drive) as the new newdir. */
1202 const int adir_size
= MAX_UTF8_PATH
;
1204 const int adir_size
= MAXPATHLEN
+ 1;
1207 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1209 drive
= (unsigned char) newdir
[0];
1212 if (!IS_DIRECTORY_SEP (nm
[0]))
1214 ptrdiff_t nmlen
= nmlim
- nm
;
1215 ptrdiff_t newdirlen
= newdirlim
- newdir
;
1216 char *tmp
= alloca (newdirlen
+ file_name_as_directory_slop
1218 ptrdiff_t dlen
= file_name_as_directory (tmp
, newdir
, newdirlen
,
1220 memcpy (tmp
+ dlen
, nm
, nmlen
+ 1);
1222 nmlim
= nm
+ dlen
+ nmlen
;
1224 adir
= alloca (adir_size
);
1227 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1231 getcwd (adir
, adir_size
);
1234 Lisp_Object tem
= build_string (adir
);
1236 tem
= DECODE_FILE (tem
);
1237 newdirlim
= adir
+ SBYTES (tem
);
1238 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1241 newdirlim
= adir
+ strlen (adir
);
1245 /* Strip off drive name from prefix, if present. */
1246 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1252 /* Keep only a prefix from newdir if nm starts with slash
1253 (//server/share for UNC, nothing otherwise). */
1254 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1257 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1258 && !IS_DIRECTORY_SEP (newdir
[2]))
1260 char *adir
= strcpy (alloca (newdirlim
- newdir
+ 1), newdir
);
1262 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1264 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1267 newdirlim
= newdir
+ strlen (adir
);
1271 newdir
= newdirlim
= "";
1276 /* Ignore any slash at the end of newdir, unless newdir is
1277 just "/" or "//". */
1278 length
= newdirlim
- newdir
;
1279 while (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1280 && ! (length
== 2 && IS_DIRECTORY_SEP (newdir
[0])))
1283 /* Now concatenate the directory and name to new space in the stack frame. */
1284 tlen
= length
+ file_name_as_directory_slop
+ (nmlim
- nm
) + 1;
1285 eassert (tlen
> file_name_as_directory_slop
+ 1);
1287 /* Reserve space for drive specifier and escape prefix, since either
1288 or both may need to be inserted. (The Microsoft x86 compiler
1289 produces incorrect code if the following two lines are combined.) */
1290 target
= alloca (tlen
+ 4);
1292 #else /* not DOS_NT */
1293 target
= SAFE_ALLOCA (tlen
);
1294 #endif /* not DOS_NT */
1300 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1303 /* If newdir is effectively "C:/", then the drive letter will have
1304 been stripped and newdir will be "/". Concatenating with an
1305 absolute directory in nm produces "//", which will then be
1306 incorrectly treated as a network share. Ignore newdir in
1307 this case (keeping the drive letter). */
1308 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1309 && newdir
[1] == '\0'))
1312 memcpy (target
, newdir
, length
);
1318 nbytes
= file_name_as_directory (target
, newdir
, length
, multibyte
);
1321 memcpy (target
+ nbytes
, nm
, nmlim
- nm
+ 1);
1323 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1331 if (!IS_DIRECTORY_SEP (*p
))
1335 else if (p
[1] == '.'
1336 && (IS_DIRECTORY_SEP (p
[2])
1339 /* If "/." is the entire filename, keep the "/". Otherwise,
1340 just delete the whole "/.". */
1341 if (o
== target
&& p
[2] == '\0')
1345 else if (p
[1] == '.' && p
[2] == '.'
1346 /* `/../' is the "superroot" on certain file systems.
1347 Turned off on DOS_NT systems because they have no
1348 "superroot" and because this causes us to produce
1349 file names like "d:/../foo" which fail file-related
1350 functions of the underlying OS. (To reproduce, try a
1351 long series of "../../" in default_directory, longer
1352 than the number of levels from the root.) */
1356 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1361 while (o
!= target
&& (--o
, !IS_DIRECTORY_SEP (*o
)))
1364 /* Don't go below server level in UNC filenames. */
1365 if (o
== target
+ 1 && IS_DIRECTORY_SEP (*o
)
1366 && IS_DIRECTORY_SEP (*target
))
1370 /* Keep initial / only if this is the whole name. */
1371 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1375 else if (IS_DIRECTORY_SEP (p
[1])
1376 && (p
!= target
|| IS_DIRECTORY_SEP (p
[2])))
1377 /* Collapse multiple "/", except leave leading "//" alone. */
1386 /* At last, set drive name. */
1388 /* Except for network file name. */
1389 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1390 #endif /* WINDOWSNT */
1392 if (!drive
) emacs_abort ();
1394 target
[0] = DRIVE_LETTER (drive
);
1397 /* Reinsert the escape prefix if required. */
1404 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1405 dostounix_filename (SSDATA (result
));
1407 if (!NILP (Vw32_downcase_file_names
))
1408 result
= Fdowncase (result
);
1411 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1412 #endif /* !DOS_NT */
1415 /* Again look to see if the file name has special constructs in it
1416 and perhaps call the corresponding file handler. This is needed
1417 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1418 the ".." component gives us "/user@host:/bar/../baz" which needs
1419 to be expanded again. */
1420 handler
= Ffind_file_name_handler (result
, Qexpand_file_name
);
1421 if (!NILP (handler
))
1423 handled_name
= call3 (handler
, Qexpand_file_name
,
1424 result
, default_directory
);
1425 if (! STRINGP (handled_name
))
1426 error ("Invalid handler in `file-name-handler-alist'");
1427 result
= handled_name
;
1435 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1436 This is the old version of expand-file-name, before it was thoroughly
1437 rewritten for Emacs 10.31. We leave this version here commented-out,
1438 because the code is very complex and likely to have subtle bugs. If
1439 bugs _are_ found, it might be of interest to look at the old code and
1440 see what did it do in the relevant situation.
1442 Don't remove this code: it's true that it will be accessible
1443 from the repository, but a few years from deletion, people will
1444 forget it is there. */
1446 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1447 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1448 "Convert FILENAME to absolute, and canonicalize it.\n\
1449 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1450 \(does not start with slash); if DEFAULT is nil or missing,\n\
1451 the current buffer's value of default-directory is used.\n\
1452 Filenames containing `.' or `..' as components are simplified;\n\
1453 initial `~/' expands to your home directory.\n\
1454 See also the function `substitute-in-file-name'.")
1456 Lisp_Object name
, defalt
;
1460 register unsigned char *newdir
, *p
, *o
;
1462 unsigned char *target
;
1465 CHECK_STRING (name
);
1468 /* If nm is absolute, flush ...// and detect /./ and /../.
1469 If no /./ or /../ we can return right away. */
1476 if (p
[0] == '/' && p
[1] == '/')
1478 if (p
[0] == '/' && p
[1] == '~')
1479 nm
= p
+ 1, lose
= 1;
1480 if (p
[0] == '/' && p
[1] == '.'
1481 && (p
[2] == '/' || p
[2] == 0
1482 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1488 if (nm
== SDATA (name
))
1490 return build_string (nm
);
1494 /* Now determine directory to start with and put it in NEWDIR. */
1498 if (nm
[0] == '~') /* prefix ~ */
1499 if (nm
[1] == '/' || nm
[1] == 0)/* ~/filename */
1501 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1502 newdir
= (unsigned char *) "";
1505 else /* ~user/filename */
1507 /* Get past ~ to user. */
1508 unsigned char *user
= nm
+ 1;
1509 /* Find end of name. */
1510 unsigned char *ptr
= (unsigned char *) strchr (user
, '/');
1511 ptrdiff_t len
= ptr
? ptr
- user
: strlen (user
);
1512 /* Copy the user name into temp storage. */
1513 o
= alloca (len
+ 1);
1514 memcpy (o
, user
, len
);
1517 /* Look up the user name. */
1519 pw
= (struct passwd
*) getpwnam (o
+ 1);
1522 error ("\"%s\" isn't a registered user", o
+ 1);
1524 newdir
= (unsigned char *) pw
->pw_dir
;
1526 /* Discard the user name from NM. */
1530 if (nm
[0] != '/' && !newdir
)
1533 defalt
= current_buffer
->directory
;
1534 CHECK_STRING (defalt
);
1535 newdir
= SDATA (defalt
);
1538 /* Now concatenate the directory and name to new space in the stack frame. */
1540 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1541 target
= alloca (tlen
);
1546 if (nm
[0] == 0 || nm
[0] == '/')
1547 strcpy (target
, newdir
);
1549 file_name_as_directory (target
, newdir
);
1552 strcat (target
, nm
);
1554 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1565 else if (!strncmp (p
, "//", 2)
1571 else if (p
[0] == '/' && p
[1] == '.'
1572 && (p
[2] == '/' || p
[2] == 0))
1574 else if (!strncmp (p
, "/..", 3)
1575 /* `/../' is the "superroot" on certain file systems. */
1577 && (p
[3] == '/' || p
[3] == 0))
1579 while (o
!= target
&& *--o
!= '/')
1581 if (o
== target
&& *o
== '/')
1591 return make_string (target
, o
- target
);
1595 /* If /~ or // appears, discard everything through first slash. */
1597 file_name_absolute_p (const char *filename
)
1600 (IS_DIRECTORY_SEP (*filename
) || *filename
== '~'
1602 || (IS_DRIVE (*filename
) && IS_DEVICE_SEP (filename
[1])
1603 && IS_DIRECTORY_SEP (filename
[2]))
1609 search_embedded_absfilename (char *nm
, char *endp
)
1613 for (p
= nm
+ 1; p
< endp
; p
++)
1615 if (IS_DIRECTORY_SEP (p
[-1])
1616 && file_name_absolute_p (p
)
1617 #if defined (WINDOWSNT) || defined (CYGWIN)
1618 /* // at start of file name is meaningful in Apollo,
1619 WindowsNT and Cygwin systems. */
1620 && !(IS_DIRECTORY_SEP (p
[0]) && p
- 1 == nm
)
1621 #endif /* not (WINDOWSNT || CYGWIN) */
1624 for (s
= p
; *s
&& !IS_DIRECTORY_SEP (*s
); s
++);
1625 if (p
[0] == '~' && s
> p
+ 1) /* We've got "/~something/". */
1628 char *o
= SAFE_ALLOCA (s
- p
+ 1);
1630 memcpy (o
, p
, s
- p
);
1633 /* If we have ~user and `user' exists, discard
1634 everything up to ~. But if `user' does not exist, leave
1635 ~user alone, it might be a literal file name. */
1637 pw
= getpwnam (o
+ 1);
1650 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
1651 Ssubstitute_in_file_name
, 1, 1, 0,
1652 doc
: /* Substitute environment variables referred to in FILENAME.
1653 `$FOO' where FOO is an environment variable name means to substitute
1654 the value of that variable. The variable name should be terminated
1655 with a character not a letter, digit or underscore; otherwise, enclose
1656 the entire variable name in braces.
1658 If `/~' appears, all of FILENAME through that `/' is discarded.
1659 If `//' appears, everything up to and including the first of
1660 those `/' is discarded. */)
1661 (Lisp_Object filename
)
1663 char *nm
, *p
, *x
, *endp
;
1664 bool substituted
= false;
1667 Lisp_Object handler
;
1669 CHECK_STRING (filename
);
1671 multibyte
= STRING_MULTIBYTE (filename
);
1673 /* If the file name has special constructs in it,
1674 call the corresponding file handler. */
1675 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
1676 if (!NILP (handler
))
1678 Lisp_Object handled_name
= call2 (handler
, Qsubstitute_in_file_name
,
1680 if (STRINGP (handled_name
))
1681 return handled_name
;
1682 error ("Invalid handler in `file-name-handler-alist'");
1685 /* Always work on a copy of the string, in case GC happens during
1686 decode of environment variables, causing the original Lisp_String
1687 data to be relocated. */
1689 SAFE_ALLOCA_STRING (nm
, filename
);
1692 dostounix_filename (nm
);
1693 substituted
= (memcmp (nm
, SDATA (filename
), SBYTES (filename
)) != 0);
1695 endp
= nm
+ SBYTES (filename
);
1697 /* If /~ or // appears, discard everything through first slash. */
1698 p
= search_embedded_absfilename (nm
, endp
);
1700 /* Start over with the new string, so we check the file-name-handler
1701 again. Important with filenames like "/home/foo//:/hello///there"
1702 which would substitute to "/:/hello///there" rather than "/there". */
1705 = (Fsubstitute_in_file_name
1706 (make_specified_string (p
, -1, endp
- p
, multibyte
)));
1711 /* See if any variables are substituted into the string. */
1713 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name
)))
1716 = (!substituted
? filename
1717 : make_specified_string (nm
, -1, endp
- nm
, multibyte
));
1718 Lisp_Object tmp
= call1 (Qsubstitute_env_in_file_name
, name
);
1720 if (!EQ (tmp
, name
))
1728 if (!NILP (Vw32_downcase_file_names
))
1729 filename
= Fdowncase (filename
);
1735 xnm
= SSDATA (filename
);
1736 x
= xnm
+ SBYTES (filename
);
1738 /* If /~ or // appears, discard everything through first slash. */
1739 while ((p
= search_embedded_absfilename (xnm
, x
)) != NULL
)
1740 /* This time we do not start over because we've already expanded envvars
1741 and replaced $$ with $. Maybe we should start over as well, but we'd
1742 need to quote some $ to $$ first. */
1746 if (!NILP (Vw32_downcase_file_names
))
1748 Lisp_Object xname
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1750 filename
= Fdowncase (xname
);
1754 if (xnm
!= SSDATA (filename
))
1755 filename
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1760 /* A slightly faster and more convenient way to get
1761 (directory-file-name (expand-file-name FOO)). */
1764 expand_and_dir_to_file (Lisp_Object filename
)
1766 Lisp_Object absname
= Fexpand_file_name (filename
, Qnil
);
1768 /* Remove final slash, if any (unless this is the root dir).
1769 stat behaves differently depending! */
1770 if (SCHARS (absname
) > 1
1771 && IS_DIRECTORY_SEP (SREF (absname
, SBYTES (absname
) - 1))
1772 && !IS_DEVICE_SEP (SREF (absname
, SBYTES (absname
) - 2)))
1773 /* We cannot take shortcuts; they might be wrong for magic file names. */
1774 absname
= Fdirectory_file_name (absname
);
1778 /* Signal an error if the file ABSNAME already exists.
1779 If KNOWN_TO_EXIST, the file is known to exist.
1780 QUERYSTRING is a name for the action that is being considered
1782 If INTERACTIVE, ask the user whether to proceed,
1783 and bypass the error if the user says to go ahead.
1784 If QUICK, ask for y or n, not yes or no. */
1787 barf_or_query_if_file_exists (Lisp_Object absname
, bool known_to_exist
,
1788 const char *querystring
, bool interactive
,
1791 Lisp_Object tem
, encoded_filename
;
1792 struct stat statbuf
;
1794 encoded_filename
= ENCODE_FILE (absname
);
1796 if (! known_to_exist
&& lstat (SSDATA (encoded_filename
), &statbuf
) == 0)
1798 if (S_ISDIR (statbuf
.st_mode
))
1799 xsignal2 (Qfile_error
,
1800 build_string ("File is a directory"), absname
);
1801 known_to_exist
= true;
1807 xsignal2 (Qfile_already_exists
,
1808 build_string ("File already exists"), absname
);
1809 AUTO_STRING (format
, "File %s already exists; %s anyway? ");
1810 tem
= CALLN (Fformat
, format
, absname
, build_string (querystring
));
1812 tem
= call1 (intern ("y-or-n-p"), tem
);
1814 tem
= do_yes_or_no_p (tem
);
1816 xsignal2 (Qfile_already_exists
,
1817 build_string ("File already exists"), absname
);
1822 /* Copy data to DEST from SOURCE if possible. Return true if OK. */
1824 clone_file (int dest
, int source
)
1827 return ioctl (dest
, FICLONE
, source
) == 0;
1833 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 6,
1834 "fCopy file: \nGCopy %s to file: \np\nP",
1835 doc
: /* Copy FILE to NEWNAME. Both args must be strings.
1836 If NEWNAME names a directory, copy FILE there.
1838 This function always sets the file modes of the output file to match
1841 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1842 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil,
1843 signal a `file-already-exists' error without overwriting. If
1844 OK-IF-ALREADY-EXISTS is an integer, request confirmation from the user
1845 about overwriting; this is what happens in interactive use with M-x.
1846 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1849 Fourth arg KEEP-TIME non-nil means give the output file the same
1850 last-modified time as the old one. (This works on only some systems.)
1852 A prefix arg makes KEEP-TIME non-nil.
1854 If PRESERVE-UID-GID is non-nil, try to transfer the uid and gid of
1857 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1858 this includes the file modes, along with ACL entries and SELinux
1859 context if present. Otherwise, if NEWNAME is created its file
1860 permission bits are those of FILE, masked by the default file
1862 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
,
1863 Lisp_Object keep_time
, Lisp_Object preserve_uid_gid
,
1864 Lisp_Object preserve_permissions
)
1866 Lisp_Object handler
;
1867 ptrdiff_t count
= SPECPDL_INDEX ();
1868 Lisp_Object encoded_file
, encoded_newname
;
1870 security_context_t con
;
1876 bool already_exists
= false;
1882 file
= Fexpand_file_name (file
, Qnil
);
1883 newname
= expand_cp_target (file
, newname
);
1885 /* If the input file name has special constructs in it,
1886 call the corresponding file handler. */
1887 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
1888 /* Likewise for output file name. */
1890 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
1891 if (!NILP (handler
))
1892 return call7 (handler
, Qcopy_file
, file
, newname
,
1893 ok_if_already_exists
, keep_time
, preserve_uid_gid
,
1894 preserve_permissions
);
1896 encoded_file
= ENCODE_FILE (file
);
1897 encoded_newname
= ENCODE_FILE (newname
);
1900 if (NILP (ok_if_already_exists
)
1901 || INTEGERP (ok_if_already_exists
))
1902 barf_or_query_if_file_exists (newname
, false, "copy to it",
1903 INTEGERP (ok_if_already_exists
), false);
1905 result
= w32_copy_file (SSDATA (encoded_file
), SSDATA (encoded_newname
),
1906 !NILP (keep_time
), !NILP (preserve_uid_gid
),
1907 !NILP (preserve_permissions
));
1911 report_file_error ("Copying file", list2 (file
, newname
));
1913 report_file_error ("Copying permissions from", file
);
1915 xsignal2 (Qfile_date_error
,
1916 build_string ("Resetting file times"), newname
);
1918 report_file_error ("Copying permissions to", newname
);
1920 #else /* not WINDOWSNT */
1921 ifd
= emacs_open (SSDATA (encoded_file
), O_RDONLY
, 0);
1924 report_file_error ("Opening input file", file
);
1926 record_unwind_protect_int (close_file_unwind
, ifd
);
1928 if (fstat (ifd
, &st
) != 0)
1929 report_file_error ("Input file status", file
);
1931 if (!NILP (preserve_permissions
))
1934 if (is_selinux_enabled ())
1936 conlength
= fgetfilecon (ifd
, &con
);
1937 if (conlength
== -1)
1938 report_file_error ("Doing fgetfilecon", file
);
1943 /* We can copy only regular files. */
1944 if (!S_ISREG (st
.st_mode
))
1945 report_file_errno ("Non-regular file", file
,
1946 S_ISDIR (st
.st_mode
) ? EISDIR
: EINVAL
);
1949 new_mask
= st
.st_mode
& (!NILP (preserve_uid_gid
) ? 0700 : 0777);
1951 new_mask
= S_IREAD
| S_IWRITE
;
1954 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
| O_CREAT
| O_EXCL
,
1956 if (ofd
< 0 && errno
== EEXIST
)
1958 if (NILP (ok_if_already_exists
) || INTEGERP (ok_if_already_exists
))
1959 barf_or_query_if_file_exists (newname
, true, "copy to it",
1960 INTEGERP (ok_if_already_exists
), false);
1961 already_exists
= true;
1962 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
, 0);
1965 report_file_error ("Opening output file", newname
);
1967 record_unwind_protect_int (close_file_unwind
, ofd
);
1969 off_t oldsize
= 0, newsize
;
1974 if (fstat (ofd
, &out_st
) != 0)
1975 report_file_error ("Output file status", newname
);
1976 if (st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
1977 report_file_errno ("Input and output files are the same",
1978 list2 (file
, newname
), 0);
1979 if (S_ISREG (out_st
.st_mode
))
1980 oldsize
= out_st
.st_size
;
1985 if (clone_file (ofd
, ifd
))
1986 newsize
= st
.st_size
;
1989 char buf
[MAX_ALLOCA
];
1991 for (newsize
= 0; 0 < (n
= emacs_read_quit (ifd
, buf
, sizeof buf
));
1993 if (emacs_write_quit (ofd
, buf
, n
) != n
)
1994 report_file_error ("Write error", newname
);
1996 report_file_error ("Read error", file
);
1999 /* Truncate any existing output file after writing the data. This
2000 is more likely to work than truncation before writing, if the
2001 file system is out of space or the user is over disk quota. */
2002 if (newsize
< oldsize
&& ftruncate (ofd
, newsize
) != 0)
2003 report_file_error ("Truncating output file", newname
);
2006 /* Preserve the original file permissions, and if requested, also its
2009 mode_t preserved_permissions
= st
.st_mode
& 07777;
2010 mode_t default_permissions
= st
.st_mode
& 0777 & ~realmask
;
2011 if (!NILP (preserve_uid_gid
))
2013 /* Attempt to change owner and group. If that doesn't work
2014 attempt to change just the group, as that is sometimes allowed.
2015 Adjust the mode mask to eliminate setuid or setgid bits
2016 or group permissions bits that are inappropriate if the
2017 owner or group are wrong. */
2018 if (fchown (ofd
, st
.st_uid
, st
.st_gid
) != 0)
2020 if (fchown (ofd
, -1, st
.st_gid
) == 0)
2021 preserved_permissions
&= ~04000;
2024 preserved_permissions
&= ~06000;
2026 /* Copy the other bits to the group bits, since the
2028 preserved_permissions
&= ~070;
2029 preserved_permissions
|= (preserved_permissions
& 7) << 3;
2030 default_permissions
&= ~070;
2031 default_permissions
|= (default_permissions
& 7) << 3;
2036 switch (!NILP (preserve_permissions
)
2037 ? qcopy_acl (SSDATA (encoded_file
), ifd
,
2038 SSDATA (encoded_newname
), ofd
,
2039 preserved_permissions
)
2041 || (new_mask
& ~realmask
) == default_permissions
)
2043 : fchmod (ofd
, default_permissions
))
2045 case -2: report_file_error ("Copying permissions from", file
);
2046 case -1: report_file_error ("Copying permissions to", newname
);
2049 #endif /* not MSDOS */
2054 /* Set the modified context back to the file. */
2055 bool fail
= fsetfilecon (ofd
, con
) != 0;
2056 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2057 if (fail
&& errno
!= ENOTSUP
)
2058 report_file_error ("Doing fsetfilecon", newname
);
2064 if (!NILP (keep_time
))
2066 struct timespec atime
= get_stat_atime (&st
);
2067 struct timespec mtime
= get_stat_mtime (&st
);
2068 if (set_file_times (ofd
, SSDATA (encoded_newname
), atime
, mtime
) != 0)
2069 xsignal2 (Qfile_date_error
,
2070 build_string ("Cannot set file date"), newname
);
2073 if (emacs_close (ofd
) < 0)
2074 report_file_error ("Write error", newname
);
2079 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2080 and if it can't, it tells so. Otherwise, under MSDOS we usually
2081 get only the READ bit, which will make the copied file read-only,
2082 so it's better not to chmod at all. */
2083 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2084 chmod (SDATA (encoded_newname
), st
.st_mode
& 07777);
2086 #endif /* not WINDOWSNT */
2088 /* Discard the unwind protects. */
2089 specpdl_ptr
= specpdl
+ count
;
2094 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2095 Smake_directory_internal
, 1, 1, 0,
2096 doc
: /* Create a new directory named DIRECTORY. */)
2097 (Lisp_Object directory
)
2100 Lisp_Object handler
;
2101 Lisp_Object encoded_dir
;
2103 CHECK_STRING (directory
);
2104 directory
= Fexpand_file_name (directory
, Qnil
);
2106 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2107 if (!NILP (handler
))
2108 return call2 (handler
, Qmake_directory_internal
, directory
);
2110 encoded_dir
= ENCODE_FILE (directory
);
2112 dir
= SSDATA (encoded_dir
);
2114 if (mkdir (dir
, 0777 & ~auto_saving_dir_umask
) != 0)
2115 report_file_error ("Creating directory", directory
);
2120 DEFUN ("delete-directory-internal", Fdelete_directory_internal
,
2121 Sdelete_directory_internal
, 1, 1, 0,
2122 doc
: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2123 (Lisp_Object directory
)
2126 Lisp_Object encoded_dir
;
2128 CHECK_STRING (directory
);
2129 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2130 encoded_dir
= ENCODE_FILE (directory
);
2131 dir
= SSDATA (encoded_dir
);
2133 if (rmdir (dir
) != 0)
2134 report_file_error ("Removing directory", directory
);
2139 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 2,
2140 "(list (read-file-name \
2141 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2142 \"Move file to trash: \" \"Delete file: \") \
2143 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2144 (null current-prefix-arg))",
2145 doc
: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2146 If file has multiple names, it continues to exist with the other names.
2147 TRASH non-nil means to trash the file instead of deleting, provided
2148 `delete-by-moving-to-trash' is non-nil.
2150 When called interactively, TRASH is t if no prefix argument is given.
2151 With a prefix argument, TRASH is nil. */)
2152 (Lisp_Object filename
, Lisp_Object trash
)
2154 Lisp_Object handler
;
2155 Lisp_Object encoded_file
;
2157 if (!NILP (Ffile_directory_p (filename
))
2158 && NILP (Ffile_symlink_p (filename
)))
2159 xsignal2 (Qfile_error
,
2160 build_string ("Removing old name: is a directory"),
2162 filename
= Fexpand_file_name (filename
, Qnil
);
2164 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2165 if (!NILP (handler
))
2166 return call3 (handler
, Qdelete_file
, filename
, trash
);
2168 if (delete_by_moving_to_trash
&& !NILP (trash
))
2169 return call1 (Qmove_file_to_trash
, filename
);
2171 encoded_file
= ENCODE_FILE (filename
);
2173 if (unlink (SSDATA (encoded_file
)) != 0 && errno
!= ENOENT
)
2174 report_file_error ("Removing old name", filename
);
2179 internal_delete_file_1 (Lisp_Object ignore
)
2184 /* Delete file FILENAME, returning true if successful.
2185 This ignores `delete-by-moving-to-trash'. */
2188 internal_delete_file (Lisp_Object filename
)
2192 tem
= internal_condition_case_2 (Fdelete_file
, filename
, Qnil
,
2193 Qt
, internal_delete_file_1
);
2197 /* Filesystems are case-sensitive on all supported systems except
2198 MS-Windows, MS-DOS, Cygwin, and Mac OS X. They are always
2199 case-insensitive on the first two, but they may or may not be
2200 case-insensitive on Cygwin and OS X. The following function
2201 attempts to provide a runtime test on those two systems. If the
2202 test is not conclusive, we assume case-insensitivity on Cygwin and
2203 case-sensitivity on Mac OS X.
2205 FIXME: Mounted filesystems on Posix hosts, like Samba shares or
2206 NFS-mounted Windows volumes, might be case-insensitive. Can we
2210 file_name_case_insensitive_p (const char *filename
)
2212 /* Use pathconf with _PC_CASE_INSENSITIVE or _PC_CASE_SENSITIVE if
2213 those flags are available. As of this writing (2017-05-20),
2214 Cygwin is the only platform known to support the former (starting
2215 with Cygwin-2.6.1), and macOS is the only platform known to
2216 support the latter. */
2218 #ifdef _PC_CASE_INSENSITIVE
2219 int res
= pathconf (filename
, _PC_CASE_INSENSITIVE
);
2222 #elif defined _PC_CASE_SENSITIVE
2223 int res
= pathconf (filename
, _PC_CASE_SENSITIVE
);
2228 #if defined CYGWIN || defined DOS_NT
2235 DEFUN ("file-name-case-insensitive-p", Ffile_name_case_insensitive_p
,
2236 Sfile_name_case_insensitive_p
, 1, 1, 0,
2237 doc
: /* Return t if file FILENAME is on a case-insensitive filesystem.
2238 The arg must be a string. */)
2239 (Lisp_Object filename
)
2241 Lisp_Object handler
;
2243 CHECK_STRING (filename
);
2244 filename
= Fexpand_file_name (filename
, Qnil
);
2246 /* If the file name has special constructs in it,
2247 call the corresponding file handler. */
2248 handler
= Ffind_file_name_handler (filename
, Qfile_name_case_insensitive_p
);
2249 if (!NILP (handler
))
2250 return call2 (handler
, Qfile_name_case_insensitive_p
, filename
);
2252 filename
= ENCODE_FILE (filename
);
2253 return file_name_case_insensitive_p (SSDATA (filename
)) ? Qt
: Qnil
;
2256 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2257 "fRename file: \nGRename %s to file: \np",
2258 doc
: /* Rename FILE as NEWNAME. Both args must be strings.
2259 If file has names other than FILE, it continues to have those names.
2260 Signal a `file-already-exists' error if a file NEWNAME already exists
2261 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2262 An integer third arg means request confirmation if NEWNAME already exists.
2263 This is what happens in interactive use with M-x. */)
2264 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2266 Lisp_Object handler
;
2267 Lisp_Object encoded_file
, encoded_newname
, symlink_target
;
2270 file
= Fexpand_file_name (file
, Qnil
);
2272 /* If the filesystem is case-insensitive and the file names are
2273 identical but for case, treat it as a change-case request, and do
2274 not worry whether NEWNAME exists or whether it is a directory, as
2275 it is already another name for FILE. */
2276 bool case_only_rename
= false;
2277 #if defined CYGWIN || defined DOS_NT
2278 if (!NILP (Ffile_name_case_insensitive_p (file
)))
2280 newname
= Fexpand_file_name (newname
, Qnil
);
2281 case_only_rename
= !NILP (Fstring_equal (Fdowncase (file
),
2282 Fdowncase (newname
)));
2286 if (!case_only_rename
)
2287 newname
= expand_cp_target (Fdirectory_file_name (file
), newname
);
2289 /* If the file name has special constructs in it,
2290 call the corresponding file handler. */
2291 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2293 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2294 if (!NILP (handler
))
2295 return call4 (handler
, Qrename_file
,
2296 file
, newname
, ok_if_already_exists
);
2298 encoded_file
= ENCODE_FILE (file
);
2299 encoded_newname
= ENCODE_FILE (newname
);
2301 bool plain_rename
= (case_only_rename
2302 || (!NILP (ok_if_already_exists
)
2303 && !INTEGERP (ok_if_already_exists
)));
2307 if (renameat_noreplace (AT_FDCWD
, SSDATA (encoded_file
),
2308 AT_FDCWD
, SSDATA (encoded_newname
))
2312 rename_errno
= errno
;
2313 switch (rename_errno
)
2315 case EEXIST
: case EINVAL
: case ENOSYS
:
2316 #if ENOSYS != ENOTSUP
2319 barf_or_query_if_file_exists (newname
, rename_errno
== EEXIST
,
2321 INTEGERP (ok_if_already_exists
),
2323 plain_rename
= true;
2330 if (rename (SSDATA (encoded_file
), SSDATA (encoded_newname
)) == 0)
2332 rename_errno
= errno
;
2333 /* Don't prompt again. */
2334 ok_if_already_exists
= Qt
;
2336 else if (!NILP (ok_if_already_exists
))
2337 ok_if_already_exists
= Qt
;
2339 if (rename_errno
!= EXDEV
)
2340 report_file_errno ("Renaming", list2 (file
, newname
), rename_errno
);
2342 symlink_target
= Ffile_symlink_p (file
);
2343 if (!NILP (symlink_target
))
2344 Fmake_symbolic_link (symlink_target
, newname
, ok_if_already_exists
);
2348 dirp
= directory_like (file
);
2350 call4 (Qcopy_directory
, file
, newname
, Qt
, Qnil
);
2352 Fcopy_file (file
, newname
, ok_if_already_exists
, Qt
, Qt
, Qt
);
2355 ptrdiff_t count
= SPECPDL_INDEX ();
2356 specbind (Qdelete_by_moving_to_trash
, Qnil
);
2357 if (dirp
&& NILP (symlink_target
))
2358 call2 (Qdelete_directory
, file
, Qt
);
2360 Fdelete_file (file
, Qnil
);
2361 return unbind_to (count
, Qnil
);
2364 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2365 "fAdd name to file: \nGName to add to %s: \np",
2366 doc
: /* Give FILE additional name NEWNAME. Both args must be strings.
2367 Signal a `file-already-exists' error if a file NEWNAME already exists
2368 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2369 An integer third arg means request confirmation if NEWNAME already exists.
2370 This is what happens in interactive use with M-x. */)
2371 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2373 Lisp_Object handler
;
2374 Lisp_Object encoded_file
, encoded_newname
;
2376 file
= Fexpand_file_name (file
, Qnil
);
2377 newname
= expand_cp_target (file
, newname
);
2379 /* If the file name has special constructs in it,
2380 call the corresponding file handler. */
2381 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2382 if (!NILP (handler
))
2383 return call4 (handler
, Qadd_name_to_file
, file
,
2384 newname
, ok_if_already_exists
);
2386 /* If the new name has special constructs in it,
2387 call the corresponding file handler. */
2388 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2389 if (!NILP (handler
))
2390 return call4 (handler
, Qadd_name_to_file
, file
,
2391 newname
, ok_if_already_exists
);
2393 encoded_file
= ENCODE_FILE (file
);
2394 encoded_newname
= ENCODE_FILE (newname
);
2396 if (link (SSDATA (encoded_file
), SSDATA (encoded_newname
)) == 0)
2399 if (errno
== EEXIST
)
2401 if (NILP (ok_if_already_exists
)
2402 || INTEGERP (ok_if_already_exists
))
2403 barf_or_query_if_file_exists (newname
, true, "make it a new name",
2404 INTEGERP (ok_if_already_exists
), false);
2405 unlink (SSDATA (newname
));
2406 if (link (SSDATA (encoded_file
), SSDATA (encoded_newname
)) == 0)
2410 report_file_error ("Adding new name", list2 (file
, newname
));
2413 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2414 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2415 doc
: /* Make a symbolic link to TARGET, named LINKNAME.
2416 Both args must be strings.
2417 Signal a `file-already-exists' error if a file LINKNAME already exists
2418 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2419 An integer third arg means request confirmation if LINKNAME already
2420 exists, and expand leading "~" or strip leading "/:" in TARGET.
2421 This happens for interactive use with M-x. */)
2422 (Lisp_Object target
, Lisp_Object linkname
, Lisp_Object ok_if_already_exists
)
2424 Lisp_Object handler
;
2425 Lisp_Object encoded_target
, encoded_linkname
;
2427 CHECK_STRING (target
);
2428 if (INTEGERP (ok_if_already_exists
))
2430 if (SREF (target
, 0) == '~')
2431 target
= Fexpand_file_name (target
, Qnil
);
2432 else if (SREF (target
, 0) == '/' && SREF (target
, 1) == ':')
2433 target
= Fsubstring_no_properties (target
, make_number (2), Qnil
);
2435 linkname
= expand_cp_target (target
, linkname
);
2437 /* If the new link name has special constructs in it,
2438 call the corresponding file handler. */
2439 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2440 if (!NILP (handler
))
2441 return call4 (handler
, Qmake_symbolic_link
, target
,
2442 linkname
, ok_if_already_exists
);
2444 encoded_target
= ENCODE_FILE (target
);
2445 encoded_linkname
= ENCODE_FILE (linkname
);
2447 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
)) == 0)
2450 if (errno
== ENOSYS
)
2451 xsignal1 (Qfile_error
,
2452 build_string ("Symbolic links are not supported"));
2454 if (errno
== EEXIST
)
2456 if (NILP (ok_if_already_exists
)
2457 || INTEGERP (ok_if_already_exists
))
2458 barf_or_query_if_file_exists (linkname
, true, "make it a link",
2459 INTEGERP (ok_if_already_exists
), false);
2460 unlink (SSDATA (encoded_linkname
));
2461 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
)) == 0)
2465 report_file_error ("Making symbolic link", list2 (target
, linkname
));
2469 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2471 doc
: /* Return t if FILENAME is an absolute file name or starts with `~'.
2472 On Unix, absolute file names start with `/'. */)
2473 (Lisp_Object filename
)
2475 CHECK_STRING (filename
);
2476 return file_name_absolute_p (SSDATA (filename
)) ? Qt
: Qnil
;
2479 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2480 doc
: /* Return t if file FILENAME exists (whether or not you can read it.)
2481 See also `file-readable-p' and `file-attributes'.
2482 This returns nil for a symlink to a nonexistent file.
2483 Use `file-symlink-p' to test for such links. */)
2484 (Lisp_Object filename
)
2486 Lisp_Object absname
;
2487 Lisp_Object handler
;
2489 CHECK_STRING (filename
);
2490 absname
= Fexpand_file_name (filename
, Qnil
);
2492 /* If the file name has special constructs in it,
2493 call the corresponding file handler. */
2494 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2495 if (!NILP (handler
))
2497 Lisp_Object result
= call2 (handler
, Qfile_exists_p
, absname
);
2502 absname
= ENCODE_FILE (absname
);
2504 return check_existing (SSDATA (absname
)) ? Qt
: Qnil
;
2507 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2508 doc
: /* Return t if FILENAME can be executed by you.
2509 For a directory, this means you can access files in that directory.
2510 \(It is generally better to use `file-accessible-directory-p' for that
2511 purpose, though.) */)
2512 (Lisp_Object filename
)
2514 Lisp_Object absname
;
2515 Lisp_Object handler
;
2517 CHECK_STRING (filename
);
2518 absname
= Fexpand_file_name (filename
, Qnil
);
2520 /* If the file name has special constructs in it,
2521 call the corresponding file handler. */
2522 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
2523 if (!NILP (handler
))
2524 return call2 (handler
, Qfile_executable_p
, absname
);
2526 absname
= ENCODE_FILE (absname
);
2528 return (check_executable (SSDATA (absname
)) ? Qt
: Qnil
);
2531 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
2532 doc
: /* Return t if file FILENAME exists and you can read it.
2533 See also `file-exists-p' and `file-attributes'. */)
2534 (Lisp_Object filename
)
2536 Lisp_Object absname
;
2537 Lisp_Object handler
;
2539 CHECK_STRING (filename
);
2540 absname
= Fexpand_file_name (filename
, Qnil
);
2542 /* If the file name has special constructs in it,
2543 call the corresponding file handler. */
2544 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
2545 if (!NILP (handler
))
2546 return call2 (handler
, Qfile_readable_p
, absname
);
2548 absname
= ENCODE_FILE (absname
);
2549 return (faccessat (AT_FDCWD
, SSDATA (absname
), R_OK
, AT_EACCESS
) == 0
2553 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
2554 doc
: /* Return t if file FILENAME can be written or created by you. */)
2555 (Lisp_Object filename
)
2557 Lisp_Object absname
, dir
, encoded
;
2558 Lisp_Object handler
;
2560 CHECK_STRING (filename
);
2561 absname
= Fexpand_file_name (filename
, Qnil
);
2563 /* If the file name has special constructs in it,
2564 call the corresponding file handler. */
2565 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
2566 if (!NILP (handler
))
2567 return call2 (handler
, Qfile_writable_p
, absname
);
2569 encoded
= ENCODE_FILE (absname
);
2570 if (check_writable (SSDATA (encoded
), W_OK
))
2572 if (errno
!= ENOENT
)
2575 dir
= Ffile_name_directory (absname
);
2576 eassert (!NILP (dir
));
2578 dir
= Fdirectory_file_name (dir
);
2581 dir
= ENCODE_FILE (dir
);
2583 /* The read-only attribute of the parent directory doesn't affect
2584 whether a file or directory can be created within it. Some day we
2585 should check ACLs though, which do affect this. */
2586 return file_directory_p (SSDATA (dir
)) ? Qt
: Qnil
;
2588 return check_writable (SSDATA (dir
), W_OK
| X_OK
) ? Qt
: Qnil
;
2592 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
2593 doc
: /* Access file FILENAME, and get an error if that does not work.
2594 The second argument STRING is prepended to the error message.
2595 If there is no error, returns nil. */)
2596 (Lisp_Object filename
, Lisp_Object string
)
2598 Lisp_Object handler
, encoded_filename
, absname
;
2600 CHECK_STRING (filename
);
2601 absname
= Fexpand_file_name (filename
, Qnil
);
2603 CHECK_STRING (string
);
2605 /* If the file name has special constructs in it,
2606 call the corresponding file handler. */
2607 handler
= Ffind_file_name_handler (absname
, Qaccess_file
);
2608 if (!NILP (handler
))
2609 return call3 (handler
, Qaccess_file
, absname
, string
);
2611 encoded_filename
= ENCODE_FILE (absname
);
2613 if (faccessat (AT_FDCWD
, SSDATA (encoded_filename
), R_OK
, AT_EACCESS
) != 0)
2614 report_file_error (SSDATA (string
), filename
);
2619 /* Relative to directory FD, return the symbolic link value of FILENAME.
2620 On failure, return nil. */
2622 emacs_readlinkat (int fd
, char const *filename
)
2624 static struct allocator
const emacs_norealloc_allocator
=
2625 { xmalloc
, NULL
, xfree
, memory_full
};
2627 char readlink_buf
[1024];
2628 char *buf
= careadlinkat (fd
, filename
, readlink_buf
, sizeof readlink_buf
,
2629 &emacs_norealloc_allocator
, readlinkat
);
2633 val
= build_unibyte_string (buf
);
2634 if (buf
!= readlink_buf
)
2636 val
= DECODE_FILE (val
);
2640 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
2641 doc
: /* Return non-nil if file FILENAME is the name of a symbolic link.
2642 The value is the link target, as a string.
2643 Otherwise it returns nil.
2645 This function does not check whether the link target exists. */)
2646 (Lisp_Object filename
)
2648 Lisp_Object handler
;
2650 CHECK_STRING (filename
);
2651 filename
= Fexpand_file_name (filename
, Qnil
);
2653 /* If the file name has special constructs in it,
2654 call the corresponding file handler. */
2655 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
2656 if (!NILP (handler
))
2657 return call2 (handler
, Qfile_symlink_p
, filename
);
2659 filename
= ENCODE_FILE (filename
);
2661 return emacs_readlinkat (AT_FDCWD
, SSDATA (filename
));
2664 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
2665 doc
: /* Return t if FILENAME names an existing directory.
2666 Symbolic links to directories count as directories.
2667 See `file-symlink-p' to distinguish symlinks. */)
2668 (Lisp_Object filename
)
2670 Lisp_Object absname
= expand_and_dir_to_file (filename
);
2672 /* If the file name has special constructs in it,
2673 call the corresponding file handler. */
2674 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
2675 if (!NILP (handler
))
2676 return call2 (handler
, Qfile_directory_p
, absname
);
2678 absname
= ENCODE_FILE (absname
);
2680 return file_directory_p (SSDATA (absname
)) ? Qt
: Qnil
;
2683 /* Return true if FILE is a directory or a symlink to a directory. */
2685 file_directory_p (char const *file
)
2688 /* This is cheaper than 'stat'. */
2689 return faccessat (AT_FDCWD
, file
, D_OK
, AT_EACCESS
) == 0;
2692 return stat (file
, &st
) == 0 && S_ISDIR (st
.st_mode
);
2696 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
,
2697 Sfile_accessible_directory_p
, 1, 1, 0,
2698 doc
: /* Return t if FILENAME names a directory you can open.
2699 For the value to be t, FILENAME must specify the name of a directory
2700 as a file, and the directory must allow you to open files in it. In
2701 order to use a directory as a buffer's current directory, this
2702 predicate must return true. A directory name spec may be given
2703 instead; then the value is t if the directory so specified exists and
2704 really is a readable and searchable directory. */)
2705 (Lisp_Object filename
)
2707 Lisp_Object absname
;
2708 Lisp_Object handler
;
2710 CHECK_STRING (filename
);
2711 absname
= Fexpand_file_name (filename
, Qnil
);
2713 /* If the file name has special constructs in it,
2714 call the corresponding file handler. */
2715 handler
= Ffind_file_name_handler (absname
, Qfile_accessible_directory_p
);
2716 if (!NILP (handler
))
2718 Lisp_Object r
= call2 (handler
, Qfile_accessible_directory_p
, absname
);
2720 /* Set errno in case the handler failed. EACCES might be a lie
2721 (e.g., the directory might not exist, or be a regular file),
2722 but at least it does TRT in the "usual" case of an existing
2723 directory that is not accessible by the current user, and
2724 avoids reporting "Success" for a failed operation. Perhaps
2725 someday we can fix this in a better way, by improving
2726 file-accessible-directory-p's API; see Bug#25419. */
2733 absname
= ENCODE_FILE (absname
);
2734 return file_accessible_directory_p (absname
) ? Qt
: Qnil
;
2737 /* If FILE is a searchable directory or a symlink to a
2738 searchable directory, return true. Otherwise return
2739 false and set errno to an error number. */
2741 file_accessible_directory_p (Lisp_Object file
)
2745 /* We need a special-purpose test because (a) NTFS security data is
2746 not reflected in Posix-style mode bits, and (b) the trick with
2747 accessing "DIR/.", used below on Posix hosts, doesn't work on
2748 Windows, because "DIR/." is normalized to just "DIR" before
2749 hitting the disk. */
2750 return (SBYTES (file
) == 0
2751 || w32_accessible_directory_p (SSDATA (file
), SBYTES (file
)));
2753 return file_directory_p (SSDATA (file
));
2756 /* On POSIXish platforms, use just one system call; this avoids a
2757 race and is typically faster. */
2758 const char *data
= SSDATA (file
);
2759 ptrdiff_t len
= SBYTES (file
);
2765 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2766 There are three exceptions: "", "/", and "//". Leave "" alone,
2767 as it's invalid. Append only "." to the other two exceptions as
2768 "/" and "//" are distinct on some platforms, whereas "/", "///",
2769 "////", etc. are all equivalent. */
2774 /* Just check for trailing '/' when deciding whether to append '/'.
2775 That's simpler than testing the two special cases "/" and "//",
2776 and it's a safe optimization here. */
2777 char *buf
= SAFE_ALLOCA (len
+ 3);
2778 memcpy (buf
, data
, len
);
2779 strcpy (buf
+ len
, &"/."[data
[len
- 1] == '/']);
2783 ok
= check_existing (dir
);
2784 saved_errno
= errno
;
2786 errno
= saved_errno
;
2788 #endif /* !DOS_NT */
2791 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
2792 doc
: /* Return t if FILENAME names a regular file.
2793 This is the sort of file that holds an ordinary stream of data bytes.
2794 Symbolic links to regular files count as regular files.
2795 See `file-symlink-p' to distinguish symlinks. */)
2796 (Lisp_Object filename
)
2799 Lisp_Object absname
= expand_and_dir_to_file (filename
);
2801 /* If the file name has special constructs in it,
2802 call the corresponding file handler. */
2803 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
2804 if (!NILP (handler
))
2805 return call2 (handler
, Qfile_regular_p
, absname
);
2807 absname
= ENCODE_FILE (absname
);
2812 Lisp_Object tem
= Vw32_get_true_file_attributes
;
2814 /* Tell stat to use expensive method to get accurate info. */
2815 Vw32_get_true_file_attributes
= Qt
;
2816 result
= stat (SSDATA (absname
), &st
);
2817 Vw32_get_true_file_attributes
= tem
;
2821 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2824 if (stat (SSDATA (absname
), &st
) < 0)
2826 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2830 DEFUN ("file-selinux-context", Ffile_selinux_context
,
2831 Sfile_selinux_context
, 1, 1, 0,
2832 doc
: /* Return SELinux context of file named FILENAME.
2833 The return value is a list (USER ROLE TYPE RANGE), where the list
2834 elements are strings naming the user, role, type, and range of the
2835 file's SELinux security context.
2837 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2838 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2839 (Lisp_Object filename
)
2841 Lisp_Object user
= Qnil
, role
= Qnil
, type
= Qnil
, range
= Qnil
;
2842 Lisp_Object absname
= expand_and_dir_to_file (filename
);
2844 /* If the file name has special constructs in it,
2845 call the corresponding file handler. */
2846 Lisp_Object handler
= Ffind_file_name_handler (absname
,
2847 Qfile_selinux_context
);
2848 if (!NILP (handler
))
2849 return call2 (handler
, Qfile_selinux_context
, absname
);
2851 absname
= ENCODE_FILE (absname
);
2854 if (is_selinux_enabled ())
2856 security_context_t con
;
2857 int conlength
= lgetfilecon (SSDATA (absname
), &con
);
2860 context_t context
= context_new (con
);
2861 if (context_user_get (context
))
2862 user
= build_string (context_user_get (context
));
2863 if (context_role_get (context
))
2864 role
= build_string (context_role_get (context
));
2865 if (context_type_get (context
))
2866 type
= build_string (context_type_get (context
));
2867 if (context_range_get (context
))
2868 range
= build_string (context_range_get (context
));
2869 context_free (context
);
2875 return list4 (user
, role
, type
, range
);
2878 DEFUN ("set-file-selinux-context", Fset_file_selinux_context
,
2879 Sset_file_selinux_context
, 2, 2, 0,
2880 doc
: /* Set SELinux context of file named FILENAME to CONTEXT.
2881 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2882 elements are strings naming the components of a SELinux context.
2884 Value is t if setting of SELinux context was successful, nil otherwise.
2886 This function does nothing and returns nil if SELinux is disabled,
2887 or if Emacs was not compiled with SELinux support. */)
2888 (Lisp_Object filename
, Lisp_Object context
)
2890 Lisp_Object absname
;
2891 Lisp_Object handler
;
2893 Lisp_Object encoded_absname
;
2894 Lisp_Object user
= CAR_SAFE (context
);
2895 Lisp_Object role
= CAR_SAFE (CDR_SAFE (context
));
2896 Lisp_Object type
= CAR_SAFE (CDR_SAFE (CDR_SAFE (context
)));
2897 Lisp_Object range
= CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context
))));
2898 security_context_t con
;
2901 context_t parsed_con
;
2904 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2906 /* If the file name has special constructs in it,
2907 call the corresponding file handler. */
2908 handler
= Ffind_file_name_handler (absname
, Qset_file_selinux_context
);
2909 if (!NILP (handler
))
2910 return call3 (handler
, Qset_file_selinux_context
, absname
, context
);
2913 if (is_selinux_enabled ())
2915 /* Get current file context. */
2916 encoded_absname
= ENCODE_FILE (absname
);
2917 conlength
= lgetfilecon (SSDATA (encoded_absname
), &con
);
2920 parsed_con
= context_new (con
);
2921 /* Change the parts defined in the parameter.*/
2924 if (context_user_set (parsed_con
, SSDATA (user
)))
2925 error ("Doing context_user_set");
2929 if (context_role_set (parsed_con
, SSDATA (role
)))
2930 error ("Doing context_role_set");
2934 if (context_type_set (parsed_con
, SSDATA (type
)))
2935 error ("Doing context_type_set");
2937 if (STRINGP (range
))
2939 if (context_range_set (parsed_con
, SSDATA (range
)))
2940 error ("Doing context_range_set");
2943 /* Set the modified context back to the file. */
2944 fail
= (lsetfilecon (SSDATA (encoded_absname
),
2945 context_str (parsed_con
))
2947 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2948 if (fail
&& errno
!= ENOTSUP
)
2949 report_file_error ("Doing lsetfilecon", absname
);
2951 context_free (parsed_con
);
2953 return fail
? Qnil
: Qt
;
2956 report_file_error ("Doing lgetfilecon", absname
);
2963 DEFUN ("file-acl", Ffile_acl
, Sfile_acl
, 1, 1, 0,
2964 doc
: /* Return ACL entries of file named FILENAME.
2965 The entries are returned in a format suitable for use in `set-file-acl'
2966 but is otherwise undocumented and subject to change.
2967 Return nil if file does not exist or is not accessible, or if Emacs
2968 was unable to determine the ACL entries. */)
2969 (Lisp_Object filename
)
2971 Lisp_Object acl_string
= Qnil
;
2974 Lisp_Object absname
= expand_and_dir_to_file (filename
);
2976 /* If the file name has special constructs in it,
2977 call the corresponding file handler. */
2978 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_acl
);
2979 if (!NILP (handler
))
2980 return call2 (handler
, Qfile_acl
, absname
);
2982 # ifdef HAVE_ACL_SET_FILE
2983 absname
= ENCODE_FILE (absname
);
2985 # ifndef HAVE_ACL_TYPE_EXTENDED
2986 acl_type_t ACL_TYPE_EXTENDED
= ACL_TYPE_ACCESS
;
2988 acl_t acl
= acl_get_file (SSDATA (absname
), ACL_TYPE_EXTENDED
);
2992 char *str
= acl_to_text (acl
, NULL
);
2999 acl_string
= build_string (str
);
3008 DEFUN ("set-file-acl", Fset_file_acl
, Sset_file_acl
,
3010 doc
: /* Set ACL of file named FILENAME to ACL-STRING.
3011 ACL-STRING should contain the textual representation of the ACL
3012 entries in a format suitable for the platform.
3014 Value is t if setting of ACL was successful, nil otherwise.
3016 Setting ACL for local files requires Emacs to be built with ACL
3018 (Lisp_Object filename
, Lisp_Object acl_string
)
3021 Lisp_Object absname
;
3022 Lisp_Object handler
;
3023 # ifdef HAVE_ACL_SET_FILE
3024 Lisp_Object encoded_absname
;
3029 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3031 /* If the file name has special constructs in it,
3032 call the corresponding file handler. */
3033 handler
= Ffind_file_name_handler (absname
, Qset_file_acl
);
3034 if (!NILP (handler
))
3035 return call3 (handler
, Qset_file_acl
, absname
, acl_string
);
3037 # ifdef HAVE_ACL_SET_FILE
3038 if (STRINGP (acl_string
))
3040 acl
= acl_from_text (SSDATA (acl_string
));
3043 report_file_error ("Converting ACL", absname
);
3047 encoded_absname
= ENCODE_FILE (absname
);
3049 fail
= (acl_set_file (SSDATA (encoded_absname
), ACL_TYPE_ACCESS
,
3052 if (fail
&& acl_errno_valid (errno
))
3053 report_file_error ("Setting ACL", absname
);
3056 return fail
? Qnil
: Qt
;
3064 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
3065 doc
: /* Return mode bits of file named FILENAME, as an integer.
3066 Return nil, if file does not exist or is not accessible. */)
3067 (Lisp_Object filename
)
3070 Lisp_Object absname
= expand_and_dir_to_file (filename
);
3072 /* If the file name has special constructs in it,
3073 call the corresponding file handler. */
3074 Lisp_Object handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
3075 if (!NILP (handler
))
3076 return call2 (handler
, Qfile_modes
, absname
);
3078 absname
= ENCODE_FILE (absname
);
3080 if (stat (SSDATA (absname
), &st
) < 0)
3083 return make_number (st
.st_mode
& 07777);
3086 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2,
3087 "(let ((file (read-file-name \"File: \"))) \
3088 (list file (read-file-modes nil file)))",
3089 doc
: /* Set mode bits of file named FILENAME to MODE (an integer).
3090 Only the 12 low bits of MODE are used.
3092 Interactively, mode bits are read by `read-file-modes', which accepts
3093 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3094 (Lisp_Object filename
, Lisp_Object mode
)
3096 Lisp_Object absname
, encoded_absname
;
3097 Lisp_Object handler
;
3099 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3100 CHECK_NUMBER (mode
);
3102 /* If the file name has special constructs in it,
3103 call the corresponding file handler. */
3104 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
3105 if (!NILP (handler
))
3106 return call3 (handler
, Qset_file_modes
, absname
, mode
);
3108 encoded_absname
= ENCODE_FILE (absname
);
3110 if (chmod (SSDATA (encoded_absname
), XINT (mode
) & 07777) < 0)
3111 report_file_error ("Doing chmod", absname
);
3116 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
3117 doc
: /* Set the file permission bits for newly created files.
3118 The argument MODE should be an integer; only the low 9 bits are used.
3119 This setting is inherited by subprocesses. */)
3122 mode_t oldrealmask
, oldumask
, newumask
;
3123 CHECK_NUMBER (mode
);
3124 oldrealmask
= realmask
;
3125 newumask
= ~ XINT (mode
) & 0777;
3128 realmask
= newumask
;
3129 oldumask
= umask (newumask
);
3132 eassert (oldumask
== oldrealmask
);
3136 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
3137 doc
: /* Return the default file protection for created files.
3138 The value is an integer. */)
3142 XSETINT (value
, (~ realmask
) & 0777);
3147 DEFUN ("set-file-times", Fset_file_times
, Sset_file_times
, 1, 2, 0,
3148 doc
: /* Set times of file FILENAME to TIMESTAMP.
3149 Set both access and modification times.
3150 Return t on success, else nil.
3151 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3153 (Lisp_Object filename
, Lisp_Object timestamp
)
3155 Lisp_Object absname
, encoded_absname
;
3156 Lisp_Object handler
;
3157 struct timespec t
= lisp_time_argument (timestamp
);
3159 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3161 /* If the file name has special constructs in it,
3162 call the corresponding file handler. */
3163 handler
= Ffind_file_name_handler (absname
, Qset_file_times
);
3164 if (!NILP (handler
))
3165 return call3 (handler
, Qset_file_times
, absname
, timestamp
);
3167 encoded_absname
= ENCODE_FILE (absname
);
3170 if (set_file_times (-1, SSDATA (encoded_absname
), t
, t
) != 0)
3173 /* Setting times on a directory always fails. */
3174 if (file_directory_p (SSDATA (encoded_absname
)))
3177 report_file_error ("Setting file times", absname
);
3185 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3186 doc
: /* Tell Unix to finish all pending disk updates. */)
3193 #endif /* HAVE_SYNC */
3195 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3196 doc
: /* Return t if file FILE1 is newer than file FILE2.
3197 If FILE1 does not exist, the answer is nil;
3198 otherwise, if FILE2 does not exist, the answer is t. */)
3199 (Lisp_Object file1
, Lisp_Object file2
)
3201 struct stat st1
, st2
;
3203 CHECK_STRING (file1
);
3204 CHECK_STRING (file2
);
3206 Lisp_Object absname1
= expand_and_dir_to_file (file1
);
3207 Lisp_Object absname2
= expand_and_dir_to_file (file2
);
3209 /* If the file name has special constructs in it,
3210 call the corresponding file handler. */
3211 Lisp_Object handler
= Ffind_file_name_handler (absname1
,
3212 Qfile_newer_than_file_p
);
3214 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3215 if (!NILP (handler
))
3216 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3218 absname1
= ENCODE_FILE (absname1
);
3219 absname2
= ENCODE_FILE (absname2
);
3221 if (stat (SSDATA (absname1
), &st1
) < 0)
3224 if (stat (SSDATA (absname2
), &st2
) < 0)
3227 return (timespec_cmp (get_stat_mtime (&st2
), get_stat_mtime (&st1
)) < 0
3231 enum { READ_BUF_SIZE
= MAX_ALLOCA
};
3233 /* This function is called after Lisp functions to decide a coding
3234 system are called, or when they cause an error. Before they are
3235 called, the current buffer is set unibyte and it contains only a
3236 newly inserted text (thus the buffer was empty before the
3239 The functions may set markers, overlays, text properties, or even
3240 alter the buffer contents, change the current buffer.
3242 Here, we reset all those changes by:
3243 o set back the current buffer.
3244 o move all markers and overlays to BEG.
3245 o remove all text properties.
3246 o set back the buffer multibyteness. */
3249 decide_coding_unwind (Lisp_Object unwind_data
)
3251 Lisp_Object multibyte
, undo_list
, buffer
;
3253 multibyte
= XCAR (unwind_data
);
3254 unwind_data
= XCDR (unwind_data
);
3255 undo_list
= XCAR (unwind_data
);
3256 buffer
= XCDR (unwind_data
);
3258 set_buffer_internal (XBUFFER (buffer
));
3259 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3260 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3261 set_buffer_intervals (current_buffer
, NULL
);
3262 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3264 /* Now we are safe to change the buffer's multibyteness directly. */
3265 bset_enable_multibyte_characters (current_buffer
, multibyte
);
3266 bset_undo_list (current_buffer
, undo_list
);
3269 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3270 object where slot 0 is the file descriptor, slot 1 specifies
3271 an offset to put the read bytes, and slot 2 is the maximum
3272 amount of bytes to read. Value is the number of bytes read. */
3275 read_non_regular (Lisp_Object state
)
3277 int nbytes
= emacs_read_quit (XSAVE_INTEGER (state
, 0),
3278 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
3279 + XSAVE_INTEGER (state
, 1)),
3280 XSAVE_INTEGER (state
, 2));
3281 /* Fast recycle this object for the likely next call. */
3283 return make_number (nbytes
);
3287 /* Condition-case handler used when reading from non-regular files
3288 in insert-file-contents. */
3291 read_non_regular_quit (Lisp_Object ignore
)
3296 /* Return the file offset that VAL represents, checking for type
3297 errors and overflow. */
3299 file_offset (Lisp_Object val
)
3301 if (RANGED_INTEGERP (0, val
, TYPE_MAXIMUM (off_t
)))
3306 double v
= XFLOAT_DATA (val
);
3307 if (0 <= v
&& v
< 1.0 + TYPE_MAXIMUM (off_t
))
3315 wrong_type_argument (intern ("file-offset"), val
);
3318 /* Return a special time value indicating the error number ERRNUM. */
3319 static struct timespec
3320 time_error_value (int errnum
)
3322 int ns
= (errnum
== ENOENT
|| errnum
== EACCES
|| errnum
== ENOTDIR
3323 ? NONEXISTENT_MODTIME_NSECS
3324 : UNKNOWN_MODTIME_NSECS
);
3325 return make_timespec (0, ns
);
3329 get_window_points_and_markers (void)
3331 Lisp_Object pt_marker
= Fpoint_marker ();
3333 = call3 (Qget_buffer_window_list
, Fcurrent_buffer (), Qnil
, Qt
);
3334 Lisp_Object window_markers
= windows
;
3335 /* Window markers (and point) are handled specially: rather than move to
3336 just before or just after the modified text, we try to keep the
3337 markers at the same distance (bug#19161).
3338 In general, this is wrong, but for window-markers, this should be harmless
3339 and is convenient for the end user when most of the file is unmodified,
3340 except for a few minor details near the beginning and near the end. */
3341 for (; CONSP (windows
); windows
= XCDR (windows
))
3342 if (WINDOWP (XCAR (windows
)))
3344 Lisp_Object window_marker
= XWINDOW (XCAR (windows
))->pointm
;
3346 Fcons (window_marker
, Fmarker_position (window_marker
)));
3348 return Fcons (Fcons (pt_marker
, Fpoint ()), window_markers
);
3352 restore_window_points (Lisp_Object window_markers
, ptrdiff_t inserted
,
3353 ptrdiff_t same_at_start
, ptrdiff_t same_at_end
)
3355 for (; CONSP (window_markers
); window_markers
= XCDR (window_markers
))
3356 if (CONSP (XCAR (window_markers
)))
3358 Lisp_Object car
= XCAR (window_markers
);
3359 Lisp_Object marker
= XCAR (car
);
3360 Lisp_Object oldpos
= XCDR (car
);
3361 if (MARKERP (marker
) && INTEGERP (oldpos
)
3362 && XINT (oldpos
) > same_at_start
3363 && XINT (oldpos
) < same_at_end
)
3365 ptrdiff_t oldsize
= same_at_end
- same_at_start
;
3366 ptrdiff_t newsize
= inserted
;
3367 double growth
= newsize
/ (double)oldsize
;
3369 = same_at_start
+ growth
* (XINT (oldpos
) - same_at_start
);
3370 Fset_marker (marker
, make_number (newpos
), Qnil
);
3375 /* Make sure the gap is at Z_BYTE. This is required to treat buffer
3376 text as a linear C char array. */
3378 maybe_move_gap (struct buffer
*b
)
3380 if (BUF_GPT_BYTE (b
) != BUF_Z_BYTE (b
))
3382 struct buffer
*cb
= current_buffer
;
3384 set_buffer_internal (b
);
3385 move_gap_both (Z
, Z_BYTE
);
3386 set_buffer_internal (cb
);
3390 /* FIXME: insert-file-contents should be split with the top-level moved to
3391 Elisp and only the core kept in C. */
3393 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3395 doc
: /* Insert contents of file FILENAME after point.
3396 Returns list of absolute file name and number of characters inserted.
3397 If second argument VISIT is non-nil, the buffer's visited filename and
3398 last save file modtime are set, and it is marked unmodified. If
3399 visiting and the file does not exist, visiting is completed before the
3402 The optional third and fourth arguments BEG and END specify what portion
3403 of the file to insert. These arguments count bytes in the file, not
3404 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3406 If optional fifth argument REPLACE is non-nil, replace the current
3407 buffer contents (in the accessible portion) with the file contents.
3408 This is better than simply deleting and inserting the whole thing
3409 because (1) it preserves some marker positions and (2) it puts less data
3410 in the undo list. When REPLACE is non-nil, the second return value is
3411 the number of characters that replace previous buffer contents.
3413 This function does code conversion according to the value of
3414 `coding-system-for-read' or `file-coding-system-alist', and sets the
3415 variable `last-coding-system-used' to the coding system actually used.
3417 In addition, this function decodes the inserted text from known formats
3418 by calling `format-decode', which see. */)
3419 (Lisp_Object filename
, Lisp_Object visit
, Lisp_Object beg
, Lisp_Object end
, Lisp_Object replace
)
3422 struct timespec mtime
;
3424 ptrdiff_t inserted
= 0;
3426 off_t beg_offset
, end_offset
;
3428 ptrdiff_t count
= SPECPDL_INDEX ();
3429 Lisp_Object handler
, val
, insval
, orig_filename
, old_undo
;
3431 ptrdiff_t total
= 0;
3432 bool not_regular
= 0;
3434 char read_buf
[READ_BUF_SIZE
];
3435 struct coding_system coding
;
3436 bool replace_handled
= false;
3437 bool set_coding_system
= false;
3438 Lisp_Object coding_system
;
3439 bool read_quit
= false;
3440 /* If the undo log only contains the insertion, there's no point
3441 keeping it. It's typically when we first fill a file-buffer. */
3442 bool empty_undo_list_p
3443 = (!NILP (visit
) && NILP (BVAR (current_buffer
, undo_list
))
3445 Lisp_Object old_Vdeactivate_mark
= Vdeactivate_mark
;
3446 bool we_locked_file
= false;
3448 Lisp_Object window_markers
= Qnil
;
3449 /* same_at_start and same_at_end count bytes, because file access counts
3450 bytes and BEG and END count bytes. */
3451 ptrdiff_t same_at_start
= BEGV_BYTE
;
3452 ptrdiff_t same_at_end
= ZV_BYTE
;
3453 /* SAME_AT_END_CHARPOS counts characters, because
3454 restore_window_points needs the old character count. */
3455 ptrdiff_t same_at_end_charpos
= ZV
;
3457 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3458 error ("Cannot do file visiting in an indirect buffer");
3460 if (!NILP (BVAR (current_buffer
, read_only
)))
3461 Fbarf_if_buffer_read_only (Qnil
);
3465 orig_filename
= Qnil
;
3468 CHECK_STRING (filename
);
3469 filename
= Fexpand_file_name (filename
, Qnil
);
3471 /* The value Qnil means that the coding system is not yet
3473 coding_system
= Qnil
;
3475 /* If the file name has special constructs in it,
3476 call the corresponding file handler. */
3477 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3478 if (!NILP (handler
))
3480 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3481 visit
, beg
, end
, replace
);
3482 if (CONSP (val
) && CONSP (XCDR (val
))
3483 && RANGED_INTEGERP (0, XCAR (XCDR (val
)), ZV
- PT
))
3484 inserted
= XINT (XCAR (XCDR (val
)));
3488 orig_filename
= filename
;
3489 filename
= ENCODE_FILE (filename
);
3491 fd
= emacs_open (SSDATA (filename
), O_RDONLY
, 0);
3496 report_file_error ("Opening input file", orig_filename
);
3497 mtime
= time_error_value (save_errno
);
3499 if (!NILP (Vcoding_system_for_read
))
3501 /* Don't let invalid values into buffer-file-coding-system. */
3502 CHECK_CODING_SYSTEM (Vcoding_system_for_read
);
3503 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3508 fd_index
= SPECPDL_INDEX ();
3509 record_unwind_protect_int (close_file_unwind
, fd
);
3511 /* Replacement should preserve point as it preserves markers. */
3512 if (!NILP (replace
))
3514 window_markers
= get_window_points_and_markers ();
3515 record_unwind_protect (restore_point_unwind
,
3516 XCAR (XCAR (window_markers
)));
3519 if (fstat (fd
, &st
) != 0)
3520 report_file_error ("Input file status", orig_filename
);
3521 mtime
= get_stat_mtime (&st
);
3523 /* This code will need to be changed in order to work on named
3524 pipes, and it's probably just not worth it. So we should at
3525 least signal an error. */
3526 if (!S_ISREG (st
.st_mode
))
3533 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3534 xsignal2 (Qfile_error
,
3535 build_string ("not a regular file"), orig_filename
);
3540 if (!NILP (beg
) || !NILP (end
))
3541 error ("Attempt to visit less than an entire file");
3542 if (BEG
< Z
&& NILP (replace
))
3543 error ("Cannot do file visiting in a non-empty buffer");
3547 beg_offset
= file_offset (beg
);
3552 end_offset
= file_offset (end
);
3556 end_offset
= TYPE_MAXIMUM (off_t
);
3559 end_offset
= st
.st_size
;
3561 /* A negative size can happen on a platform that allows file
3562 sizes greater than the maximum off_t value. */
3566 /* The file size returned from stat may be zero, but data
3567 may be readable nonetheless, for example when this is a
3568 file in the /proc filesystem. */
3569 if (end_offset
== 0)
3570 end_offset
= READ_BUF_SIZE
;
3574 /* Check now whether the buffer will become too large,
3575 in the likely case where the file's length is not changing.
3576 This saves a lot of needless work before a buffer overflow. */
3579 /* The likely offset where we will stop reading. We could read
3580 more (or less), if the file grows (or shrinks) as we read it. */
3581 off_t likely_end
= min (end_offset
, st
.st_size
);
3583 if (beg_offset
< likely_end
)
3586 = Z_BYTE
- (!NILP (replace
) ? ZV_BYTE
- BEGV_BYTE
: 0);
3587 ptrdiff_t buf_growth_max
= BUF_BYTES_MAX
- buf_bytes
;
3588 off_t likely_growth
= likely_end
- beg_offset
;
3589 if (buf_growth_max
< likely_growth
)
3594 /* Prevent redisplay optimizations. */
3595 current_buffer
->clip_changed
= true;
3597 if (EQ (Vcoding_system_for_read
, Qauto_save_coding
))
3599 coding_system
= coding_inherit_eol_type (Qutf_8_emacs
, Qunix
);
3600 setup_coding_system (coding_system
, &coding
);
3601 /* Ensure we set Vlast_coding_system_used. */
3602 set_coding_system
= true;
3606 /* Decide the coding system to use for reading the file now
3607 because we can't use an optimized method for handling
3608 `coding:' tag if the current buffer is not empty. */
3609 if (!NILP (Vcoding_system_for_read
))
3610 coding_system
= Vcoding_system_for_read
;
3613 /* Don't try looking inside a file for a coding system
3614 specification if it is not seekable. */
3615 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3617 /* Find a coding system specified in the heading two
3618 lines or in the tailing several lines of the file.
3619 We assume that the 1K-byte and 3K-byte for heading
3620 and tailing respectively are sufficient for this
3624 if (st
.st_size
<= (1024 * 4))
3625 nread
= emacs_read_quit (fd
, read_buf
, 1024 * 4);
3628 nread
= emacs_read_quit (fd
, read_buf
, 1024);
3632 if (lseek (fd
, - (1024 * 3), SEEK_END
) < 0)
3633 report_file_error ("Setting file position",
3635 ntail
= emacs_read_quit (fd
, read_buf
+ nread
, 1024 * 3);
3636 nread
= ntail
< 0 ? ntail
: nread
+ ntail
;
3641 report_file_error ("Read error", orig_filename
);
3644 AUTO_STRING (name
, " *code-converting-work*");
3645 struct buffer
*prev
= current_buffer
;
3646 Lisp_Object workbuf
;
3649 record_unwind_current_buffer ();
3651 workbuf
= Fget_buffer_create (name
);
3652 buf
= XBUFFER (workbuf
);
3654 delete_all_overlays (buf
);
3655 bset_directory (buf
, BVAR (current_buffer
, directory
));
3656 bset_read_only (buf
, Qnil
);
3657 bset_filename (buf
, Qnil
);
3658 bset_undo_list (buf
, Qt
);
3659 eassert (buf
->overlays_before
== NULL
);
3660 eassert (buf
->overlays_after
== NULL
);
3662 set_buffer_internal (buf
);
3664 bset_enable_multibyte_characters (buf
, Qnil
);
3666 insert_1_both ((char *) read_buf
, nread
, nread
, 0, 0, 0);
3667 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3668 coding_system
= call2 (Vset_auto_coding_function
,
3669 filename
, make_number (nread
));
3670 set_buffer_internal (prev
);
3672 /* Discard the unwind protect for recovering the
3676 /* Rewind the file for the actual read done later. */
3677 if (lseek (fd
, 0, SEEK_SET
) < 0)
3678 report_file_error ("Setting file position", orig_filename
);
3682 if (NILP (coding_system
))
3684 /* If we have not yet decided a coding system, check
3685 file-coding-system-alist. */
3686 coding_system
= CALLN (Ffind_operation_coding_system
,
3687 Qinsert_file_contents
, orig_filename
,
3688 visit
, beg
, end
, replace
);
3689 if (CONSP (coding_system
))
3690 coding_system
= XCAR (coding_system
);
3694 if (NILP (coding_system
))
3695 coding_system
= Qundecided
;
3697 CHECK_CODING_SYSTEM (coding_system
);
3699 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3700 /* We must suppress all character code conversion except for
3701 end-of-line conversion. */
3702 coding_system
= raw_text_coding_system (coding_system
);
3704 setup_coding_system (coding_system
, &coding
);
3705 /* Ensure we set Vlast_coding_system_used. */
3706 set_coding_system
= true;
3709 /* If requested, replace the accessible part of the buffer
3710 with the file contents. Avoid replacing text at the
3711 beginning or end of the buffer that matches the file contents;
3712 that preserves markers pointing to the unchanged parts.
3714 Here we implement this feature in an optimized way
3715 for the case where code conversion is NOT needed.
3716 The following if-statement handles the case of conversion
3717 in a less optimal way.
3719 If the code conversion is "automatic" then we try using this
3720 method and hope for the best.
3721 But if we discover the need for conversion, we give up on this method
3722 and let the following if-statement handle the replace job. */
3725 && (NILP (coding_system
)
3726 || ! CODING_REQUIRE_DECODING (&coding
)))
3729 /* There is still a possibility we will find the need to do code
3730 conversion. If that happens, set this variable to
3731 give up on handling REPLACE in the optimized way. */
3732 bool giveup_match_end
= false;
3734 if (beg_offset
!= 0)
3736 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3737 report_file_error ("Setting file position", orig_filename
);
3740 /* Count how many chars at the start of the file
3741 match the text at the beginning of the buffer. */
3744 int nread
= emacs_read_quit (fd
, read_buf
, sizeof read_buf
);
3746 report_file_error ("Read error", orig_filename
);
3747 else if (nread
== 0)
3750 if (CODING_REQUIRE_DETECTION (&coding
))
3752 coding_system
= detect_coding_system ((unsigned char *) read_buf
,
3755 setup_coding_system (coding_system
, &coding
);
3758 if (CODING_REQUIRE_DECODING (&coding
))
3759 /* We found that the file should be decoded somehow.
3760 Let's give up here. */
3762 giveup_match_end
= true;
3767 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3768 && FETCH_BYTE (same_at_start
) == read_buf
[bufpos
])
3769 same_at_start
++, bufpos
++;
3770 /* If we found a discrepancy, stop the scan.
3771 Otherwise loop around and scan the next bufferful. */
3772 if (bufpos
!= nread
)
3775 /* If the file matches the buffer completely,
3776 there's no need to replace anything. */
3777 if (same_at_start
- BEGV_BYTE
== end_offset
- beg_offset
)
3780 clear_unwind_protect (fd_index
);
3782 /* Truncate the buffer to the size of the file. */
3783 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3787 /* Count how many chars at the end of the file
3788 match the text at the end of the buffer. But, if we have
3789 already found that decoding is necessary, don't waste time. */
3790 while (!giveup_match_end
)
3792 int total_read
, nread
, bufpos
, trial
;
3795 /* At what file position are we now scanning? */
3796 curpos
= end_offset
- (ZV_BYTE
- same_at_end
);
3797 /* If the entire file matches the buffer tail, stop the scan. */
3800 /* How much can we scan in the next step? */
3801 trial
= min (curpos
, sizeof read_buf
);
3802 if (lseek (fd
, curpos
- trial
, SEEK_SET
) < 0)
3803 report_file_error ("Setting file position", orig_filename
);
3805 total_read
= nread
= 0;
3806 while (total_read
< trial
)
3808 nread
= emacs_read_quit (fd
, read_buf
+ total_read
,
3809 trial
- total_read
);
3811 report_file_error ("Read error", orig_filename
);
3812 else if (nread
== 0)
3814 total_read
+= nread
;
3817 /* Scan this bufferful from the end, comparing with
3818 the Emacs buffer. */
3819 bufpos
= total_read
;
3821 /* Compare with same_at_start to avoid counting some buffer text
3822 as matching both at the file's beginning and at the end. */
3823 while (bufpos
> 0 && same_at_end
> same_at_start
3824 && FETCH_BYTE (same_at_end
- 1) == read_buf
[bufpos
- 1])
3825 same_at_end
--, bufpos
--;
3827 /* If we found a discrepancy, stop the scan.
3828 Otherwise loop around and scan the preceding bufferful. */
3831 /* If this discrepancy is because of code conversion,
3832 we cannot use this method; giveup and try the other. */
3833 if (same_at_end
> same_at_start
3834 && FETCH_BYTE (same_at_end
- 1) >= 0200
3835 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
))
3836 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3837 giveup_match_end
= true;
3845 if (! giveup_match_end
)
3848 ptrdiff_t this_count
= SPECPDL_INDEX ();
3850 /* We win! We can handle REPLACE the optimized way. */
3852 /* Extend the start of non-matching text area to multibyte
3853 character boundary. */
3854 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3855 while (same_at_start
> BEGV_BYTE
3856 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3859 /* Extend the end of non-matching text area to multibyte
3860 character boundary. */
3861 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3862 while (same_at_end
< ZV_BYTE
3863 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3866 /* Don't try to reuse the same piece of text twice. */
3867 overlap
= (same_at_start
- BEGV_BYTE
3869 + (! NILP (end
) ? end_offset
: st
.st_size
) - ZV_BYTE
));
3871 same_at_end
+= overlap
;
3872 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
3874 /* Arrange to read only the nonmatching middle part of the file. */
3875 beg_offset
+= same_at_start
- BEGV_BYTE
;
3876 end_offset
-= ZV_BYTE
- same_at_end
;
3878 /* This binding is to avoid ask-user-about-supersession-threat
3879 being called in insert_from_buffer or del_range_bytes (via
3880 prepare_to_modify_buffer).
3881 AFAICT we could avoid ask-user-about-supersession-threat by setting
3882 current_buffer->modtime earlier, but we could still end up calling
3883 ask-user-about-supersession-threat if the file is modified while
3884 we read it, so we bind buffer-file-name instead. */
3885 specbind (intern ("buffer-file-name"), Qnil
);
3886 del_range_byte (same_at_start
, same_at_end
);
3887 /* Insert from the file at the proper position. */
3888 temp
= BYTE_TO_CHAR (same_at_start
);
3889 SET_PT_BOTH (temp
, same_at_start
);
3890 unbind_to (this_count
, Qnil
);
3892 /* If display currently starts at beginning of line,
3893 keep it that way. */
3894 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
3895 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
3897 replace_handled
= true;
3901 /* If requested, replace the accessible part of the buffer
3902 with the file contents. Avoid replacing text at the
3903 beginning or end of the buffer that matches the file contents;
3904 that preserves markers pointing to the unchanged parts.
3906 Here we implement this feature for the case where code conversion
3907 is needed, in a simple way that needs a lot of memory.
3908 The preceding if-statement handles the case of no conversion
3909 in a more optimized way. */
3910 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
3912 ptrdiff_t same_at_start_charpos
;
3913 ptrdiff_t inserted_chars
;
3916 unsigned char *decoded
;
3919 ptrdiff_t this_count
= SPECPDL_INDEX ();
3921 = ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3922 Lisp_Object conversion_buffer
;
3924 conversion_buffer
= code_conversion_save (1, multibyte
);
3926 /* First read the whole file, performing code conversion into
3927 CONVERSION_BUFFER. */
3929 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3930 report_file_error ("Setting file position", orig_filename
);
3932 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
3933 unprocessed
= 0; /* Bytes not processed in previous loop. */
3937 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3938 quitting while reading a huge file. */
3940 this = emacs_read_quit (fd
, read_buf
+ unprocessed
,
3941 READ_BUF_SIZE
- unprocessed
);
3945 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer
),
3946 BUF_Z (XBUFFER (conversion_buffer
)));
3947 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3948 unprocessed
+ this, conversion_buffer
);
3949 unprocessed
= coding
.carryover_bytes
;
3950 if (coding
.carryover_bytes
> 0)
3951 memcpy (read_buf
, coding
.carryover
, unprocessed
);
3955 report_file_error ("Read error", orig_filename
);
3957 clear_unwind_protect (fd_index
);
3959 if (unprocessed
> 0)
3961 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
3962 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3963 unprocessed
, conversion_buffer
);
3964 coding
.mode
&= ~CODING_MODE_LAST_BLOCK
;
3967 coding_system
= CODING_ID_NAME (coding
.id
);
3968 set_coding_system
= true;
3969 maybe_move_gap (XBUFFER (conversion_buffer
));
3970 decoded
= BUF_BEG_ADDR (XBUFFER (conversion_buffer
));
3971 inserted
= (BUF_Z_BYTE (XBUFFER (conversion_buffer
))
3972 - BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
3974 /* Compare the beginning of the converted string with the buffer
3978 while (bufpos
< inserted
&& same_at_start
< same_at_end
3979 && FETCH_BYTE (same_at_start
) == decoded
[bufpos
])
3980 same_at_start
++, bufpos
++;
3982 /* If the file matches the head of buffer completely,
3983 there's no need to replace anything. */
3985 if (bufpos
== inserted
)
3987 /* Truncate the buffer to the size of the file. */
3988 if (same_at_start
!= same_at_end
)
3990 /* See previous specbind for the reason behind this. */
3991 specbind (intern ("buffer-file-name"), Qnil
);
3992 del_range_byte (same_at_start
, same_at_end
);
3996 unbind_to (this_count
, Qnil
);
4000 /* Extend the start of non-matching text area to the previous
4001 multibyte character boundary. */
4002 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4003 while (same_at_start
> BEGV_BYTE
4004 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
4007 /* Scan this bufferful from the end, comparing with
4008 the Emacs buffer. */
4011 /* Compare with same_at_start to avoid counting some buffer text
4012 as matching both at the file's beginning and at the end. */
4013 while (bufpos
> 0 && same_at_end
> same_at_start
4014 && FETCH_BYTE (same_at_end
- 1) == decoded
[bufpos
- 1])
4015 same_at_end
--, bufpos
--;
4017 /* Extend the end of non-matching text area to the next
4018 multibyte character boundary. */
4019 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4020 while (same_at_end
< ZV_BYTE
4021 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
4024 /* Don't try to reuse the same piece of text twice. */
4025 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
4027 same_at_end
+= overlap
;
4028 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
4030 /* If display currently starts at beginning of line,
4031 keep it that way. */
4032 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
4033 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
4035 /* Replace the chars that we need to replace,
4036 and update INSERTED to equal the number of bytes
4037 we are taking from the decoded string. */
4038 inserted
-= (ZV_BYTE
- same_at_end
) + (same_at_start
- BEGV_BYTE
);
4040 /* See previous specbind for the reason behind this. */
4041 specbind (intern ("buffer-file-name"), Qnil
);
4042 if (same_at_end
!= same_at_start
)
4044 del_range_byte (same_at_start
, same_at_end
);
4046 eassert (same_at_start
== GPT_BYTE
);
4047 same_at_start
= GPT_BYTE
;
4051 temp
= same_at_end_charpos
;
4053 /* Insert from the file at the proper position. */
4054 SET_PT_BOTH (temp
, same_at_start
);
4055 same_at_start_charpos
4056 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4057 same_at_start
- BEGV_BYTE
4058 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4059 eassert (same_at_start_charpos
== temp
- (BEGV
- BEG
));
4061 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4062 same_at_start
+ inserted
- BEGV_BYTE
4063 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)))
4064 - same_at_start_charpos
);
4065 insert_from_buffer (XBUFFER (conversion_buffer
),
4066 same_at_start_charpos
, inserted_chars
, 0);
4067 /* Set `inserted' to the number of inserted characters. */
4068 inserted
= PT
- temp
;
4069 /* Set point before the inserted characters. */
4070 SET_PT_BOTH (temp
, same_at_start
);
4072 unbind_to (this_count
, Qnil
);
4078 total
= end_offset
- beg_offset
;
4080 /* For a special file, all we can do is guess. */
4081 total
= READ_BUF_SIZE
;
4083 if (NILP (visit
) && total
> 0)
4085 if (!NILP (BVAR (current_buffer
, file_truename
))
4086 /* Make binding buffer-file-name to nil effective. */
4087 && !NILP (BVAR (current_buffer
, filename
))
4088 && SAVE_MODIFF
>= MODIFF
)
4089 we_locked_file
= true;
4090 prepare_to_modify_buffer (PT
, PT
, NULL
);
4093 move_gap_both (PT
, PT_BYTE
);
4094 if (GAP_SIZE
< total
)
4095 make_gap (total
- GAP_SIZE
);
4097 if (beg_offset
!= 0 || !NILP (replace
))
4099 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
4100 report_file_error ("Setting file position", orig_filename
);
4103 /* In the following loop, HOW_MUCH contains the total bytes read so
4104 far for a regular file, and not changed for a special file. But,
4105 before exiting the loop, it is set to a negative value if I/O
4109 /* Total bytes inserted. */
4112 /* Here, we don't do code conversion in the loop. It is done by
4113 decode_coding_gap after all data are read into the buffer. */
4115 ptrdiff_t gap_size
= GAP_SIZE
;
4117 while (how_much
< total
)
4119 /* `try' is reserved in some compilers (Microsoft C). */
4120 ptrdiff_t trytry
= min (total
- how_much
, READ_BUF_SIZE
);
4127 /* Maybe make more room. */
4128 if (gap_size
< trytry
)
4130 make_gap (trytry
- gap_size
);
4131 gap_size
= GAP_SIZE
- inserted
;
4134 /* Read from the file, capturing `quit'. When an
4135 error occurs, end the loop, and arrange for a quit
4136 to be signaled after decoding the text we read. */
4137 nbytes
= internal_condition_case_1
4139 make_save_int_int_int (fd
, inserted
, trytry
),
4140 Qerror
, read_non_regular_quit
);
4148 this = XINT (nbytes
);
4152 /* Allow quitting out of the actual I/O. We don't make text
4153 part of the buffer until all the reading is done, so a C-g
4154 here doesn't do any harm. */
4155 this = emacs_read_quit (fd
,
4156 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
4169 /* For a regular file, where TOTAL is the real size,
4170 count HOW_MUCH to compare with it.
4171 For a special file, where TOTAL is just a buffer size,
4172 so don't bother counting in HOW_MUCH.
4173 (INSERTED is where we count the number of characters inserted.) */
4180 /* Now we have either read all the file data into the gap,
4181 or stop reading on I/O error or quit. If nothing was
4182 read, undo marking the buffer modified. */
4187 unlock_file (BVAR (current_buffer
, file_truename
));
4188 Vdeactivate_mark
= old_Vdeactivate_mark
;
4191 Fset (Qdeactivate_mark
, Qt
);
4194 clear_unwind_protect (fd_index
);
4197 report_file_error ("Read error", orig_filename
);
4199 /* Make the text read part of the buffer. */
4200 GAP_SIZE
-= inserted
;
4202 GPT_BYTE
+= inserted
;
4204 ZV_BYTE
+= inserted
;
4209 /* Put an anchor to ensure multi-byte form ends at gap. */
4214 if (NILP (coding_system
))
4216 /* The coding system is not yet decided. Decide it by an
4217 optimized method for handling `coding:' tag.
4219 Note that we can get here only if the buffer was empty
4220 before the insertion. */
4222 if (!NILP (Vcoding_system_for_read
))
4223 coding_system
= Vcoding_system_for_read
;
4226 /* Since we are sure that the current buffer was empty
4227 before the insertion, we can toggle
4228 enable-multibyte-characters directly here without taking
4229 care of marker adjustment. By this way, we can run Lisp
4230 program safely before decoding the inserted text. */
4231 Lisp_Object unwind_data
;
4232 ptrdiff_t count1
= SPECPDL_INDEX ();
4234 unwind_data
= Fcons (BVAR (current_buffer
, enable_multibyte_characters
),
4235 Fcons (BVAR (current_buffer
, undo_list
),
4236 Fcurrent_buffer ()));
4237 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4238 bset_undo_list (current_buffer
, Qt
);
4239 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4241 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4243 coding_system
= call2 (Vset_auto_coding_function
,
4244 filename
, make_number (inserted
));
4247 if (NILP (coding_system
))
4249 /* If the coding system is not yet decided, check
4250 file-coding-system-alist. */
4251 coding_system
= CALLN (Ffind_operation_coding_system
,
4252 Qinsert_file_contents
, orig_filename
,
4253 visit
, beg
, end
, Qnil
);
4254 if (CONSP (coding_system
))
4255 coding_system
= XCAR (coding_system
);
4257 unbind_to (count1
, Qnil
);
4258 inserted
= Z_BYTE
- BEG_BYTE
;
4261 if (NILP (coding_system
))
4262 coding_system
= Qundecided
;
4264 CHECK_CODING_SYSTEM (coding_system
);
4266 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4267 /* We must suppress all character code conversion except for
4268 end-of-line conversion. */
4269 coding_system
= raw_text_coding_system (coding_system
);
4270 setup_coding_system (coding_system
, &coding
);
4271 /* Ensure we set Vlast_coding_system_used. */
4272 set_coding_system
= true;
4277 /* When we visit a file by raw-text, we change the buffer to
4279 if (CODING_FOR_UNIBYTE (&coding
)
4280 /* Can't do this if part of the buffer might be preserved. */
4283 /* Visiting a file with these coding system makes the buffer
4286 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4288 Fset_buffer_multibyte (Qnil
);
4292 coding
.dst_multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
4293 if (CODING_MAY_REQUIRE_DECODING (&coding
)
4294 && (inserted
> 0 || CODING_REQUIRE_FLUSHING (&coding
)))
4296 move_gap_both (PT
, PT_BYTE
);
4297 GAP_SIZE
+= inserted
;
4298 ZV_BYTE
-= inserted
;
4302 decode_coding_gap (&coding
, inserted
, inserted
);
4303 inserted
= coding
.produced_char
;
4304 coding_system
= CODING_ID_NAME (coding
.id
);
4306 else if (inserted
> 0)
4308 invalidate_buffer_caches (current_buffer
, PT
, PT
+ inserted
);
4309 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4313 /* Call after-change hooks for the inserted text, aside from the case
4314 of normal visiting (not with REPLACE), which is done in a new buffer
4315 "before" the buffer is changed. */
4316 if (inserted
> 0 && total
> 0
4317 && (NILP (visit
) || !NILP (replace
)))
4319 signal_after_change (PT
, 0, inserted
);
4320 update_compositions (PT
, PT
, CHECK_BORDER
);
4323 /* Now INSERTED is measured in characters. */
4328 restore_window_points (window_markers
, inserted
,
4329 BYTE_TO_CHAR (same_at_start
),
4330 same_at_end_charpos
);
4334 if (empty_undo_list_p
)
4335 bset_undo_list (current_buffer
, Qnil
);
4339 current_buffer
->modtime
= mtime
;
4340 current_buffer
->modtime_size
= st
.st_size
;
4341 bset_filename (current_buffer
, orig_filename
);
4344 SAVE_MODIFF
= MODIFF
;
4345 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
4346 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4349 if (!NILP (BVAR (current_buffer
, file_truename
)))
4350 unlock_file (BVAR (current_buffer
, file_truename
));
4351 unlock_file (filename
);
4354 xsignal2 (Qfile_error
,
4355 build_string ("not a regular file"), orig_filename
);
4358 if (set_coding_system
)
4359 Vlast_coding_system_used
= coding_system
;
4361 if (! NILP (Ffboundp (Qafter_insert_file_set_coding
)))
4363 insval
= call2 (Qafter_insert_file_set_coding
, make_number (inserted
),
4365 if (! NILP (insval
))
4367 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4368 wrong_type_argument (intern ("inserted-chars"), insval
);
4369 inserted
= XFASTINT (insval
);
4373 /* Decode file format. */
4376 /* Don't run point motion or modification hooks when decoding. */
4377 ptrdiff_t count1
= SPECPDL_INDEX ();
4378 ptrdiff_t old_inserted
= inserted
;
4379 specbind (Qinhibit_point_motion_hooks
, Qt
);
4380 specbind (Qinhibit_modification_hooks
, Qt
);
4382 /* Save old undo list and don't record undo for decoding. */
4383 old_undo
= BVAR (current_buffer
, undo_list
);
4384 bset_undo_list (current_buffer
, Qt
);
4388 insval
= call3 (Qformat_decode
,
4389 Qnil
, make_number (inserted
), visit
);
4390 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4391 wrong_type_argument (intern ("inserted-chars"), insval
);
4392 inserted
= XFASTINT (insval
);
4396 /* If REPLACE is non-nil and we succeeded in not replacing the
4397 beginning or end of the buffer text with the file's contents,
4398 call format-decode with `point' positioned at the beginning
4399 of the buffer and `inserted' equaling the number of
4400 characters in the buffer. Otherwise, format-decode might
4401 fail to correctly analyze the beginning or end of the buffer.
4402 Hence we temporarily save `point' and `inserted' here and
4403 restore `point' iff format-decode did not insert or delete
4404 any text. Otherwise we leave `point' at point-min. */
4405 ptrdiff_t opoint
= PT
;
4406 ptrdiff_t opoint_byte
= PT_BYTE
;
4407 ptrdiff_t oinserted
= ZV
- BEGV
;
4408 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4410 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4411 insval
= call3 (Qformat_decode
,
4412 Qnil
, make_number (oinserted
), visit
);
4413 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4414 wrong_type_argument (intern ("inserted-chars"), insval
);
4415 if (ochars_modiff
== CHARS_MODIFF
)
4416 /* format_decode didn't modify buffer's characters => move
4417 point back to position before inserted text and leave
4418 value of inserted alone. */
4419 SET_PT_BOTH (opoint
, opoint_byte
);
4421 /* format_decode modified buffer's characters => consider
4422 entire buffer changed and leave point at point-min. */
4423 inserted
= XFASTINT (insval
);
4426 /* For consistency with format-decode call these now iff inserted > 0
4427 (martin 2007-06-28). */
4428 p
= Vafter_insert_file_functions
;
4433 insval
= call1 (XCAR (p
), make_number (inserted
));
4436 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4437 wrong_type_argument (intern ("inserted-chars"), insval
);
4438 inserted
= XFASTINT (insval
);
4443 /* For the rationale of this see the comment on
4444 format-decode above. */
4445 ptrdiff_t opoint
= PT
;
4446 ptrdiff_t opoint_byte
= PT_BYTE
;
4447 ptrdiff_t oinserted
= ZV
- BEGV
;
4448 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4450 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4451 insval
= call1 (XCAR (p
), make_number (oinserted
));
4454 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4455 wrong_type_argument (intern ("inserted-chars"), insval
);
4456 if (ochars_modiff
== CHARS_MODIFF
)
4457 /* after_insert_file_functions didn't modify
4458 buffer's characters => move point back to
4459 position before inserted text and leave value of
4461 SET_PT_BOTH (opoint
, opoint_byte
);
4463 /* after_insert_file_functions did modify buffer's
4464 characters => consider entire buffer changed and
4465 leave point at point-min. */
4466 inserted
= XFASTINT (insval
);
4474 if (!empty_undo_list_p
)
4476 bset_undo_list (current_buffer
, old_undo
);
4477 if (CONSP (old_undo
) && inserted
!= old_inserted
)
4479 /* Adjust the last undo record for the size change during
4480 the format conversion. */
4481 Lisp_Object tem
= XCAR (old_undo
);
4482 if (CONSP (tem
) && INTEGERP (XCAR (tem
))
4483 && INTEGERP (XCDR (tem
))
4484 && XFASTINT (XCDR (tem
)) == PT
+ old_inserted
)
4485 XSETCDR (tem
, make_number (PT
+ inserted
));
4489 /* If undo_list was Qt before, keep it that way.
4490 Otherwise start with an empty undo_list. */
4491 bset_undo_list (current_buffer
, EQ (old_undo
, Qt
) ? Qt
: Qnil
);
4493 unbind_to (count1
, Qnil
);
4497 && current_buffer
->modtime
.tv_nsec
== NONEXISTENT_MODTIME_NSECS
)
4499 /* If visiting nonexistent file, return nil. */
4500 report_file_errno ("Opening input file", orig_filename
, save_errno
);
4503 /* We made a lot of deletions and insertions above, so invalidate
4504 the newline cache for the entire region of the inserted
4506 if (current_buffer
->base_buffer
&& current_buffer
->base_buffer
->newline_cache
)
4507 invalidate_region_cache (current_buffer
->base_buffer
,
4508 current_buffer
->base_buffer
->newline_cache
,
4509 PT
- BEG
, Z
- PT
- inserted
);
4510 else if (current_buffer
->newline_cache
)
4511 invalidate_region_cache (current_buffer
,
4512 current_buffer
->newline_cache
,
4513 PT
- BEG
, Z
- PT
- inserted
);
4518 /* Retval needs to be dealt with in all cases consistently. */
4520 val
= list2 (orig_filename
, make_number (inserted
));
4522 return unbind_to (count
, val
);
4525 static Lisp_Object
build_annotations (Lisp_Object
, Lisp_Object
);
4528 build_annotations_unwind (Lisp_Object arg
)
4530 Vwrite_region_annotation_buffers
= arg
;
4533 /* Decide the coding-system to encode the data with. */
4536 choose_write_coding_system (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4537 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4538 struct coding_system
*coding
)
4541 Lisp_Object eol_parent
= Qnil
;
4544 && NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4545 BVAR (current_buffer
, auto_save_file_name
))))
4550 else if (!NILP (Vcoding_system_for_write
))
4552 val
= Vcoding_system_for_write
;
4553 if (coding_system_require_warning
4554 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4555 /* Confirm that VAL can surely encode the current region. */
4556 val
= call5 (Vselect_safe_coding_system_function
,
4557 start
, end
, list2 (Qt
, val
),
4562 /* If the variable `buffer-file-coding-system' is set locally,
4563 it means that the file was read with some kind of code
4564 conversion or the variable is explicitly set by users. We
4565 had better write it out with the same coding system even if
4566 `enable-multibyte-characters' is nil.
4568 If it is not set locally, we anyway have to convert EOL
4569 format if the default value of `buffer-file-coding-system'
4570 tells that it is not Unix-like (LF only) format. */
4571 bool using_default_coding
= 0;
4572 bool force_raw_text
= 0;
4574 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4576 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4579 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4585 /* Check file-coding-system-alist. */
4586 Lisp_Object coding_systems
4587 = CALLN (Ffind_operation_coding_system
, Qwrite_region
, start
, end
,
4588 filename
, append
, visit
, lockname
);
4589 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4590 val
= XCDR (coding_systems
);
4595 /* If we still have not decided a coding system, use the
4596 current buffer's value of buffer-file-coding-system. */
4597 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4598 using_default_coding
= 1;
4601 if (! NILP (val
) && ! force_raw_text
)
4603 Lisp_Object spec
, attrs
;
4605 CHECK_CODING_SYSTEM (val
);
4606 CHECK_CODING_SYSTEM_GET_SPEC (val
, spec
);
4607 attrs
= AREF (spec
, 0);
4608 if (EQ (CODING_ATTR_TYPE (attrs
), Qraw_text
))
4613 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4615 /* Confirm that VAL can surely encode the current region. */
4616 val
= call5 (Vselect_safe_coding_system_function
,
4617 start
, end
, val
, Qnil
, filename
);
4618 /* As the function specified by select-safe-coding-system-function
4619 is out of our control, make sure we are not fed by bogus
4622 CHECK_CODING_SYSTEM (val
);
4625 /* If the decided coding-system doesn't specify end-of-line
4626 format, we use that of `buffer-file-coding-system'. */
4627 if (! using_default_coding
)
4629 Lisp_Object dflt
= BVAR (&buffer_defaults
, buffer_file_coding_system
);
4632 val
= coding_inherit_eol_type (val
, dflt
);
4635 /* If we decide not to encode text, use `raw-text' or one of its
4638 val
= raw_text_coding_system (val
);
4641 val
= coding_inherit_eol_type (val
, eol_parent
);
4642 setup_coding_system (val
, coding
);
4644 if (!STRINGP (start
) && !NILP (BVAR (current_buffer
, selective_display
)))
4645 coding
->mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4649 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4650 "r\nFWrite region to file: \ni\ni\ni\np",
4651 doc
: /* Write current region into specified file.
4652 When called from a program, requires three arguments:
4653 START, END and FILENAME. START and END are normally buffer positions
4654 specifying the part of the buffer to write.
4655 If START is nil, that means to use the entire buffer contents; END is
4657 If START is a string, then output that string to the file
4658 instead of any buffer contents; END is ignored.
4660 Optional fourth argument APPEND if non-nil means
4661 append to existing file contents (if any). If it is a number,
4662 seek to that offset in the file before writing.
4663 Optional fifth argument VISIT, if t or a string, means
4664 set the last-save-file-modtime of buffer to this file's modtime
4665 and mark buffer not modified.
4666 If VISIT is a string, it is a second file name;
4667 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4668 VISIT is also the file name to lock and unlock for clash detection.
4669 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4670 do not display the \"Wrote file\" message.
4671 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4672 use for locking and unlocking, overriding FILENAME and VISIT.
4673 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4674 for an existing file with the same name. If MUSTBENEW is `excl',
4675 that means to get an error if the file already exists; never overwrite.
4676 If MUSTBENEW is neither nil nor `excl', that means ask for
4677 confirmation before overwriting, but do go ahead and overwrite the file
4678 if the user confirms.
4680 This does code conversion according to the value of
4681 `coding-system-for-write', `buffer-file-coding-system', or
4682 `file-coding-system-alist', and sets the variable
4683 `last-coding-system-used' to the coding system actually used.
4685 This calls `write-region-annotate-functions' at the start, and
4686 `write-region-post-annotation-function' at the end. */)
4687 (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
, Lisp_Object append
,
4688 Lisp_Object visit
, Lisp_Object lockname
, Lisp_Object mustbenew
)
4690 return write_region (start
, end
, filename
, append
, visit
, lockname
, mustbenew
,
4694 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4695 descriptor for FILENAME, so do not open or close FILENAME. */
4698 write_region (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4699 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4700 Lisp_Object mustbenew
, int desc
)
4704 off_t offset UNINIT
;
4705 bool open_and_close_file
= desc
< 0;
4710 struct timespec modtime
;
4711 ptrdiff_t count
= SPECPDL_INDEX ();
4712 ptrdiff_t count1 UNINIT
;
4713 Lisp_Object handler
;
4714 Lisp_Object visit_file
;
4715 Lisp_Object annotations
;
4716 Lisp_Object encoded_filename
;
4717 bool visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4718 bool quietly
= !NILP (visit
);
4719 bool file_locked
= 0;
4720 struct buffer
*given_buffer
;
4721 struct coding_system coding
;
4723 if (current_buffer
->base_buffer
&& visiting
)
4724 error ("Cannot do file visiting in an indirect buffer");
4726 if (!NILP (start
) && !STRINGP (start
))
4727 validate_region (&start
, &end
);
4731 filename
= Fexpand_file_name (filename
, Qnil
);
4733 if (!NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4734 barf_or_query_if_file_exists (filename
, false, "overwrite", true, true);
4736 if (STRINGP (visit
))
4737 visit_file
= Fexpand_file_name (visit
, Qnil
);
4739 visit_file
= filename
;
4741 if (NILP (lockname
))
4742 lockname
= visit_file
;
4746 /* If the file name has special constructs in it,
4747 call the corresponding file handler. */
4748 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4749 /* If FILENAME has no handler, see if VISIT has one. */
4750 if (NILP (handler
) && STRINGP (visit
))
4751 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4753 if (!NILP (handler
))
4756 val
= call8 (handler
, Qwrite_region
, start
, end
,
4757 filename
, append
, visit
, lockname
, mustbenew
);
4761 SAVE_MODIFF
= MODIFF
;
4762 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4763 bset_filename (current_buffer
, visit_file
);
4769 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
4771 /* Special kludge to simplify auto-saving. */
4774 /* Do it later, so write-region-annotate-function can work differently
4775 if we save "the buffer" vs "a region".
4776 This is useful in tar-mode. --Stef
4777 XSETFASTINT (start, BEG);
4778 XSETFASTINT (end, Z); */
4782 record_unwind_protect (build_annotations_unwind
,
4783 Vwrite_region_annotation_buffers
);
4784 Vwrite_region_annotation_buffers
= list1 (Fcurrent_buffer ());
4786 given_buffer
= current_buffer
;
4788 if (!STRINGP (start
))
4790 annotations
= build_annotations (start
, end
);
4792 if (current_buffer
!= given_buffer
)
4794 XSETFASTINT (start
, BEGV
);
4795 XSETFASTINT (end
, ZV
);
4801 XSETFASTINT (start
, BEGV
);
4802 XSETFASTINT (end
, ZV
);
4805 /* Decide the coding-system to encode the data with.
4806 We used to make this choice before calling build_annotations, but that
4807 leads to problems when a write-annotate-function takes care of
4808 unsavable chars (as was the case with X-Symbol). */
4809 Vlast_coding_system_used
4810 = choose_write_coding_system (start
, end
, filename
,
4811 append
, visit
, lockname
, &coding
);
4813 if (open_and_close_file
&& !auto_saving
)
4815 lock_file (lockname
);
4819 encoded_filename
= ENCODE_FILE (filename
);
4820 fn
= SSDATA (encoded_filename
);
4821 open_flags
= O_WRONLY
| O_CREAT
;
4822 open_flags
|= EQ (mustbenew
, Qexcl
) ? O_EXCL
: !NILP (append
) ? 0 : O_TRUNC
;
4823 if (NUMBERP (append
))
4824 offset
= file_offset (append
);
4825 else if (!NILP (append
))
4826 open_flags
|= O_APPEND
;
4828 mode
= S_IREAD
| S_IWRITE
;
4830 mode
= auto_saving
? auto_save_mode_bits
: 0666;
4833 if (open_and_close_file
)
4835 desc
= emacs_open (fn
, open_flags
, mode
);
4838 int open_errno
= errno
;
4840 unlock_file (lockname
);
4841 report_file_errno ("Opening output file", filename
, open_errno
);
4844 count1
= SPECPDL_INDEX ();
4845 record_unwind_protect_int (close_file_unwind
, desc
);
4848 if (NUMBERP (append
))
4850 off_t ret
= lseek (desc
, offset
, SEEK_SET
);
4853 int lseek_errno
= errno
;
4855 unlock_file (lockname
);
4856 report_file_errno ("Lseek error", filename
, lseek_errno
);
4860 if (STRINGP (start
))
4861 ok
= a_write (desc
, start
, 0, SCHARS (start
), &annotations
, &coding
);
4862 else if (XINT (start
) != XINT (end
))
4863 ok
= a_write (desc
, Qnil
, XINT (start
), XINT (end
) - XINT (start
),
4864 &annotations
, &coding
);
4867 /* If file was empty, still need to write the annotations. */
4868 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4869 ok
= a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4873 if (ok
&& CODING_REQUIRE_FLUSHING (&coding
)
4874 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
))
4876 /* We have to flush out a data. */
4877 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4878 ok
= e_write (desc
, Qnil
, 1, 1, &coding
);
4882 /* fsync is not crucial for temporary files. Nor for auto-save
4883 files, since they might lose some work anyway. */
4884 if (open_and_close_file
&& !auto_saving
&& !write_region_inhibit_fsync
)
4886 /* Transfer data and metadata to disk, retrying if interrupted.
4887 fsync can report a write failure here, e.g., due to disk full
4888 under NFS. But ignore EINVAL, which means fsync is not
4889 supported on this file. */
4890 while (fsync (desc
) != 0)
4893 if (errno
!= EINVAL
)
4894 ok
= 0, save_errno
= errno
;
4899 modtime
= invalid_timespec ();
4902 if (fstat (desc
, &st
) == 0)
4903 modtime
= get_stat_mtime (&st
);
4905 ok
= 0, save_errno
= errno
;
4908 if (open_and_close_file
)
4910 /* NFS can report a write failure now. */
4911 if (emacs_close (desc
) < 0)
4912 ok
= 0, save_errno
= errno
;
4914 /* Discard the unwind protect for close_file_unwind. */
4915 specpdl_ptr
= specpdl
+ count1
;
4918 /* Some file systems have a bug where st_mtime is not updated
4919 properly after a write. For example, CIFS might not see the
4920 st_mtime change until after the file is opened again.
4922 Attempt to detect this file system bug, and update MODTIME to the
4923 newer st_mtime if the bug appears to be present. This introduces
4924 a race condition, so to avoid most instances of the race condition
4925 on non-buggy file systems, skip this check if the most recently
4926 encountered non-buggy file system was the current file system.
4928 A race condition can occur if some other process modifies the
4929 file between the fstat above and the fstat below, but the race is
4930 unlikely and a similar race between the last write and the fstat
4931 above cannot possibly be closed anyway. */
4933 if (timespec_valid_p (modtime
)
4934 && ! (valid_timestamp_file_system
&& st
.st_dev
== timestamp_file_system
))
4936 int desc1
= emacs_open (fn
, O_WRONLY
, 0);
4940 if (fstat (desc1
, &st1
) == 0
4941 && st
.st_dev
== st1
.st_dev
&& st
.st_ino
== st1
.st_ino
)
4943 /* Use the heuristic if it appears to be valid. With neither
4944 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4945 file, the time stamp won't change. Also, some non-POSIX
4946 systems don't update an empty file's time stamp when
4947 truncating it. Finally, file systems with 100 ns or worse
4948 resolution sometimes seem to have bugs: on a system with ns
4949 resolution, checking ns % 100 incorrectly avoids the heuristic
4950 1% of the time, but the problem should be temporary as we will
4951 try again on the next time stamp. */
4953 = ((open_flags
& (O_EXCL
| O_TRUNC
)) != 0
4955 && modtime
.tv_nsec
% 100 != 0);
4957 struct timespec modtime1
= get_stat_mtime (&st1
);
4959 && timespec_cmp (modtime
, modtime1
) == 0
4960 && st
.st_size
== st1
.st_size
)
4962 timestamp_file_system
= st
.st_dev
;
4963 valid_timestamp_file_system
= 1;
4967 st
.st_size
= st1
.st_size
;
4971 emacs_close (desc1
);
4975 /* Call write-region-post-annotation-function. */
4976 while (CONSP (Vwrite_region_annotation_buffers
))
4978 Lisp_Object buf
= XCAR (Vwrite_region_annotation_buffers
);
4979 if (!NILP (Fbuffer_live_p (buf
)))
4982 if (FUNCTIONP (Vwrite_region_post_annotation_function
))
4983 call0 (Vwrite_region_post_annotation_function
);
4985 Vwrite_region_annotation_buffers
4986 = XCDR (Vwrite_region_annotation_buffers
);
4989 unbind_to (count
, Qnil
);
4992 unlock_file (lockname
);
4994 /* Do this before reporting IO error
4995 to avoid a "file has changed on disk" warning on
4996 next attempt to save. */
4997 if (timespec_valid_p (modtime
))
4999 current_buffer
->modtime
= modtime
;
5000 current_buffer
->modtime_size
= st
.st_size
;
5004 report_file_errno ("Write error", filename
, save_errno
);
5006 bool auto_saving_into_visited_file
=
5008 && ! NILP (Fstring_equal (BVAR (current_buffer
, filename
),
5009 BVAR (current_buffer
, auto_save_file_name
)));
5012 SAVE_MODIFF
= MODIFF
;
5013 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5014 bset_filename (current_buffer
, visit_file
);
5015 update_mode_lines
= 14;
5016 if (auto_saving_into_visited_file
)
5017 unlock_file (lockname
);
5021 if (auto_saving_into_visited_file
)
5023 SAVE_MODIFF
= MODIFF
;
5024 unlock_file (lockname
);
5030 if (!auto_saving
&& !noninteractive
)
5031 message_with_string ((NUMBERP (append
)
5041 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
5042 doc
: /* Return t if (car A) is numerically less than (car B). */)
5043 (Lisp_Object a
, Lisp_Object b
)
5045 return arithcompare (Fcar (a
), Fcar (b
), ARITH_LESS
);
5048 /* Build the complete list of annotations appropriate for writing out
5049 the text between START and END, by calling all the functions in
5050 write-region-annotate-functions and merging the lists they return.
5051 If one of these functions switches to a different buffer, we assume
5052 that buffer contains altered text. Therefore, the caller must
5053 make sure to restore the current buffer in all cases,
5054 as save-excursion would do. */
5057 build_annotations (Lisp_Object start
, Lisp_Object end
)
5059 Lisp_Object annotations
;
5061 Lisp_Object original_buffer
;
5063 bool used_global
= false;
5065 XSETBUFFER (original_buffer
, current_buffer
);
5068 p
= Vwrite_region_annotate_functions
;
5071 struct buffer
*given_buffer
= current_buffer
;
5072 if (EQ (Qt
, XCAR (p
)) && !used_global
)
5073 { /* Use the global value of the hook. */
5076 Fdefault_value (Qwrite_region_annotate_functions
),
5080 Vwrite_region_annotations_so_far
= annotations
;
5081 res
= call2 (XCAR (p
), start
, end
);
5082 /* If the function makes a different buffer current,
5083 assume that means this buffer contains altered text to be output.
5084 Reset START and END from the buffer bounds
5085 and discard all previous annotations because they should have
5086 been dealt with by this function. */
5087 if (current_buffer
!= given_buffer
)
5089 Vwrite_region_annotation_buffers
5090 = Fcons (Fcurrent_buffer (),
5091 Vwrite_region_annotation_buffers
);
5092 XSETFASTINT (start
, BEGV
);
5093 XSETFASTINT (end
, ZV
);
5096 Flength (res
); /* Check basic validity of return value */
5097 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5101 /* Now do the same for annotation functions implied by the file-format */
5102 if (auto_saving
&& (!EQ (BVAR (current_buffer
, auto_save_file_format
), Qt
)))
5103 p
= BVAR (current_buffer
, auto_save_file_format
);
5105 p
= BVAR (current_buffer
, file_format
);
5106 for (i
= 0; CONSP (p
); p
= XCDR (p
), ++i
)
5108 struct buffer
*given_buffer
= current_buffer
;
5110 Vwrite_region_annotations_so_far
= annotations
;
5112 /* Value is either a list of annotations or nil if the function
5113 has written annotations to a temporary buffer, which is now
5115 res
= call5 (Qformat_annotate_function
, XCAR (p
), start
, end
,
5116 original_buffer
, make_number (i
));
5117 if (current_buffer
!= given_buffer
)
5119 XSETFASTINT (start
, BEGV
);
5120 XSETFASTINT (end
, ZV
);
5125 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5132 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5133 If STRING is nil, POS is the character position in the current buffer.
5134 Intersperse with them the annotations from *ANNOT
5135 which fall within the range of POS to POS + NCHARS,
5136 each at its appropriate position.
5138 We modify *ANNOT by discarding elements as we use them up.
5140 Return true if successful. */
5143 a_write (int desc
, Lisp_Object string
, ptrdiff_t pos
,
5144 ptrdiff_t nchars
, Lisp_Object
*annot
,
5145 struct coding_system
*coding
)
5149 ptrdiff_t lastpos
= pos
+ nchars
;
5151 while (NILP (*annot
) || CONSP (*annot
))
5153 tem
= Fcar_safe (Fcar (*annot
));
5156 nextpos
= XFASTINT (tem
);
5158 /* If there are no more annotations in this range,
5159 output the rest of the range all at once. */
5160 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
5161 return e_write (desc
, string
, pos
, lastpos
, coding
);
5163 /* Output buffer text up to the next annotation's position. */
5166 if (!e_write (desc
, string
, pos
, nextpos
, coding
))
5170 /* Output the annotation. */
5171 tem
= Fcdr (Fcar (*annot
));
5174 if (!e_write (desc
, tem
, 0, SCHARS (tem
), coding
))
5177 *annot
= Fcdr (*annot
);
5182 /* Maximum number of characters that the next
5183 function encodes per one loop iteration. */
5185 enum { E_WRITE_MAX
= 8 * 1024 * 1024 };
5187 /* Write text in the range START and END into descriptor DESC,
5188 encoding them with coding system CODING. If STRING is nil, START
5189 and END are character positions of the current buffer, else they
5190 are indexes to the string STRING. Return true if successful. */
5193 e_write (int desc
, Lisp_Object string
, ptrdiff_t start
, ptrdiff_t end
,
5194 struct coding_system
*coding
)
5196 if (STRINGP (string
))
5199 end
= SCHARS (string
);
5202 /* We used to have a code for handling selective display here. But,
5203 now it is handled within encode_coding. */
5207 if (STRINGP (string
))
5209 coding
->src_multibyte
= SCHARS (string
) < SBYTES (string
);
5210 if (CODING_REQUIRE_ENCODING (coding
))
5212 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5214 /* Avoid creating huge Lisp string in encode_coding_object. */
5215 if (nchars
== E_WRITE_MAX
)
5216 coding
->raw_destination
= 1;
5218 encode_coding_object
5219 (coding
, string
, start
, string_char_to_byte (string
, start
),
5220 start
+ nchars
, string_char_to_byte (string
, start
+ nchars
),
5225 coding
->dst_object
= string
;
5226 coding
->consumed_char
= SCHARS (string
);
5227 coding
->produced
= SBYTES (string
);
5232 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
5233 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
5235 coding
->src_multibyte
= (end
- start
) < (end_byte
- start_byte
);
5236 if (CODING_REQUIRE_ENCODING (coding
))
5238 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5241 if (nchars
== E_WRITE_MAX
)
5242 coding
->raw_destination
= 1;
5244 encode_coding_object
5245 (coding
, Fcurrent_buffer (), start
, start_byte
,
5246 start
+ nchars
, CHAR_TO_BYTE (start
+ nchars
), Qt
);
5250 coding
->dst_object
= Qnil
;
5251 coding
->dst_pos_byte
= start_byte
;
5252 if (start
>= GPT
|| end
<= GPT
)
5254 coding
->consumed_char
= end
- start
;
5255 coding
->produced
= end_byte
- start_byte
;
5259 coding
->consumed_char
= GPT
- start
;
5260 coding
->produced
= GPT_BYTE
- start_byte
;
5265 if (coding
->produced
> 0)
5267 char *buf
= (coding
->raw_destination
? (char *) coding
->destination
5268 : (STRINGP (coding
->dst_object
)
5269 ? SSDATA (coding
->dst_object
)
5270 : (char *) BYTE_POS_ADDR (coding
->dst_pos_byte
)));
5271 coding
->produced
-= emacs_write_quit (desc
, buf
, coding
->produced
);
5273 if (coding
->raw_destination
)
5275 /* We're responsible for freeing this, see
5276 encode_coding_object to check why. */
5277 xfree (coding
->destination
);
5278 coding
->raw_destination
= 0;
5280 if (coding
->produced
)
5283 start
+= coding
->consumed_char
;
5289 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5290 Sverify_visited_file_modtime
, 0, 1, 0,
5291 doc
: /* Return t if last mod time of BUF's visited file matches what BUF records.
5292 This means that the file has not been changed since it was visited or saved.
5293 If BUF is omitted or nil, it defaults to the current buffer.
5294 See Info node `(elisp)Modification Time' for more details. */)
5297 struct buffer
*b
= decode_buffer (buf
);
5299 Lisp_Object handler
;
5300 Lisp_Object filename
;
5301 struct timespec mtime
;
5303 if (!STRINGP (BVAR (b
, filename
))) return Qt
;
5304 if (b
->modtime
.tv_nsec
== UNKNOWN_MODTIME_NSECS
) return Qt
;
5306 /* If the file name has special constructs in it,
5307 call the corresponding file handler. */
5308 handler
= Ffind_file_name_handler (BVAR (b
, filename
),
5309 Qverify_visited_file_modtime
);
5310 if (!NILP (handler
))
5311 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5313 filename
= ENCODE_FILE (BVAR (b
, filename
));
5315 mtime
= (stat (SSDATA (filename
), &st
) == 0
5316 ? get_stat_mtime (&st
)
5317 : time_error_value (errno
));
5318 if (timespec_cmp (mtime
, b
->modtime
) == 0
5319 && (b
->modtime_size
< 0
5320 || st
.st_size
== b
->modtime_size
))
5325 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5326 Svisited_file_modtime
, 0, 0, 0,
5327 doc
: /* Return the current buffer's recorded visited file modification time.
5328 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5329 `file-attributes' returns. If the current buffer has no recorded file
5330 modification time, this function returns 0. If the visited file
5331 doesn't exist, return -1.
5332 See Info node `(elisp)Modification Time' for more details. */)
5335 int ns
= current_buffer
->modtime
.tv_nsec
;
5337 return make_number (UNKNOWN_MODTIME_NSECS
- ns
);
5338 return make_lisp_time (current_buffer
->modtime
);
5341 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5342 Sset_visited_file_modtime
, 0, 1, 0,
5343 doc
: /* Update buffer's recorded modification time from the visited file's time.
5344 Useful if the buffer was not read from the file normally
5345 or if the file itself has been changed for some known benign reason.
5346 An argument specifies the modification time value to use
5347 \(instead of that of the visited file), in the form of a list
5348 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5349 `visited-file-modtime'. */)
5350 (Lisp_Object time_flag
)
5352 if (!NILP (time_flag
))
5354 struct timespec mtime
;
5355 if (INTEGERP (time_flag
))
5357 CHECK_RANGED_INTEGER (time_flag
, -1, 0);
5358 mtime
= make_timespec (0, UNKNOWN_MODTIME_NSECS
- XINT (time_flag
));
5361 mtime
= lisp_time_argument (time_flag
);
5363 current_buffer
->modtime
= mtime
;
5364 current_buffer
->modtime_size
= -1;
5368 register Lisp_Object filename
;
5370 Lisp_Object handler
;
5372 filename
= Fexpand_file_name (BVAR (current_buffer
, filename
), Qnil
);
5374 /* If the file name has special constructs in it,
5375 call the corresponding file handler. */
5376 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5377 if (!NILP (handler
))
5378 /* The handler can find the file name the same way we did. */
5379 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5381 filename
= ENCODE_FILE (filename
);
5383 if (stat (SSDATA (filename
), &st
) >= 0)
5385 current_buffer
->modtime
= get_stat_mtime (&st
);
5386 current_buffer
->modtime_size
= st
.st_size
;
5394 auto_save_error (Lisp_Object error_val
)
5396 auto_save_error_occurred
= 1;
5398 ring_bell (XFRAME (selected_frame
));
5400 AUTO_STRING (format
, "Auto-saving %s: %s");
5401 Lisp_Object msg
= CALLN (Fformat
, format
, BVAR (current_buffer
, name
),
5402 Ferror_message_string (error_val
));
5403 call3 (intern ("display-warning"),
5404 intern ("auto-save"), msg
, intern ("error"));
5415 auto_save_mode_bits
= 0666;
5417 /* Get visited file's mode to become the auto save file's mode. */
5418 if (! NILP (BVAR (current_buffer
, filename
)))
5420 if (stat (SSDATA (BVAR (current_buffer
, filename
)), &st
) >= 0)
5421 /* But make sure we can overwrite it later! */
5422 auto_save_mode_bits
= (st
.st_mode
| 0600) & 0777;
5423 else if (modes
= Ffile_modes (BVAR (current_buffer
, filename
)),
5425 /* Remote files don't cooperate with stat. */
5426 auto_save_mode_bits
= (XINT (modes
) | 0600) & 0777;
5430 Fwrite_region (Qnil
, Qnil
, BVAR (current_buffer
, auto_save_file_name
), Qnil
,
5431 NILP (Vauto_save_visited_file_name
) ? Qlambda
: Qt
,
5435 struct auto_save_unwind
5442 do_auto_save_unwind (void *arg
)
5444 struct auto_save_unwind
*p
= arg
;
5445 FILE *stream
= p
->stream
;
5446 minibuffer_auto_raise
= p
->auto_raise
;
5457 do_auto_save_make_dir (Lisp_Object dir
)
5461 auto_saving_dir_umask
= 077;
5462 result
= call2 (Qmake_directory
, dir
, Qt
);
5463 auto_saving_dir_umask
= 0;
5468 do_auto_save_eh (Lisp_Object ignore
)
5470 auto_saving_dir_umask
= 0;
5474 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5475 doc
: /* Auto-save all buffers that need it.
5476 This is all buffers that have auto-saving enabled
5477 and are changed since last auto-saved.
5478 Auto-saving writes the buffer into a file
5479 so that your editing is not lost if the system crashes.
5480 This file is not the file you visited; that changes only when you save.
5481 Normally, run the normal hook `auto-save-hook' before saving.
5483 A non-nil NO-MESSAGE argument means do not print any message if successful.
5484 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5485 (Lisp_Object no_message
, Lisp_Object current_only
)
5487 struct buffer
*old
= current_buffer
, *b
;
5488 Lisp_Object tail
, buf
, hook
;
5489 bool auto_saved
= 0;
5490 int do_handled_files
;
5492 FILE *stream
= NULL
;
5493 ptrdiff_t count
= SPECPDL_INDEX ();
5494 bool orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5495 bool old_message_p
= 0;
5496 struct auto_save_unwind auto_save_unwind
;
5498 if (max_specpdl_size
< specpdl_size
+ 40)
5499 max_specpdl_size
= specpdl_size
+ 40;
5504 if (NILP (no_message
))
5506 old_message_p
= push_message ();
5507 record_unwind_protect_void (pop_message_unwind
);
5510 /* Ordinarily don't quit within this function,
5511 but don't make it impossible to quit (in case we get hung in I/O). */
5515 hook
= intern ("auto-save-hook");
5516 safe_run_hooks (hook
);
5518 if (STRINGP (Vauto_save_list_file_name
))
5520 Lisp_Object listfile
;
5522 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5524 /* Don't try to create the directory when shutting down Emacs,
5525 because creating the directory might signal an error, and
5526 that would leave Emacs in a strange state. */
5527 if (!NILP (Vrun_hooks
))
5530 dir
= Ffile_name_directory (listfile
);
5531 if (NILP (Ffile_directory_p (dir
)))
5532 internal_condition_case_1 (do_auto_save_make_dir
,
5537 stream
= emacs_fopen (SSDATA (listfile
), "w");
5540 auto_save_unwind
.stream
= stream
;
5541 auto_save_unwind
.auto_raise
= minibuffer_auto_raise
;
5542 record_unwind_protect_ptr (do_auto_save_unwind
, &auto_save_unwind
);
5543 minibuffer_auto_raise
= 0;
5545 auto_save_error_occurred
= 0;
5547 /* On first pass, save all files that don't have handlers.
5548 On second pass, save all files that do have handlers.
5550 If Emacs is crashing, the handlers may tweak what is causing
5551 Emacs to crash in the first place, and it would be a shame if
5552 Emacs failed to autosave perfectly ordinary files because it
5553 couldn't handle some ange-ftp'd file. */
5555 for (do_handled_files
= 0; do_handled_files
< 2; do_handled_files
++)
5556 FOR_EACH_LIVE_BUFFER (tail
, buf
)
5560 /* Record all the buffers that have auto save mode
5561 in the special file that lists them. For each of these buffers,
5562 Record visited name (if any) and auto save name. */
5563 if (STRINGP (BVAR (b
, auto_save_file_name
))
5564 && stream
!= NULL
&& do_handled_files
== 0)
5567 if (!NILP (BVAR (b
, filename
)))
5568 fwrite_unlocked (SDATA (BVAR (b
, filename
)), 1,
5569 SBYTES (BVAR (b
, filename
)), stream
);
5570 putc_unlocked ('\n', stream
);
5571 fwrite_unlocked (SDATA (BVAR (b
, auto_save_file_name
)), 1,
5572 SBYTES (BVAR (b
, auto_save_file_name
)), stream
);
5573 putc_unlocked ('\n', stream
);
5577 if (!NILP (current_only
)
5578 && b
!= current_buffer
)
5581 /* Don't auto-save indirect buffers.
5582 The base buffer takes care of it. */
5586 /* Check for auto save enabled
5587 and file changed since last auto save
5588 and file changed since last real save. */
5589 if (STRINGP (BVAR (b
, auto_save_file_name
))
5590 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
)
5591 && BUF_AUTOSAVE_MODIFF (b
) < BUF_MODIFF (b
)
5592 /* -1 means we've turned off autosaving for a while--see below. */
5593 && XINT (BVAR (b
, save_length
)) >= 0
5594 && (do_handled_files
5595 || NILP (Ffind_file_name_handler (BVAR (b
, auto_save_file_name
),
5598 struct timespec before_time
= current_timespec ();
5599 struct timespec after_time
;
5601 /* If we had a failure, don't try again for 20 minutes. */
5602 if (b
->auto_save_failure_time
> 0
5603 && before_time
.tv_sec
- b
->auto_save_failure_time
< 1200)
5606 set_buffer_internal (b
);
5607 if (NILP (Vauto_save_include_big_deletions
)
5608 && (XFASTINT (BVAR (b
, save_length
)) * 10
5609 > (BUF_Z (b
) - BUF_BEG (b
)) * 13)
5610 /* A short file is likely to change a large fraction;
5611 spare the user annoying messages. */
5612 && XFASTINT (BVAR (b
, save_length
)) > 5000
5613 /* These messages are frequent and annoying for `*mail*'. */
5614 && !EQ (BVAR (b
, filename
), Qnil
)
5615 && NILP (no_message
))
5617 /* It has shrunk too much; turn off auto-saving here. */
5618 minibuffer_auto_raise
= orig_minibuffer_auto_raise
;
5619 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5621 minibuffer_auto_raise
= 0;
5622 /* Turn off auto-saving until there's a real save,
5623 and prevent any more warnings. */
5624 XSETINT (BVAR (b
, save_length
), -1);
5625 Fsleep_for (make_number (1), Qnil
);
5628 if (!auto_saved
&& NILP (no_message
))
5629 message1 ("Auto-saving...");
5630 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
5632 BUF_AUTOSAVE_MODIFF (b
) = BUF_MODIFF (b
);
5633 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5634 set_buffer_internal (old
);
5636 after_time
= current_timespec ();
5638 /* If auto-save took more than 60 seconds,
5639 assume it was an NFS failure that got a timeout. */
5640 if (after_time
.tv_sec
- before_time
.tv_sec
> 60)
5641 b
->auto_save_failure_time
= after_time
.tv_sec
;
5645 /* Prevent another auto save till enough input events come in. */
5646 record_auto_save ();
5648 if (auto_saved
&& NILP (no_message
))
5652 /* If we are going to restore an old message,
5653 give time to read ours. */
5654 sit_for (make_number (1), 0, 0);
5657 else if (!auto_save_error_occurred
)
5658 /* Don't overwrite the error message if an error occurred.
5659 If we displayed a message and then restored a state
5660 with no message, leave a "done" message on the screen. */
5661 message1 ("Auto-saving...done");
5666 /* This restores the message-stack status. */
5667 unbind_to (count
, Qnil
);
5671 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved
,
5672 Sset_buffer_auto_saved
, 0, 0, 0,
5673 doc
: /* Mark current buffer as auto-saved with its current text.
5674 No auto-save file will be written until the buffer changes again. */)
5677 /* FIXME: This should not be called in indirect buffers, since
5678 they're not autosaved. */
5679 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
5680 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5681 current_buffer
->auto_save_failure_time
= 0;
5685 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure
,
5686 Sclear_buffer_auto_save_failure
, 0, 0, 0,
5687 doc
: /* Clear any record of a recent auto-save failure in the current buffer. */)
5690 current_buffer
->auto_save_failure_time
= 0;
5694 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
5696 doc
: /* Return t if current buffer has been auto-saved recently.
5697 More precisely, if it has been auto-saved since last read from or saved
5698 in the visited file. If the buffer has no visited file,
5699 then any auto-save counts as "recent". */)
5702 /* FIXME: maybe we should return nil for indirect buffers since
5703 they're never autosaved. */
5704 return (SAVE_MODIFF
< BUF_AUTOSAVE_MODIFF (current_buffer
) ? Qt
: Qnil
);
5707 /* Reading and completing file names. */
5709 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p
,
5710 Snext_read_file_uses_dialog_p
, 0, 0, 0,
5711 doc
: /* Return t if a call to `read-file-name' will use a dialog.
5712 The return value is only relevant for a call to `read-file-name' that happens
5713 before any other event (mouse or keypress) is handled. */)
5716 #if (defined USE_GTK || defined USE_MOTIF \
5717 || defined HAVE_NS || defined HAVE_NTGUI)
5718 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5721 && window_system_available (SELECTED_FRAME ()))
5728 DEFUN ("set-binary-mode", Fset_binary_mode
, Sset_binary_mode
, 2, 2, 0,
5729 doc
: /* Switch STREAM to binary I/O mode or text I/O mode.
5730 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5731 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5734 As a side effect, this function flushes any pending STREAM's data.
5736 Value is the previous value of STREAM's I/O mode, nil for text mode,
5737 non-nil for binary mode.
5739 On MS-Windows and MS-DOS, binary mode is needed to read or write
5740 arbitrary binary data, and for disabling translation between CR-LF
5741 pairs and a single newline character. Examples include generation
5742 of text files with Unix-style end-of-line format using `princ' in
5743 batch mode, with standard output redirected to a file.
5745 On Posix systems, this function always returns non-nil, and has no
5746 effect except for flushing STREAM's data. */)
5747 (Lisp_Object stream
, Lisp_Object mode
)
5752 CHECK_SYMBOL (stream
);
5753 if (EQ (stream
, Qstdin
))
5755 else if (EQ (stream
, Qstdout
))
5757 else if (EQ (stream
, Qstderr
))
5760 xsignal2 (Qerror
, build_string ("unsupported stream"), stream
);
5762 binmode
= NILP (mode
) ? O_TEXT
: O_BINARY
;
5764 fflush_unlocked (fp
);
5766 return (set_binary_mode (fileno (fp
), binmode
) == O_BINARY
) ? Qt
: Qnil
;
5772 realmask
= umask (0);
5775 valid_timestamp_file_system
= 0;
5777 /* fsync can be a significant performance hit. Often it doesn't
5778 suffice to make the file-save operation survive a crash. For
5779 batch scripts, which are typically part of larger shell commands
5780 that don't fsync other files, its effect on performance can be
5781 significant so its utility is particularly questionable.
5782 Hence, for now by default fsync is used only when interactive.
5784 For more on why fsync often fails to work on today's hardware, see:
5785 Zheng M et al. Understanding the robustness of SSDs under power fault.
5786 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5787 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5789 For more on why fsync does not suffice even if it works properly, see:
5790 Roche X. Necessary step(s) to synchronize filename operations on disk.
5791 Austin Group Defect 672, 2013-03-19
5792 http://austingroupbugs.net/view.php?id=672 */
5793 write_region_inhibit_fsync
= noninteractive
;
5797 syms_of_fileio (void)
5799 /* Property name of a file name handler,
5800 which gives a list of operations it handles. */
5801 DEFSYM (Qoperations
, "operations");
5803 DEFSYM (Qexpand_file_name
, "expand-file-name");
5804 DEFSYM (Qsubstitute_in_file_name
, "substitute-in-file-name");
5805 DEFSYM (Qdirectory_file_name
, "directory-file-name");
5806 DEFSYM (Qfile_name_directory
, "file-name-directory");
5807 DEFSYM (Qfile_name_nondirectory
, "file-name-nondirectory");
5808 DEFSYM (Qunhandled_file_name_directory
, "unhandled-file-name-directory");
5809 DEFSYM (Qfile_name_as_directory
, "file-name-as-directory");
5810 DEFSYM (Qcopy_file
, "copy-file");
5811 DEFSYM (Qmake_directory_internal
, "make-directory-internal");
5812 DEFSYM (Qmake_directory
, "make-directory");
5813 DEFSYM (Qdelete_file
, "delete-file");
5814 DEFSYM (Qfile_name_case_insensitive_p
, "file-name-case-insensitive-p");
5815 DEFSYM (Qrename_file
, "rename-file");
5816 DEFSYM (Qadd_name_to_file
, "add-name-to-file");
5817 DEFSYM (Qmake_symbolic_link
, "make-symbolic-link");
5818 DEFSYM (Qfile_exists_p
, "file-exists-p");
5819 DEFSYM (Qfile_executable_p
, "file-executable-p");
5820 DEFSYM (Qfile_readable_p
, "file-readable-p");
5821 DEFSYM (Qfile_writable_p
, "file-writable-p");
5822 DEFSYM (Qfile_symlink_p
, "file-symlink-p");
5823 DEFSYM (Qaccess_file
, "access-file");
5824 DEFSYM (Qfile_directory_p
, "file-directory-p");
5825 DEFSYM (Qfile_regular_p
, "file-regular-p");
5826 DEFSYM (Qfile_accessible_directory_p
, "file-accessible-directory-p");
5827 DEFSYM (Qfile_modes
, "file-modes");
5828 DEFSYM (Qset_file_modes
, "set-file-modes");
5829 DEFSYM (Qset_file_times
, "set-file-times");
5830 DEFSYM (Qfile_selinux_context
, "file-selinux-context");
5831 DEFSYM (Qset_file_selinux_context
, "set-file-selinux-context");
5832 DEFSYM (Qfile_acl
, "file-acl");
5833 DEFSYM (Qset_file_acl
, "set-file-acl");
5834 DEFSYM (Qfile_newer_than_file_p
, "file-newer-than-file-p");
5835 DEFSYM (Qinsert_file_contents
, "insert-file-contents");
5836 DEFSYM (Qwrite_region
, "write-region");
5837 DEFSYM (Qverify_visited_file_modtime
, "verify-visited-file-modtime");
5838 DEFSYM (Qset_visited_file_modtime
, "set-visited-file-modtime");
5840 /* The symbol bound to coding-system-for-read when
5841 insert-file-contents is called for recovering a file. This is not
5842 an actual coding system name, but just an indicator to tell
5843 insert-file-contents to use `emacs-mule' with a special flag for
5844 auto saving and recovering a file. */
5845 DEFSYM (Qauto_save_coding
, "auto-save-coding");
5847 DEFSYM (Qfile_name_history
, "file-name-history");
5848 Fset (Qfile_name_history
, Qnil
);
5850 DEFSYM (Qfile_error
, "file-error");
5851 DEFSYM (Qfile_already_exists
, "file-already-exists");
5852 DEFSYM (Qfile_date_error
, "file-date-error");
5853 DEFSYM (Qfile_missing
, "file-missing");
5854 DEFSYM (Qfile_notify_error
, "file-notify-error");
5855 DEFSYM (Qexcl
, "excl");
5857 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system
,
5858 doc
: /* Coding system for encoding file names.
5859 If it is nil, `default-file-name-coding-system' (which see) is used.
5861 On MS-Windows, the value of this variable is largely ignored if
5862 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5863 behaves as if file names were encoded in `utf-8'. */);
5864 Vfile_name_coding_system
= Qnil
;
5866 DEFVAR_LISP ("default-file-name-coding-system",
5867 Vdefault_file_name_coding_system
,
5868 doc
: /* Default coding system for encoding file names.
5869 This variable is used only when `file-name-coding-system' is nil.
5871 This variable is set/changed by the command `set-language-environment'.
5872 User should not set this variable manually,
5873 instead use `file-name-coding-system' to get a constant encoding
5874 of file names regardless of the current language environment.
5876 On MS-Windows, the value of this variable is largely ignored if
5877 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5878 behaves as if file names were encoded in `utf-8'. */);
5879 Vdefault_file_name_coding_system
= Qnil
;
5881 /* Lisp functions for translating file formats. */
5882 DEFSYM (Qformat_decode
, "format-decode");
5883 DEFSYM (Qformat_annotate_function
, "format-annotate-function");
5885 /* Lisp function for setting buffer-file-coding-system and the
5886 multibyteness of the current buffer after inserting a file. */
5887 DEFSYM (Qafter_insert_file_set_coding
, "after-insert-file-set-coding");
5889 DEFSYM (Qcar_less_than_car
, "car-less-than-car");
5891 Fput (Qfile_error
, Qerror_conditions
,
5892 Fpurecopy (list2 (Qfile_error
, Qerror
)));
5893 Fput (Qfile_error
, Qerror_message
,
5894 build_pure_c_string ("File error"));
5896 Fput (Qfile_already_exists
, Qerror_conditions
,
5897 Fpurecopy (list3 (Qfile_already_exists
, Qfile_error
, Qerror
)));
5898 Fput (Qfile_already_exists
, Qerror_message
,
5899 build_pure_c_string ("File already exists"));
5901 Fput (Qfile_date_error
, Qerror_conditions
,
5902 Fpurecopy (list3 (Qfile_date_error
, Qfile_error
, Qerror
)));
5903 Fput (Qfile_date_error
, Qerror_message
,
5904 build_pure_c_string ("Cannot set file date"));
5906 Fput (Qfile_missing
, Qerror_conditions
,
5907 Fpurecopy (list3 (Qfile_missing
, Qfile_error
, Qerror
)));
5908 Fput (Qfile_missing
, Qerror_message
,
5909 build_pure_c_string ("File is missing"));
5911 Fput (Qfile_notify_error
, Qerror_conditions
,
5912 Fpurecopy (list3 (Qfile_notify_error
, Qfile_error
, Qerror
)));
5913 Fput (Qfile_notify_error
, Qerror_message
,
5914 build_pure_c_string ("File notification error"));
5916 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist
,
5917 doc
: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5918 If a file name matches REGEXP, all I/O on that file is done by calling
5919 HANDLER. If a file name matches more than one handler, the handler
5920 whose match starts last in the file name gets precedence. The
5921 function `find-file-name-handler' checks this list for a handler for
5924 HANDLER should be a function. The first argument given to it is the
5925 name of the I/O primitive to be handled; the remaining arguments are
5926 the arguments that were passed to that primitive. For example, if you
5927 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5928 HANDLER is called like this:
5930 (funcall HANDLER \\='file-exists-p FILENAME)
5932 Note that HANDLER must be able to handle all I/O primitives; if it has
5933 nothing special to do for a primitive, it should reinvoke the
5934 primitive to handle the operation \"the usual way\".
5935 See Info node `(elisp)Magic File Names' for more details. */);
5936 Vfile_name_handler_alist
= Qnil
;
5938 DEFVAR_LISP ("set-auto-coding-function",
5939 Vset_auto_coding_function
,
5940 doc
: /* If non-nil, a function to call to decide a coding system of file.
5941 Two arguments are passed to this function: the file name
5942 and the length of a file contents following the point.
5943 This function should return a coding system to decode the file contents.
5944 It should check the file name against `auto-coding-alist'.
5945 If no coding system is decided, it should check a coding system
5946 specified in the heading lines with the format:
5947 -*- ... coding: CODING-SYSTEM; ... -*-
5948 or local variable spec of the tailing lines with `coding:' tag. */);
5949 Vset_auto_coding_function
= Qnil
;
5951 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions
,
5952 doc
: /* A list of functions to be called at the end of `insert-file-contents'.
5953 Each is passed one argument, the number of characters inserted,
5954 with point at the start of the inserted text. Each function
5955 should leave point the same, and return the new character count.
5956 If `insert-file-contents' is intercepted by a handler from
5957 `file-name-handler-alist', that handler is responsible for calling the
5958 functions in `after-insert-file-functions' if appropriate. */);
5959 Vafter_insert_file_functions
= Qnil
;
5961 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions
,
5962 doc
: /* A list of functions to be called at the start of `write-region'.
5963 Each is passed two arguments, START and END as for `write-region'.
5964 These are usually two numbers but not always; see the documentation
5965 for `write-region'. The function should return a list of pairs
5966 of the form (POSITION . STRING), consisting of strings to be effectively
5967 inserted at the specified positions of the file being written (1 means to
5968 insert before the first byte written). The POSITIONs must be sorted into
5971 If there are several annotation functions, the lists returned by these
5972 functions are merged destructively. As each annotation function runs,
5973 the variable `write-region-annotations-so-far' contains a list of all
5974 annotations returned by previous annotation functions.
5976 An annotation function can return with a different buffer current.
5977 Doing so removes the annotations returned by previous functions, and
5978 resets START and END to `point-min' and `point-max' of the new buffer.
5980 After `write-region' completes, Emacs calls the function stored in
5981 `write-region-post-annotation-function', once for each buffer that was
5982 current when building the annotations (i.e., at least once), with that
5983 buffer current. */);
5984 Vwrite_region_annotate_functions
= Qnil
;
5985 DEFSYM (Qwrite_region_annotate_functions
, "write-region-annotate-functions");
5987 DEFVAR_LISP ("write-region-post-annotation-function",
5988 Vwrite_region_post_annotation_function
,
5989 doc
: /* Function to call after `write-region' completes.
5990 The function is called with no arguments. If one or more of the
5991 annotation functions in `write-region-annotate-functions' changed the
5992 current buffer, the function stored in this variable is called for
5993 each of those additional buffers as well, in addition to the original
5994 buffer. The relevant buffer is current during each function call. */);
5995 Vwrite_region_post_annotation_function
= Qnil
;
5996 staticpro (&Vwrite_region_annotation_buffers
);
5998 DEFVAR_LISP ("write-region-annotations-so-far",
5999 Vwrite_region_annotations_so_far
,
6000 doc
: /* When an annotation function is called, this holds the previous annotations.
6001 These are the annotations made by other annotation functions
6002 that were already called. See also `write-region-annotate-functions'. */);
6003 Vwrite_region_annotations_so_far
= Qnil
;
6005 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers
,
6006 doc
: /* A list of file name handlers that temporarily should not be used.
6007 This applies only to the operation `inhibit-file-name-operation'. */);
6008 Vinhibit_file_name_handlers
= Qnil
;
6010 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation
,
6011 doc
: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6012 Vinhibit_file_name_operation
= Qnil
;
6014 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name
,
6015 doc
: /* File name in which to write a list of all auto save file names.
6016 This variable is initialized automatically from `auto-save-list-file-prefix'
6017 shortly after Emacs reads your init file, if you have not yet given it
6018 a non-nil value. */);
6019 Vauto_save_list_file_name
= Qnil
;
6021 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name
,
6022 doc
: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6023 Normally auto-save files are written under other names. */);
6024 Vauto_save_visited_file_name
= Qnil
;
6026 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions
,
6027 doc
: /* If non-nil, auto-save even if a large part of the text is deleted.
6028 If nil, deleting a substantial portion of the text disables auto-save
6029 in the buffer; this is the default behavior, because the auto-save
6030 file is usually more useful if it contains the deleted text. */);
6031 Vauto_save_include_big_deletions
= Qnil
;
6033 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync
,
6034 doc
: /* Non-nil means don't call fsync in `write-region'.
6035 This variable affects calls to `write-region' as well as save commands.
6036 Setting this to nil may avoid data loss if the system loses power or
6037 the operating system crashes. By default, it is non-nil in batch mode. */);
6038 write_region_inhibit_fsync
= 0; /* See also `init_fileio' above. */
6040 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash
,
6041 doc
: /* Specifies whether to use the system's trash can.
6042 When non-nil, certain file deletion commands use the function
6043 `move-file-to-trash' instead of deleting files outright.
6044 This includes interactive calls to `delete-file' and
6045 `delete-directory' and the Dired deletion commands. */);
6046 delete_by_moving_to_trash
= 0;
6047 DEFSYM (Qdelete_by_moving_to_trash
, "delete-by-moving-to-trash");
6049 /* Lisp function for moving files to trash. */
6050 DEFSYM (Qmove_file_to_trash
, "move-file-to-trash");
6052 /* Lisp function for recursively copying directories. */
6053 DEFSYM (Qcopy_directory
, "copy-directory");
6055 /* Lisp function for recursively deleting directories. */
6056 DEFSYM (Qdelete_directory
, "delete-directory");
6058 DEFSYM (Qsubstitute_env_in_file_name
, "substitute-env-in-file-name");
6059 DEFSYM (Qget_buffer_window_list
, "get-buffer-window-list");
6061 DEFSYM (Qstdin
, "stdin");
6062 DEFSYM (Qstdout
, "stdout");
6063 DEFSYM (Qstderr
, "stderr");
6065 defsubr (&Sfind_file_name_handler
);
6066 defsubr (&Sfile_name_directory
);
6067 defsubr (&Sfile_name_nondirectory
);
6068 defsubr (&Sunhandled_file_name_directory
);
6069 defsubr (&Sfile_name_as_directory
);
6070 defsubr (&Sdirectory_name_p
);
6071 defsubr (&Sdirectory_file_name
);
6072 defsubr (&Smake_temp_file_internal
);
6073 defsubr (&Smake_temp_name
);
6074 defsubr (&Sexpand_file_name
);
6075 defsubr (&Ssubstitute_in_file_name
);
6076 defsubr (&Scopy_file
);
6077 defsubr (&Smake_directory_internal
);
6078 defsubr (&Sdelete_directory_internal
);
6079 defsubr (&Sdelete_file
);
6080 defsubr (&Sfile_name_case_insensitive_p
);
6081 defsubr (&Srename_file
);
6082 defsubr (&Sadd_name_to_file
);
6083 defsubr (&Smake_symbolic_link
);
6084 defsubr (&Sfile_name_absolute_p
);
6085 defsubr (&Sfile_exists_p
);
6086 defsubr (&Sfile_executable_p
);
6087 defsubr (&Sfile_readable_p
);
6088 defsubr (&Sfile_writable_p
);
6089 defsubr (&Saccess_file
);
6090 defsubr (&Sfile_symlink_p
);
6091 defsubr (&Sfile_directory_p
);
6092 defsubr (&Sfile_accessible_directory_p
);
6093 defsubr (&Sfile_regular_p
);
6094 defsubr (&Sfile_modes
);
6095 defsubr (&Sset_file_modes
);
6096 defsubr (&Sset_file_times
);
6097 defsubr (&Sfile_selinux_context
);
6098 defsubr (&Sfile_acl
);
6099 defsubr (&Sset_file_acl
);
6100 defsubr (&Sset_file_selinux_context
);
6101 defsubr (&Sset_default_file_modes
);
6102 defsubr (&Sdefault_file_modes
);
6103 defsubr (&Sfile_newer_than_file_p
);
6104 defsubr (&Sinsert_file_contents
);
6105 defsubr (&Swrite_region
);
6106 defsubr (&Scar_less_than_car
);
6107 defsubr (&Sverify_visited_file_modtime
);
6108 defsubr (&Svisited_file_modtime
);
6109 defsubr (&Sset_visited_file_modtime
);
6110 defsubr (&Sdo_auto_save
);
6111 defsubr (&Sset_buffer_auto_saved
);
6112 defsubr (&Sclear_buffer_auto_save_failure
);
6113 defsubr (&Srecent_auto_save_p
);
6115 defsubr (&Snext_read_file_uses_dialog_p
);
6117 defsubr (&Sset_binary_mode
);
6120 defsubr (&Sunix_sync
);