1 /* File IO for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 #include <sys/types.h>
34 #ifdef HAVE_LIBSELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/context.h>
39 #ifdef HAVE_ACL_SET_FILE
46 #include "intervals.h"
47 #include "character.h"
51 #include "blockinput.h"
52 #include "region-cache.h"
54 #include "dispextern.h"
61 #endif /* not WINDOWSNT */
65 #include <sys/param.h>
69 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
70 redirector allows the six letters between 'Z' and 'a' as well. */
72 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
75 #define IS_DRIVE(x) c_isalpha (x)
77 /* Need to lower-case the drive letter, or else expanded
78 filenames will sometimes compare unequal, because
79 `expand-file-name' doesn't always down-case the drive letter. */
80 #define DRIVE_LETTER(x) c_tolower (x)
85 #include <allocator.h>
86 #include <careadlinkat.h>
87 #include <stat-time.h>
89 #include <binary-io.h>
97 /* True during writing of auto-save files. */
98 static bool auto_saving
;
100 /* Emacs's real umask. */
101 static mode_t realmask
;
103 /* Nonzero umask during creation of auto-save directories. */
104 static mode_t auto_saving_dir_umask
;
106 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
107 a new file with the same mode as the original. */
108 static mode_t auto_save_mode_bits
;
110 /* Set by auto_save_1 if an error occurred during the last auto-save. */
111 static bool auto_save_error_occurred
;
113 /* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
114 number of a file system where time stamps were observed to to work. */
115 static bool valid_timestamp_file_system
;
116 static dev_t timestamp_file_system
;
118 /* Each time an annotation function changes the buffer, the new buffer
120 static Lisp_Object Vwrite_region_annotation_buffers
;
122 static bool a_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
123 Lisp_Object
*, struct coding_system
*);
124 static bool e_write (int, Lisp_Object
, ptrdiff_t, ptrdiff_t,
125 struct coding_system
*);
128 /* Return true if FILENAME exists. */
131 check_existing (const char *filename
)
133 return faccessat (AT_FDCWD
, filename
, F_OK
, AT_EACCESS
) == 0;
136 /* Return true if file FILENAME exists and can be executed. */
139 check_executable (char *filename
)
141 return faccessat (AT_FDCWD
, filename
, X_OK
, AT_EACCESS
) == 0;
144 /* Return true if file FILENAME exists and can be accessed
145 according to AMODE, which should include W_OK.
146 On failure, return false and set errno. */
149 check_writable (const char *filename
, int amode
)
152 /* FIXME: an faccessat implementation should be added to the
153 DOS/Windows ports and this #ifdef branch should be removed. */
155 if (stat (filename
, &st
) < 0)
158 return (st
.st_mode
& S_IWRITE
|| S_ISDIR (st
.st_mode
));
159 #else /* not MSDOS */
160 bool res
= faccessat (AT_FDCWD
, filename
, amode
, AT_EACCESS
) == 0;
162 /* faccessat may have returned failure because Cygwin couldn't
163 determine the file's UID or GID; if so, we return success. */
166 int faccessat_errno
= errno
;
168 if (stat (filename
, &st
) < 0)
170 res
= (st
.st_uid
== -1 || st
.st_gid
== -1);
171 errno
= faccessat_errno
;
175 #endif /* not MSDOS */
178 /* Signal a file-access failure. STRING describes the failure,
179 NAME the file involved, and ERRORNO the errno value.
181 If NAME is neither null nor a pair, package it up as a singleton
182 list before reporting it; this saves report_file_errno's caller the
183 trouble of preserving errno before calling list1. */
186 report_file_errno (char const *string
, Lisp_Object name
, int errorno
)
188 Lisp_Object data
= CONSP (name
) || NILP (name
) ? name
: list1 (name
);
189 synchronize_system_messages_locale ();
190 char *str
= strerror (errorno
);
191 Lisp_Object errstring
192 = code_convert_string_norecord (build_unibyte_string (str
),
193 Vlocale_coding_system
, 0);
194 Lisp_Object errdata
= Fcons (errstring
, data
);
196 if (errorno
== EEXIST
)
197 xsignal (Qfile_already_exists
, errdata
);
199 xsignal (Qfile_error
, Fcons (build_string (string
), errdata
));
202 /* Signal a file-access failure that set errno. STRING describes the
203 failure, NAME the file involved. When invoking this function, take
204 care to not use arguments such as build_string ("foo") that involve
205 side effects that may set errno. */
208 report_file_error (char const *string
, Lisp_Object name
)
210 report_file_errno (string
, name
, errno
);
214 close_file_unwind (int fd
)
220 fclose_unwind (void *arg
)
226 /* Restore point, having saved it as a marker. */
229 restore_point_unwind (Lisp_Object location
)
231 Fgoto_char (location
);
232 unchain_marker (XMARKER (location
));
236 DEFUN ("find-file-name-handler", Ffind_file_name_handler
,
237 Sfind_file_name_handler
, 2, 2, 0,
238 doc
: /* Return FILENAME's handler function for OPERATION, if it has one.
239 Otherwise, return nil.
240 A file name is handled if one of the regular expressions in
241 `file-name-handler-alist' matches it.
243 If OPERATION equals `inhibit-file-name-operation', then we ignore
244 any handlers that are members of `inhibit-file-name-handlers',
245 but we still do run any other handlers. This lets handlers
246 use the standard functions without calling themselves recursively. */)
247 (Lisp_Object filename
, Lisp_Object operation
)
249 /* This function must not munge the match data. */
250 Lisp_Object chain
, inhibited_handlers
, result
;
254 CHECK_STRING (filename
);
256 if (EQ (operation
, Vinhibit_file_name_operation
))
257 inhibited_handlers
= Vinhibit_file_name_handlers
;
259 inhibited_handlers
= Qnil
;
261 for (chain
= Vfile_name_handler_alist
; CONSP (chain
);
262 chain
= XCDR (chain
))
268 Lisp_Object string
= XCAR (elt
);
270 Lisp_Object handler
= XCDR (elt
);
271 Lisp_Object operations
= Qnil
;
273 if (SYMBOLP (handler
))
274 operations
= Fget (handler
, Qoperations
);
277 && (match_pos
= fast_string_match (string
, filename
)) > pos
278 && (NILP (operations
) || ! NILP (Fmemq (operation
, operations
))))
282 handler
= XCDR (elt
);
283 tem
= Fmemq (handler
, inhibited_handlers
);
297 DEFUN ("file-name-directory", Ffile_name_directory
, Sfile_name_directory
,
299 doc
: /* Return the directory component in file name FILENAME.
300 Return nil if FILENAME does not include a directory.
301 Otherwise return a directory name.
302 Given a Unix syntax file name, returns a string ending in slash. */)
303 (Lisp_Object filename
)
307 CHECK_STRING (filename
);
309 /* If the file name has special constructs in it,
310 call the corresponding file handler. */
311 handler
= Ffind_file_name_handler (filename
, Qfile_name_directory
);
314 Lisp_Object handled_name
= call2 (handler
, Qfile_name_directory
,
316 return STRINGP (handled_name
) ? handled_name
: Qnil
;
319 char *beg
= SSDATA (filename
);
320 char const *p
= beg
+ SBYTES (filename
);
322 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
324 /* only recognize drive specifier at the beginning */
326 /* handle the "/:d:foo" and "/:foo" cases correctly */
327 && ((p
== beg
+ 2 && !IS_DIRECTORY_SEP (*beg
))
328 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
335 /* Expansion of "c:" to drive and default directory. */
338 SAFE_ALLOCA_STRING (beg
, filename
);
339 p
= beg
+ (p
- SSDATA (filename
));
343 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
344 char *res
= alloca (MAXPATHLEN
+ 1);
347 if (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
) && beg
[1] == ':')
349 memcpy (res
, beg
, 2);
354 if (getdefdir (c_toupper (*beg
) - 'A' + 1, r
))
356 size_t l
= strlen (res
);
358 if (l
> 3 || !IS_DIRECTORY_SEP (res
[l
- 1]))
361 p
= beg
+ strlen (beg
);
362 dostounix_filename (beg
);
363 tem_fn
= make_specified_string (beg
, -1, p
- beg
,
364 STRING_MULTIBYTE (filename
));
367 tem_fn
= make_specified_string (beg
- 2, -1, p
- beg
+ 2,
368 STRING_MULTIBYTE (filename
));
370 else if (STRING_MULTIBYTE (filename
))
372 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 1);
373 dostounix_filename (SSDATA (tem_fn
));
375 if (!NILP (Vw32_downcase_file_names
))
376 tem_fn
= Fdowncase (tem_fn
);
381 dostounix_filename (beg
);
382 tem_fn
= make_specified_string (beg
, -1, p
- beg
, 0);
387 return make_specified_string (beg
, -1, p
- beg
, STRING_MULTIBYTE (filename
));
391 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory
,
392 Sfile_name_nondirectory
, 1, 1, 0,
393 doc
: /* Return file name FILENAME sans its directory.
394 For example, in a Unix-syntax file name,
395 this is everything after the last slash,
396 or the entire name if it contains no slash. */)
397 (Lisp_Object filename
)
399 register const char *beg
, *p
, *end
;
402 CHECK_STRING (filename
);
404 /* If the file name has special constructs in it,
405 call the corresponding file handler. */
406 handler
= Ffind_file_name_handler (filename
, Qfile_name_nondirectory
);
409 Lisp_Object handled_name
= call2 (handler
, Qfile_name_nondirectory
,
411 if (STRINGP (handled_name
))
413 error ("Invalid handler in `file-name-handler-alist'");
416 beg
= SSDATA (filename
);
417 end
= p
= beg
+ SBYTES (filename
);
419 while (p
!= beg
&& !IS_DIRECTORY_SEP (p
[-1])
421 /* only recognize drive specifier at beginning */
423 /* handle the "/:d:foo" case correctly */
424 && (p
== beg
+ 2 || (p
== beg
+ 4 && IS_DIRECTORY_SEP (*beg
))))
429 return make_specified_string (p
, -1, end
- p
, STRING_MULTIBYTE (filename
));
432 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory
,
433 Sunhandled_file_name_directory
, 1, 1, 0,
434 doc
: /* Return a directly usable directory name somehow associated with FILENAME.
435 A `directly usable' directory name is one that may be used without the
436 intervention of any file handler.
437 If FILENAME is a directly usable file itself, return
438 \(file-name-directory FILENAME).
439 If FILENAME refers to a file which is not accessible from a local process,
440 then this should return nil.
441 The `call-process' and `start-process' functions use this function to
442 get a current directory to run processes in. */)
443 (Lisp_Object filename
)
447 /* If the file name has special constructs in it,
448 call the corresponding file handler. */
449 handler
= Ffind_file_name_handler (filename
, Qunhandled_file_name_directory
);
452 Lisp_Object handled_name
= call2 (handler
, Qunhandled_file_name_directory
,
454 return STRINGP (handled_name
) ? handled_name
: Qnil
;
457 return Ffile_name_directory (filename
);
460 /* Maximum number of bytes that DST will be longer than SRC
461 in file_name_as_directory. This occurs when SRCLEN == 0. */
462 enum { file_name_as_directory_slop
= 2 };
464 /* Convert from file name SRC of length SRCLEN to directory name in
465 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
466 string. On UNIX, just make sure there is a terminating /. Return
467 the length of DST in bytes. */
470 file_name_as_directory (char *dst
, const char *src
, ptrdiff_t srclen
,
481 memcpy (dst
, src
, srclen
);
482 if (!IS_DIRECTORY_SEP (dst
[srclen
- 1]))
483 dst
[srclen
++] = DIRECTORY_SEP
;
486 dostounix_filename (dst
);
491 DEFUN ("file-name-as-directory", Ffile_name_as_directory
,
492 Sfile_name_as_directory
, 1, 1, 0,
493 doc
: /* Return a string representing the file name FILE interpreted as a directory.
494 This operation exists because a directory is also a file, but its name as
495 a directory is different from its name as a file.
496 The result can be used as the value of `default-directory'
497 or passed as second argument to `expand-file-name'.
498 For a Unix-syntax file name, just appends a slash. */)
503 Lisp_Object handler
, val
;
508 /* If the file name has special constructs in it,
509 call the corresponding file handler. */
510 handler
= Ffind_file_name_handler (file
, Qfile_name_as_directory
);
513 Lisp_Object handled_name
= call2 (handler
, Qfile_name_as_directory
,
515 if (STRINGP (handled_name
))
517 error ("Invalid handler in `file-name-handler-alist'");
521 if (!NILP (Vw32_downcase_file_names
))
522 file
= Fdowncase (file
);
524 buf
= SAFE_ALLOCA (SBYTES (file
) + file_name_as_directory_slop
+ 1);
525 length
= file_name_as_directory (buf
, SSDATA (file
), SBYTES (file
),
526 STRING_MULTIBYTE (file
));
527 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (file
));
532 /* Convert from directory name SRC of length SRCLEN to file name in
533 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
534 string. On UNIX, just make sure there isn't a terminating /.
535 Return the length of DST in bytes. */
538 directory_file_name (char *dst
, char *src
, ptrdiff_t srclen
, bool multibyte
)
540 /* Process as Unix format: just remove any final slash.
541 But leave "/" and "//" unchanged. */
544 && !IS_ANY_SEP (src
[srclen
- 2])
546 && IS_DIRECTORY_SEP (src
[srclen
- 1])
547 && ! (srclen
== 2 && IS_DIRECTORY_SEP (src
[0])))
550 memcpy (dst
, src
, srclen
);
553 dostounix_filename (dst
);
558 DEFUN ("directory-file-name", Fdirectory_file_name
, Sdirectory_file_name
,
560 doc
: /* Returns the file name of the directory named DIRECTORY.
561 This is the name of the file that holds the data for the directory DIRECTORY.
562 This operation exists because a directory is also a file, but its name as
563 a directory is different from its name as a file.
564 In Unix-syntax, this function just removes the final slash. */)
565 (Lisp_Object directory
)
569 Lisp_Object handler
, val
;
572 CHECK_STRING (directory
);
574 /* If the file name has special constructs in it,
575 call the corresponding file handler. */
576 handler
= Ffind_file_name_handler (directory
, Qdirectory_file_name
);
579 Lisp_Object handled_name
= call2 (handler
, Qdirectory_file_name
,
581 if (STRINGP (handled_name
))
583 error ("Invalid handler in `file-name-handler-alist'");
587 if (!NILP (Vw32_downcase_file_names
))
588 directory
= Fdowncase (directory
);
590 buf
= SAFE_ALLOCA (SBYTES (directory
) + 1);
591 length
= directory_file_name (buf
, SSDATA (directory
), SBYTES (directory
),
592 STRING_MULTIBYTE (directory
));
593 val
= make_specified_string (buf
, -1, length
, STRING_MULTIBYTE (directory
));
598 static const char make_temp_name_tbl
[64] =
600 'A','B','C','D','E','F','G','H',
601 'I','J','K','L','M','N','O','P',
602 'Q','R','S','T','U','V','W','X',
603 'Y','Z','a','b','c','d','e','f',
604 'g','h','i','j','k','l','m','n',
605 'o','p','q','r','s','t','u','v',
606 'w','x','y','z','0','1','2','3',
607 '4','5','6','7','8','9','-','_'
610 static unsigned make_temp_name_count
, make_temp_name_count_initialized_p
;
612 /* Value is a temporary file name starting with PREFIX, a string.
614 The Emacs process number forms part of the result, so there is
615 no danger of generating a name being used by another process.
616 In addition, this function makes an attempt to choose a name
617 which has no existing file. To make this work, PREFIX should be
618 an absolute file name.
620 BASE64_P means add the pid as 3 characters in base64
621 encoding. In this case, 6 characters will be added to PREFIX to
622 form the file name. Otherwise, if Emacs is running on a system
623 with long file names, add the pid as a decimal number.
625 This function signals an error if no unique file name could be
629 make_temp_name (Lisp_Object prefix
, bool base64_p
)
631 Lisp_Object val
, encoded_prefix
;
635 char pidbuf
[INT_BUFSIZE_BOUND (printmax_t
)];
638 CHECK_STRING (prefix
);
640 /* VAL is created by adding 6 characters to PREFIX. The first
641 three are the PID of this process, in base 64, and the second
642 three are incremented if the file already exists. This ensures
643 262144 unique file names per PID per PREFIX. */
649 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
650 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
651 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
656 #ifdef HAVE_LONG_FILE_NAMES
657 pidlen
= sprintf (pidbuf
, "%"pMd
, pid
);
659 pidbuf
[0] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
660 pidbuf
[1] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
661 pidbuf
[2] = make_temp_name_tbl
[pid
& 63], pid
>>= 6;
666 encoded_prefix
= ENCODE_FILE (prefix
);
667 len
= SBYTES (encoded_prefix
);
668 val
= make_uninit_string (len
+ 3 + pidlen
);
670 memcpy (data
, SSDATA (encoded_prefix
), len
);
673 memcpy (p
, pidbuf
, pidlen
);
676 /* Here we try to minimize useless stat'ing when this function is
677 invoked many times successively with the same PREFIX. We achieve
678 this by initializing count to a random value, and incrementing it
681 We don't want make-temp-name to be called while dumping,
682 because then make_temp_name_count_initialized_p would get set
683 and then make_temp_name_count would not be set when Emacs starts. */
685 if (!make_temp_name_count_initialized_p
)
687 make_temp_name_count
= time (NULL
);
688 make_temp_name_count_initialized_p
= 1;
693 unsigned num
= make_temp_name_count
;
695 p
[0] = make_temp_name_tbl
[num
& 63], num
>>= 6;
696 p
[1] = make_temp_name_tbl
[num
& 63], num
>>= 6;
697 p
[2] = make_temp_name_tbl
[num
& 63], num
>>= 6;
699 /* Poor man's congruential RN generator. Replace with
700 ++make_temp_name_count for debugging. */
701 make_temp_name_count
+= 25229;
702 make_temp_name_count
%= 225307;
704 if (!check_existing (data
))
706 /* We want to return only if errno is ENOENT. */
708 return DECODE_FILE (val
);
710 /* The error here is dubious, but there is little else we
711 can do. The alternatives are to return nil, which is
712 as bad as (and in many cases worse than) throwing the
713 error, or to ignore the error, which will likely result
714 in looping through 225307 stat's, which is not only
715 dog-slow, but also useless since eventually nil would
716 have to be returned anyway. */
717 report_file_error ("Cannot create temporary name for prefix",
725 DEFUN ("make-temp-name", Fmake_temp_name
, Smake_temp_name
, 1, 1, 0,
726 doc
: /* Generate temporary file name (string) starting with PREFIX (a string).
727 The Emacs process number forms part of the result, so there is no
728 danger of generating a name being used by another Emacs process
729 \(so long as only a single host can access the containing directory...).
731 This function tries to choose a name that has no existing file.
732 For this to work, PREFIX should be an absolute file name.
734 There is a race condition between calling `make-temp-name' and creating the
735 file, which opens all kinds of security holes. For that reason, you should
736 normally use `make-temp-file' instead. */)
739 return make_temp_name (prefix
, 0);
742 DEFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
743 doc
: /* Convert filename NAME to absolute, and canonicalize it.
744 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
745 \(does not start with slash or tilde); both the directory name and
746 a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
747 missing, the current buffer's value of `default-directory' is used.
748 NAME should be a string that is a valid file name for the underlying
750 File name components that are `.' are removed, and
751 so are file name components followed by `..', along with the `..' itself;
752 note that these simplifications are done without checking the resulting
753 file names in the file system.
754 Multiple consecutive slashes are collapsed into a single slash,
755 except at the beginning of the file name when they are significant (e.g.,
756 UNC file names on MS-Windows.)
757 An initial `~/' expands to your home directory.
758 An initial `~USER/' expands to USER's home directory.
759 See also the function `substitute-in-file-name'.
761 For technical reasons, this function can return correct but
762 non-intuitive results for the root directory; for instance,
763 \(expand-file-name ".." "/") returns "/..". For this reason, use
764 \(directory-file-name (file-name-directory dirname)) to traverse a
765 filesystem tree, not (expand-file-name ".." dirname). */)
766 (Lisp_Object name
, Lisp_Object default_directory
)
768 /* These point to SDATA and need to be careful with string-relocation
769 during GC (via DECODE_FILE). */
773 const char *newdirlim
;
774 /* This should only point to alloca'd data. */
781 bool collapse_newdir
= true;
784 ptrdiff_t length
, nbytes
;
785 Lisp_Object handler
, result
, handled_name
;
792 /* If the file name has special constructs in it,
793 call the corresponding file handler. */
794 handler
= Ffind_file_name_handler (name
, Qexpand_file_name
);
797 handled_name
= call3 (handler
, Qexpand_file_name
,
798 name
, default_directory
);
799 if (STRINGP (handled_name
))
801 error ("Invalid handler in `file-name-handler-alist'");
805 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
806 if (NILP (default_directory
))
807 default_directory
= BVAR (current_buffer
, directory
);
808 if (! STRINGP (default_directory
))
811 /* "/" is not considered a root directory on DOS_NT, so using "/"
812 here causes an infinite recursion in, e.g., the following:
814 (let (default-directory)
815 (expand-file-name "a"))
817 To avoid this, we set default_directory to the root of the
819 default_directory
= build_string (emacs_root_dir ());
821 default_directory
= build_string ("/");
825 if (!NILP (default_directory
))
827 handler
= Ffind_file_name_handler (default_directory
, Qexpand_file_name
);
830 handled_name
= call3 (handler
, Qexpand_file_name
,
831 name
, default_directory
);
832 if (STRINGP (handled_name
))
834 error ("Invalid handler in `file-name-handler-alist'");
839 char *o
= SSDATA (default_directory
);
841 /* Make sure DEFAULT_DIRECTORY is properly expanded.
842 It would be better to do this down below where we actually use
843 default_directory. Unfortunately, calling Fexpand_file_name recursively
844 could invoke GC, and the strings might be relocated. This would
845 be annoying because we have pointers into strings lying around
846 that would need adjusting, and people would add new pointers to
847 the code and forget to adjust them, resulting in intermittent bugs.
848 Putting this call here avoids all that crud.
850 The EQ test avoids infinite recursion. */
851 if (! NILP (default_directory
) && !EQ (default_directory
, name
)
852 /* Save time in some common cases - as long as default_directory
853 is not relative, it can be canonicalized with name below (if it
854 is needed at all) without requiring it to be expanded now. */
856 /* Detect MSDOS file names with drive specifiers. */
857 && ! (IS_DRIVE (o
[0]) && IS_DEVICE_SEP (o
[1])
858 && IS_DIRECTORY_SEP (o
[2]))
860 /* Detect Windows file names in UNC format. */
861 && ! (IS_DIRECTORY_SEP (o
[0]) && IS_DIRECTORY_SEP (o
[1]))
863 #else /* not DOS_NT */
864 /* Detect Unix absolute file names (/... alone is not absolute on
866 && ! (IS_DIRECTORY_SEP (o
[0]))
867 #endif /* not DOS_NT */
870 default_directory
= Fexpand_file_name (default_directory
, Qnil
);
873 multibyte
= STRING_MULTIBYTE (name
);
874 if (multibyte
!= STRING_MULTIBYTE (default_directory
))
878 unsigned char *p
= SDATA (name
);
880 while (*p
&& ASCII_CHAR_P (*p
))
884 /* NAME is a pure ASCII string, and DEFAULT_DIRECTORY is
885 unibyte. Do not convert DEFAULT_DIRECTORY to
886 multibyte; instead, convert NAME to a unibyte string,
887 so that the result of this function is also a unibyte
888 string. This is needed during bootstrapping and
889 dumping, when Emacs cannot decode file names, because
890 the locale environment is not set up. */
891 name
= make_unibyte_string (SSDATA (name
), SBYTES (name
));
895 default_directory
= string_to_multibyte (default_directory
);
899 name
= string_to_multibyte (name
);
905 if (!NILP (Vw32_downcase_file_names
))
906 default_directory
= Fdowncase (default_directory
);
909 /* Make a local copy of NAME to protect it from GC in DECODE_FILE below. */
910 SAFE_ALLOCA_STRING (nm
, name
);
911 nmlim
= nm
+ SBYTES (name
);
914 /* Note if special escape prefix is present, but remove for now. */
915 if (nm
[0] == '/' && nm
[1] == ':')
921 /* Find and remove drive specifier if present; this makes nm absolute
922 even if the rest of the name appears to be relative. Only look for
923 drive specifier at the beginning. */
924 if (IS_DRIVE (nm
[0]) && IS_DEVICE_SEP (nm
[1]))
926 drive
= (unsigned char) nm
[0];
931 /* If we see "c://somedir", we want to strip the first slash after the
932 colon when stripping the drive letter. Otherwise, this expands to
934 if (drive
&& IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1]))
937 /* Discard any previous drive specifier if nm is now in UNC format. */
938 if (IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
939 && !IS_DIRECTORY_SEP (nm
[2]))
941 #endif /* WINDOWSNT */
944 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
945 none are found, we can probably return right away. We will avoid
946 allocating a new string if name is already fully expanded. */
948 IS_DIRECTORY_SEP (nm
[0])
950 && drive
&& !is_escaped
953 && (drive
|| IS_DIRECTORY_SEP (nm
[1])) && !is_escaped
957 /* If it turns out that the filename we want to return is just a
958 suffix of FILENAME, we don't need to go through and edit
959 things; we just need to construct a new string using data
960 starting at the middle of FILENAME. If we set LOSE, that
961 means we've discovered that we can't do that cool trick. */
967 /* Since we know the name is absolute, we can assume that each
968 element starts with a "/". */
970 /* "." and ".." are hairy. */
971 if (IS_DIRECTORY_SEP (p
[0])
973 && (IS_DIRECTORY_SEP (p
[2])
975 || (p
[2] == '.' && (IS_DIRECTORY_SEP (p
[3])
978 /* Replace multiple slashes with a single one, except
979 leave leading "//" alone. */
980 else if (IS_DIRECTORY_SEP (p
[0])
981 && IS_DIRECTORY_SEP (p
[1])
982 && (p
!= nm
|| IS_DIRECTORY_SEP (p
[2])))
989 /* Make sure directories are all separated with /, but
990 avoid allocation of a new string when not required. */
991 dostounix_filename (nm
);
993 if (IS_DIRECTORY_SEP (nm
[1]))
995 if (strcmp (nm
, SSDATA (name
)) != 0)
996 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1000 /* Drive must be set, so this is okay. */
1001 if (strcmp (nm
- 2, SSDATA (name
)) != 0)
1005 name
= make_specified_string (nm
, -1, p
- nm
, multibyte
);
1006 temp
[0] = DRIVE_LETTER (drive
);
1007 AUTO_STRING (drive_prefix
, temp
);
1008 name
= concat2 (drive_prefix
, name
);
1011 if (!NILP (Vw32_downcase_file_names
))
1012 name
= Fdowncase (name
);
1014 #else /* not DOS_NT */
1015 if (strcmp (nm
, SSDATA (name
)) != 0)
1016 name
= make_specified_string (nm
, -1, nmlim
- nm
, multibyte
);
1017 #endif /* not DOS_NT */
1023 /* At this point, nm might or might not be an absolute file name. We
1024 need to expand ~ or ~user if present, otherwise prefix nm with
1025 default_directory if nm is not absolute, and finally collapse /./
1026 and /foo/../ sequences.
1028 We set newdir to be the appropriate prefix if one is needed:
1029 - the relevant user directory if nm starts with ~ or ~user
1030 - the specified drive's working dir (DOS/NT only) if nm does not
1032 - the value of default_directory.
1034 Note that these prefixes are not guaranteed to be absolute (except
1035 for the working dir of a drive). Therefore, to ensure we always
1036 return an absolute name, if the final prefix is not absolute we
1037 append it to the current working directory. */
1039 newdir
= newdirlim
= 0;
1041 if (nm
[0] == '~') /* prefix ~ */
1043 if (IS_DIRECTORY_SEP (nm
[1])
1044 || nm
[1] == 0) /* ~ by itself */
1048 if (!(newdir
= egetenv ("HOME")))
1049 newdir
= newdirlim
= "";
1051 /* `egetenv' may return a unibyte string, which will bite us since
1052 we expect the directory to be multibyte. */
1056 char newdir_utf8
[MAX_UTF8_PATH
];
1058 filename_from_ansi (newdir
, newdir_utf8
);
1059 tem
= make_unibyte_string (newdir_utf8
, strlen (newdir_utf8
));
1063 tem
= build_string (newdir
);
1064 newdirlim
= newdir
+ SBYTES (tem
);
1065 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1067 hdir
= DECODE_FILE (tem
);
1068 newdir
= SSDATA (hdir
);
1069 newdirlim
= newdir
+ SBYTES (hdir
);
1072 collapse_newdir
= false;
1075 else /* ~user/filename */
1078 for (p
= nm
; *p
&& !IS_DIRECTORY_SEP (*p
); p
++)
1080 o
= SAFE_ALLOCA (p
- nm
+ 1);
1081 memcpy (o
, nm
, p
- nm
);
1085 pw
= getpwnam (o
+ 1);
1091 newdir
= pw
->pw_dir
;
1092 /* `getpwnam' may return a unibyte string, which will
1093 bite us since we expect the directory to be
1095 tem
= make_unibyte_string (newdir
, strlen (newdir
));
1096 newdirlim
= newdir
+ SBYTES (tem
);
1097 if (multibyte
&& !STRING_MULTIBYTE (tem
))
1099 hdir
= DECODE_FILE (tem
);
1100 newdir
= SSDATA (hdir
);
1101 newdirlim
= newdir
+ SBYTES (hdir
);
1105 collapse_newdir
= false;
1109 /* If we don't find a user of that name, leave the name
1110 unchanged; don't move nm forward to p. */
1115 /* On DOS and Windows, nm is absolute if a drive name was specified;
1116 use the drive's current directory as the prefix if needed. */
1117 if (!newdir
&& drive
)
1119 /* Get default directory if needed to make nm absolute. */
1121 if (!IS_DIRECTORY_SEP (nm
[0]))
1123 adir
= alloca (MAXPATHLEN
+ 1);
1124 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1128 Lisp_Object tem
= build_string (adir
);
1130 tem
= DECODE_FILE (tem
);
1131 newdirlim
= adir
+ SBYTES (tem
);
1132 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1135 newdirlim
= adir
+ strlen (adir
);
1139 /* Either nm starts with /, or drive isn't mounted. */
1141 adir
[0] = DRIVE_LETTER (drive
);
1145 newdirlim
= adir
+ 3;
1151 /* Finally, if no prefix has been specified and nm is not absolute,
1152 then it must be expanded relative to default_directory. */
1156 /* /... alone is not absolute on DOS and Windows. */
1157 && !IS_DIRECTORY_SEP (nm
[0])
1160 && !(IS_DIRECTORY_SEP (nm
[0]) && IS_DIRECTORY_SEP (nm
[1])
1161 && !IS_DIRECTORY_SEP (nm
[2]))
1165 newdir
= SSDATA (default_directory
);
1166 newdirlim
= newdir
+ SBYTES (default_directory
);
1168 /* Note if special escape prefix is present, but remove for now. */
1169 if (newdir
[0] == '/' && newdir
[1] == ':')
1180 /* First ensure newdir is an absolute name. */
1182 /* Detect MSDOS file names with drive specifiers. */
1183 ! (IS_DRIVE (newdir
[0])
1184 && IS_DEVICE_SEP (newdir
[1]) && IS_DIRECTORY_SEP (newdir
[2]))
1186 /* Detect Windows file names in UNC format. */
1187 && ! (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1188 && !IS_DIRECTORY_SEP (newdir
[2]))
1192 /* Effectively, let newdir be (expand-file-name newdir cwd).
1193 Because of the admonition against calling expand-file-name
1194 when we have pointers into lisp strings, we accomplish this
1195 indirectly by prepending newdir to nm if necessary, and using
1196 cwd (or the wd of newdir's drive) as the new newdir. */
1199 const int adir_size
= MAX_UTF8_PATH
;
1201 const int adir_size
= MAXPATHLEN
+ 1;
1204 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1206 drive
= (unsigned char) newdir
[0];
1209 if (!IS_DIRECTORY_SEP (nm
[0]))
1211 ptrdiff_t nmlen
= nmlim
- nm
;
1212 ptrdiff_t newdirlen
= newdirlim
- newdir
;
1213 char *tmp
= alloca (newdirlen
+ file_name_as_directory_slop
1215 ptrdiff_t dlen
= file_name_as_directory (tmp
, newdir
, newdirlen
,
1217 memcpy (tmp
+ dlen
, nm
, nmlen
+ 1);
1219 nmlim
= nm
+ dlen
+ nmlen
;
1221 adir
= alloca (adir_size
);
1224 if (!getdefdir (c_toupper (drive
) - 'A' + 1, adir
))
1228 getcwd (adir
, adir_size
);
1231 Lisp_Object tem
= build_string (adir
);
1233 tem
= DECODE_FILE (tem
);
1234 newdirlim
= adir
+ SBYTES (tem
);
1235 memcpy (adir
, SSDATA (tem
), SBYTES (tem
) + 1);
1238 newdirlim
= adir
+ strlen (adir
);
1242 /* Strip off drive name from prefix, if present. */
1243 if (IS_DRIVE (newdir
[0]) && IS_DEVICE_SEP (newdir
[1]))
1249 /* Keep only a prefix from newdir if nm starts with slash
1250 (//server/share for UNC, nothing otherwise). */
1251 if (IS_DIRECTORY_SEP (nm
[0]) && collapse_newdir
)
1254 if (IS_DIRECTORY_SEP (newdir
[0]) && IS_DIRECTORY_SEP (newdir
[1])
1255 && !IS_DIRECTORY_SEP (newdir
[2]))
1257 char *adir
= strcpy (alloca (newdirlim
- newdir
+ 1), newdir
);
1259 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1261 while (*p
&& !IS_DIRECTORY_SEP (*p
)) p
++;
1264 newdirlim
= newdir
+ strlen (adir
);
1268 newdir
= newdirlim
= "";
1273 /* Ignore any slash at the end of newdir, unless newdir is
1274 just "/" or "//". */
1275 length
= newdirlim
- newdir
;
1276 while (length
> 1 && IS_DIRECTORY_SEP (newdir
[length
- 1])
1277 && ! (length
== 2 && IS_DIRECTORY_SEP (newdir
[0])))
1280 /* Now concatenate the directory and name to new space in the stack frame. */
1281 tlen
= length
+ file_name_as_directory_slop
+ (nmlim
- nm
) + 1;
1282 eassert (tlen
> file_name_as_directory_slop
+ 1);
1284 /* Reserve space for drive specifier and escape prefix, since either
1285 or both may need to be inserted. (The Microsoft x86 compiler
1286 produces incorrect code if the following two lines are combined.) */
1287 target
= alloca (tlen
+ 4);
1289 #else /* not DOS_NT */
1290 target
= SAFE_ALLOCA (tlen
);
1291 #endif /* not DOS_NT */
1297 if (nm
[0] == 0 || IS_DIRECTORY_SEP (nm
[0]))
1300 /* If newdir is effectively "C:/", then the drive letter will have
1301 been stripped and newdir will be "/". Concatenating with an
1302 absolute directory in nm produces "//", which will then be
1303 incorrectly treated as a network share. Ignore newdir in
1304 this case (keeping the drive letter). */
1305 if (!(drive
&& nm
[0] && IS_DIRECTORY_SEP (newdir
[0])
1306 && newdir
[1] == '\0'))
1309 memcpy (target
, newdir
, length
);
1315 nbytes
= file_name_as_directory (target
, newdir
, length
, multibyte
);
1318 memcpy (target
+ nbytes
, nm
, nmlim
- nm
+ 1);
1320 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1328 if (!IS_DIRECTORY_SEP (*p
))
1332 else if (p
[1] == '.'
1333 && (IS_DIRECTORY_SEP (p
[2])
1336 /* If "/." is the entire filename, keep the "/". Otherwise,
1337 just delete the whole "/.". */
1338 if (o
== target
&& p
[2] == '\0')
1342 else if (p
[1] == '.' && p
[2] == '.'
1343 /* `/../' is the "superroot" on certain file systems.
1344 Turned off on DOS_NT systems because they have no
1345 "superroot" and because this causes us to produce
1346 file names like "d:/../foo" which fail file-related
1347 functions of the underlying OS. (To reproduce, try a
1348 long series of "../../" in default_directory, longer
1349 than the number of levels from the root.) */
1353 && (IS_DIRECTORY_SEP (p
[3]) || p
[3] == 0))
1358 while (o
!= target
&& (--o
, !IS_DIRECTORY_SEP (*o
)))
1361 /* Don't go below server level in UNC filenames. */
1362 if (o
== target
+ 1 && IS_DIRECTORY_SEP (*o
)
1363 && IS_DIRECTORY_SEP (*target
))
1367 /* Keep initial / only if this is the whole name. */
1368 if (o
== target
&& IS_ANY_SEP (*o
) && p
[3] == 0)
1372 else if (IS_DIRECTORY_SEP (p
[1])
1373 && (p
!= target
|| IS_DIRECTORY_SEP (p
[2])))
1374 /* Collapse multiple "/", except leave leading "//" alone. */
1383 /* At last, set drive name. */
1385 /* Except for network file name. */
1386 if (!(IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1])))
1387 #endif /* WINDOWSNT */
1389 if (!drive
) emacs_abort ();
1391 target
[0] = DRIVE_LETTER (drive
);
1394 /* Reinsert the escape prefix if required. */
1401 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1402 dostounix_filename (SSDATA (result
));
1404 if (!NILP (Vw32_downcase_file_names
))
1405 result
= Fdowncase (result
);
1408 result
= make_specified_string (target
, -1, o
- target
, multibyte
);
1409 #endif /* !DOS_NT */
1412 /* Again look to see if the file name has special constructs in it
1413 and perhaps call the corresponding file handler. This is needed
1414 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1415 the ".." component gives us "/user@host:/bar/../baz" which needs
1416 to be expanded again. */
1417 handler
= Ffind_file_name_handler (result
, Qexpand_file_name
);
1418 if (!NILP (handler
))
1420 handled_name
= call3 (handler
, Qexpand_file_name
,
1421 result
, default_directory
);
1422 if (! STRINGP (handled_name
))
1423 error ("Invalid handler in `file-name-handler-alist'");
1424 result
= handled_name
;
1432 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1433 This is the old version of expand-file-name, before it was thoroughly
1434 rewritten for Emacs 10.31. We leave this version here commented-out,
1435 because the code is very complex and likely to have subtle bugs. If
1436 bugs _are_ found, it might be of interest to look at the old code and
1437 see what did it do in the relevant situation.
1439 Don't remove this code: it's true that it will be accessible
1440 from the repository, but a few years from deletion, people will
1441 forget it is there. */
1443 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1444 DEAFUN ("expand-file-name", Fexpand_file_name
, Sexpand_file_name
, 1, 2, 0,
1445 "Convert FILENAME to absolute, and canonicalize it.\n\
1446 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1447 \(does not start with slash); if DEFAULT is nil or missing,\n\
1448 the current buffer's value of default-directory is used.\n\
1449 Filenames containing `.' or `..' as components are simplified;\n\
1450 initial `~/' expands to your home directory.\n\
1451 See also the function `substitute-in-file-name'.")
1453 Lisp_Object name
, defalt
;
1457 register unsigned char *newdir
, *p
, *o
;
1459 unsigned char *target
;
1462 CHECK_STRING (name
);
1465 /* If nm is absolute, flush ...// and detect /./ and /../.
1466 If no /./ or /../ we can return right away. */
1473 if (p
[0] == '/' && p
[1] == '/')
1475 if (p
[0] == '/' && p
[1] == '~')
1476 nm
= p
+ 1, lose
= 1;
1477 if (p
[0] == '/' && p
[1] == '.'
1478 && (p
[2] == '/' || p
[2] == 0
1479 || (p
[2] == '.' && (p
[3] == '/' || p
[3] == 0))))
1485 if (nm
== SDATA (name
))
1487 return build_string (nm
);
1491 /* Now determine directory to start with and put it in NEWDIR. */
1495 if (nm
[0] == '~') /* prefix ~ */
1496 if (nm
[1] == '/' || nm
[1] == 0)/* ~/filename */
1498 if (!(newdir
= (unsigned char *) egetenv ("HOME")))
1499 newdir
= (unsigned char *) "";
1502 else /* ~user/filename */
1504 /* Get past ~ to user. */
1505 unsigned char *user
= nm
+ 1;
1506 /* Find end of name. */
1507 unsigned char *ptr
= (unsigned char *) strchr (user
, '/');
1508 ptrdiff_t len
= ptr
? ptr
- user
: strlen (user
);
1509 /* Copy the user name into temp storage. */
1510 o
= alloca (len
+ 1);
1511 memcpy (o
, user
, len
);
1514 /* Look up the user name. */
1516 pw
= (struct passwd
*) getpwnam (o
+ 1);
1519 error ("\"%s\" isn't a registered user", o
+ 1);
1521 newdir
= (unsigned char *) pw
->pw_dir
;
1523 /* Discard the user name from NM. */
1527 if (nm
[0] != '/' && !newdir
)
1530 defalt
= current_buffer
->directory
;
1531 CHECK_STRING (defalt
);
1532 newdir
= SDATA (defalt
);
1535 /* Now concatenate the directory and name to new space in the stack frame. */
1537 tlen
= (newdir
? strlen (newdir
) + 1 : 0) + strlen (nm
) + 1;
1538 target
= alloca (tlen
);
1543 if (nm
[0] == 0 || nm
[0] == '/')
1544 strcpy (target
, newdir
);
1546 file_name_as_directory (target
, newdir
);
1549 strcat (target
, nm
);
1551 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1562 else if (!strncmp (p
, "//", 2)
1568 else if (p
[0] == '/' && p
[1] == '.'
1569 && (p
[2] == '/' || p
[2] == 0))
1571 else if (!strncmp (p
, "/..", 3)
1572 /* `/../' is the "superroot" on certain file systems. */
1574 && (p
[3] == '/' || p
[3] == 0))
1576 while (o
!= target
&& *--o
!= '/')
1578 if (o
== target
&& *o
== '/')
1588 return make_string (target
, o
- target
);
1592 /* If /~ or // appears, discard everything through first slash. */
1594 file_name_absolute_p (const char *filename
)
1597 (IS_DIRECTORY_SEP (*filename
) || *filename
== '~'
1599 || (IS_DRIVE (*filename
) && IS_DEVICE_SEP (filename
[1])
1600 && IS_DIRECTORY_SEP (filename
[2]))
1606 search_embedded_absfilename (char *nm
, char *endp
)
1610 for (p
= nm
+ 1; p
< endp
; p
++)
1612 if (IS_DIRECTORY_SEP (p
[-1])
1613 && file_name_absolute_p (p
)
1614 #if defined (WINDOWSNT) || defined (CYGWIN)
1615 /* // at start of file name is meaningful in Apollo,
1616 WindowsNT and Cygwin systems. */
1617 && !(IS_DIRECTORY_SEP (p
[0]) && p
- 1 == nm
)
1618 #endif /* not (WINDOWSNT || CYGWIN) */
1621 for (s
= p
; *s
&& !IS_DIRECTORY_SEP (*s
); s
++);
1622 if (p
[0] == '~' && s
> p
+ 1) /* We've got "/~something/". */
1625 char *o
= SAFE_ALLOCA (s
- p
+ 1);
1627 memcpy (o
, p
, s
- p
);
1630 /* If we have ~user and `user' exists, discard
1631 everything up to ~. But if `user' does not exist, leave
1632 ~user alone, it might be a literal file name. */
1634 pw
= getpwnam (o
+ 1);
1647 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name
,
1648 Ssubstitute_in_file_name
, 1, 1, 0,
1649 doc
: /* Substitute environment variables referred to in FILENAME.
1650 `$FOO' where FOO is an environment variable name means to substitute
1651 the value of that variable. The variable name should be terminated
1652 with a character not a letter, digit or underscore; otherwise, enclose
1653 the entire variable name in braces.
1655 If `/~' appears, all of FILENAME through that `/' is discarded.
1656 If `//' appears, everything up to and including the first of
1657 those `/' is discarded. */)
1658 (Lisp_Object filename
)
1660 char *nm
, *p
, *x
, *endp
;
1661 bool substituted
= false;
1664 Lisp_Object handler
;
1666 CHECK_STRING (filename
);
1668 multibyte
= STRING_MULTIBYTE (filename
);
1670 /* If the file name has special constructs in it,
1671 call the corresponding file handler. */
1672 handler
= Ffind_file_name_handler (filename
, Qsubstitute_in_file_name
);
1673 if (!NILP (handler
))
1675 Lisp_Object handled_name
= call2 (handler
, Qsubstitute_in_file_name
,
1677 if (STRINGP (handled_name
))
1678 return handled_name
;
1679 error ("Invalid handler in `file-name-handler-alist'");
1682 /* Always work on a copy of the string, in case GC happens during
1683 decode of environment variables, causing the original Lisp_String
1684 data to be relocated. */
1686 SAFE_ALLOCA_STRING (nm
, filename
);
1689 dostounix_filename (nm
);
1690 substituted
= (memcmp (nm
, SDATA (filename
), SBYTES (filename
)) != 0);
1692 endp
= nm
+ SBYTES (filename
);
1694 /* If /~ or // appears, discard everything through first slash. */
1695 p
= search_embedded_absfilename (nm
, endp
);
1697 /* Start over with the new string, so we check the file-name-handler
1698 again. Important with filenames like "/home/foo//:/hello///there"
1699 which would substitute to "/:/hello///there" rather than "/there". */
1702 = (Fsubstitute_in_file_name
1703 (make_specified_string (p
, -1, endp
- p
, multibyte
)));
1708 /* See if any variables are substituted into the string. */
1710 if (!NILP (Ffboundp (Qsubstitute_env_in_file_name
)))
1713 = (!substituted
? filename
1714 : make_specified_string (nm
, -1, endp
- nm
, multibyte
));
1715 Lisp_Object tmp
= call1 (Qsubstitute_env_in_file_name
, name
);
1717 if (!EQ (tmp
, name
))
1725 if (!NILP (Vw32_downcase_file_names
))
1726 filename
= Fdowncase (filename
);
1732 xnm
= SSDATA (filename
);
1733 x
= xnm
+ SBYTES (filename
);
1735 /* If /~ or // appears, discard everything through first slash. */
1736 while ((p
= search_embedded_absfilename (xnm
, x
)) != NULL
)
1737 /* This time we do not start over because we've already expanded envvars
1738 and replaced $$ with $. Maybe we should start over as well, but we'd
1739 need to quote some $ to $$ first. */
1743 if (!NILP (Vw32_downcase_file_names
))
1745 Lisp_Object xname
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1747 filename
= Fdowncase (xname
);
1751 if (xnm
!= SSDATA (filename
))
1752 filename
= make_specified_string (xnm
, -1, x
- xnm
, multibyte
);
1757 /* A slightly faster and more convenient way to get
1758 (directory-file-name (expand-file-name FOO)). */
1761 expand_and_dir_to_file (Lisp_Object filename
, Lisp_Object defdir
)
1763 register Lisp_Object absname
;
1765 absname
= Fexpand_file_name (filename
, defdir
);
1767 /* Remove final slash, if any (unless this is the root dir).
1768 stat behaves differently depending! */
1769 if (SCHARS (absname
) > 1
1770 && IS_DIRECTORY_SEP (SREF (absname
, SBYTES (absname
) - 1))
1771 && !IS_DEVICE_SEP (SREF (absname
, SBYTES (absname
) - 2)))
1772 /* We cannot take shortcuts; they might be wrong for magic file names. */
1773 absname
= Fdirectory_file_name (absname
);
1777 /* Signal an error if the file ABSNAME already exists.
1778 If KNOWN_TO_EXIST, the file is known to exist.
1779 QUERYSTRING is a name for the action that is being considered
1781 If INTERACTIVE, ask the user whether to proceed,
1782 and bypass the error if the user says to go ahead.
1783 If QUICK, ask for y or n, not yes or no. */
1786 barf_or_query_if_file_exists (Lisp_Object absname
, bool known_to_exist
,
1787 const char *querystring
, bool interactive
,
1790 Lisp_Object tem
, encoded_filename
;
1791 struct stat statbuf
;
1793 encoded_filename
= ENCODE_FILE (absname
);
1795 if (! known_to_exist
&& lstat (SSDATA (encoded_filename
), &statbuf
) == 0)
1797 if (S_ISDIR (statbuf
.st_mode
))
1798 xsignal2 (Qfile_error
,
1799 build_string ("File is a directory"), absname
);
1800 known_to_exist
= true;
1806 xsignal2 (Qfile_already_exists
,
1807 build_string ("File already exists"), absname
);
1808 AUTO_STRING (format
, "File %s already exists; %s anyway? ");
1809 tem
= CALLN (Fformat
, format
, absname
, build_string (querystring
));
1811 tem
= call1 (intern ("y-or-n-p"), tem
);
1813 tem
= do_yes_or_no_p (tem
);
1815 xsignal2 (Qfile_already_exists
,
1816 build_string ("File already exists"), absname
);
1820 DEFUN ("copy-file", Fcopy_file
, Scopy_file
, 2, 6,
1821 "fCopy file: \nGCopy %s to file: \np\nP",
1822 doc
: /* Copy FILE to NEWNAME. Both args must be strings.
1823 If NEWNAME names a directory, copy FILE there.
1825 This function always sets the file modes of the output file to match
1828 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1829 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1830 signal a `file-already-exists' error without overwriting. If
1831 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1832 about overwriting; this is what happens in interactive use with M-x.
1833 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1836 Fourth arg KEEP-TIME non-nil means give the output file the same
1837 last-modified time as the old one. (This works on only some systems.)
1839 A prefix arg makes KEEP-TIME non-nil.
1841 If PRESERVE-UID-GID is non-nil, we try to transfer the
1842 uid and gid of FILE to NEWNAME.
1844 If PRESERVE-PERMISSIONS is non-nil, copy permissions of FILE to NEWNAME;
1845 this includes the file modes, along with ACL entries and SELinux
1846 context if present. Otherwise, if NEWNAME is created its file
1847 permission bits are those of FILE, masked by the default file
1849 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
,
1850 Lisp_Object keep_time
, Lisp_Object preserve_uid_gid
,
1851 Lisp_Object preserve_permissions
)
1853 Lisp_Object handler
;
1854 ptrdiff_t count
= SPECPDL_INDEX ();
1855 Lisp_Object encoded_file
, encoded_newname
;
1857 security_context_t con
;
1863 bool already_exists
= false;
1869 encoded_file
= encoded_newname
= Qnil
;
1870 CHECK_STRING (file
);
1871 CHECK_STRING (newname
);
1873 if (!NILP (Ffile_directory_p (newname
)))
1874 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
1876 newname
= Fexpand_file_name (newname
, Qnil
);
1878 file
= Fexpand_file_name (file
, Qnil
);
1880 /* If the input file name has special constructs in it,
1881 call the corresponding file handler. */
1882 handler
= Ffind_file_name_handler (file
, Qcopy_file
);
1883 /* Likewise for output file name. */
1885 handler
= Ffind_file_name_handler (newname
, Qcopy_file
);
1886 if (!NILP (handler
))
1887 return call7 (handler
, Qcopy_file
, file
, newname
,
1888 ok_if_already_exists
, keep_time
, preserve_uid_gid
,
1889 preserve_permissions
);
1891 encoded_file
= ENCODE_FILE (file
);
1892 encoded_newname
= ENCODE_FILE (newname
);
1895 if (NILP (ok_if_already_exists
)
1896 || INTEGERP (ok_if_already_exists
))
1897 barf_or_query_if_file_exists (newname
, false, "copy to it",
1898 INTEGERP (ok_if_already_exists
), false);
1900 result
= w32_copy_file (SSDATA (encoded_file
), SSDATA (encoded_newname
),
1901 !NILP (keep_time
), !NILP (preserve_uid_gid
),
1902 !NILP (preserve_permissions
));
1906 report_file_error ("Copying file", list2 (file
, newname
));
1908 report_file_error ("Copying permissions from", file
);
1910 xsignal2 (Qfile_date_error
,
1911 build_string ("Resetting file times"), newname
);
1913 report_file_error ("Copying permissions to", newname
);
1915 #else /* not WINDOWSNT */
1917 ifd
= emacs_open (SSDATA (encoded_file
), O_RDONLY
, 0);
1921 report_file_error ("Opening input file", file
);
1923 record_unwind_protect_int (close_file_unwind
, ifd
);
1925 if (fstat (ifd
, &st
) != 0)
1926 report_file_error ("Input file status", file
);
1928 if (!NILP (preserve_permissions
))
1931 if (is_selinux_enabled ())
1933 conlength
= fgetfilecon (ifd
, &con
);
1934 if (conlength
== -1)
1935 report_file_error ("Doing fgetfilecon", file
);
1940 /* We can copy only regular files. */
1941 if (!S_ISREG (st
.st_mode
))
1942 report_file_errno ("Non-regular file", file
,
1943 S_ISDIR (st
.st_mode
) ? EISDIR
: EINVAL
);
1946 new_mask
= st
.st_mode
& (!NILP (preserve_uid_gid
) ? 0700 : 0777);
1948 new_mask
= S_IREAD
| S_IWRITE
;
1951 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
| O_CREAT
| O_EXCL
,
1953 if (ofd
< 0 && errno
== EEXIST
)
1955 if (NILP (ok_if_already_exists
) || INTEGERP (ok_if_already_exists
))
1956 barf_or_query_if_file_exists (newname
, true, "copy to it",
1957 INTEGERP (ok_if_already_exists
), false);
1958 already_exists
= true;
1959 ofd
= emacs_open (SSDATA (encoded_newname
), O_WRONLY
, 0);
1962 report_file_error ("Opening output file", newname
);
1964 record_unwind_protect_int (close_file_unwind
, ofd
);
1966 off_t oldsize
= 0, newsize
= 0;
1971 if (fstat (ofd
, &out_st
) != 0)
1972 report_file_error ("Output file status", newname
);
1973 if (st
.st_dev
== out_st
.st_dev
&& st
.st_ino
== out_st
.st_ino
)
1974 report_file_errno ("Input and output files are the same",
1975 list2 (file
, newname
), 0);
1976 if (S_ISREG (out_st
.st_mode
))
1977 oldsize
= out_st
.st_size
;
1984 char buf
[MAX_ALLOCA
];
1985 ptrdiff_t n
= emacs_read (ifd
, buf
, sizeof buf
);
1987 report_file_error ("Read error", file
);
1990 if (emacs_write_sig (ofd
, buf
, n
) != n
)
1991 report_file_error ("Write error", newname
);
1995 /* Truncate any existing output file after writing the data. This
1996 is more likely to work than truncation before writing, if the
1997 file system is out of space or the user is over disk quota. */
1998 if (newsize
< oldsize
&& ftruncate (ofd
, newsize
) != 0)
1999 report_file_error ("Truncating output file", newname
);
2004 /* Preserve the original file permissions, and if requested, also its
2007 mode_t preserved_permissions
= st
.st_mode
& 07777;
2008 mode_t default_permissions
= st
.st_mode
& 0777 & ~realmask
;
2009 if (!NILP (preserve_uid_gid
))
2011 /* Attempt to change owner and group. If that doesn't work
2012 attempt to change just the group, as that is sometimes allowed.
2013 Adjust the mode mask to eliminate setuid or setgid bits
2014 or group permissions bits that are inappropriate if the
2015 owner or group are wrong. */
2016 if (fchown (ofd
, st
.st_uid
, st
.st_gid
) != 0)
2018 if (fchown (ofd
, -1, st
.st_gid
) == 0)
2019 preserved_permissions
&= ~04000;
2022 preserved_permissions
&= ~06000;
2024 /* Copy the other bits to the group bits, since the
2026 preserved_permissions
&= ~070;
2027 preserved_permissions
|= (preserved_permissions
& 7) << 3;
2028 default_permissions
&= ~070;
2029 default_permissions
|= (default_permissions
& 7) << 3;
2034 switch (!NILP (preserve_permissions
)
2035 ? qcopy_acl (SSDATA (encoded_file
), ifd
,
2036 SSDATA (encoded_newname
), ofd
,
2037 preserved_permissions
)
2039 || (new_mask
& ~realmask
) == default_permissions
)
2041 : fchmod (ofd
, default_permissions
))
2043 case -2: report_file_error ("Copying permissions from", file
);
2044 case -1: report_file_error ("Copying permissions to", newname
);
2047 #endif /* not MSDOS */
2052 /* Set the modified context back to the file. */
2053 bool fail
= fsetfilecon (ofd
, con
) != 0;
2054 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2055 if (fail
&& errno
!= ENOTSUP
)
2056 report_file_error ("Doing fsetfilecon", newname
);
2062 if (!NILP (keep_time
))
2064 struct timespec atime
= get_stat_atime (&st
);
2065 struct timespec mtime
= get_stat_mtime (&st
);
2066 if (set_file_times (ofd
, SSDATA (encoded_newname
), atime
, mtime
) != 0)
2067 xsignal2 (Qfile_date_error
,
2068 build_string ("Cannot set file date"), newname
);
2071 if (emacs_close (ofd
) < 0)
2072 report_file_error ("Write error", newname
);
2077 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2078 and if it can't, it tells so. Otherwise, under MSDOS we usually
2079 get only the READ bit, which will make the copied file read-only,
2080 so it's better not to chmod at all. */
2081 if ((_djstat_flags
& _STFAIL_WRITEBIT
) == 0)
2082 chmod (SDATA (encoded_newname
), st
.st_mode
& 07777);
2084 #endif /* not WINDOWSNT */
2086 /* Discard the unwind protects. */
2087 specpdl_ptr
= specpdl
+ count
;
2092 DEFUN ("make-directory-internal", Fmake_directory_internal
,
2093 Smake_directory_internal
, 1, 1, 0,
2094 doc
: /* Create a new directory named DIRECTORY. */)
2095 (Lisp_Object directory
)
2098 Lisp_Object handler
;
2099 Lisp_Object encoded_dir
;
2101 CHECK_STRING (directory
);
2102 directory
= Fexpand_file_name (directory
, Qnil
);
2104 handler
= Ffind_file_name_handler (directory
, Qmake_directory_internal
);
2105 if (!NILP (handler
))
2106 return call2 (handler
, Qmake_directory_internal
, directory
);
2108 encoded_dir
= ENCODE_FILE (directory
);
2110 dir
= SSDATA (encoded_dir
);
2113 if (mkdir (dir
) != 0)
2115 if (mkdir (dir
, 0777 & ~auto_saving_dir_umask
) != 0)
2117 report_file_error ("Creating directory", directory
);
2122 DEFUN ("delete-directory-internal", Fdelete_directory_internal
,
2123 Sdelete_directory_internal
, 1, 1, 0,
2124 doc
: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2125 (Lisp_Object directory
)
2128 Lisp_Object encoded_dir
;
2130 CHECK_STRING (directory
);
2131 directory
= Fdirectory_file_name (Fexpand_file_name (directory
, Qnil
));
2132 encoded_dir
= ENCODE_FILE (directory
);
2133 dir
= SSDATA (encoded_dir
);
2135 if (rmdir (dir
) != 0)
2136 report_file_error ("Removing directory", directory
);
2141 DEFUN ("delete-file", Fdelete_file
, Sdelete_file
, 1, 2,
2142 "(list (read-file-name \
2143 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2144 \"Move file to trash: \" \"Delete file: \") \
2145 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2146 (null current-prefix-arg))",
2147 doc
: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2148 If file has multiple names, it continues to exist with the other names.
2149 TRASH non-nil means to trash the file instead of deleting, provided
2150 `delete-by-moving-to-trash' is non-nil.
2152 When called interactively, TRASH is t if no prefix argument is given.
2153 With a prefix argument, TRASH is nil. */)
2154 (Lisp_Object filename
, Lisp_Object trash
)
2156 Lisp_Object handler
;
2157 Lisp_Object encoded_file
;
2159 if (!NILP (Ffile_directory_p (filename
))
2160 && NILP (Ffile_symlink_p (filename
)))
2161 xsignal2 (Qfile_error
,
2162 build_string ("Removing old name: is a directory"),
2164 filename
= Fexpand_file_name (filename
, Qnil
);
2166 handler
= Ffind_file_name_handler (filename
, Qdelete_file
);
2167 if (!NILP (handler
))
2168 return call3 (handler
, Qdelete_file
, filename
, trash
);
2170 if (delete_by_moving_to_trash
&& !NILP (trash
))
2171 return call1 (Qmove_file_to_trash
, filename
);
2173 encoded_file
= ENCODE_FILE (filename
);
2175 if (unlink (SSDATA (encoded_file
)) < 0)
2176 report_file_error ("Removing old name", filename
);
2181 internal_delete_file_1 (Lisp_Object ignore
)
2186 /* Delete file FILENAME, returning true if successful.
2187 This ignores `delete-by-moving-to-trash'. */
2190 internal_delete_file (Lisp_Object filename
)
2194 tem
= internal_condition_case_2 (Fdelete_file
, filename
, Qnil
,
2195 Qt
, internal_delete_file_1
);
2199 DEFUN ("rename-file", Frename_file
, Srename_file
, 2, 3,
2200 "fRename file: \nGRename %s to file: \np",
2201 doc
: /* Rename FILE as NEWNAME. Both args must be strings.
2202 If file has names other than FILE, it continues to have those names.
2203 Signals a `file-already-exists' error if a file NEWNAME already exists
2204 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2205 A number as third arg means request confirmation if NEWNAME already exists.
2206 This is what happens in interactive use with M-x. */)
2207 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2209 Lisp_Object handler
;
2210 Lisp_Object encoded_file
, encoded_newname
, symlink_target
;
2212 symlink_target
= encoded_file
= encoded_newname
= Qnil
;
2213 CHECK_STRING (file
);
2214 CHECK_STRING (newname
);
2215 file
= Fexpand_file_name (file
, Qnil
);
2217 if ((!NILP (Ffile_directory_p (newname
)))
2219 /* If the file names are identical but for the case,
2220 don't attempt to move directory to itself. */
2221 && (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2225 Lisp_Object fname
= (NILP (Ffile_directory_p (file
))
2226 ? file
: Fdirectory_file_name (file
));
2227 newname
= Fexpand_file_name (Ffile_name_nondirectory (fname
), newname
);
2230 newname
= Fexpand_file_name (newname
, Qnil
);
2232 /* If the file name has special constructs in it,
2233 call the corresponding file handler. */
2234 handler
= Ffind_file_name_handler (file
, Qrename_file
);
2236 handler
= Ffind_file_name_handler (newname
, Qrename_file
);
2237 if (!NILP (handler
))
2238 return call4 (handler
, Qrename_file
,
2239 file
, newname
, ok_if_already_exists
);
2241 encoded_file
= ENCODE_FILE (file
);
2242 encoded_newname
= ENCODE_FILE (newname
);
2245 /* If the file names are identical but for the case, don't ask for
2246 confirmation: they simply want to change the letter-case of the
2248 if (NILP (Fstring_equal (Fdowncase (file
), Fdowncase (newname
))))
2250 if (NILP (ok_if_already_exists
)
2251 || INTEGERP (ok_if_already_exists
))
2252 barf_or_query_if_file_exists (newname
, false, "rename to it",
2253 INTEGERP (ok_if_already_exists
), false);
2254 if (rename (SSDATA (encoded_file
), SSDATA (encoded_newname
)) < 0)
2256 int rename_errno
= errno
;
2257 if (rename_errno
== EXDEV
)
2260 symlink_target
= Ffile_symlink_p (file
);
2261 if (! NILP (symlink_target
))
2262 Fmake_symbolic_link (symlink_target
, newname
,
2263 NILP (ok_if_already_exists
) ? Qnil
: Qt
);
2264 else if (!NILP (Ffile_directory_p (file
)))
2265 call4 (Qcopy_directory
, file
, newname
, Qt
, Qnil
);
2267 /* We have already prompted if it was an integer, so don't
2268 have copy-file prompt again. */
2269 Fcopy_file (file
, newname
,
2270 NILP (ok_if_already_exists
) ? Qnil
: Qt
,
2273 count
= SPECPDL_INDEX ();
2274 specbind (Qdelete_by_moving_to_trash
, Qnil
);
2276 if (!NILP (Ffile_directory_p (file
)) && NILP (symlink_target
))
2277 call2 (Qdelete_directory
, file
, Qt
);
2279 Fdelete_file (file
, Qnil
);
2280 unbind_to (count
, Qnil
);
2283 report_file_errno ("Renaming", list2 (file
, newname
), rename_errno
);
2289 DEFUN ("add-name-to-file", Fadd_name_to_file
, Sadd_name_to_file
, 2, 3,
2290 "fAdd name to file: \nGName to add to %s: \np",
2291 doc
: /* Give FILE additional name NEWNAME. Both args must be strings.
2292 Signals a `file-already-exists' error if a file NEWNAME already exists
2293 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2294 A number as third arg means request confirmation if NEWNAME already exists.
2295 This is what happens in interactive use with M-x. */)
2296 (Lisp_Object file
, Lisp_Object newname
, Lisp_Object ok_if_already_exists
)
2298 Lisp_Object handler
;
2299 Lisp_Object encoded_file
, encoded_newname
;
2301 encoded_file
= encoded_newname
= Qnil
;
2302 CHECK_STRING (file
);
2303 CHECK_STRING (newname
);
2304 file
= Fexpand_file_name (file
, Qnil
);
2306 if (!NILP (Ffile_directory_p (newname
)))
2307 newname
= Fexpand_file_name (Ffile_name_nondirectory (file
), newname
);
2309 newname
= Fexpand_file_name (newname
, Qnil
);
2311 /* If the file name has special constructs in it,
2312 call the corresponding file handler. */
2313 handler
= Ffind_file_name_handler (file
, Qadd_name_to_file
);
2314 if (!NILP (handler
))
2315 return call4 (handler
, Qadd_name_to_file
, file
,
2316 newname
, ok_if_already_exists
);
2318 /* If the new name has special constructs in it,
2319 call the corresponding file handler. */
2320 handler
= Ffind_file_name_handler (newname
, Qadd_name_to_file
);
2321 if (!NILP (handler
))
2322 return call4 (handler
, Qadd_name_to_file
, file
,
2323 newname
, ok_if_already_exists
);
2325 encoded_file
= ENCODE_FILE (file
);
2326 encoded_newname
= ENCODE_FILE (newname
);
2328 if (NILP (ok_if_already_exists
)
2329 || INTEGERP (ok_if_already_exists
))
2330 barf_or_query_if_file_exists (newname
, false, "make it a new name",
2331 INTEGERP (ok_if_already_exists
), false);
2333 unlink (SSDATA (newname
));
2334 if (link (SSDATA (encoded_file
), SSDATA (encoded_newname
)) < 0)
2336 int link_errno
= errno
;
2337 report_file_errno ("Adding new name", list2 (file
, newname
), link_errno
);
2343 DEFUN ("make-symbolic-link", Fmake_symbolic_link
, Smake_symbolic_link
, 2, 3,
2344 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2345 doc
: /* Make a symbolic link to TARGET, named LINKNAME.
2346 Both args must be strings.
2347 Signals a `file-already-exists' error if a file LINKNAME already exists
2348 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2349 A number as third arg means request confirmation if LINKNAME already exists.
2350 This happens for interactive use with M-x. */)
2351 (Lisp_Object target
, Lisp_Object linkname
, Lisp_Object ok_if_already_exists
)
2353 Lisp_Object handler
;
2354 Lisp_Object encoded_target
, encoded_linkname
;
2356 encoded_target
= encoded_linkname
= Qnil
;
2357 CHECK_STRING (target
);
2358 CHECK_STRING (linkname
);
2359 /* If the link target has a ~, we must expand it to get
2360 a truly valid file name. Otherwise, do not expand;
2361 we want to permit links to relative file names. */
2362 if (SREF (target
, 0) == '~')
2363 target
= Fexpand_file_name (target
, Qnil
);
2365 if (!NILP (Ffile_directory_p (linkname
)))
2366 linkname
= Fexpand_file_name (Ffile_name_nondirectory (target
), linkname
);
2368 linkname
= Fexpand_file_name (linkname
, Qnil
);
2370 /* If the file name has special constructs in it,
2371 call the corresponding file handler. */
2372 handler
= Ffind_file_name_handler (target
, Qmake_symbolic_link
);
2373 if (!NILP (handler
))
2374 return call4 (handler
, Qmake_symbolic_link
, target
,
2375 linkname
, ok_if_already_exists
);
2377 /* If the new link name has special constructs in it,
2378 call the corresponding file handler. */
2379 handler
= Ffind_file_name_handler (linkname
, Qmake_symbolic_link
);
2380 if (!NILP (handler
))
2381 return call4 (handler
, Qmake_symbolic_link
, target
,
2382 linkname
, ok_if_already_exists
);
2384 encoded_target
= ENCODE_FILE (target
);
2385 encoded_linkname
= ENCODE_FILE (linkname
);
2387 if (NILP (ok_if_already_exists
)
2388 || INTEGERP (ok_if_already_exists
))
2389 barf_or_query_if_file_exists (linkname
, false, "make it a link",
2390 INTEGERP (ok_if_already_exists
), false);
2391 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
)) < 0)
2393 /* If we didn't complain already, silently delete existing file. */
2395 if (errno
== EEXIST
)
2397 unlink (SSDATA (encoded_linkname
));
2398 if (symlink (SSDATA (encoded_target
), SSDATA (encoded_linkname
))
2402 if (errno
== ENOSYS
)
2403 xsignal1 (Qfile_error
,
2404 build_string ("Symbolic links are not supported"));
2406 symlink_errno
= errno
;
2407 report_file_errno ("Making symbolic link", list2 (target
, linkname
),
2415 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p
, Sfile_name_absolute_p
,
2417 doc
: /* Return t if file FILENAME specifies an absolute file name.
2418 On Unix, this is a name starting with a `/' or a `~'. */)
2419 (Lisp_Object filename
)
2421 CHECK_STRING (filename
);
2422 return file_name_absolute_p (SSDATA (filename
)) ? Qt
: Qnil
;
2425 DEFUN ("file-exists-p", Ffile_exists_p
, Sfile_exists_p
, 1, 1, 0,
2426 doc
: /* Return t if file FILENAME exists (whether or not you can read it.)
2427 See also `file-readable-p' and `file-attributes'.
2428 This returns nil for a symlink to a nonexistent file.
2429 Use `file-symlink-p' to test for such links. */)
2430 (Lisp_Object filename
)
2432 Lisp_Object absname
;
2433 Lisp_Object handler
;
2435 CHECK_STRING (filename
);
2436 absname
= Fexpand_file_name (filename
, Qnil
);
2438 /* If the file name has special constructs in it,
2439 call the corresponding file handler. */
2440 handler
= Ffind_file_name_handler (absname
, Qfile_exists_p
);
2441 if (!NILP (handler
))
2443 Lisp_Object result
= call2 (handler
, Qfile_exists_p
, absname
);
2448 absname
= ENCODE_FILE (absname
);
2450 return check_existing (SSDATA (absname
)) ? Qt
: Qnil
;
2453 DEFUN ("file-executable-p", Ffile_executable_p
, Sfile_executable_p
, 1, 1, 0,
2454 doc
: /* Return t if FILENAME can be executed by you.
2455 For a directory, this means you can access files in that directory.
2456 \(It is generally better to use `file-accessible-directory-p' for that
2457 purpose, though.) */)
2458 (Lisp_Object filename
)
2460 Lisp_Object absname
;
2461 Lisp_Object handler
;
2463 CHECK_STRING (filename
);
2464 absname
= Fexpand_file_name (filename
, Qnil
);
2466 /* If the file name has special constructs in it,
2467 call the corresponding file handler. */
2468 handler
= Ffind_file_name_handler (absname
, Qfile_executable_p
);
2469 if (!NILP (handler
))
2470 return call2 (handler
, Qfile_executable_p
, absname
);
2472 absname
= ENCODE_FILE (absname
);
2474 return (check_executable (SSDATA (absname
)) ? Qt
: Qnil
);
2477 DEFUN ("file-readable-p", Ffile_readable_p
, Sfile_readable_p
, 1, 1, 0,
2478 doc
: /* Return t if file FILENAME exists and you can read it.
2479 See also `file-exists-p' and `file-attributes'. */)
2480 (Lisp_Object filename
)
2482 Lisp_Object absname
;
2483 Lisp_Object handler
;
2485 CHECK_STRING (filename
);
2486 absname
= Fexpand_file_name (filename
, Qnil
);
2488 /* If the file name has special constructs in it,
2489 call the corresponding file handler. */
2490 handler
= Ffind_file_name_handler (absname
, Qfile_readable_p
);
2491 if (!NILP (handler
))
2492 return call2 (handler
, Qfile_readable_p
, absname
);
2494 absname
= ENCODE_FILE (absname
);
2495 return (faccessat (AT_FDCWD
, SSDATA (absname
), R_OK
, AT_EACCESS
) == 0
2499 DEFUN ("file-writable-p", Ffile_writable_p
, Sfile_writable_p
, 1, 1, 0,
2500 doc
: /* Return t if file FILENAME can be written or created by you. */)
2501 (Lisp_Object filename
)
2503 Lisp_Object absname
, dir
, encoded
;
2504 Lisp_Object handler
;
2506 CHECK_STRING (filename
);
2507 absname
= Fexpand_file_name (filename
, Qnil
);
2509 /* If the file name has special constructs in it,
2510 call the corresponding file handler. */
2511 handler
= Ffind_file_name_handler (absname
, Qfile_writable_p
);
2512 if (!NILP (handler
))
2513 return call2 (handler
, Qfile_writable_p
, absname
);
2515 encoded
= ENCODE_FILE (absname
);
2516 if (check_writable (SSDATA (encoded
), W_OK
))
2518 if (errno
!= ENOENT
)
2521 dir
= Ffile_name_directory (absname
);
2522 eassert (!NILP (dir
));
2524 dir
= Fdirectory_file_name (dir
);
2527 dir
= ENCODE_FILE (dir
);
2529 /* The read-only attribute of the parent directory doesn't affect
2530 whether a file or directory can be created within it. Some day we
2531 should check ACLs though, which do affect this. */
2532 return file_directory_p (SDATA (dir
)) ? Qt
: Qnil
;
2534 return check_writable (SSDATA (dir
), W_OK
| X_OK
) ? Qt
: Qnil
;
2538 DEFUN ("access-file", Faccess_file
, Saccess_file
, 2, 2, 0,
2539 doc
: /* Access file FILENAME, and get an error if that does not work.
2540 The second argument STRING is used in the error message.
2541 If there is no error, returns nil. */)
2542 (Lisp_Object filename
, Lisp_Object string
)
2544 Lisp_Object handler
, encoded_filename
, absname
;
2546 CHECK_STRING (filename
);
2547 absname
= Fexpand_file_name (filename
, Qnil
);
2549 CHECK_STRING (string
);
2551 /* If the file name has special constructs in it,
2552 call the corresponding file handler. */
2553 handler
= Ffind_file_name_handler (absname
, Qaccess_file
);
2554 if (!NILP (handler
))
2555 return call3 (handler
, Qaccess_file
, absname
, string
);
2557 encoded_filename
= ENCODE_FILE (absname
);
2559 if (faccessat (AT_FDCWD
, SSDATA (encoded_filename
), R_OK
, AT_EACCESS
) != 0)
2560 report_file_error (SSDATA (string
), filename
);
2565 /* Relative to directory FD, return the symbolic link value of FILENAME.
2566 On failure, return nil. */
2568 emacs_readlinkat (int fd
, char const *filename
)
2570 static struct allocator
const emacs_norealloc_allocator
=
2571 { xmalloc
, NULL
, xfree
, memory_full
};
2573 char readlink_buf
[1024];
2574 char *buf
= careadlinkat (fd
, filename
, readlink_buf
, sizeof readlink_buf
,
2575 &emacs_norealloc_allocator
, readlinkat
);
2579 val
= build_unibyte_string (buf
);
2580 if (buf
[0] == '/' && strchr (buf
, ':'))
2582 AUTO_STRING (slash_colon
, "/:");
2583 val
= concat2 (slash_colon
, val
);
2585 if (buf
!= readlink_buf
)
2587 val
= DECODE_FILE (val
);
2591 DEFUN ("file-symlink-p", Ffile_symlink_p
, Sfile_symlink_p
, 1, 1, 0,
2592 doc
: /* Return non-nil if file FILENAME is the name of a symbolic link.
2593 The value is the link target, as a string.
2594 Otherwise it returns nil.
2596 This function does not check whether the link target exists. */)
2597 (Lisp_Object filename
)
2599 Lisp_Object handler
;
2601 CHECK_STRING (filename
);
2602 filename
= Fexpand_file_name (filename
, Qnil
);
2604 /* If the file name has special constructs in it,
2605 call the corresponding file handler. */
2606 handler
= Ffind_file_name_handler (filename
, Qfile_symlink_p
);
2607 if (!NILP (handler
))
2608 return call2 (handler
, Qfile_symlink_p
, filename
);
2610 filename
= ENCODE_FILE (filename
);
2612 return emacs_readlinkat (AT_FDCWD
, SSDATA (filename
));
2615 DEFUN ("file-directory-p", Ffile_directory_p
, Sfile_directory_p
, 1, 1, 0,
2616 doc
: /* Return t if FILENAME names an existing directory.
2617 Symbolic links to directories count as directories.
2618 See `file-symlink-p' to distinguish symlinks. */)
2619 (Lisp_Object filename
)
2621 Lisp_Object absname
;
2622 Lisp_Object handler
;
2624 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2626 /* If the file name has special constructs in it,
2627 call the corresponding file handler. */
2628 handler
= Ffind_file_name_handler (absname
, Qfile_directory_p
);
2629 if (!NILP (handler
))
2630 return call2 (handler
, Qfile_directory_p
, absname
);
2632 absname
= ENCODE_FILE (absname
);
2634 return file_directory_p (SSDATA (absname
)) ? Qt
: Qnil
;
2637 /* Return true if FILE is a directory or a symlink to a directory. */
2639 file_directory_p (char const *file
)
2642 /* This is cheaper than 'stat'. */
2643 return faccessat (AT_FDCWD
, file
, D_OK
, AT_EACCESS
) == 0;
2646 return stat (file
, &st
) == 0 && S_ISDIR (st
.st_mode
);
2650 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p
,
2651 Sfile_accessible_directory_p
, 1, 1, 0,
2652 doc
: /* Return t if file FILENAME names a directory you can open.
2653 For the value to be t, FILENAME must specify the name of a directory as a file,
2654 and the directory must allow you to open files in it. In order to use a
2655 directory as a buffer's current directory, this predicate must return true.
2656 A directory name spec may be given instead; then the value is t
2657 if the directory so specified exists and really is a readable and
2658 searchable directory.
2660 The result might be a false positive on MS-Windows in some rare cases,
2661 i.e., this function could return t for a directory that is not
2662 accessible by the current user. */)
2663 (Lisp_Object filename
)
2665 Lisp_Object absname
;
2666 Lisp_Object handler
;
2668 CHECK_STRING (filename
);
2669 absname
= Fexpand_file_name (filename
, Qnil
);
2671 /* If the file name has special constructs in it,
2672 call the corresponding file handler. */
2673 handler
= Ffind_file_name_handler (absname
, Qfile_accessible_directory_p
);
2674 if (!NILP (handler
))
2676 Lisp_Object r
= call2 (handler
, Qfile_accessible_directory_p
, absname
);
2681 absname
= ENCODE_FILE (absname
);
2682 return file_accessible_directory_p (absname
) ? Qt
: Qnil
;
2685 /* If FILE is a searchable directory or a symlink to a
2686 searchable directory, return true. Otherwise return
2687 false and set errno to an error number. */
2689 file_accessible_directory_p (Lisp_Object file
)
2692 /* There's no need to test whether FILE is searchable, as the
2693 searchable/executable bit is invented on DOS_NT platforms. */
2694 return file_directory_p (SSDATA (file
));
2696 /* On POSIXish platforms, use just one system call; this avoids a
2697 race and is typically faster. */
2698 const char *data
= SSDATA (file
);
2699 ptrdiff_t len
= SBYTES (file
);
2705 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2706 There are three exceptions: "", "/", and "//". Leave "" alone,
2707 as it's invalid. Append only "." to the other two exceptions as
2708 "/" and "//" are distinct on some platforms, whereas "/", "///",
2709 "////", etc. are all equivalent. */
2714 /* Just check for trailing '/' when deciding whether to append '/'.
2715 That's simpler than testing the two special cases "/" and "//",
2716 and it's a safe optimization here. */
2717 char *buf
= SAFE_ALLOCA (len
+ 3);
2718 memcpy (buf
, data
, len
);
2719 strcpy (buf
+ len
, &"/."[data
[len
- 1] == '/']);
2723 ok
= check_existing (dir
);
2724 saved_errno
= errno
;
2726 errno
= saved_errno
;
2731 DEFUN ("file-regular-p", Ffile_regular_p
, Sfile_regular_p
, 1, 1, 0,
2732 doc
: /* Return t if FILENAME names a regular file.
2733 This is the sort of file that holds an ordinary stream of data bytes.
2734 Symbolic links to regular files count as regular files.
2735 See `file-symlink-p' to distinguish symlinks. */)
2736 (Lisp_Object filename
)
2738 register Lisp_Object absname
;
2740 Lisp_Object handler
;
2742 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2744 /* If the file name has special constructs in it,
2745 call the corresponding file handler. */
2746 handler
= Ffind_file_name_handler (absname
, Qfile_regular_p
);
2747 if (!NILP (handler
))
2748 return call2 (handler
, Qfile_regular_p
, absname
);
2750 absname
= ENCODE_FILE (absname
);
2755 Lisp_Object tem
= Vw32_get_true_file_attributes
;
2757 /* Tell stat to use expensive method to get accurate info. */
2758 Vw32_get_true_file_attributes
= Qt
;
2759 result
= stat (SDATA (absname
), &st
);
2760 Vw32_get_true_file_attributes
= tem
;
2764 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2767 if (stat (SSDATA (absname
), &st
) < 0)
2769 return S_ISREG (st
.st_mode
) ? Qt
: Qnil
;
2773 DEFUN ("file-selinux-context", Ffile_selinux_context
,
2774 Sfile_selinux_context
, 1, 1, 0,
2775 doc
: /* Return SELinux context of file named FILENAME.
2776 The return value is a list (USER ROLE TYPE RANGE), where the list
2777 elements are strings naming the user, role, type, and range of the
2778 file's SELinux security context.
2780 Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2781 or if SELinux is disabled, or if Emacs lacks SELinux support. */)
2782 (Lisp_Object filename
)
2784 Lisp_Object absname
;
2785 Lisp_Object user
= Qnil
, role
= Qnil
, type
= Qnil
, range
= Qnil
;
2787 Lisp_Object handler
;
2789 security_context_t con
;
2794 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
2796 /* If the file name has special constructs in it,
2797 call the corresponding file handler. */
2798 handler
= Ffind_file_name_handler (absname
, Qfile_selinux_context
);
2799 if (!NILP (handler
))
2800 return call2 (handler
, Qfile_selinux_context
, absname
);
2802 absname
= ENCODE_FILE (absname
);
2805 if (is_selinux_enabled ())
2807 conlength
= lgetfilecon (SSDATA (absname
), &con
);
2810 context
= context_new (con
);
2811 if (context_user_get (context
))
2812 user
= build_string (context_user_get (context
));
2813 if (context_role_get (context
))
2814 role
= build_string (context_role_get (context
));
2815 if (context_type_get (context
))
2816 type
= build_string (context_type_get (context
));
2817 if (context_range_get (context
))
2818 range
= build_string (context_range_get (context
));
2819 context_free (context
);
2825 return list4 (user
, role
, type
, range
);
2828 DEFUN ("set-file-selinux-context", Fset_file_selinux_context
,
2829 Sset_file_selinux_context
, 2, 2, 0,
2830 doc
: /* Set SELinux context of file named FILENAME to CONTEXT.
2831 CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
2832 elements are strings naming the components of a SELinux context.
2834 Value is t if setting of SELinux context was successful, nil otherwise.
2836 This function does nothing and returns nil if SELinux is disabled,
2837 or if Emacs was not compiled with SELinux support. */)
2838 (Lisp_Object filename
, Lisp_Object context
)
2840 Lisp_Object absname
;
2841 Lisp_Object handler
;
2843 Lisp_Object encoded_absname
;
2844 Lisp_Object user
= CAR_SAFE (context
);
2845 Lisp_Object role
= CAR_SAFE (CDR_SAFE (context
));
2846 Lisp_Object type
= CAR_SAFE (CDR_SAFE (CDR_SAFE (context
)));
2847 Lisp_Object range
= CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context
))));
2848 security_context_t con
;
2851 context_t parsed_con
;
2854 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2856 /* If the file name has special constructs in it,
2857 call the corresponding file handler. */
2858 handler
= Ffind_file_name_handler (absname
, Qset_file_selinux_context
);
2859 if (!NILP (handler
))
2860 return call3 (handler
, Qset_file_selinux_context
, absname
, context
);
2863 if (is_selinux_enabled ())
2865 /* Get current file context. */
2866 encoded_absname
= ENCODE_FILE (absname
);
2867 conlength
= lgetfilecon (SSDATA (encoded_absname
), &con
);
2870 parsed_con
= context_new (con
);
2871 /* Change the parts defined in the parameter.*/
2874 if (context_user_set (parsed_con
, SSDATA (user
)))
2875 error ("Doing context_user_set");
2879 if (context_role_set (parsed_con
, SSDATA (role
)))
2880 error ("Doing context_role_set");
2884 if (context_type_set (parsed_con
, SSDATA (type
)))
2885 error ("Doing context_type_set");
2887 if (STRINGP (range
))
2889 if (context_range_set (parsed_con
, SSDATA (range
)))
2890 error ("Doing context_range_set");
2893 /* Set the modified context back to the file. */
2894 fail
= (lsetfilecon (SSDATA (encoded_absname
),
2895 context_str (parsed_con
))
2897 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2898 if (fail
&& errno
!= ENOTSUP
)
2899 report_file_error ("Doing lsetfilecon", absname
);
2901 context_free (parsed_con
);
2903 return fail
? Qnil
: Qt
;
2906 report_file_error ("Doing lgetfilecon", absname
);
2913 DEFUN ("file-acl", Ffile_acl
, Sfile_acl
, 1, 1, 0,
2914 doc
: /* Return ACL entries of file named FILENAME.
2915 The entries are returned in a format suitable for use in `set-file-acl'
2916 but is otherwise undocumented and subject to change.
2917 Return nil if file does not exist or is not accessible, or if Emacs
2918 was unable to determine the ACL entries. */)
2919 (Lisp_Object filename
)
2921 Lisp_Object absname
;
2922 Lisp_Object handler
;
2923 #ifdef HAVE_ACL_SET_FILE
2925 Lisp_Object acl_string
;
2927 # ifndef HAVE_ACL_TYPE_EXTENDED
2928 acl_type_t ACL_TYPE_EXTENDED
= ACL_TYPE_ACCESS
;
2932 absname
= expand_and_dir_to_file (filename
,
2933 BVAR (current_buffer
, directory
));
2935 /* If the file name has special constructs in it,
2936 call the corresponding file handler. */
2937 handler
= Ffind_file_name_handler (absname
, Qfile_acl
);
2938 if (!NILP (handler
))
2939 return call2 (handler
, Qfile_acl
, absname
);
2941 #ifdef HAVE_ACL_SET_FILE
2942 absname
= ENCODE_FILE (absname
);
2944 acl
= acl_get_file (SSDATA (absname
), ACL_TYPE_EXTENDED
);
2948 str
= acl_to_text (acl
, NULL
);
2955 acl_string
= build_string (str
);
2965 DEFUN ("set-file-acl", Fset_file_acl
, Sset_file_acl
,
2967 doc
: /* Set ACL of file named FILENAME to ACL-STRING.
2968 ACL-STRING should contain the textual representation of the ACL
2969 entries in a format suitable for the platform.
2971 Value is t if setting of ACL was successful, nil otherwise.
2973 Setting ACL for local files requires Emacs to be built with ACL
2975 (Lisp_Object filename
, Lisp_Object acl_string
)
2977 Lisp_Object absname
;
2978 Lisp_Object handler
;
2979 #ifdef HAVE_ACL_SET_FILE
2980 Lisp_Object encoded_absname
;
2985 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
2987 /* If the file name has special constructs in it,
2988 call the corresponding file handler. */
2989 handler
= Ffind_file_name_handler (absname
, Qset_file_acl
);
2990 if (!NILP (handler
))
2991 return call3 (handler
, Qset_file_acl
, absname
, acl_string
);
2993 #ifdef HAVE_ACL_SET_FILE
2994 if (STRINGP (acl_string
))
2996 acl
= acl_from_text (SSDATA (acl_string
));
2999 report_file_error ("Converting ACL", absname
);
3003 encoded_absname
= ENCODE_FILE (absname
);
3005 fail
= (acl_set_file (SSDATA (encoded_absname
), ACL_TYPE_ACCESS
,
3008 if (fail
&& acl_errno_valid (errno
))
3009 report_file_error ("Setting ACL", absname
);
3012 return fail
? Qnil
: Qt
;
3019 DEFUN ("file-modes", Ffile_modes
, Sfile_modes
, 1, 1, 0,
3020 doc
: /* Return mode bits of file named FILENAME, as an integer.
3021 Return nil, if file does not exist or is not accessible. */)
3022 (Lisp_Object filename
)
3024 Lisp_Object absname
;
3026 Lisp_Object handler
;
3028 absname
= expand_and_dir_to_file (filename
, BVAR (current_buffer
, directory
));
3030 /* If the file name has special constructs in it,
3031 call the corresponding file handler. */
3032 handler
= Ffind_file_name_handler (absname
, Qfile_modes
);
3033 if (!NILP (handler
))
3034 return call2 (handler
, Qfile_modes
, absname
);
3036 absname
= ENCODE_FILE (absname
);
3038 if (stat (SSDATA (absname
), &st
) < 0)
3041 return make_number (st
.st_mode
& 07777);
3044 DEFUN ("set-file-modes", Fset_file_modes
, Sset_file_modes
, 2, 2,
3045 "(let ((file (read-file-name \"File: \"))) \
3046 (list file (read-file-modes nil file)))",
3047 doc
: /* Set mode bits of file named FILENAME to MODE (an integer).
3048 Only the 12 low bits of MODE are used.
3050 Interactively, mode bits are read by `read-file-modes', which accepts
3051 symbolic notation, like the `chmod' command from GNU Coreutils. */)
3052 (Lisp_Object filename
, Lisp_Object mode
)
3054 Lisp_Object absname
, encoded_absname
;
3055 Lisp_Object handler
;
3057 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3058 CHECK_NUMBER (mode
);
3060 /* If the file name has special constructs in it,
3061 call the corresponding file handler. */
3062 handler
= Ffind_file_name_handler (absname
, Qset_file_modes
);
3063 if (!NILP (handler
))
3064 return call3 (handler
, Qset_file_modes
, absname
, mode
);
3066 encoded_absname
= ENCODE_FILE (absname
);
3068 if (chmod (SSDATA (encoded_absname
), XINT (mode
) & 07777) < 0)
3069 report_file_error ("Doing chmod", absname
);
3074 DEFUN ("set-default-file-modes", Fset_default_file_modes
, Sset_default_file_modes
, 1, 1, 0,
3075 doc
: /* Set the file permission bits for newly created files.
3076 The argument MODE should be an integer; only the low 9 bits are used.
3077 This setting is inherited by subprocesses. */)
3080 mode_t oldrealmask
, oldumask
, newumask
;
3081 CHECK_NUMBER (mode
);
3082 oldrealmask
= realmask
;
3083 newumask
= ~ XINT (mode
) & 0777;
3086 realmask
= newumask
;
3087 oldumask
= umask (newumask
);
3090 eassert (oldumask
== oldrealmask
);
3094 DEFUN ("default-file-modes", Fdefault_file_modes
, Sdefault_file_modes
, 0, 0, 0,
3095 doc
: /* Return the default file protection for created files.
3096 The value is an integer. */)
3100 XSETINT (value
, (~ realmask
) & 0777);
3105 DEFUN ("set-file-times", Fset_file_times
, Sset_file_times
, 1, 2, 0,
3106 doc
: /* Set times of file FILENAME to TIMESTAMP.
3107 Set both access and modification times.
3108 Return t on success, else nil.
3109 Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
3111 (Lisp_Object filename
, Lisp_Object timestamp
)
3113 Lisp_Object absname
, encoded_absname
;
3114 Lisp_Object handler
;
3115 struct timespec t
= lisp_time_argument (timestamp
);
3117 absname
= Fexpand_file_name (filename
, BVAR (current_buffer
, directory
));
3119 /* If the file name has special constructs in it,
3120 call the corresponding file handler. */
3121 handler
= Ffind_file_name_handler (absname
, Qset_file_times
);
3122 if (!NILP (handler
))
3123 return call3 (handler
, Qset_file_times
, absname
, timestamp
);
3125 encoded_absname
= ENCODE_FILE (absname
);
3128 if (set_file_times (-1, SSDATA (encoded_absname
), t
, t
) != 0)
3131 /* Setting times on a directory always fails. */
3132 if (file_directory_p (SSDATA (encoded_absname
)))
3135 report_file_error ("Setting file times", absname
);
3143 DEFUN ("unix-sync", Funix_sync
, Sunix_sync
, 0, 0, "",
3144 doc
: /* Tell Unix to finish all pending disk updates. */)
3151 #endif /* HAVE_SYNC */
3153 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p
, Sfile_newer_than_file_p
, 2, 2, 0,
3154 doc
: /* Return t if file FILE1 is newer than file FILE2.
3155 If FILE1 does not exist, the answer is nil;
3156 otherwise, if FILE2 does not exist, the answer is t. */)
3157 (Lisp_Object file1
, Lisp_Object file2
)
3159 Lisp_Object absname1
, absname2
;
3160 struct stat st1
, st2
;
3161 Lisp_Object handler
;
3163 CHECK_STRING (file1
);
3164 CHECK_STRING (file2
);
3167 absname1
= expand_and_dir_to_file (file1
, BVAR (current_buffer
, directory
));
3168 absname2
= expand_and_dir_to_file (file2
, BVAR (current_buffer
, directory
));
3170 /* If the file name has special constructs in it,
3171 call the corresponding file handler. */
3172 handler
= Ffind_file_name_handler (absname1
, Qfile_newer_than_file_p
);
3174 handler
= Ffind_file_name_handler (absname2
, Qfile_newer_than_file_p
);
3175 if (!NILP (handler
))
3176 return call3 (handler
, Qfile_newer_than_file_p
, absname1
, absname2
);
3178 absname1
= ENCODE_FILE (absname1
);
3179 absname2
= ENCODE_FILE (absname2
);
3181 if (stat (SSDATA (absname1
), &st1
) < 0)
3184 if (stat (SSDATA (absname2
), &st2
) < 0)
3187 return (timespec_cmp (get_stat_mtime (&st2
), get_stat_mtime (&st1
)) < 0
3191 #ifndef READ_BUF_SIZE
3192 #define READ_BUF_SIZE (64 << 10)
3194 /* Some buffer offsets are stored in 'int' variables. */
3195 verify (READ_BUF_SIZE
<= INT_MAX
);
3197 /* This function is called after Lisp functions to decide a coding
3198 system are called, or when they cause an error. Before they are
3199 called, the current buffer is set unibyte and it contains only a
3200 newly inserted text (thus the buffer was empty before the
3203 The functions may set markers, overlays, text properties, or even
3204 alter the buffer contents, change the current buffer.
3206 Here, we reset all those changes by:
3207 o set back the current buffer.
3208 o move all markers and overlays to BEG.
3209 o remove all text properties.
3210 o set back the buffer multibyteness. */
3213 decide_coding_unwind (Lisp_Object unwind_data
)
3215 Lisp_Object multibyte
, undo_list
, buffer
;
3217 multibyte
= XCAR (unwind_data
);
3218 unwind_data
= XCDR (unwind_data
);
3219 undo_list
= XCAR (unwind_data
);
3220 buffer
= XCDR (unwind_data
);
3222 set_buffer_internal (XBUFFER (buffer
));
3223 adjust_markers_for_delete (BEG
, BEG_BYTE
, Z
, Z_BYTE
);
3224 adjust_overlays_for_delete (BEG
, Z
- BEG
);
3225 set_buffer_intervals (current_buffer
, NULL
);
3226 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3228 /* Now we are safe to change the buffer's multibyteness directly. */
3229 bset_enable_multibyte_characters (current_buffer
, multibyte
);
3230 bset_undo_list (current_buffer
, undo_list
);
3233 /* Read from a non-regular file. STATE is a Lisp_Save_Value
3234 object where slot 0 is the file descriptor, slot 1 specifies
3235 an offset to put the read bytes, and slot 2 is the maximum
3236 amount of bytes to read. Value is the number of bytes read. */
3239 read_non_regular (Lisp_Object state
)
3245 nbytes
= emacs_read (XSAVE_INTEGER (state
, 0),
3246 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
3247 + XSAVE_INTEGER (state
, 1)),
3248 XSAVE_INTEGER (state
, 2));
3250 /* Fast recycle this object for the likely next call. */
3252 return make_number (nbytes
);
3256 /* Condition-case handler used when reading from non-regular files
3257 in insert-file-contents. */
3260 read_non_regular_quit (Lisp_Object ignore
)
3265 /* Return the file offset that VAL represents, checking for type
3266 errors and overflow. */
3268 file_offset (Lisp_Object val
)
3270 if (RANGED_INTEGERP (0, val
, TYPE_MAXIMUM (off_t
)))
3275 double v
= XFLOAT_DATA (val
);
3277 && (sizeof (off_t
) < sizeof v
3278 ? v
<= TYPE_MAXIMUM (off_t
)
3279 : v
< TYPE_MAXIMUM (off_t
)))
3283 wrong_type_argument (intern ("file-offset"), val
);
3286 /* Return a special time value indicating the error number ERRNUM. */
3287 static struct timespec
3288 time_error_value (int errnum
)
3290 int ns
= (errnum
== ENOENT
|| errnum
== EACCES
|| errnum
== ENOTDIR
3291 ? NONEXISTENT_MODTIME_NSECS
3292 : UNKNOWN_MODTIME_NSECS
);
3293 return make_timespec (0, ns
);
3297 get_window_points_and_markers (void)
3299 Lisp_Object pt_marker
= Fpoint_marker ();
3301 = call3 (Qget_buffer_window_list
, Fcurrent_buffer (), Qnil
, Qt
);
3302 Lisp_Object window_markers
= windows
;
3303 /* Window markers (and point) are handled specially: rather than move to
3304 just before or just after the modified text, we try to keep the
3305 markers at the same distance (bug#19161).
3306 In general, this is wrong, but for window-markers, this should be harmless
3307 and is convenient for the end user when most of the file is unmodified,
3308 except for a few minor details near the beginning and near the end. */
3309 for (; CONSP (windows
); windows
= XCDR (windows
))
3310 if (WINDOWP (XCAR (windows
)))
3312 Lisp_Object window_marker
= XWINDOW (XCAR (windows
))->pointm
;
3314 Fcons (window_marker
, Fmarker_position (window_marker
)));
3316 return Fcons (Fcons (pt_marker
, Fpoint ()), window_markers
);
3320 restore_window_points (Lisp_Object window_markers
, ptrdiff_t inserted
,
3321 ptrdiff_t same_at_start
, ptrdiff_t same_at_end
)
3323 for (; CONSP (window_markers
); window_markers
= XCDR (window_markers
))
3324 if (CONSP (XCAR (window_markers
)))
3326 Lisp_Object car
= XCAR (window_markers
);
3327 Lisp_Object marker
= XCAR (car
);
3328 Lisp_Object oldpos
= XCDR (car
);
3329 if (MARKERP (marker
) && INTEGERP (oldpos
)
3330 && XINT (oldpos
) > same_at_start
3331 && XINT (oldpos
) < same_at_end
)
3333 ptrdiff_t oldsize
= same_at_end
- same_at_start
;
3334 ptrdiff_t newsize
= inserted
;
3335 double growth
= newsize
/ (double)oldsize
;
3337 = same_at_start
+ growth
* (XINT (oldpos
) - same_at_start
);
3338 Fset_marker (marker
, make_number (newpos
), Qnil
);
3343 /* FIXME: insert-file-contents should be split with the top-level moved to
3344 Elisp and only the core kept in C. */
3346 DEFUN ("insert-file-contents", Finsert_file_contents
, Sinsert_file_contents
,
3348 doc
: /* Insert contents of file FILENAME after point.
3349 Returns list of absolute file name and number of characters inserted.
3350 If second argument VISIT is non-nil, the buffer's visited filename and
3351 last save file modtime are set, and it is marked unmodified. If
3352 visiting and the file does not exist, visiting is completed before the
3355 The optional third and fourth arguments BEG and END specify what portion
3356 of the file to insert. These arguments count bytes in the file, not
3357 characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3359 If optional fifth argument REPLACE is non-nil, replace the current
3360 buffer contents (in the accessible portion) with the file contents.
3361 This is better than simply deleting and inserting the whole thing
3362 because (1) it preserves some marker positions and (2) it puts less data
3363 in the undo list. When REPLACE is non-nil, the second return value is
3364 the number of characters that replace previous buffer contents.
3366 This function does code conversion according to the value of
3367 `coding-system-for-read' or `file-coding-system-alist', and sets the
3368 variable `last-coding-system-used' to the coding system actually used.
3370 In addition, this function decodes the inserted text from known formats
3371 by calling `format-decode', which see. */)
3372 (Lisp_Object filename
, Lisp_Object visit
, Lisp_Object beg
, Lisp_Object end
, Lisp_Object replace
)
3375 struct timespec mtime
;
3377 ptrdiff_t inserted
= 0;
3379 off_t beg_offset
, end_offset
;
3381 ptrdiff_t count
= SPECPDL_INDEX ();
3382 Lisp_Object handler
, val
, insval
, orig_filename
, old_undo
;
3384 ptrdiff_t total
= 0;
3385 bool not_regular
= 0;
3387 char read_buf
[READ_BUF_SIZE
];
3388 struct coding_system coding
;
3389 bool replace_handled
= false;
3390 bool set_coding_system
= false;
3391 Lisp_Object coding_system
;
3392 bool read_quit
= false;
3393 /* If the undo log only contains the insertion, there's no point
3394 keeping it. It's typically when we first fill a file-buffer. */
3395 bool empty_undo_list_p
3396 = (!NILP (visit
) && NILP (BVAR (current_buffer
, undo_list
))
3398 Lisp_Object old_Vdeactivate_mark
= Vdeactivate_mark
;
3399 bool we_locked_file
= false;
3401 Lisp_Object window_markers
= Qnil
;
3402 /* same_at_start and same_at_end count bytes, because file access counts
3403 bytes and BEG and END count bytes. */
3404 ptrdiff_t same_at_start
= BEGV_BYTE
;
3405 ptrdiff_t same_at_end
= ZV_BYTE
;
3406 /* SAME_AT_END_CHARPOS counts characters, because
3407 restore_window_points needs the old character count. */
3408 ptrdiff_t same_at_end_charpos
= ZV
;
3410 if (current_buffer
->base_buffer
&& ! NILP (visit
))
3411 error ("Cannot do file visiting in an indirect buffer");
3413 if (!NILP (BVAR (current_buffer
, read_only
)))
3414 Fbarf_if_buffer_read_only (Qnil
);
3418 orig_filename
= Qnil
;
3421 CHECK_STRING (filename
);
3422 filename
= Fexpand_file_name (filename
, Qnil
);
3424 /* The value Qnil means that the coding system is not yet
3426 coding_system
= Qnil
;
3428 /* If the file name has special constructs in it,
3429 call the corresponding file handler. */
3430 handler
= Ffind_file_name_handler (filename
, Qinsert_file_contents
);
3431 if (!NILP (handler
))
3433 val
= call6 (handler
, Qinsert_file_contents
, filename
,
3434 visit
, beg
, end
, replace
);
3435 if (CONSP (val
) && CONSP (XCDR (val
))
3436 && RANGED_INTEGERP (0, XCAR (XCDR (val
)), ZV
- PT
))
3437 inserted
= XINT (XCAR (XCDR (val
)));
3441 orig_filename
= filename
;
3442 filename
= ENCODE_FILE (filename
);
3444 fd
= emacs_open (SSDATA (filename
), O_RDONLY
, 0);
3449 report_file_error ("Opening input file", orig_filename
);
3450 mtime
= time_error_value (save_errno
);
3452 if (!NILP (Vcoding_system_for_read
))
3453 Fset (Qbuffer_file_coding_system
, Vcoding_system_for_read
);
3457 fd_index
= SPECPDL_INDEX ();
3458 record_unwind_protect_int (close_file_unwind
, fd
);
3460 /* Replacement should preserve point as it preserves markers. */
3461 if (!NILP (replace
))
3463 window_markers
= get_window_points_and_markers ();
3464 record_unwind_protect (restore_point_unwind
,
3465 XCAR (XCAR (window_markers
)));
3468 if (fstat (fd
, &st
) != 0)
3469 report_file_error ("Input file status", orig_filename
);
3470 mtime
= get_stat_mtime (&st
);
3472 /* This code will need to be changed in order to work on named
3473 pipes, and it's probably just not worth it. So we should at
3474 least signal an error. */
3475 if (!S_ISREG (st
.st_mode
))
3482 if (! NILP (replace
) || ! NILP (beg
) || ! NILP (end
))
3483 xsignal2 (Qfile_error
,
3484 build_string ("not a regular file"), orig_filename
);
3489 if (!NILP (beg
) || !NILP (end
))
3490 error ("Attempt to visit less than an entire file");
3491 if (BEG
< Z
&& NILP (replace
))
3492 error ("Cannot do file visiting in a non-empty buffer");
3496 beg_offset
= file_offset (beg
);
3501 end_offset
= file_offset (end
);
3505 end_offset
= TYPE_MAXIMUM (off_t
);
3508 end_offset
= st
.st_size
;
3510 /* A negative size can happen on a platform that allows file
3511 sizes greater than the maximum off_t value. */
3515 /* The file size returned from stat may be zero, but data
3516 may be readable nonetheless, for example when this is a
3517 file in the /proc filesystem. */
3518 if (end_offset
== 0)
3519 end_offset
= READ_BUF_SIZE
;
3523 /* Check now whether the buffer will become too large,
3524 in the likely case where the file's length is not changing.
3525 This saves a lot of needless work before a buffer overflow. */
3528 /* The likely offset where we will stop reading. We could read
3529 more (or less), if the file grows (or shrinks) as we read it. */
3530 off_t likely_end
= min (end_offset
, st
.st_size
);
3532 if (beg_offset
< likely_end
)
3535 = Z_BYTE
- (!NILP (replace
) ? ZV_BYTE
- BEGV_BYTE
: 0);
3536 ptrdiff_t buf_growth_max
= BUF_BYTES_MAX
- buf_bytes
;
3537 off_t likely_growth
= likely_end
- beg_offset
;
3538 if (buf_growth_max
< likely_growth
)
3543 /* Prevent redisplay optimizations. */
3544 current_buffer
->clip_changed
= true;
3546 if (EQ (Vcoding_system_for_read
, Qauto_save_coding
))
3548 coding_system
= coding_inherit_eol_type (Qutf_8_emacs
, Qunix
);
3549 setup_coding_system (coding_system
, &coding
);
3550 /* Ensure we set Vlast_coding_system_used. */
3551 set_coding_system
= true;
3555 /* Decide the coding system to use for reading the file now
3556 because we can't use an optimized method for handling
3557 `coding:' tag if the current buffer is not empty. */
3558 if (!NILP (Vcoding_system_for_read
))
3559 coding_system
= Vcoding_system_for_read
;
3562 /* Don't try looking inside a file for a coding system
3563 specification if it is not seekable. */
3564 if (! not_regular
&& ! NILP (Vset_auto_coding_function
))
3566 /* Find a coding system specified in the heading two
3567 lines or in the tailing several lines of the file.
3568 We assume that the 1K-byte and 3K-byte for heading
3569 and tailing respectively are sufficient for this
3573 if (st
.st_size
<= (1024 * 4))
3574 nread
= emacs_read (fd
, read_buf
, 1024 * 4);
3577 nread
= emacs_read (fd
, read_buf
, 1024);
3581 if (lseek (fd
, - (1024 * 3), SEEK_END
) < 0)
3582 report_file_error ("Setting file position",
3584 ntail
= emacs_read (fd
, read_buf
+ nread
, 1024 * 3);
3585 nread
= ntail
< 0 ? ntail
: nread
+ ntail
;
3590 report_file_error ("Read error", orig_filename
);
3593 AUTO_STRING (name
, " *code-converting-work*");
3594 struct buffer
*prev
= current_buffer
;
3595 Lisp_Object workbuf
;
3598 record_unwind_current_buffer ();
3600 workbuf
= Fget_buffer_create (name
);
3601 buf
= XBUFFER (workbuf
);
3603 delete_all_overlays (buf
);
3604 bset_directory (buf
, BVAR (current_buffer
, directory
));
3605 bset_read_only (buf
, Qnil
);
3606 bset_filename (buf
, Qnil
);
3607 bset_undo_list (buf
, Qt
);
3608 eassert (buf
->overlays_before
== NULL
);
3609 eassert (buf
->overlays_after
== NULL
);
3611 set_buffer_internal (buf
);
3613 bset_enable_multibyte_characters (buf
, Qnil
);
3615 insert_1_both ((char *) read_buf
, nread
, nread
, 0, 0, 0);
3616 TEMP_SET_PT_BOTH (BEG
, BEG_BYTE
);
3617 coding_system
= call2 (Vset_auto_coding_function
,
3618 filename
, make_number (nread
));
3619 set_buffer_internal (prev
);
3621 /* Discard the unwind protect for recovering the
3625 /* Rewind the file for the actual read done later. */
3626 if (lseek (fd
, 0, SEEK_SET
) < 0)
3627 report_file_error ("Setting file position", orig_filename
);
3631 if (NILP (coding_system
))
3633 /* If we have not yet decided a coding system, check
3634 file-coding-system-alist. */
3635 coding_system
= CALLN (Ffind_operation_coding_system
,
3636 Qinsert_file_contents
, orig_filename
,
3637 visit
, beg
, end
, replace
);
3638 if (CONSP (coding_system
))
3639 coding_system
= XCAR (coding_system
);
3643 if (NILP (coding_system
))
3644 coding_system
= Qundecided
;
3646 CHECK_CODING_SYSTEM (coding_system
);
3648 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3649 /* We must suppress all character code conversion except for
3650 end-of-line conversion. */
3651 coding_system
= raw_text_coding_system (coding_system
);
3653 setup_coding_system (coding_system
, &coding
);
3654 /* Ensure we set Vlast_coding_system_used. */
3655 set_coding_system
= true;
3658 /* If requested, replace the accessible part of the buffer
3659 with the file contents. Avoid replacing text at the
3660 beginning or end of the buffer that matches the file contents;
3661 that preserves markers pointing to the unchanged parts.
3663 Here we implement this feature in an optimized way
3664 for the case where code conversion is NOT needed.
3665 The following if-statement handles the case of conversion
3666 in a less optimal way.
3668 If the code conversion is "automatic" then we try using this
3669 method and hope for the best.
3670 But if we discover the need for conversion, we give up on this method
3671 and let the following if-statement handle the replace job. */
3674 && (NILP (coding_system
)
3675 || ! CODING_REQUIRE_DECODING (&coding
)))
3678 /* There is still a possibility we will find the need to do code
3679 conversion. If that happens, set this variable to
3680 give up on handling REPLACE in the optimized way. */
3681 bool giveup_match_end
= false;
3683 if (beg_offset
!= 0)
3685 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3686 report_file_error ("Setting file position", orig_filename
);
3691 /* Count how many chars at the start of the file
3692 match the text at the beginning of the buffer. */
3697 nread
= emacs_read (fd
, read_buf
, sizeof read_buf
);
3699 report_file_error ("Read error", orig_filename
);
3700 else if (nread
== 0)
3703 if (CODING_REQUIRE_DETECTION (&coding
))
3705 coding_system
= detect_coding_system ((unsigned char *) read_buf
,
3708 setup_coding_system (coding_system
, &coding
);
3711 if (CODING_REQUIRE_DECODING (&coding
))
3712 /* We found that the file should be decoded somehow.
3713 Let's give up here. */
3715 giveup_match_end
= true;
3720 while (bufpos
< nread
&& same_at_start
< ZV_BYTE
3721 && FETCH_BYTE (same_at_start
) == read_buf
[bufpos
])
3722 same_at_start
++, bufpos
++;
3723 /* If we found a discrepancy, stop the scan.
3724 Otherwise loop around and scan the next bufferful. */
3725 if (bufpos
!= nread
)
3728 immediate_quit
= false;
3729 /* If the file matches the buffer completely,
3730 there's no need to replace anything. */
3731 if (same_at_start
- BEGV_BYTE
== end_offset
- beg_offset
)
3734 clear_unwind_protect (fd_index
);
3736 /* Truncate the buffer to the size of the file. */
3737 del_range_1 (same_at_start
, same_at_end
, 0, 0);
3740 immediate_quit
= true;
3742 /* Count how many chars at the end of the file
3743 match the text at the end of the buffer. But, if we have
3744 already found that decoding is necessary, don't waste time. */
3745 while (!giveup_match_end
)
3747 int total_read
, nread
, bufpos
, trial
;
3750 /* At what file position are we now scanning? */
3751 curpos
= end_offset
- (ZV_BYTE
- same_at_end
);
3752 /* If the entire file matches the buffer tail, stop the scan. */
3755 /* How much can we scan in the next step? */
3756 trial
= min (curpos
, sizeof read_buf
);
3757 if (lseek (fd
, curpos
- trial
, SEEK_SET
) < 0)
3758 report_file_error ("Setting file position", orig_filename
);
3760 total_read
= nread
= 0;
3761 while (total_read
< trial
)
3763 nread
= emacs_read (fd
, read_buf
+ total_read
, trial
- total_read
);
3765 report_file_error ("Read error", orig_filename
);
3766 else if (nread
== 0)
3768 total_read
+= nread
;
3771 /* Scan this bufferful from the end, comparing with
3772 the Emacs buffer. */
3773 bufpos
= total_read
;
3775 /* Compare with same_at_start to avoid counting some buffer text
3776 as matching both at the file's beginning and at the end. */
3777 while (bufpos
> 0 && same_at_end
> same_at_start
3778 && FETCH_BYTE (same_at_end
- 1) == read_buf
[bufpos
- 1])
3779 same_at_end
--, bufpos
--;
3781 /* If we found a discrepancy, stop the scan.
3782 Otherwise loop around and scan the preceding bufferful. */
3785 /* If this discrepancy is because of code conversion,
3786 we cannot use this method; giveup and try the other. */
3787 if (same_at_end
> same_at_start
3788 && FETCH_BYTE (same_at_end
- 1) >= 0200
3789 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
))
3790 && (CODING_MAY_REQUIRE_DECODING (&coding
)))
3791 giveup_match_end
= true;
3800 if (! giveup_match_end
)
3804 /* We win! We can handle REPLACE the optimized way. */
3806 /* Extend the start of non-matching text area to multibyte
3807 character boundary. */
3808 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3809 while (same_at_start
> BEGV_BYTE
3810 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3813 /* Extend the end of non-matching text area to multibyte
3814 character boundary. */
3815 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3816 while (same_at_end
< ZV_BYTE
3817 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3820 /* Don't try to reuse the same piece of text twice. */
3821 overlap
= (same_at_start
- BEGV_BYTE
3823 + (! NILP (end
) ? end_offset
: st
.st_size
) - ZV_BYTE
));
3825 same_at_end
+= overlap
;
3826 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
3828 /* Arrange to read only the nonmatching middle part of the file. */
3829 beg_offset
+= same_at_start
- BEGV_BYTE
;
3830 end_offset
-= ZV_BYTE
- same_at_end
;
3832 invalidate_buffer_caches (current_buffer
,
3833 BYTE_TO_CHAR (same_at_start
),
3834 same_at_end_charpos
);
3835 del_range_byte (same_at_start
, same_at_end
, 0);
3836 /* Insert from the file at the proper position. */
3837 temp
= BYTE_TO_CHAR (same_at_start
);
3838 SET_PT_BOTH (temp
, same_at_start
);
3840 /* If display currently starts at beginning of line,
3841 keep it that way. */
3842 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
3843 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
3845 replace_handled
= true;
3849 /* If requested, replace the accessible part of the buffer
3850 with the file contents. Avoid replacing text at the
3851 beginning or end of the buffer that matches the file contents;
3852 that preserves markers pointing to the unchanged parts.
3854 Here we implement this feature for the case where code conversion
3855 is needed, in a simple way that needs a lot of memory.
3856 The preceding if-statement handles the case of no conversion
3857 in a more optimized way. */
3858 if (!NILP (replace
) && ! replace_handled
&& BEGV
< ZV
)
3860 ptrdiff_t same_at_start_charpos
;
3861 ptrdiff_t inserted_chars
;
3864 unsigned char *decoded
;
3867 ptrdiff_t this_count
= SPECPDL_INDEX ();
3869 = ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3870 Lisp_Object conversion_buffer
;
3872 conversion_buffer
= code_conversion_save (1, multibyte
);
3874 /* First read the whole file, performing code conversion into
3875 CONVERSION_BUFFER. */
3877 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
3878 report_file_error ("Setting file position", orig_filename
);
3880 inserted
= 0; /* Bytes put into CONVERSION_BUFFER so far. */
3881 unprocessed
= 0; /* Bytes not processed in previous loop. */
3885 /* Read at most READ_BUF_SIZE bytes at a time, to allow
3886 quitting while reading a huge file. */
3888 /* Allow quitting out of the actual I/O. */
3891 this = emacs_read (fd
, read_buf
+ unprocessed
,
3892 READ_BUF_SIZE
- unprocessed
);
3898 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer
),
3899 BUF_Z (XBUFFER (conversion_buffer
)));
3900 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3901 unprocessed
+ this, conversion_buffer
);
3902 unprocessed
= coding
.carryover_bytes
;
3903 if (coding
.carryover_bytes
> 0)
3904 memcpy (read_buf
, coding
.carryover
, unprocessed
);
3908 report_file_error ("Read error", orig_filename
);
3910 clear_unwind_protect (fd_index
);
3912 if (unprocessed
> 0)
3914 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
3915 decode_coding_c_string (&coding
, (unsigned char *) read_buf
,
3916 unprocessed
, conversion_buffer
);
3917 coding
.mode
&= ~CODING_MODE_LAST_BLOCK
;
3920 coding_system
= CODING_ID_NAME (coding
.id
);
3921 set_coding_system
= true;
3922 decoded
= BUF_BEG_ADDR (XBUFFER (conversion_buffer
));
3923 inserted
= (BUF_Z_BYTE (XBUFFER (conversion_buffer
))
3924 - BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
3926 /* Compare the beginning of the converted string with the buffer
3930 while (bufpos
< inserted
&& same_at_start
< same_at_end
3931 && FETCH_BYTE (same_at_start
) == decoded
[bufpos
])
3932 same_at_start
++, bufpos
++;
3934 /* If the file matches the head of buffer completely,
3935 there's no need to replace anything. */
3937 if (bufpos
== inserted
)
3939 /* Truncate the buffer to the size of the file. */
3940 if (same_at_start
!= same_at_end
)
3942 invalidate_buffer_caches (current_buffer
,
3943 BYTE_TO_CHAR (same_at_start
),
3944 BYTE_TO_CHAR (same_at_end
));
3945 del_range_byte (same_at_start
, same_at_end
, 0);
3949 unbind_to (this_count
, Qnil
);
3953 /* Extend the start of non-matching text area to the previous
3954 multibyte character boundary. */
3955 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3956 while (same_at_start
> BEGV_BYTE
3957 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start
)))
3960 /* Scan this bufferful from the end, comparing with
3961 the Emacs buffer. */
3964 /* Compare with same_at_start to avoid counting some buffer text
3965 as matching both at the file's beginning and at the end. */
3966 while (bufpos
> 0 && same_at_end
> same_at_start
3967 && FETCH_BYTE (same_at_end
- 1) == decoded
[bufpos
- 1])
3968 same_at_end
--, bufpos
--;
3970 /* Extend the end of non-matching text area to the next
3971 multibyte character boundary. */
3972 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
3973 while (same_at_end
< ZV_BYTE
3974 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end
)))
3977 /* Don't try to reuse the same piece of text twice. */
3978 overlap
= same_at_start
- BEGV_BYTE
- (same_at_end
+ inserted
- ZV_BYTE
);
3980 same_at_end
+= overlap
;
3981 same_at_end_charpos
= BYTE_TO_CHAR (same_at_end
);
3983 /* If display currently starts at beginning of line,
3984 keep it that way. */
3985 if (XBUFFER (XWINDOW (selected_window
)->contents
) == current_buffer
)
3986 XWINDOW (selected_window
)->start_at_line_beg
= !NILP (Fbolp ());
3988 /* Replace the chars that we need to replace,
3989 and update INSERTED to equal the number of bytes
3990 we are taking from the decoded string. */
3991 inserted
-= (ZV_BYTE
- same_at_end
) + (same_at_start
- BEGV_BYTE
);
3993 if (same_at_end
!= same_at_start
)
3995 invalidate_buffer_caches (current_buffer
,
3996 BYTE_TO_CHAR (same_at_start
),
3997 same_at_end_charpos
);
3998 del_range_byte (same_at_start
, same_at_end
, 0);
4000 eassert (same_at_start
== GPT_BYTE
);
4001 same_at_start
= GPT_BYTE
;
4005 temp
= same_at_end_charpos
;
4007 /* Insert from the file at the proper position. */
4008 SET_PT_BOTH (temp
, same_at_start
);
4009 same_at_start_charpos
4010 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4011 same_at_start
- BEGV_BYTE
4012 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)));
4013 eassert (same_at_start_charpos
== temp
- (BEGV
- BEG
));
4015 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer
),
4016 same_at_start
+ inserted
- BEGV_BYTE
4017 + BUF_BEG_BYTE (XBUFFER (conversion_buffer
)))
4018 - same_at_start_charpos
);
4019 /* This binding is to avoid ask-user-about-supersession-threat
4020 being called in insert_from_buffer (via in
4021 prepare_to_modify_buffer). */
4022 specbind (intern ("buffer-file-name"), Qnil
);
4023 insert_from_buffer (XBUFFER (conversion_buffer
),
4024 same_at_start_charpos
, inserted_chars
, 0);
4025 /* Set `inserted' to the number of inserted characters. */
4026 inserted
= PT
- temp
;
4027 /* Set point before the inserted characters. */
4028 SET_PT_BOTH (temp
, same_at_start
);
4030 unbind_to (this_count
, Qnil
);
4036 total
= end_offset
- beg_offset
;
4038 /* For a special file, all we can do is guess. */
4039 total
= READ_BUF_SIZE
;
4041 if (NILP (visit
) && total
> 0)
4043 if (!NILP (BVAR (current_buffer
, file_truename
))
4044 /* Make binding buffer-file-name to nil effective. */
4045 && !NILP (BVAR (current_buffer
, filename
))
4046 && SAVE_MODIFF
>= MODIFF
)
4047 we_locked_file
= true;
4048 prepare_to_modify_buffer (PT
, PT
, NULL
);
4051 move_gap_both (PT
, PT_BYTE
);
4052 if (GAP_SIZE
< total
)
4053 make_gap (total
- GAP_SIZE
);
4055 if (beg_offset
!= 0 || !NILP (replace
))
4057 if (lseek (fd
, beg_offset
, SEEK_SET
) < 0)
4058 report_file_error ("Setting file position", orig_filename
);
4061 /* In the following loop, HOW_MUCH contains the total bytes read so
4062 far for a regular file, and not changed for a special file. But,
4063 before exiting the loop, it is set to a negative value if I/O
4067 /* Total bytes inserted. */
4070 /* Here, we don't do code conversion in the loop. It is done by
4071 decode_coding_gap after all data are read into the buffer. */
4073 ptrdiff_t gap_size
= GAP_SIZE
;
4075 while (how_much
< total
)
4077 /* `try' is reserved in some compilers (Microsoft C). */
4078 ptrdiff_t trytry
= min (total
- how_much
, READ_BUF_SIZE
);
4085 /* Maybe make more room. */
4086 if (gap_size
< trytry
)
4088 make_gap (trytry
- gap_size
);
4089 gap_size
= GAP_SIZE
- inserted
;
4092 /* Read from the file, capturing `quit'. When an
4093 error occurs, end the loop, and arrange for a quit
4094 to be signaled after decoding the text we read. */
4095 nbytes
= internal_condition_case_1
4097 make_save_int_int_int (fd
, inserted
, trytry
),
4098 Qerror
, read_non_regular_quit
);
4106 this = XINT (nbytes
);
4110 /* Allow quitting out of the actual I/O. We don't make text
4111 part of the buffer until all the reading is done, so a C-g
4112 here doesn't do any harm. */
4115 this = emacs_read (fd
,
4116 ((char *) BEG_ADDR
+ PT_BYTE
- BEG_BYTE
4130 /* For a regular file, where TOTAL is the real size,
4131 count HOW_MUCH to compare with it.
4132 For a special file, where TOTAL is just a buffer size,
4133 so don't bother counting in HOW_MUCH.
4134 (INSERTED is where we count the number of characters inserted.) */
4141 /* Now we have either read all the file data into the gap,
4142 or stop reading on I/O error or quit. If nothing was
4143 read, undo marking the buffer modified. */
4148 unlock_file (BVAR (current_buffer
, file_truename
));
4149 Vdeactivate_mark
= old_Vdeactivate_mark
;
4152 Fset (Qdeactivate_mark
, Qt
);
4155 clear_unwind_protect (fd_index
);
4158 report_file_error ("Read error", orig_filename
);
4160 /* Make the text read part of the buffer. */
4161 GAP_SIZE
-= inserted
;
4163 GPT_BYTE
+= inserted
;
4165 ZV_BYTE
+= inserted
;
4170 /* Put an anchor to ensure multi-byte form ends at gap. */
4175 if (NILP (coding_system
))
4177 /* The coding system is not yet decided. Decide it by an
4178 optimized method for handling `coding:' tag.
4180 Note that we can get here only if the buffer was empty
4181 before the insertion. */
4183 if (!NILP (Vcoding_system_for_read
))
4184 coding_system
= Vcoding_system_for_read
;
4187 /* Since we are sure that the current buffer was empty
4188 before the insertion, we can toggle
4189 enable-multibyte-characters directly here without taking
4190 care of marker adjustment. By this way, we can run Lisp
4191 program safely before decoding the inserted text. */
4192 Lisp_Object unwind_data
;
4193 ptrdiff_t count1
= SPECPDL_INDEX ();
4195 unwind_data
= Fcons (BVAR (current_buffer
, enable_multibyte_characters
),
4196 Fcons (BVAR (current_buffer
, undo_list
),
4197 Fcurrent_buffer ()));
4198 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4199 bset_undo_list (current_buffer
, Qt
);
4200 record_unwind_protect (decide_coding_unwind
, unwind_data
);
4202 if (inserted
> 0 && ! NILP (Vset_auto_coding_function
))
4204 coding_system
= call2 (Vset_auto_coding_function
,
4205 filename
, make_number (inserted
));
4208 if (NILP (coding_system
))
4210 /* If the coding system is not yet decided, check
4211 file-coding-system-alist. */
4212 coding_system
= CALLN (Ffind_operation_coding_system
,
4213 Qinsert_file_contents
, orig_filename
,
4214 visit
, beg
, end
, Qnil
);
4215 if (CONSP (coding_system
))
4216 coding_system
= XCAR (coding_system
);
4218 unbind_to (count1
, Qnil
);
4219 inserted
= Z_BYTE
- BEG_BYTE
;
4222 if (NILP (coding_system
))
4223 coding_system
= Qundecided
;
4225 CHECK_CODING_SYSTEM (coding_system
);
4227 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4228 /* We must suppress all character code conversion except for
4229 end-of-line conversion. */
4230 coding_system
= raw_text_coding_system (coding_system
);
4231 setup_coding_system (coding_system
, &coding
);
4232 /* Ensure we set Vlast_coding_system_used. */
4233 set_coding_system
= true;
4238 /* When we visit a file by raw-text, we change the buffer to
4240 if (CODING_FOR_UNIBYTE (&coding
)
4241 /* Can't do this if part of the buffer might be preserved. */
4243 /* Visiting a file with these coding system makes the buffer
4245 bset_enable_multibyte_characters (current_buffer
, Qnil
);
4248 coding
.dst_multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
4249 if (CODING_MAY_REQUIRE_DECODING (&coding
)
4250 && (inserted
> 0 || CODING_REQUIRE_FLUSHING (&coding
)))
4252 move_gap_both (PT
, PT_BYTE
);
4253 GAP_SIZE
+= inserted
;
4254 ZV_BYTE
-= inserted
;
4258 decode_coding_gap (&coding
, inserted
, inserted
);
4259 inserted
= coding
.produced_char
;
4260 coding_system
= CODING_ID_NAME (coding
.id
);
4262 else if (inserted
> 0)
4264 invalidate_buffer_caches (current_buffer
, PT
, PT
+ inserted
);
4265 adjust_after_insert (PT
, PT_BYTE
, PT
+ inserted
, PT_BYTE
+ inserted
,
4269 /* Call after-change hooks for the inserted text, aside from the case
4270 of normal visiting (not with REPLACE), which is done in a new buffer
4271 "before" the buffer is changed. */
4272 if (inserted
> 0 && total
> 0
4273 && (NILP (visit
) || !NILP (replace
)))
4275 signal_after_change (PT
, 0, inserted
);
4276 update_compositions (PT
, PT
, CHECK_BORDER
);
4279 /* Now INSERTED is measured in characters. */
4284 restore_window_points (window_markers
, inserted
,
4285 BYTE_TO_CHAR (same_at_start
),
4286 same_at_end_charpos
);
4290 if (empty_undo_list_p
)
4291 bset_undo_list (current_buffer
, Qnil
);
4295 current_buffer
->modtime
= mtime
;
4296 current_buffer
->modtime_size
= st
.st_size
;
4297 bset_filename (current_buffer
, orig_filename
);
4300 SAVE_MODIFF
= MODIFF
;
4301 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
4302 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4305 if (!NILP (BVAR (current_buffer
, file_truename
)))
4306 unlock_file (BVAR (current_buffer
, file_truename
));
4307 unlock_file (filename
);
4310 xsignal2 (Qfile_error
,
4311 build_string ("not a regular file"), orig_filename
);
4314 if (set_coding_system
)
4315 Vlast_coding_system_used
= coding_system
;
4317 if (! NILP (Ffboundp (Qafter_insert_file_set_coding
)))
4319 insval
= call2 (Qafter_insert_file_set_coding
, make_number (inserted
),
4321 if (! NILP (insval
))
4323 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4324 wrong_type_argument (intern ("inserted-chars"), insval
);
4325 inserted
= XFASTINT (insval
);
4329 /* Decode file format. */
4332 /* Don't run point motion or modification hooks when decoding. */
4333 ptrdiff_t count1
= SPECPDL_INDEX ();
4334 ptrdiff_t old_inserted
= inserted
;
4335 specbind (Qinhibit_point_motion_hooks
, Qt
);
4336 specbind (Qinhibit_modification_hooks
, Qt
);
4338 /* Save old undo list and don't record undo for decoding. */
4339 old_undo
= BVAR (current_buffer
, undo_list
);
4340 bset_undo_list (current_buffer
, Qt
);
4344 insval
= call3 (Qformat_decode
,
4345 Qnil
, make_number (inserted
), visit
);
4346 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4347 wrong_type_argument (intern ("inserted-chars"), insval
);
4348 inserted
= XFASTINT (insval
);
4352 /* If REPLACE is non-nil and we succeeded in not replacing the
4353 beginning or end of the buffer text with the file's contents,
4354 call format-decode with `point' positioned at the beginning
4355 of the buffer and `inserted' equaling the number of
4356 characters in the buffer. Otherwise, format-decode might
4357 fail to correctly analyze the beginning or end of the buffer.
4358 Hence we temporarily save `point' and `inserted' here and
4359 restore `point' iff format-decode did not insert or delete
4360 any text. Otherwise we leave `point' at point-min. */
4361 ptrdiff_t opoint
= PT
;
4362 ptrdiff_t opoint_byte
= PT_BYTE
;
4363 ptrdiff_t oinserted
= ZV
- BEGV
;
4364 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4366 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4367 insval
= call3 (Qformat_decode
,
4368 Qnil
, make_number (oinserted
), visit
);
4369 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4370 wrong_type_argument (intern ("inserted-chars"), insval
);
4371 if (ochars_modiff
== CHARS_MODIFF
)
4372 /* format_decode didn't modify buffer's characters => move
4373 point back to position before inserted text and leave
4374 value of inserted alone. */
4375 SET_PT_BOTH (opoint
, opoint_byte
);
4377 /* format_decode modified buffer's characters => consider
4378 entire buffer changed and leave point at point-min. */
4379 inserted
= XFASTINT (insval
);
4382 /* For consistency with format-decode call these now iff inserted > 0
4383 (martin 2007-06-28). */
4384 p
= Vafter_insert_file_functions
;
4389 insval
= call1 (XCAR (p
), make_number (inserted
));
4392 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4393 wrong_type_argument (intern ("inserted-chars"), insval
);
4394 inserted
= XFASTINT (insval
);
4399 /* For the rationale of this see the comment on
4400 format-decode above. */
4401 ptrdiff_t opoint
= PT
;
4402 ptrdiff_t opoint_byte
= PT_BYTE
;
4403 ptrdiff_t oinserted
= ZV
- BEGV
;
4404 EMACS_INT ochars_modiff
= CHARS_MODIFF
;
4406 TEMP_SET_PT_BOTH (BEGV
, BEGV_BYTE
);
4407 insval
= call1 (XCAR (p
), make_number (oinserted
));
4410 if (! RANGED_INTEGERP (0, insval
, ZV
- PT
))
4411 wrong_type_argument (intern ("inserted-chars"), insval
);
4412 if (ochars_modiff
== CHARS_MODIFF
)
4413 /* after_insert_file_functions didn't modify
4414 buffer's characters => move point back to
4415 position before inserted text and leave value of
4417 SET_PT_BOTH (opoint
, opoint_byte
);
4419 /* after_insert_file_functions did modify buffer's
4420 characters => consider entire buffer changed and
4421 leave point at point-min. */
4422 inserted
= XFASTINT (insval
);
4430 if (!empty_undo_list_p
)
4432 bset_undo_list (current_buffer
, old_undo
);
4433 if (CONSP (old_undo
) && inserted
!= old_inserted
)
4435 /* Adjust the last undo record for the size change during
4436 the format conversion. */
4437 Lisp_Object tem
= XCAR (old_undo
);
4438 if (CONSP (tem
) && INTEGERP (XCAR (tem
))
4439 && INTEGERP (XCDR (tem
))
4440 && XFASTINT (XCDR (tem
)) == PT
+ old_inserted
)
4441 XSETCDR (tem
, make_number (PT
+ inserted
));
4445 /* If undo_list was Qt before, keep it that way.
4446 Otherwise start with an empty undo_list. */
4447 bset_undo_list (current_buffer
, EQ (old_undo
, Qt
) ? Qt
: Qnil
);
4449 unbind_to (count1
, Qnil
);
4453 && current_buffer
->modtime
.tv_nsec
== NONEXISTENT_MODTIME_NSECS
)
4455 /* If visiting nonexistent file, return nil. */
4456 report_file_errno ("Opening input file", orig_filename
, save_errno
);
4459 /* We made a lot of deletions and insertions above, so invalidate
4460 the newline cache for the entire region of the inserted
4462 if (current_buffer
->base_buffer
&& current_buffer
->base_buffer
->newline_cache
)
4463 invalidate_region_cache (current_buffer
->base_buffer
,
4464 current_buffer
->base_buffer
->newline_cache
,
4465 PT
- BEG
, Z
- PT
- inserted
);
4466 else if (current_buffer
->newline_cache
)
4467 invalidate_region_cache (current_buffer
,
4468 current_buffer
->newline_cache
,
4469 PT
- BEG
, Z
- PT
- inserted
);
4472 Fsignal (Qquit
, Qnil
);
4474 /* Retval needs to be dealt with in all cases consistently. */
4476 val
= list2 (orig_filename
, make_number (inserted
));
4478 return unbind_to (count
, val
);
4481 static Lisp_Object
build_annotations (Lisp_Object
, Lisp_Object
);
4484 build_annotations_unwind (Lisp_Object arg
)
4486 Vwrite_region_annotation_buffers
= arg
;
4489 /* Decide the coding-system to encode the data with. */
4492 choose_write_coding_system (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4493 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4494 struct coding_system
*coding
)
4497 Lisp_Object eol_parent
= Qnil
;
4500 && NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4501 BVAR (current_buffer
, auto_save_file_name
))))
4506 else if (!NILP (Vcoding_system_for_write
))
4508 val
= Vcoding_system_for_write
;
4509 if (coding_system_require_warning
4510 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4511 /* Confirm that VAL can surely encode the current region. */
4512 val
= call5 (Vselect_safe_coding_system_function
,
4513 start
, end
, list2 (Qt
, val
),
4518 /* If the variable `buffer-file-coding-system' is set locally,
4519 it means that the file was read with some kind of code
4520 conversion or the variable is explicitly set by users. We
4521 had better write it out with the same coding system even if
4522 `enable-multibyte-characters' is nil.
4524 If it is not set locally, we anyway have to convert EOL
4525 format if the default value of `buffer-file-coding-system'
4526 tells that it is not Unix-like (LF only) format. */
4527 bool using_default_coding
= 0;
4528 bool force_raw_text
= 0;
4530 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4532 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4535 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4541 /* Check file-coding-system-alist. */
4542 Lisp_Object coding_systems
4543 = CALLN (Ffind_operation_coding_system
, Qwrite_region
, start
, end
,
4544 filename
, append
, visit
, lockname
);
4545 if (CONSP (coding_systems
) && !NILP (XCDR (coding_systems
)))
4546 val
= XCDR (coding_systems
);
4551 /* If we still have not decided a coding system, use the
4552 default value of buffer-file-coding-system. */
4553 val
= BVAR (current_buffer
, buffer_file_coding_system
);
4554 using_default_coding
= 1;
4557 if (! NILP (val
) && ! force_raw_text
)
4559 Lisp_Object spec
, attrs
;
4561 CHECK_CODING_SYSTEM_GET_SPEC (val
, spec
);
4562 attrs
= AREF (spec
, 0);
4563 if (EQ (CODING_ATTR_TYPE (attrs
), Qraw_text
))
4568 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4569 /* Confirm that VAL can surely encode the current region. */
4570 val
= call5 (Vselect_safe_coding_system_function
,
4571 start
, end
, val
, Qnil
, filename
);
4573 /* If the decided coding-system doesn't specify end-of-line
4574 format, we use that of
4575 `default-buffer-file-coding-system'. */
4576 if (! using_default_coding
4577 && ! NILP (BVAR (&buffer_defaults
, buffer_file_coding_system
)))
4578 val
= (coding_inherit_eol_type
4579 (val
, BVAR (&buffer_defaults
, buffer_file_coding_system
)));
4581 /* If we decide not to encode text, use `raw-text' or one of its
4584 val
= raw_text_coding_system (val
);
4587 val
= coding_inherit_eol_type (val
, eol_parent
);
4588 setup_coding_system (val
, coding
);
4590 if (!STRINGP (start
) && !NILP (BVAR (current_buffer
, selective_display
)))
4591 coding
->mode
|= CODING_MODE_SELECTIVE_DISPLAY
;
4595 DEFUN ("write-region", Fwrite_region
, Swrite_region
, 3, 7,
4596 "r\nFWrite region to file: \ni\ni\ni\np",
4597 doc
: /* Write current region into specified file.
4598 When called from a program, requires three arguments:
4599 START, END and FILENAME. START and END are normally buffer positions
4600 specifying the part of the buffer to write.
4601 If START is nil, that means to use the entire buffer contents.
4602 If START is a string, then output that string to the file
4603 instead of any buffer contents; END is ignored.
4605 Optional fourth argument APPEND if non-nil means
4606 append to existing file contents (if any). If it is a number,
4607 seek to that offset in the file before writing.
4608 Optional fifth argument VISIT, if t or a string, means
4609 set the last-save-file-modtime of buffer to this file's modtime
4610 and mark buffer not modified.
4611 If VISIT is a string, it is a second file name;
4612 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4613 VISIT is also the file name to lock and unlock for clash detection.
4614 If VISIT is neither t nor nil nor a string, or if Emacs is in batch mode,
4615 do not display the \"Wrote file\" message.
4616 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4617 use for locking and unlocking, overriding FILENAME and VISIT.
4618 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4619 for an existing file with the same name. If MUSTBENEW is `excl',
4620 that means to get an error if the file already exists; never overwrite.
4621 If MUSTBENEW is neither nil nor `excl', that means ask for
4622 confirmation before overwriting, but do go ahead and overwrite the file
4623 if the user confirms.
4625 This does code conversion according to the value of
4626 `coding-system-for-write', `buffer-file-coding-system', or
4627 `file-coding-system-alist', and sets the variable
4628 `last-coding-system-used' to the coding system actually used.
4630 This calls `write-region-annotate-functions' at the start, and
4631 `write-region-post-annotation-function' at the end. */)
4632 (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
, Lisp_Object append
,
4633 Lisp_Object visit
, Lisp_Object lockname
, Lisp_Object mustbenew
)
4635 return write_region (start
, end
, filename
, append
, visit
, lockname
, mustbenew
,
4639 /* Like Fwrite_region, except that if DESC is nonnegative, it is a file
4640 descriptor for FILENAME, so do not open or close FILENAME. */
4643 write_region (Lisp_Object start
, Lisp_Object end
, Lisp_Object filename
,
4644 Lisp_Object append
, Lisp_Object visit
, Lisp_Object lockname
,
4645 Lisp_Object mustbenew
, int desc
)
4649 off_t offset
IF_LINT (= 0);
4650 bool open_and_close_file
= desc
< 0;
4655 struct timespec modtime
;
4656 ptrdiff_t count
= SPECPDL_INDEX ();
4657 ptrdiff_t count1
IF_LINT (= 0);
4658 Lisp_Object handler
;
4659 Lisp_Object visit_file
;
4660 Lisp_Object annotations
;
4661 Lisp_Object encoded_filename
;
4662 bool visiting
= (EQ (visit
, Qt
) || STRINGP (visit
));
4663 bool quietly
= !NILP (visit
);
4664 bool file_locked
= 0;
4665 struct buffer
*given_buffer
;
4666 struct coding_system coding
;
4668 if (current_buffer
->base_buffer
&& visiting
)
4669 error ("Cannot do file visiting in an indirect buffer");
4671 if (!NILP (start
) && !STRINGP (start
))
4672 validate_region (&start
, &end
);
4676 filename
= Fexpand_file_name (filename
, Qnil
);
4678 if (!NILP (mustbenew
) && !EQ (mustbenew
, Qexcl
))
4679 barf_or_query_if_file_exists (filename
, false, "overwrite", true, true);
4681 if (STRINGP (visit
))
4682 visit_file
= Fexpand_file_name (visit
, Qnil
);
4684 visit_file
= filename
;
4686 if (NILP (lockname
))
4687 lockname
= visit_file
;
4691 /* If the file name has special constructs in it,
4692 call the corresponding file handler. */
4693 handler
= Ffind_file_name_handler (filename
, Qwrite_region
);
4694 /* If FILENAME has no handler, see if VISIT has one. */
4695 if (NILP (handler
) && STRINGP (visit
))
4696 handler
= Ffind_file_name_handler (visit
, Qwrite_region
);
4698 if (!NILP (handler
))
4701 val
= call6 (handler
, Qwrite_region
, start
, end
,
4702 filename
, append
, visit
);
4706 SAVE_MODIFF
= MODIFF
;
4707 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4708 bset_filename (current_buffer
, visit_file
);
4714 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
4716 /* Special kludge to simplify auto-saving. */
4719 /* Do it later, so write-region-annotate-function can work differently
4720 if we save "the buffer" vs "a region".
4721 This is useful in tar-mode. --Stef
4722 XSETFASTINT (start, BEG);
4723 XSETFASTINT (end, Z); */
4727 record_unwind_protect (build_annotations_unwind
,
4728 Vwrite_region_annotation_buffers
);
4729 Vwrite_region_annotation_buffers
= list1 (Fcurrent_buffer ());
4731 given_buffer
= current_buffer
;
4733 if (!STRINGP (start
))
4735 annotations
= build_annotations (start
, end
);
4737 if (current_buffer
!= given_buffer
)
4739 XSETFASTINT (start
, BEGV
);
4740 XSETFASTINT (end
, ZV
);
4746 XSETFASTINT (start
, BEGV
);
4747 XSETFASTINT (end
, ZV
);
4750 /* Decide the coding-system to encode the data with.
4751 We used to make this choice before calling build_annotations, but that
4752 leads to problems when a write-annotate-function takes care of
4753 unsavable chars (as was the case with X-Symbol). */
4754 Vlast_coding_system_used
4755 = choose_write_coding_system (start
, end
, filename
,
4756 append
, visit
, lockname
, &coding
);
4758 if (open_and_close_file
&& !auto_saving
)
4760 lock_file (lockname
);
4764 encoded_filename
= ENCODE_FILE (filename
);
4765 fn
= SSDATA (encoded_filename
);
4766 open_flags
= O_WRONLY
| O_BINARY
| O_CREAT
;
4767 open_flags
|= EQ (mustbenew
, Qexcl
) ? O_EXCL
: !NILP (append
) ? 0 : O_TRUNC
;
4768 if (NUMBERP (append
))
4769 offset
= file_offset (append
);
4770 else if (!NILP (append
))
4771 open_flags
|= O_APPEND
;
4773 mode
= S_IREAD
| S_IWRITE
;
4775 mode
= auto_saving
? auto_save_mode_bits
: 0666;
4778 if (open_and_close_file
)
4780 desc
= emacs_open (fn
, open_flags
, mode
);
4783 int open_errno
= errno
;
4785 unlock_file (lockname
);
4786 report_file_errno ("Opening output file", filename
, open_errno
);
4789 count1
= SPECPDL_INDEX ();
4790 record_unwind_protect_int (close_file_unwind
, desc
);
4793 if (NUMBERP (append
))
4795 off_t ret
= lseek (desc
, offset
, SEEK_SET
);
4798 int lseek_errno
= errno
;
4800 unlock_file (lockname
);
4801 report_file_errno ("Lseek error", filename
, lseek_errno
);
4807 if (STRINGP (start
))
4808 ok
= a_write (desc
, start
, 0, SCHARS (start
), &annotations
, &coding
);
4809 else if (XINT (start
) != XINT (end
))
4810 ok
= a_write (desc
, Qnil
, XINT (start
), XINT (end
) - XINT (start
),
4811 &annotations
, &coding
);
4814 /* If file was empty, still need to write the annotations. */
4815 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4816 ok
= a_write (desc
, Qnil
, XINT (end
), 0, &annotations
, &coding
);
4820 if (ok
&& CODING_REQUIRE_FLUSHING (&coding
)
4821 && !(coding
.mode
& CODING_MODE_LAST_BLOCK
))
4823 /* We have to flush out a data. */
4824 coding
.mode
|= CODING_MODE_LAST_BLOCK
;
4825 ok
= e_write (desc
, Qnil
, 1, 1, &coding
);
4831 /* fsync is not crucial for temporary files. Nor for auto-save
4832 files, since they might lose some work anyway. */
4833 if (open_and_close_file
&& !auto_saving
&& !write_region_inhibit_fsync
)
4835 /* Transfer data and metadata to disk, retrying if interrupted.
4836 fsync can report a write failure here, e.g., due to disk full
4837 under NFS. But ignore EINVAL, which means fsync is not
4838 supported on this file. */
4839 while (fsync (desc
) != 0)
4842 if (errno
!= EINVAL
)
4843 ok
= 0, save_errno
= errno
;
4848 modtime
= invalid_timespec ();
4851 if (fstat (desc
, &st
) == 0)
4852 modtime
= get_stat_mtime (&st
);
4854 ok
= 0, save_errno
= errno
;
4857 if (open_and_close_file
)
4859 /* NFS can report a write failure now. */
4860 if (emacs_close (desc
) < 0)
4861 ok
= 0, save_errno
= errno
;
4863 /* Discard the unwind protect for close_file_unwind. */
4864 specpdl_ptr
= specpdl
+ count1
;
4867 /* Some file systems have a bug where st_mtime is not updated
4868 properly after a write. For example, CIFS might not see the
4869 st_mtime change until after the file is opened again.
4871 Attempt to detect this file system bug, and update MODTIME to the
4872 newer st_mtime if the bug appears to be present. This introduces
4873 a race condition, so to avoid most instances of the race condition
4874 on non-buggy file systems, skip this check if the most recently
4875 encountered non-buggy file system was the current file system.
4877 A race condition can occur if some other process modifies the
4878 file between the fstat above and the fstat below, but the race is
4879 unlikely and a similar race between the last write and the fstat
4880 above cannot possibly be closed anyway. */
4882 if (timespec_valid_p (modtime
)
4883 && ! (valid_timestamp_file_system
&& st
.st_dev
== timestamp_file_system
))
4885 int desc1
= emacs_open (fn
, O_WRONLY
| O_BINARY
, 0);
4889 if (fstat (desc1
, &st1
) == 0
4890 && st
.st_dev
== st1
.st_dev
&& st
.st_ino
== st1
.st_ino
)
4892 /* Use the heuristic if it appears to be valid. With neither
4893 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
4894 file, the time stamp won't change. Also, some non-POSIX
4895 systems don't update an empty file's time stamp when
4896 truncating it. Finally, file systems with 100 ns or worse
4897 resolution sometimes seem to have bugs: on a system with ns
4898 resolution, checking ns % 100 incorrectly avoids the heuristic
4899 1% of the time, but the problem should be temporary as we will
4900 try again on the next time stamp. */
4902 = ((open_flags
& (O_EXCL
| O_TRUNC
)) != 0
4904 && modtime
.tv_nsec
% 100 != 0);
4906 struct timespec modtime1
= get_stat_mtime (&st1
);
4908 && timespec_cmp (modtime
, modtime1
) == 0
4909 && st
.st_size
== st1
.st_size
)
4911 timestamp_file_system
= st
.st_dev
;
4912 valid_timestamp_file_system
= 1;
4916 st
.st_size
= st1
.st_size
;
4920 emacs_close (desc1
);
4924 /* Call write-region-post-annotation-function. */
4925 while (CONSP (Vwrite_region_annotation_buffers
))
4927 Lisp_Object buf
= XCAR (Vwrite_region_annotation_buffers
);
4928 if (!NILP (Fbuffer_live_p (buf
)))
4931 if (FUNCTIONP (Vwrite_region_post_annotation_function
))
4932 call0 (Vwrite_region_post_annotation_function
);
4934 Vwrite_region_annotation_buffers
4935 = XCDR (Vwrite_region_annotation_buffers
);
4938 unbind_to (count
, Qnil
);
4941 unlock_file (lockname
);
4943 /* Do this before reporting IO error
4944 to avoid a "file has changed on disk" warning on
4945 next attempt to save. */
4946 if (timespec_valid_p (modtime
))
4948 current_buffer
->modtime
= modtime
;
4949 current_buffer
->modtime_size
= st
.st_size
;
4953 report_file_errno ("Write error", filename
, save_errno
);
4957 SAVE_MODIFF
= MODIFF
;
4958 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
4959 bset_filename (current_buffer
, visit_file
);
4960 update_mode_lines
= 14;
4965 && ! NILP (Fstring_equal (BVAR (current_buffer
, filename
),
4966 BVAR (current_buffer
, auto_save_file_name
))))
4967 SAVE_MODIFF
= MODIFF
;
4972 if (!auto_saving
&& !noninteractive
)
4973 message_with_string ((NUMBERP (append
)
4983 DEFUN ("car-less-than-car", Fcar_less_than_car
, Scar_less_than_car
, 2, 2, 0,
4984 doc
: /* Return t if (car A) is numerically less than (car B). */)
4985 (Lisp_Object a
, Lisp_Object b
)
4987 return CALLN (Flss
, Fcar (a
), Fcar (b
));
4990 /* Build the complete list of annotations appropriate for writing out
4991 the text between START and END, by calling all the functions in
4992 write-region-annotate-functions and merging the lists they return.
4993 If one of these functions switches to a different buffer, we assume
4994 that buffer contains altered text. Therefore, the caller must
4995 make sure to restore the current buffer in all cases,
4996 as save-excursion would do. */
4999 build_annotations (Lisp_Object start
, Lisp_Object end
)
5001 Lisp_Object annotations
;
5003 Lisp_Object original_buffer
;
5005 bool used_global
= false;
5007 XSETBUFFER (original_buffer
, current_buffer
);
5010 p
= Vwrite_region_annotate_functions
;
5013 struct buffer
*given_buffer
= current_buffer
;
5014 if (EQ (Qt
, XCAR (p
)) && !used_global
)
5015 { /* Use the global value of the hook. */
5018 Fdefault_value (Qwrite_region_annotate_functions
),
5022 Vwrite_region_annotations_so_far
= annotations
;
5023 res
= call2 (XCAR (p
), start
, end
);
5024 /* If the function makes a different buffer current,
5025 assume that means this buffer contains altered text to be output.
5026 Reset START and END from the buffer bounds
5027 and discard all previous annotations because they should have
5028 been dealt with by this function. */
5029 if (current_buffer
!= given_buffer
)
5031 Vwrite_region_annotation_buffers
5032 = Fcons (Fcurrent_buffer (),
5033 Vwrite_region_annotation_buffers
);
5034 XSETFASTINT (start
, BEGV
);
5035 XSETFASTINT (end
, ZV
);
5038 Flength (res
); /* Check basic validity of return value */
5039 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5043 /* Now do the same for annotation functions implied by the file-format */
5044 if (auto_saving
&& (!EQ (BVAR (current_buffer
, auto_save_file_format
), Qt
)))
5045 p
= BVAR (current_buffer
, auto_save_file_format
);
5047 p
= BVAR (current_buffer
, file_format
);
5048 for (i
= 0; CONSP (p
); p
= XCDR (p
), ++i
)
5050 struct buffer
*given_buffer
= current_buffer
;
5052 Vwrite_region_annotations_so_far
= annotations
;
5054 /* Value is either a list of annotations or nil if the function
5055 has written annotations to a temporary buffer, which is now
5057 res
= call5 (Qformat_annotate_function
, XCAR (p
), start
, end
,
5058 original_buffer
, make_number (i
));
5059 if (current_buffer
!= given_buffer
)
5061 XSETFASTINT (start
, BEGV
);
5062 XSETFASTINT (end
, ZV
);
5067 annotations
= merge (annotations
, res
, Qcar_less_than_car
);
5074 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5075 If STRING is nil, POS is the character position in the current buffer.
5076 Intersperse with them the annotations from *ANNOT
5077 which fall within the range of POS to POS + NCHARS,
5078 each at its appropriate position.
5080 We modify *ANNOT by discarding elements as we use them up.
5082 Return true if successful. */
5085 a_write (int desc
, Lisp_Object string
, ptrdiff_t pos
,
5086 ptrdiff_t nchars
, Lisp_Object
*annot
,
5087 struct coding_system
*coding
)
5091 ptrdiff_t lastpos
= pos
+ nchars
;
5093 while (NILP (*annot
) || CONSP (*annot
))
5095 tem
= Fcar_safe (Fcar (*annot
));
5098 nextpos
= XFASTINT (tem
);
5100 /* If there are no more annotations in this range,
5101 output the rest of the range all at once. */
5102 if (! (nextpos
>= pos
&& nextpos
<= lastpos
))
5103 return e_write (desc
, string
, pos
, lastpos
, coding
);
5105 /* Output buffer text up to the next annotation's position. */
5108 if (!e_write (desc
, string
, pos
, nextpos
, coding
))
5112 /* Output the annotation. */
5113 tem
= Fcdr (Fcar (*annot
));
5116 if (!e_write (desc
, tem
, 0, SCHARS (tem
), coding
))
5119 *annot
= Fcdr (*annot
);
5124 /* Maximum number of characters that the next
5125 function encodes per one loop iteration. */
5127 enum { E_WRITE_MAX
= 8 * 1024 * 1024 };
5129 /* Write text in the range START and END into descriptor DESC,
5130 encoding them with coding system CODING. If STRING is nil, START
5131 and END are character positions of the current buffer, else they
5132 are indexes to the string STRING. Return true if successful. */
5135 e_write (int desc
, Lisp_Object string
, ptrdiff_t start
, ptrdiff_t end
,
5136 struct coding_system
*coding
)
5138 if (STRINGP (string
))
5141 end
= SCHARS (string
);
5144 /* We used to have a code for handling selective display here. But,
5145 now it is handled within encode_coding. */
5149 if (STRINGP (string
))
5151 coding
->src_multibyte
= SCHARS (string
) < SBYTES (string
);
5152 if (CODING_REQUIRE_ENCODING (coding
))
5154 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5156 /* Avoid creating huge Lisp string in encode_coding_object. */
5157 if (nchars
== E_WRITE_MAX
)
5158 coding
->raw_destination
= 1;
5160 encode_coding_object
5161 (coding
, string
, start
, string_char_to_byte (string
, start
),
5162 start
+ nchars
, string_char_to_byte (string
, start
+ nchars
),
5167 coding
->dst_object
= string
;
5168 coding
->consumed_char
= SCHARS (string
);
5169 coding
->produced
= SBYTES (string
);
5174 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
5175 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
5177 coding
->src_multibyte
= (end
- start
) < (end_byte
- start_byte
);
5178 if (CODING_REQUIRE_ENCODING (coding
))
5180 ptrdiff_t nchars
= min (end
- start
, E_WRITE_MAX
);
5183 if (nchars
== E_WRITE_MAX
)
5184 coding
->raw_destination
= 1;
5186 encode_coding_object
5187 (coding
, Fcurrent_buffer (), start
, start_byte
,
5188 start
+ nchars
, CHAR_TO_BYTE (start
+ nchars
), Qt
);
5192 coding
->dst_object
= Qnil
;
5193 coding
->dst_pos_byte
= start_byte
;
5194 if (start
>= GPT
|| end
<= GPT
)
5196 coding
->consumed_char
= end
- start
;
5197 coding
->produced
= end_byte
- start_byte
;
5201 coding
->consumed_char
= GPT
- start
;
5202 coding
->produced
= GPT_BYTE
- start_byte
;
5207 if (coding
->produced
> 0)
5209 char *buf
= (coding
->raw_destination
? (char *) coding
->destination
5210 : (STRINGP (coding
->dst_object
)
5211 ? SSDATA (coding
->dst_object
)
5212 : (char *) BYTE_POS_ADDR (coding
->dst_pos_byte
)));
5213 coding
->produced
-= emacs_write_sig (desc
, buf
, coding
->produced
);
5215 if (coding
->raw_destination
)
5217 /* We're responsible for freeing this, see
5218 encode_coding_object to check why. */
5219 xfree (coding
->destination
);
5220 coding
->raw_destination
= 0;
5222 if (coding
->produced
)
5225 start
+= coding
->consumed_char
;
5231 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime
,
5232 Sverify_visited_file_modtime
, 0, 1, 0,
5233 doc
: /* Return t if last mod time of BUF's visited file matches what BUF records.
5234 This means that the file has not been changed since it was visited or saved.
5235 If BUF is omitted or nil, it defaults to the current buffer.
5236 See Info node `(elisp)Modification Time' for more details. */)
5239 struct buffer
*b
= decode_buffer (buf
);
5241 Lisp_Object handler
;
5242 Lisp_Object filename
;
5243 struct timespec mtime
;
5245 if (!STRINGP (BVAR (b
, filename
))) return Qt
;
5246 if (b
->modtime
.tv_nsec
== UNKNOWN_MODTIME_NSECS
) return Qt
;
5248 /* If the file name has special constructs in it,
5249 call the corresponding file handler. */
5250 handler
= Ffind_file_name_handler (BVAR (b
, filename
),
5251 Qverify_visited_file_modtime
);
5252 if (!NILP (handler
))
5253 return call2 (handler
, Qverify_visited_file_modtime
, buf
);
5255 filename
= ENCODE_FILE (BVAR (b
, filename
));
5257 mtime
= (stat (SSDATA (filename
), &st
) == 0
5258 ? get_stat_mtime (&st
)
5259 : time_error_value (errno
));
5260 if (timespec_cmp (mtime
, b
->modtime
) == 0
5261 && (b
->modtime_size
< 0
5262 || st
.st_size
== b
->modtime_size
))
5267 DEFUN ("visited-file-modtime", Fvisited_file_modtime
,
5268 Svisited_file_modtime
, 0, 0, 0,
5269 doc
: /* Return the current buffer's recorded visited file modification time.
5270 The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
5271 `file-attributes' returns. If the current buffer has no recorded file
5272 modification time, this function returns 0. If the visited file
5273 doesn't exist, return -1.
5274 See Info node `(elisp)Modification Time' for more details. */)
5277 int ns
= current_buffer
->modtime
.tv_nsec
;
5279 return make_number (UNKNOWN_MODTIME_NSECS
- ns
);
5280 return make_lisp_time (current_buffer
->modtime
);
5283 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime
,
5284 Sset_visited_file_modtime
, 0, 1, 0,
5285 doc
: /* Update buffer's recorded modification time from the visited file's time.
5286 Useful if the buffer was not read from the file normally
5287 or if the file itself has been changed for some known benign reason.
5288 An argument specifies the modification time value to use
5289 \(instead of that of the visited file), in the form of a list
5290 \(HIGH LOW USEC PSEC) or an integer flag as returned by
5291 `visited-file-modtime'. */)
5292 (Lisp_Object time_flag
)
5294 if (!NILP (time_flag
))
5296 struct timespec mtime
;
5297 if (INTEGERP (time_flag
))
5299 CHECK_RANGED_INTEGER (time_flag
, -1, 0);
5300 mtime
= make_timespec (0, UNKNOWN_MODTIME_NSECS
- XINT (time_flag
));
5303 mtime
= lisp_time_argument (time_flag
);
5305 current_buffer
->modtime
= mtime
;
5306 current_buffer
->modtime_size
= -1;
5310 register Lisp_Object filename
;
5312 Lisp_Object handler
;
5314 filename
= Fexpand_file_name (BVAR (current_buffer
, filename
), Qnil
);
5316 /* If the file name has special constructs in it,
5317 call the corresponding file handler. */
5318 handler
= Ffind_file_name_handler (filename
, Qset_visited_file_modtime
);
5319 if (!NILP (handler
))
5320 /* The handler can find the file name the same way we did. */
5321 return call2 (handler
, Qset_visited_file_modtime
, Qnil
);
5323 filename
= ENCODE_FILE (filename
);
5325 if (stat (SSDATA (filename
), &st
) >= 0)
5327 current_buffer
->modtime
= get_stat_mtime (&st
);
5328 current_buffer
->modtime_size
= st
.st_size
;
5336 auto_save_error (Lisp_Object error_val
)
5341 auto_save_error_occurred
= 1;
5343 ring_bell (XFRAME (selected_frame
));
5345 AUTO_STRING (format
, "Auto-saving %s: %s");
5346 msg
= CALLN (Fformat
, format
, BVAR (current_buffer
, name
),
5347 Ferror_message_string (error_val
));
5349 for (i
= 0; i
< 3; ++i
)
5354 message3_nolog (msg
);
5355 Fsleep_for (make_number (1), Qnil
);
5367 auto_save_mode_bits
= 0666;
5369 /* Get visited file's mode to become the auto save file's mode. */
5370 if (! NILP (BVAR (current_buffer
, filename
)))
5372 if (stat (SSDATA (BVAR (current_buffer
, filename
)), &st
) >= 0)
5373 /* But make sure we can overwrite it later! */
5374 auto_save_mode_bits
= (st
.st_mode
| 0600) & 0777;
5375 else if (modes
= Ffile_modes (BVAR (current_buffer
, filename
)),
5377 /* Remote files don't cooperate with stat. */
5378 auto_save_mode_bits
= (XINT (modes
) | 0600) & 0777;
5382 Fwrite_region (Qnil
, Qnil
, BVAR (current_buffer
, auto_save_file_name
), Qnil
,
5383 NILP (Vauto_save_visited_file_name
) ? Qlambda
: Qt
,
5387 struct auto_save_unwind
5394 do_auto_save_unwind (void *arg
)
5396 struct auto_save_unwind
*p
= arg
;
5397 FILE *stream
= p
->stream
;
5398 minibuffer_auto_raise
= p
->auto_raise
;
5409 do_auto_save_make_dir (Lisp_Object dir
)
5413 auto_saving_dir_umask
= 077;
5414 result
= call2 (Qmake_directory
, dir
, Qt
);
5415 auto_saving_dir_umask
= 0;
5420 do_auto_save_eh (Lisp_Object ignore
)
5422 auto_saving_dir_umask
= 0;
5426 DEFUN ("do-auto-save", Fdo_auto_save
, Sdo_auto_save
, 0, 2, "",
5427 doc
: /* Auto-save all buffers that need it.
5428 This is all buffers that have auto-saving enabled
5429 and are changed since last auto-saved.
5430 Auto-saving writes the buffer into a file
5431 so that your editing is not lost if the system crashes.
5432 This file is not the file you visited; that changes only when you save.
5433 Normally we run the normal hook `auto-save-hook' before saving.
5435 A non-nil NO-MESSAGE argument means do not print any message if successful.
5436 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5437 (Lisp_Object no_message
, Lisp_Object current_only
)
5439 struct buffer
*old
= current_buffer
, *b
;
5440 Lisp_Object tail
, buf
, hook
;
5441 bool auto_saved
= 0;
5442 int do_handled_files
;
5444 FILE *stream
= NULL
;
5445 ptrdiff_t count
= SPECPDL_INDEX ();
5446 bool orig_minibuffer_auto_raise
= minibuffer_auto_raise
;
5447 bool old_message_p
= 0;
5448 struct auto_save_unwind auto_save_unwind
;
5450 if (max_specpdl_size
< specpdl_size
+ 40)
5451 max_specpdl_size
= specpdl_size
+ 40;
5456 if (NILP (no_message
))
5458 old_message_p
= push_message ();
5459 record_unwind_protect_void (pop_message_unwind
);
5462 /* Ordinarily don't quit within this function,
5463 but don't make it impossible to quit (in case we get hung in I/O). */
5467 hook
= intern ("auto-save-hook");
5468 safe_run_hooks (hook
);
5470 if (STRINGP (Vauto_save_list_file_name
))
5472 Lisp_Object listfile
;
5474 listfile
= Fexpand_file_name (Vauto_save_list_file_name
, Qnil
);
5476 /* Don't try to create the directory when shutting down Emacs,
5477 because creating the directory might signal an error, and
5478 that would leave Emacs in a strange state. */
5479 if (!NILP (Vrun_hooks
))
5482 dir
= Ffile_name_directory (listfile
);
5483 if (NILP (Ffile_directory_p (dir
)))
5484 internal_condition_case_1 (do_auto_save_make_dir
,
5489 stream
= emacs_fopen (SSDATA (listfile
), "w");
5492 auto_save_unwind
.stream
= stream
;
5493 auto_save_unwind
.auto_raise
= minibuffer_auto_raise
;
5494 record_unwind_protect_ptr (do_auto_save_unwind
, &auto_save_unwind
);
5495 minibuffer_auto_raise
= 0;
5497 auto_save_error_occurred
= 0;
5499 /* On first pass, save all files that don't have handlers.
5500 On second pass, save all files that do have handlers.
5502 If Emacs is crashing, the handlers may tweak what is causing
5503 Emacs to crash in the first place, and it would be a shame if
5504 Emacs failed to autosave perfectly ordinary files because it
5505 couldn't handle some ange-ftp'd file. */
5507 for (do_handled_files
= 0; do_handled_files
< 2; do_handled_files
++)
5508 FOR_EACH_LIVE_BUFFER (tail
, buf
)
5512 /* Record all the buffers that have auto save mode
5513 in the special file that lists them. For each of these buffers,
5514 Record visited name (if any) and auto save name. */
5515 if (STRINGP (BVAR (b
, auto_save_file_name
))
5516 && stream
!= NULL
&& do_handled_files
== 0)
5519 if (!NILP (BVAR (b
, filename
)))
5521 fwrite (SDATA (BVAR (b
, filename
)), 1,
5522 SBYTES (BVAR (b
, filename
)), stream
);
5524 putc ('\n', stream
);
5525 fwrite (SDATA (BVAR (b
, auto_save_file_name
)), 1,
5526 SBYTES (BVAR (b
, auto_save_file_name
)), stream
);
5527 putc ('\n', stream
);
5531 if (!NILP (current_only
)
5532 && b
!= current_buffer
)
5535 /* Don't auto-save indirect buffers.
5536 The base buffer takes care of it. */
5540 /* Check for auto save enabled
5541 and file changed since last auto save
5542 and file changed since last real save. */
5543 if (STRINGP (BVAR (b
, auto_save_file_name
))
5544 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
)
5545 && BUF_AUTOSAVE_MODIFF (b
) < BUF_MODIFF (b
)
5546 /* -1 means we've turned off autosaving for a while--see below. */
5547 && XINT (BVAR (b
, save_length
)) >= 0
5548 && (do_handled_files
5549 || NILP (Ffind_file_name_handler (BVAR (b
, auto_save_file_name
),
5552 struct timespec before_time
= current_timespec ();
5553 struct timespec after_time
;
5555 /* If we had a failure, don't try again for 20 minutes. */
5556 if (b
->auto_save_failure_time
> 0
5557 && before_time
.tv_sec
- b
->auto_save_failure_time
< 1200)
5560 set_buffer_internal (b
);
5561 if (NILP (Vauto_save_include_big_deletions
)
5562 && (XFASTINT (BVAR (b
, save_length
)) * 10
5563 > (BUF_Z (b
) - BUF_BEG (b
)) * 13)
5564 /* A short file is likely to change a large fraction;
5565 spare the user annoying messages. */
5566 && XFASTINT (BVAR (b
, save_length
)) > 5000
5567 /* These messages are frequent and annoying for `*mail*'. */
5568 && !EQ (BVAR (b
, filename
), Qnil
)
5569 && NILP (no_message
))
5571 /* It has shrunk too much; turn off auto-saving here. */
5572 minibuffer_auto_raise
= orig_minibuffer_auto_raise
;
5573 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5575 minibuffer_auto_raise
= 0;
5576 /* Turn off auto-saving until there's a real save,
5577 and prevent any more warnings. */
5578 XSETINT (BVAR (b
, save_length
), -1);
5579 Fsleep_for (make_number (1), Qnil
);
5582 if (!auto_saved
&& NILP (no_message
))
5583 message1 ("Auto-saving...");
5584 internal_condition_case (auto_save_1
, Qt
, auto_save_error
);
5586 BUF_AUTOSAVE_MODIFF (b
) = BUF_MODIFF (b
);
5587 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5588 set_buffer_internal (old
);
5590 after_time
= current_timespec ();
5592 /* If auto-save took more than 60 seconds,
5593 assume it was an NFS failure that got a timeout. */
5594 if (after_time
.tv_sec
- before_time
.tv_sec
> 60)
5595 b
->auto_save_failure_time
= after_time
.tv_sec
;
5599 /* Prevent another auto save till enough input events come in. */
5600 record_auto_save ();
5602 if (auto_saved
&& NILP (no_message
))
5606 /* If we are going to restore an old message,
5607 give time to read ours. */
5608 sit_for (make_number (1), 0, 0);
5611 else if (!auto_save_error_occurred
)
5612 /* Don't overwrite the error message if an error occurred.
5613 If we displayed a message and then restored a state
5614 with no message, leave a "done" message on the screen. */
5615 message1 ("Auto-saving...done");
5620 /* This restores the message-stack status. */
5621 unbind_to (count
, Qnil
);
5625 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved
,
5626 Sset_buffer_auto_saved
, 0, 0, 0,
5627 doc
: /* Mark current buffer as auto-saved with its current text.
5628 No auto-save file will be written until the buffer changes again. */)
5631 /* FIXME: This should not be called in indirect buffers, since
5632 they're not autosaved. */
5633 BUF_AUTOSAVE_MODIFF (current_buffer
) = MODIFF
;
5634 XSETFASTINT (BVAR (current_buffer
, save_length
), Z
- BEG
);
5635 current_buffer
->auto_save_failure_time
= 0;
5639 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure
,
5640 Sclear_buffer_auto_save_failure
, 0, 0, 0,
5641 doc
: /* Clear any record of a recent auto-save failure in the current buffer. */)
5644 current_buffer
->auto_save_failure_time
= 0;
5648 DEFUN ("recent-auto-save-p", Frecent_auto_save_p
, Srecent_auto_save_p
,
5650 doc
: /* Return t if current buffer has been auto-saved recently.
5651 More precisely, if it has been auto-saved since last read from or saved
5652 in the visited file. If the buffer has no visited file,
5653 then any auto-save counts as "recent". */)
5656 /* FIXME: maybe we should return nil for indirect buffers since
5657 they're never autosaved. */
5658 return (SAVE_MODIFF
< BUF_AUTOSAVE_MODIFF (current_buffer
) ? Qt
: Qnil
);
5661 /* Reading and completing file names. */
5663 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p
,
5664 Snext_read_file_uses_dialog_p
, 0, 0, 0,
5665 doc
: /* Return t if a call to `read-file-name' will use a dialog.
5666 The return value is only relevant for a call to `read-file-name' that happens
5667 before any other event (mouse or keypress) is handled. */)
5670 #if (defined USE_GTK || defined USE_MOTIF \
5671 || defined HAVE_NS || defined HAVE_NTGUI)
5672 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
5675 && window_system_available (SELECTED_FRAME ()))
5682 DEFUN ("set-binary-mode", Fset_binary_mode
, Sset_binary_mode
, 2, 2, 0,
5683 doc
: /* Switch STREAM to binary I/O mode or text I/O mode.
5684 STREAM can be one of the symbols `stdin', `stdout', or `stderr'.
5685 If MODE is non-nil, switch STREAM to binary mode, otherwise switch
5688 As a side effect, this function flushes any pending STREAM's data.
5690 Value is the previous value of STREAM's I/O mode, nil for text mode,
5691 non-nil for binary mode.
5693 On MS-Windows and MS-DOS, binary mode is needed to read or write
5694 arbitrary binary data, and for disabling translation between CR-LF
5695 pairs and a single newline character. Examples include generation
5696 of text files with Unix-style end-of-line format using `princ' in
5697 batch mode, with standard output redirected to a file.
5699 On Posix systems, this function always returns non-nil, and has no
5700 effect except for flushing STREAM's data. */)
5701 (Lisp_Object stream
, Lisp_Object mode
)
5706 CHECK_SYMBOL (stream
);
5707 if (EQ (stream
, Qstdin
))
5709 else if (EQ (stream
, Qstdout
))
5711 else if (EQ (stream
, Qstderr
))
5714 xsignal2 (Qerror
, build_string ("unsupported stream"), stream
);
5716 binmode
= NILP (mode
) ? O_TEXT
: O_BINARY
;
5720 return (set_binary_mode (fileno (fp
), binmode
) == O_BINARY
) ? Qt
: Qnil
;
5726 realmask
= umask (0);
5729 valid_timestamp_file_system
= 0;
5731 /* fsync can be a significant performance hit. Often it doesn't
5732 suffice to make the file-save operation survive a crash. For
5733 batch scripts, which are typically part of larger shell commands
5734 that don't fsync other files, its effect on performance can be
5735 significant so its utility is particularly questionable.
5736 Hence, for now by default fsync is used only when interactive.
5738 For more on why fsync often fails to work on today's hardware, see:
5739 Zheng M et al. Understanding the robustness of SSDs under power fault.
5740 11th USENIX Conf. on File and Storage Technologies, 2013 (FAST '13), 271-84
5741 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
5743 For more on why fsync does not suffice even if it works properly, see:
5744 Roche X. Necessary step(s) to synchronize filename operations on disk.
5745 Austin Group Defect 672, 2013-03-19
5746 http://austingroupbugs.net/view.php?id=672 */
5747 write_region_inhibit_fsync
= noninteractive
;
5751 syms_of_fileio (void)
5753 /* Property name of a file name handler,
5754 which gives a list of operations it handles. */
5755 DEFSYM (Qoperations
, "operations");
5757 DEFSYM (Qexpand_file_name
, "expand-file-name");
5758 DEFSYM (Qsubstitute_in_file_name
, "substitute-in-file-name");
5759 DEFSYM (Qdirectory_file_name
, "directory-file-name");
5760 DEFSYM (Qfile_name_directory
, "file-name-directory");
5761 DEFSYM (Qfile_name_nondirectory
, "file-name-nondirectory");
5762 DEFSYM (Qunhandled_file_name_directory
, "unhandled-file-name-directory");
5763 DEFSYM (Qfile_name_as_directory
, "file-name-as-directory");
5764 DEFSYM (Qcopy_file
, "copy-file");
5765 DEFSYM (Qmake_directory_internal
, "make-directory-internal");
5766 DEFSYM (Qmake_directory
, "make-directory");
5767 DEFSYM (Qdelete_file
, "delete-file");
5768 DEFSYM (Qrename_file
, "rename-file");
5769 DEFSYM (Qadd_name_to_file
, "add-name-to-file");
5770 DEFSYM (Qmake_symbolic_link
, "make-symbolic-link");
5771 DEFSYM (Qfile_exists_p
, "file-exists-p");
5772 DEFSYM (Qfile_executable_p
, "file-executable-p");
5773 DEFSYM (Qfile_readable_p
, "file-readable-p");
5774 DEFSYM (Qfile_writable_p
, "file-writable-p");
5775 DEFSYM (Qfile_symlink_p
, "file-symlink-p");
5776 DEFSYM (Qaccess_file
, "access-file");
5777 DEFSYM (Qfile_directory_p
, "file-directory-p");
5778 DEFSYM (Qfile_regular_p
, "file-regular-p");
5779 DEFSYM (Qfile_accessible_directory_p
, "file-accessible-directory-p");
5780 DEFSYM (Qfile_modes
, "file-modes");
5781 DEFSYM (Qset_file_modes
, "set-file-modes");
5782 DEFSYM (Qset_file_times
, "set-file-times");
5783 DEFSYM (Qfile_selinux_context
, "file-selinux-context");
5784 DEFSYM (Qset_file_selinux_context
, "set-file-selinux-context");
5785 DEFSYM (Qfile_acl
, "file-acl");
5786 DEFSYM (Qset_file_acl
, "set-file-acl");
5787 DEFSYM (Qfile_newer_than_file_p
, "file-newer-than-file-p");
5788 DEFSYM (Qinsert_file_contents
, "insert-file-contents");
5789 DEFSYM (Qwrite_region
, "write-region");
5790 DEFSYM (Qverify_visited_file_modtime
, "verify-visited-file-modtime");
5791 DEFSYM (Qset_visited_file_modtime
, "set-visited-file-modtime");
5793 /* The symbol bound to coding-system-for-read when
5794 insert-file-contents is called for recovering a file. This is not
5795 an actual coding system name, but just an indicator to tell
5796 insert-file-contents to use `emacs-mule' with a special flag for
5797 auto saving and recovering a file. */
5798 DEFSYM (Qauto_save_coding
, "auto-save-coding");
5800 DEFSYM (Qfile_name_history
, "file-name-history");
5801 Fset (Qfile_name_history
, Qnil
);
5803 DEFSYM (Qfile_error
, "file-error");
5804 DEFSYM (Qfile_already_exists
, "file-already-exists");
5805 DEFSYM (Qfile_date_error
, "file-date-error");
5806 DEFSYM (Qfile_notify_error
, "file-notify-error");
5807 DEFSYM (Qexcl
, "excl");
5809 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system
,
5810 doc
: /* Coding system for encoding file names.
5811 If it is nil, `default-file-name-coding-system' (which see) is used.
5813 On MS-Windows, the value of this variable is largely ignored if
5814 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5815 behaves as if file names were encoded in `utf-8'. */);
5816 Vfile_name_coding_system
= Qnil
;
5818 DEFVAR_LISP ("default-file-name-coding-system",
5819 Vdefault_file_name_coding_system
,
5820 doc
: /* Default coding system for encoding file names.
5821 This variable is used only when `file-name-coding-system' is nil.
5823 This variable is set/changed by the command `set-language-environment'.
5824 User should not set this variable manually,
5825 instead use `file-name-coding-system' to get a constant encoding
5826 of file names regardless of the current language environment.
5828 On MS-Windows, the value of this variable is largely ignored if
5829 `w32-unicode-filenames' (which see) is non-nil. Emacs on Windows
5830 behaves as if file names were encoded in `utf-8'. */);
5831 Vdefault_file_name_coding_system
= Qnil
;
5833 /* Lisp functions for translating file formats. */
5834 DEFSYM (Qformat_decode
, "format-decode");
5835 DEFSYM (Qformat_annotate_function
, "format-annotate-function");
5837 /* Lisp function for setting buffer-file-coding-system and the
5838 multibyteness of the current buffer after inserting a file. */
5839 DEFSYM (Qafter_insert_file_set_coding
, "after-insert-file-set-coding");
5841 DEFSYM (Qcar_less_than_car
, "car-less-than-car");
5843 Fput (Qfile_error
, Qerror_conditions
,
5844 Fpurecopy (list2 (Qfile_error
, Qerror
)));
5845 Fput (Qfile_error
, Qerror_message
,
5846 build_pure_c_string ("File error"));
5848 Fput (Qfile_already_exists
, Qerror_conditions
,
5849 Fpurecopy (list3 (Qfile_already_exists
, Qfile_error
, Qerror
)));
5850 Fput (Qfile_already_exists
, Qerror_message
,
5851 build_pure_c_string ("File already exists"));
5853 Fput (Qfile_date_error
, Qerror_conditions
,
5854 Fpurecopy (list3 (Qfile_date_error
, Qfile_error
, Qerror
)));
5855 Fput (Qfile_date_error
, Qerror_message
,
5856 build_pure_c_string ("Cannot set file date"));
5858 Fput (Qfile_notify_error
, Qerror_conditions
,
5859 Fpurecopy (list3 (Qfile_notify_error
, Qfile_error
, Qerror
)));
5860 Fput (Qfile_notify_error
, Qerror_message
,
5861 build_pure_c_string ("File notification error"));
5863 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist
,
5864 doc
: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5865 If a file name matches REGEXP, all I/O on that file is done by calling
5866 HANDLER. If a file name matches more than one handler, the handler
5867 whose match starts last in the file name gets precedence. The
5868 function `find-file-name-handler' checks this list for a handler for
5871 HANDLER should be a function. The first argument given to it is the
5872 name of the I/O primitive to be handled; the remaining arguments are
5873 the arguments that were passed to that primitive. For example, if you
5874 do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5875 HANDLER is called like this:
5877 (funcall HANDLER 'file-exists-p FILENAME)
5879 Note that HANDLER must be able to handle all I/O primitives; if it has
5880 nothing special to do for a primitive, it should reinvoke the
5881 primitive to handle the operation \"the usual way\".
5882 See Info node `(elisp)Magic File Names' for more details. */);
5883 Vfile_name_handler_alist
= Qnil
;
5885 DEFVAR_LISP ("set-auto-coding-function",
5886 Vset_auto_coding_function
,
5887 doc
: /* If non-nil, a function to call to decide a coding system of file.
5888 Two arguments are passed to this function: the file name
5889 and the length of a file contents following the point.
5890 This function should return a coding system to decode the file contents.
5891 It should check the file name against `auto-coding-alist'.
5892 If no coding system is decided, it should check a coding system
5893 specified in the heading lines with the format:
5894 -*- ... coding: CODING-SYSTEM; ... -*-
5895 or local variable spec of the tailing lines with `coding:' tag. */);
5896 Vset_auto_coding_function
= Qnil
;
5898 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions
,
5899 doc
: /* A list of functions to be called at the end of `insert-file-contents'.
5900 Each is passed one argument, the number of characters inserted,
5901 with point at the start of the inserted text. Each function
5902 should leave point the same, and return the new character count.
5903 If `insert-file-contents' is intercepted by a handler from
5904 `file-name-handler-alist', that handler is responsible for calling the
5905 functions in `after-insert-file-functions' if appropriate. */);
5906 Vafter_insert_file_functions
= Qnil
;
5908 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions
,
5909 doc
: /* A list of functions to be called at the start of `write-region'.
5910 Each is passed two arguments, START and END as for `write-region'.
5911 These are usually two numbers but not always; see the documentation
5912 for `write-region'. The function should return a list of pairs
5913 of the form (POSITION . STRING), consisting of strings to be effectively
5914 inserted at the specified positions of the file being written (1 means to
5915 insert before the first byte written). The POSITIONs must be sorted into
5918 If there are several annotation functions, the lists returned by these
5919 functions are merged destructively. As each annotation function runs,
5920 the variable `write-region-annotations-so-far' contains a list of all
5921 annotations returned by previous annotation functions.
5923 An annotation function can return with a different buffer current.
5924 Doing so removes the annotations returned by previous functions, and
5925 resets START and END to `point-min' and `point-max' of the new buffer.
5927 After `write-region' completes, Emacs calls the function stored in
5928 `write-region-post-annotation-function', once for each buffer that was
5929 current when building the annotations (i.e., at least once), with that
5930 buffer current. */);
5931 Vwrite_region_annotate_functions
= Qnil
;
5932 DEFSYM (Qwrite_region_annotate_functions
, "write-region-annotate-functions");
5934 DEFVAR_LISP ("write-region-post-annotation-function",
5935 Vwrite_region_post_annotation_function
,
5936 doc
: /* Function to call after `write-region' completes.
5937 The function is called with no arguments. If one or more of the
5938 annotation functions in `write-region-annotate-functions' changed the
5939 current buffer, the function stored in this variable is called for
5940 each of those additional buffers as well, in addition to the original
5941 buffer. The relevant buffer is current during each function call. */);
5942 Vwrite_region_post_annotation_function
= Qnil
;
5943 staticpro (&Vwrite_region_annotation_buffers
);
5945 DEFVAR_LISP ("write-region-annotations-so-far",
5946 Vwrite_region_annotations_so_far
,
5947 doc
: /* When an annotation function is called, this holds the previous annotations.
5948 These are the annotations made by other annotation functions
5949 that were already called. See also `write-region-annotate-functions'. */);
5950 Vwrite_region_annotations_so_far
= Qnil
;
5952 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers
,
5953 doc
: /* A list of file name handlers that temporarily should not be used.
5954 This applies only to the operation `inhibit-file-name-operation'. */);
5955 Vinhibit_file_name_handlers
= Qnil
;
5957 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation
,
5958 doc
: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
5959 Vinhibit_file_name_operation
= Qnil
;
5961 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name
,
5962 doc
: /* File name in which we write a list of all auto save file names.
5963 This variable is initialized automatically from `auto-save-list-file-prefix'
5964 shortly after Emacs reads your init file, if you have not yet given it
5965 a non-nil value. */);
5966 Vauto_save_list_file_name
= Qnil
;
5968 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name
,
5969 doc
: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
5970 Normally auto-save files are written under other names. */);
5971 Vauto_save_visited_file_name
= Qnil
;
5973 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions
,
5974 doc
: /* If non-nil, auto-save even if a large part of the text is deleted.
5975 If nil, deleting a substantial portion of the text disables auto-save
5976 in the buffer; this is the default behavior, because the auto-save
5977 file is usually more useful if it contains the deleted text. */);
5978 Vauto_save_include_big_deletions
= Qnil
;
5980 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync
,
5981 doc
: /* Non-nil means don't call fsync in `write-region'.
5982 This variable affects calls to `write-region' as well as save commands.
5983 Setting this to nil may avoid data loss if the system loses power or
5984 the operating system crashes. By default, it is non-nil in batch mode. */);
5985 write_region_inhibit_fsync
= 0; /* See also `init_fileio' above. */
5987 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash
,
5988 doc
: /* Specifies whether to use the system's trash can.
5989 When non-nil, certain file deletion commands use the function
5990 `move-file-to-trash' instead of deleting files outright.
5991 This includes interactive calls to `delete-file' and
5992 `delete-directory' and the Dired deletion commands. */);
5993 delete_by_moving_to_trash
= 0;
5994 DEFSYM (Qdelete_by_moving_to_trash
, "delete-by-moving-to-trash");
5996 /* Lisp function for moving files to trash. */
5997 DEFSYM (Qmove_file_to_trash
, "move-file-to-trash");
5999 /* Lisp function for recursively copying directories. */
6000 DEFSYM (Qcopy_directory
, "copy-directory");
6002 /* Lisp function for recursively deleting directories. */
6003 DEFSYM (Qdelete_directory
, "delete-directory");
6005 DEFSYM (Qsubstitute_env_in_file_name
, "substitute-env-in-file-name");
6006 DEFSYM (Qget_buffer_window_list
, "get-buffer-window-list");
6008 DEFSYM (Qstdin
, "stdin");
6009 DEFSYM (Qstdout
, "stdout");
6010 DEFSYM (Qstderr
, "stderr");
6012 defsubr (&Sfind_file_name_handler
);
6013 defsubr (&Sfile_name_directory
);
6014 defsubr (&Sfile_name_nondirectory
);
6015 defsubr (&Sunhandled_file_name_directory
);
6016 defsubr (&Sfile_name_as_directory
);
6017 defsubr (&Sdirectory_file_name
);
6018 defsubr (&Smake_temp_name
);
6019 defsubr (&Sexpand_file_name
);
6020 defsubr (&Ssubstitute_in_file_name
);
6021 defsubr (&Scopy_file
);
6022 defsubr (&Smake_directory_internal
);
6023 defsubr (&Sdelete_directory_internal
);
6024 defsubr (&Sdelete_file
);
6025 defsubr (&Srename_file
);
6026 defsubr (&Sadd_name_to_file
);
6027 defsubr (&Smake_symbolic_link
);
6028 defsubr (&Sfile_name_absolute_p
);
6029 defsubr (&Sfile_exists_p
);
6030 defsubr (&Sfile_executable_p
);
6031 defsubr (&Sfile_readable_p
);
6032 defsubr (&Sfile_writable_p
);
6033 defsubr (&Saccess_file
);
6034 defsubr (&Sfile_symlink_p
);
6035 defsubr (&Sfile_directory_p
);
6036 defsubr (&Sfile_accessible_directory_p
);
6037 defsubr (&Sfile_regular_p
);
6038 defsubr (&Sfile_modes
);
6039 defsubr (&Sset_file_modes
);
6040 defsubr (&Sset_file_times
);
6041 defsubr (&Sfile_selinux_context
);
6042 defsubr (&Sfile_acl
);
6043 defsubr (&Sset_file_acl
);
6044 defsubr (&Sset_file_selinux_context
);
6045 defsubr (&Sset_default_file_modes
);
6046 defsubr (&Sdefault_file_modes
);
6047 defsubr (&Sfile_newer_than_file_p
);
6048 defsubr (&Sinsert_file_contents
);
6049 defsubr (&Swrite_region
);
6050 defsubr (&Scar_less_than_car
);
6051 defsubr (&Sverify_visited_file_modtime
);
6052 defsubr (&Svisited_file_modtime
);
6053 defsubr (&Sset_visited_file_modtime
);
6054 defsubr (&Sdo_auto_save
);
6055 defsubr (&Sset_buffer_auto_saved
);
6056 defsubr (&Sclear_buffer_auto_save_failure
);
6057 defsubr (&Srecent_auto_save_p
);
6059 defsubr (&Snext_read_file_uses_dialog_p
);
6061 defsubr (&Sset_binary_mode
);
6064 defsubr (&Sunix_sync
);