* progmodes/octave.el (inferior-octave-strip-ctrl-g)
[bpt/emacs.git] / src / fileio.c
CommitLineData
570d7624 1/* File IO for GNU Emacs.
e9bffc61 2
ab422c4d 3Copyright (C) 1985-1988, 1993-2013 Free Software Foundation, Inc.
570d7624
JB
4
5This file is part of GNU Emacs.
6
9ec0b715 7GNU Emacs is free software: you can redistribute it and/or modify
570d7624 8it under the terms of the GNU General Public License as published by
9ec0b715
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
570d7624
JB
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
9ec0b715 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
570d7624 19
18160b98 20#include <config.h>
77a28bbf 21#include <limits.h>
bb369dc6 22#include <fcntl.h>
1b335d29 23#include <stdio.h>
570d7624
JB
24#include <sys/types.h>
25#include <sys/stat.h>
29beb080 26#include <unistd.h>
29beb080 27
5b9c0a1d 28#ifdef HAVE_PWD_H
570d7624 29#include <pwd.h>
bfb61299
JB
30#endif
31
570d7624
JB
32#include <errno.h>
33
574c05e2
KK
34#ifdef HAVE_LIBSELINUX
35#include <selinux/selinux.h>
36#include <selinux/context.h>
37#endif
38
7c3d167f
RF
39#ifdef HAVE_POSIX_ACL
40#include <sys/acl.h>
41#endif
42
620f13b0
PE
43#include <c-ctype.h>
44
570d7624 45#include "lisp.h"
8d4e077b 46#include "intervals.h"
db327c7e 47#include "character.h"
e5560ff7 48#include "buffer.h"
6fdaa9a0 49#include "coding.h"
570d7624 50#include "window.h"
67c08d6c 51#include "blockinput.h"
385ed61f
KL
52#include "frame.h"
53#include "dispextern.h"
570d7624 54
5e570b75
RS
55#ifdef WINDOWSNT
56#define NOMINMAX 1
57#include <windows.h>
5e570b75 58#include <fcntl.h>
bb385a92 59#include <sys/file.h>
a68089e4 60#include "w32.h"
5e570b75
RS
61#endif /* not WINDOWSNT */
62
7990d02a
EZ
63#ifdef MSDOS
64#include "msdos.h"
65#include <sys/param.h>
7990d02a 66#include <fcntl.h>
7990d02a 67#endif
7990d02a 68
199607e4 69#ifdef DOS_NT
199607e4 70/* On Windows, drive letters must be alphabetic - on DOS, the Netware
a5bb9bd3 71 redirector allows the six letters between 'Z' and 'a' as well. */
199607e4
RS
72#ifdef MSDOS
73#define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
74#endif
75#ifdef WINDOWSNT
620f13b0 76#define IS_DRIVE(x) c_isalpha (x)
199607e4 77#endif
f54b565c 78/* Need to lower-case the drive letter, or else expanded
53964682 79 filenames will sometimes compare unequal, because
f54b565c 80 `expand-file-name' doesn't always down-case the drive letter. */
620f13b0 81#define DRIVE_LETTER(x) c_tolower (x)
199607e4
RS
82#endif
83
5406cfd9
RF
84#ifdef HAVE_POSIX_ACL
85/* FIXME: this macro was copied from gnulib's private acl-internal.h
86 header file. */
87/* Recognize some common errors such as from an NFS mount that does
88 not support ACLs, even when local drives do. */
89#if defined __APPLE__ && defined __MACH__ /* Mac OS X */
90#define ACL_NOT_WELL_SUPPORTED(Err) \
91 ((Err) == ENOTSUP || (Err) == ENOSYS || (Err) == EINVAL || (Err) == EBUSY || (Err) == ENOENT)
92#elif defined EOPNOTSUPP /* Tru64 NFS */
93#define ACL_NOT_WELL_SUPPORTED(Err) \
94 ((Err) == ENOTSUP || (Err) == ENOSYS || (Err) == EINVAL || (Err) == EBUSY || (Err) == EOPNOTSUPP)
7d9f6883
EZ
95#elif defined WINDOWSNT
96#define ACL_NOT_WELL_SUPPORTED(Err) ((Err) == ENOTSUP)
5406cfd9
RF
97#else
98#define ACL_NOT_WELL_SUPPORTED(Err) \
99 ((Err) == ENOTSUP || (Err) == ENOSYS || (Err) == EINVAL || (Err) == EBUSY)
100#endif
101#endif /* HAVE_POSIX_ACL */
102
de5bf5d3 103#include "systime.h"
8654f9d7
PE
104#include <allocator.h>
105#include <careadlinkat.h>
d35af63c 106#include <stat-time.h>
570d7624
JB
107
108#ifdef HPUX
109#include <netio.h>
47e7b9e5 110#endif
570d7624 111
9c856db9 112#include "commands.h"
9c856db9 113
f75d7a91
PE
114/* True during writing of auto-save files. */
115static bool auto_saving;
570d7624 116
71873e2b 117/* Nonzero umask during creation of auto-save directories. */
f75d7a91 118static mode_t auto_saving_dir_umask;
09450bae 119
570d7624 120/* Set by auto_save_1 to mode of original file so Fwrite_region will create
71873e2b 121 a new file with the same mode as the original. */
f75d7a91 122static mode_t auto_save_mode_bits;
570d7624 123
71873e2b 124/* Set by auto_save_1 if an error occurred during the last auto-save. */
f75d7a91 125static bool auto_save_error_occurred;
ca730bf0 126
9fe43ff6
PE
127/* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
128 number of a file system where time stamps were observed to to work. */
129static bool valid_timestamp_file_system;
130static dev_t timestamp_file_system;
131
356a6224
KH
132/* The symbol bound to coding-system-for-read when
133 insert-file-contents is called for recovering a file. This is not
134 an actual coding system name, but just an indicator to tell
135 insert-file-contents to use `emacs-mule' with a special flag for
136 auto saving and recovering a file. */
955cbe7b 137static Lisp_Object Qauto_save_coding;
356a6224 138
f6c9b683
RS
139/* Property name of a file name handler,
140 which gives a list of operations it handles.. */
955cbe7b 141static Lisp_Object Qoperations;
f6c9b683 142
71873e2b 143/* Lisp functions for translating file formats. */
955cbe7b 144static Lisp_Object Qformat_decode, Qformat_annotate_function;
0d420e88 145
2080470e 146/* Lisp function for setting buffer-file-coding-system and the
b6426b03 147 multibyteness of the current buffer after inserting a file. */
955cbe7b 148static Lisp_Object Qafter_insert_file_set_coding;
b6426b03 149
955cbe7b 150static Lisp_Object Qwrite_region_annotate_functions;
67fbc0cb
CY
151/* Each time an annotation function changes the buffer, the new buffer
152 is added here. */
5045092b 153static Lisp_Object Vwrite_region_annotation_buffers;
67fbc0cb 154
955cbe7b 155static Lisp_Object Qdelete_by_moving_to_trash;
d2b66acf 156
6cf29fe8 157/* Lisp function for moving files to trash. */
955cbe7b 158static Lisp_Object Qmove_file_to_trash;
6cf29fe8 159
8719abec 160/* Lisp function for recursively copying directories. */
955cbe7b 161static Lisp_Object Qcopy_directory;
8719abec
CY
162
163/* Lisp function for recursively deleting directories. */
955cbe7b 164static Lisp_Object Qdelete_directory;
8719abec 165
c1c4693e 166#ifdef WINDOWSNT
c1c4693e
RS
167#endif
168
955cbe7b
PE
169Lisp_Object Qfile_error;
170static Lisp_Object Qfile_already_exists, Qfile_date_error;
171static Lisp_Object Qexcl;
15c65264
RS
172Lisp_Object Qfile_name_history;
173
955cbe7b 174static Lisp_Object Qcar_less_than_car;
d6a3cc15 175
f75d7a91
PE
176static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
177 Lisp_Object *, struct coding_system *);
178static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
179 struct coding_system *);
ce51c54c 180
ec7adf26 181\f
5d01d666 182void
971de7fb 183report_file_error (const char *string, Lisp_Object data)
570d7624
JB
184{
185 Lisp_Object errstring;
505ab9bc 186 int errorno = errno;
d7259fdb 187 char *str;
570d7624 188
ca9c0567 189 synchronize_system_messages_locale ();
d7259fdb 190 str = strerror (errorno);
d7ea76b4 191 errstring = code_convert_string_norecord (build_unibyte_string (str),
68c45bf0
PE
192 Vlocale_coding_system, 0);
193
570d7624 194 while (1)
505ab9bc
RS
195 switch (errorno)
196 {
197 case EEXIST:
24b1ddad 198 xsignal (Qfile_already_exists, Fcons (errstring, data));
505ab9bc
RS
199 break;
200 default:
201 /* System error messages are capitalized. Downcase the initial
39824137
EZ
202 unless it is followed by a slash. (The slash case caters to
203 error messages that begin with "I/O" or, in German, "E/A".) */
d5443ffd
KH
204 if (STRING_MULTIBYTE (errstring)
205 && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
6c0969ca
KH
206 {
207 int c;
208
51b59d79 209 str = SSDATA (errstring);
5976c3fe 210 c = STRING_CHAR ((unsigned char *) str);
5da9919f 211 Faset (errstring, make_number (0), make_number (downcase (c)));
6c0969ca 212 }
505ab9bc 213
24b1ddad 214 xsignal (Qfile_error,
505ab9bc
RS
215 Fcons (build_string (string), Fcons (errstring, data)));
216 }
570d7624 217}
b5148e85 218
b27a1703 219Lisp_Object
971de7fb 220close_file_unwind (Lisp_Object fd)
b5148e85 221{
68c45bf0 222 emacs_close (XFASTINT (fd));
b27a1703 223 return Qnil;
b5148e85 224}
a1d2b64a
RS
225
226/* Restore point, having saved it as a marker. */
227
5dcde606 228Lisp_Object
971de7fb 229restore_point_unwind (Lisp_Object location)
a1d2b64a 230{
ec7adf26 231 Fgoto_char (location);
a1d2b64a 232 Fset_marker (location, Qnil, Qnil);
b27a1703 233 return Qnil;
a1d2b64a 234}
59c94f03 235
570d7624 236\f
955cbe7b
PE
237static Lisp_Object Qexpand_file_name;
238static Lisp_Object Qsubstitute_in_file_name;
239static Lisp_Object Qdirectory_file_name;
240static Lisp_Object Qfile_name_directory;
241static Lisp_Object Qfile_name_nondirectory;
242static Lisp_Object Qunhandled_file_name_directory;
243static Lisp_Object Qfile_name_as_directory;
244static Lisp_Object Qcopy_file;
245static Lisp_Object Qmake_directory_internal;
246static Lisp_Object Qmake_directory;
247static Lisp_Object Qdelete_directory_internal;
32f4334d 248Lisp_Object Qdelete_file;
955cbe7b
PE
249static Lisp_Object Qrename_file;
250static Lisp_Object Qadd_name_to_file;
251static Lisp_Object Qmake_symbolic_link;
32f4334d 252Lisp_Object Qfile_exists_p;
955cbe7b
PE
253static Lisp_Object Qfile_executable_p;
254static Lisp_Object Qfile_readable_p;
255static Lisp_Object Qfile_writable_p;
256static Lisp_Object Qfile_symlink_p;
257static Lisp_Object Qaccess_file;
32f4334d 258Lisp_Object Qfile_directory_p;
955cbe7b
PE
259static Lisp_Object Qfile_regular_p;
260static Lisp_Object Qfile_accessible_directory_p;
261static Lisp_Object Qfile_modes;
262static Lisp_Object Qset_file_modes;
263static Lisp_Object Qset_file_times;
264static Lisp_Object Qfile_selinux_context;
265static Lisp_Object Qset_file_selinux_context;
7c3d167f
RF
266static Lisp_Object Qfile_acl;
267static Lisp_Object Qset_file_acl;
955cbe7b 268static Lisp_Object Qfile_newer_than_file_p;
32f4334d 269Lisp_Object Qinsert_file_contents;
3f011c7f 270static Lisp_Object Qchoose_write_coding_system;
32f4334d 271Lisp_Object Qwrite_region;
955cbe7b
PE
272static Lisp_Object Qverify_visited_file_modtime;
273static Lisp_Object Qset_visited_file_modtime;
32f4334d 274
a7ca3326 275DEFUN ("find-file-name-handler", Ffind_file_name_handler,
16a97296 276 Sfind_file_name_handler, 2, 2, 0,
8c1a1077
PJ
277 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
278Otherwise, return nil.
279A file name is handled if one of the regular expressions in
280`file-name-handler-alist' matches it.
281
282If OPERATION equals `inhibit-file-name-operation', then we ignore
283any handlers that are members of `inhibit-file-name-handlers',
284but we still do run any other handlers. This lets handlers
285use the standard functions without calling themselves recursively. */)
5842a27b 286 (Lisp_Object filename, Lisp_Object operation)
32f4334d 287{
642ef245 288 /* This function must not munge the match data. */
204ee271 289 Lisp_Object chain, inhibited_handlers, result;
d311d28c 290 ptrdiff_t pos = -1;
642ef245 291
204ee271 292 result = Qnil;
b7826503 293 CHECK_STRING (filename);
e4432095 294
a65970a0
RS
295 if (EQ (operation, Vinhibit_file_name_operation))
296 inhibited_handlers = Vinhibit_file_name_handlers;
297 else
298 inhibited_handlers = Qnil;
82c2d839 299
93c30b5f 300 for (chain = Vfile_name_handler_alist; CONSP (chain);
03699b14 301 chain = XCDR (chain))
32f4334d
RS
302 {
303 Lisp_Object elt;
03699b14 304 elt = XCAR (chain);
93c30b5f 305 if (CONSP (elt))
32f4334d 306 {
f6c9b683 307 Lisp_Object string = XCAR (elt);
d311d28c 308 ptrdiff_t match_pos;
f6c9b683 309 Lisp_Object handler = XCDR (elt);
68780e2a
RS
310 Lisp_Object operations = Qnil;
311
312 if (SYMBOLP (handler))
313 operations = Fget (handler, Qoperations);
f6c9b683 314
8d2ced53 315 if (STRINGP (string)
f6c9b683
RS
316 && (match_pos = fast_string_match (string, filename)) > pos
317 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
a65970a0 318 {
f6c9b683 319 Lisp_Object tem;
a65970a0 320
03699b14 321 handler = XCDR (elt);
a65970a0
RS
322 tem = Fmemq (handler, inhibited_handlers);
323 if (NILP (tem))
8d2ced53
SM
324 {
325 result = handler;
326 pos = match_pos;
327 }
a65970a0 328 }
32f4334d 329 }
642ef245
JB
330
331 QUIT;
32f4334d 332 }
8d2ced53 333 return result;
32f4334d
RS
334}
335\f
a7ca3326 336DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
8c1a1077
PJ
337 1, 1, 0,
338 doc: /* Return the directory component in file name FILENAME.
339Return nil if FILENAME does not include a directory.
78379264 340Otherwise return a directory name.
7c2fb837 341Given a Unix syntax file name, returns a string ending in slash. */)
5842a27b 342 (Lisp_Object filename)
570d7624 343{
100c44b7 344#ifndef DOS_NT
5976c3fe 345 register const char *beg;
100c44b7 346#else
5976c3fe 347 register char *beg;
273ac8d1 348 Lisp_Object tem_fn;
100c44b7 349#endif
5976c3fe 350 register const char *p;
0bf2eed2 351 Lisp_Object handler;
570d7624 352
b7826503 353 CHECK_STRING (filename);
570d7624 354
0bf2eed2
RS
355 /* If the file name has special constructs in it,
356 call the corresponding file handler. */
3b7f6e60 357 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
0bf2eed2 358 if (!NILP (handler))
2375c96a
CY
359 {
360 Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
361 filename);
362 return STRINGP (handled_name) ? handled_name : Qnil;
363 }
0bf2eed2 364
199607e4 365#ifdef DOS_NT
38182d90 366 beg = alloca (SBYTES (filename) + 1);
5976c3fe 367 memcpy (beg, SSDATA (filename), SBYTES (filename) + 1);
0f3f018c 368#else
5976c3fe 369 beg = SSDATA (filename);
199607e4 370#endif
d5db4077 371 p = beg + SBYTES (filename);
570d7624 372
199607e4 373 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
199607e4 374#ifdef DOS_NT
e1dbe924 375 /* only recognize drive specifier at the beginning */
ba14e174
RS
376 && !(p[-1] == ':'
377 /* handle the "/:d:foo" and "/:foo" cases correctly */
378 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
379 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
199607e4 380#endif
570d7624
JB
381 ) p--;
382
383 if (p == beg)
384 return Qnil;
5e570b75 385#ifdef DOS_NT
4c3c22f3 386 /* Expansion of "c:" to drive and default directory. */
ba14e174 387 if (p[-1] == ':')
4c3c22f3 388 {
4c3c22f3 389 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
5976c3fe
PE
390 char *res = alloca (MAXPATHLEN + 1);
391 char *r = res;
ba14e174
RS
392
393 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
394 {
e99a530f 395 memcpy (res, beg, 2);
ba14e174
RS
396 beg += 2;
397 r += 2;
398 }
399
620f13b0 400 if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
4c3c22f3 401 {
e7ac588e
EZ
402 size_t l = strlen (res);
403
404 if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
4c3c22f3
RS
405 strcat (res, "/");
406 beg = res;
407 p = beg + strlen (beg);
e7ac588e 408 dostounix_filename (beg, 0);
f5c81c80
EZ
409 tem_fn = make_specified_string (beg, -1, p - beg,
410 STRING_MULTIBYTE (filename));
4c3c22f3 411 }
f5c81c80
EZ
412 else
413 tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
414 STRING_MULTIBYTE (filename));
415 }
416 else if (STRING_MULTIBYTE (filename))
417 {
e7ac588e
EZ
418 tem_fn = make_specified_string (beg, -1, p - beg, 1);
419 dostounix_filename (SSDATA (tem_fn), 1);
420#ifdef WINDOWSNT
421 if (!NILP (Vw32_downcase_file_names))
422 tem_fn = Fdowncase (tem_fn);
423#endif
f5c81c80
EZ
424 }
425 else
426 {
e7ac588e 427 dostounix_filename (beg, 0);
f5c81c80 428 tem_fn = make_specified_string (beg, -1, p - beg, 0);
4c3c22f3 429 }
f5c81c80 430 return tem_fn;
273ac8d1 431#else /* DOS_NT */
d7231f93 432 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
273ac8d1 433#endif /* DOS_NT */
570d7624
JB
434}
435
a7ca3326 436DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
60d67b83 437 Sfile_name_nondirectory, 1, 1, 0,
8c1a1077
PJ
438 doc: /* Return file name FILENAME sans its directory.
439For example, in a Unix-syntax file name,
440this is everything after the last slash,
441or the entire name if it contains no slash. */)
5842a27b 442 (Lisp_Object filename)
570d7624 443{
5976c3fe 444 register const char *beg, *p, *end;
0bf2eed2 445 Lisp_Object handler;
570d7624 446
b7826503 447 CHECK_STRING (filename);
570d7624 448
0bf2eed2
RS
449 /* If the file name has special constructs in it,
450 call the corresponding file handler. */
3b7f6e60 451 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
0bf2eed2 452 if (!NILP (handler))
2375c96a
CY
453 {
454 Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
455 filename);
456 if (STRINGP (handled_name))
457 return handled_name;
458 error ("Invalid handler in `file-name-handler-alist'");
459 }
0bf2eed2 460
5976c3fe 461 beg = SSDATA (filename);
d5db4077 462 end = p = beg + SBYTES (filename);
570d7624 463
199607e4 464 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
199607e4 465#ifdef DOS_NT
e1dbe924 466 /* only recognize drive specifier at beginning */
ba14e174
RS
467 && !(p[-1] == ':'
468 /* handle the "/:d:foo" case correctly */
469 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
199607e4 470#endif
60d67b83
RS
471 )
472 p--;
570d7624 473
d7231f93 474 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
570d7624 475}
642ef245 476
a7ca3326 477DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
60d67b83 478 Sunhandled_file_name_directory, 1, 1, 0,
8c1a1077
PJ
479 doc: /* Return a directly usable directory name somehow associated with FILENAME.
480A `directly usable' directory name is one that may be used without the
481intervention of any file handler.
482If FILENAME is a directly usable file itself, return
483\(file-name-directory FILENAME).
ca319910
SM
484If FILENAME refers to a file which is not accessible from a local process,
485then this should return nil.
8c1a1077
PJ
486The `call-process' and `start-process' functions use this function to
487get a current directory to run processes in. */)
5842a27b 488 (Lisp_Object filename)
642ef245
JB
489{
490 Lisp_Object handler;
491
492 /* If the file name has special constructs in it,
493 call the corresponding file handler. */
49307295 494 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
642ef245 495 if (!NILP (handler))
2375c96a
CY
496 {
497 Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
498 filename);
499 return STRINGP (handled_name) ? handled_name : Qnil;
500 }
642ef245
JB
501
502 return Ffile_name_directory (filename);
503}
504
f5c81c80
EZ
505/* Convert from file name SRC of length SRCLEN to directory name in
506 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
507 string. On UNIX, just make sure there is a terminating /. Return
508 the length of DST in bytes. */
570d7624 509
c293e30c 510static ptrdiff_t
f5c81c80
EZ
511file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
512 bool multibyte)
c293e30c
DA
513{
514 if (srclen == 0)
8aa3a244 515 {
c293e30c
DA
516 dst[0] = '.';
517 dst[1] = '/';
518 dst[2] = '\0';
519 return 2;
8aa3a244
RS
520 }
521
c293e30c 522 strcpy (dst, src);
93f4cf88 523
c293e30c 524 if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
5e570b75 525 {
c293e30c
DA
526 dst[srclen] = DIRECTORY_SEP;
527 dst[srclen + 1] = '\0';
528 srclen++;
5e570b75 529 }
199607e4 530#ifdef DOS_NT
e7ac588e 531 dostounix_filename (dst, multibyte);
199607e4 532#endif
c293e30c 533 return srclen;
570d7624
JB
534}
535
a7ca3326 536DEFUN ("file-name-as-directory", Ffile_name_as_directory,
570d7624 537 Sfile_name_as_directory, 1, 1, 0,
0dac4f85 538 doc: /* Return a string representing the file name FILE interpreted as a directory.
8c1a1077
PJ
539This operation exists because a directory is also a file, but its name as
540a directory is different from its name as a file.
541The result can be used as the value of `default-directory'
542or passed as second argument to `expand-file-name'.
7c2fb837 543For a Unix-syntax file name, just appends a slash. */)
5842a27b 544 (Lisp_Object file)
570d7624
JB
545{
546 char *buf;
c293e30c 547 ptrdiff_t length;
0bf2eed2 548 Lisp_Object handler;
570d7624 549
b7826503 550 CHECK_STRING (file);
265a9e55 551 if (NILP (file))
570d7624 552 return Qnil;
0bf2eed2
RS
553
554 /* If the file name has special constructs in it,
555 call the corresponding file handler. */
49307295 556 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
0bf2eed2 557 if (!NILP (handler))
2375c96a
CY
558 {
559 Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
560 file);
561 if (STRINGP (handled_name))
562 return handled_name;
563 error ("Invalid handler in `file-name-handler-alist'");
564 }
0bf2eed2 565
e7ac588e
EZ
566#ifdef WINDOWSNT
567 if (!NILP (Vw32_downcase_file_names))
568 file = Fdowncase (file);
569#endif
38182d90 570 buf = alloca (SBYTES (file) + 10);
f5c81c80
EZ
571 length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
572 STRING_MULTIBYTE (file));
c293e30c 573 return make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
570d7624
JB
574}
575\f
f5c81c80
EZ
576/* Convert from directory name SRC of length SRCLEN to file name in
577 DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
578 string. On UNIX, just make sure there isn't a terminating /.
579 Return the length of DST in bytes. */
570d7624 580
c293e30c 581static ptrdiff_t
f5c81c80 582directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
570d7624 583{
570d7624
JB
584 /* Process as Unix format: just remove any final slash.
585 But leave "/" unchanged; do not change it to "". */
586 strcpy (dst, src);
c293e30c
DA
587 if (srclen > 1
588 && IS_DIRECTORY_SEP (dst[srclen - 1])
4592782e 589#ifdef DOS_NT
c293e30c 590 && !IS_ANY_SEP (dst[srclen - 2])
4592782e
RS
591#endif
592 )
c293e30c
DA
593 {
594 dst[srclen - 1] = 0;
595 srclen--;
596 }
199607e4 597#ifdef DOS_NT
e7ac588e 598 dostounix_filename (dst, multibyte);
125feee8 599#endif
c293e30c 600 return srclen;
570d7624
JB
601}
602
a7ca3326 603DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
8c1a1077
PJ
604 1, 1, 0,
605 doc: /* Returns the file name of the directory named DIRECTORY.
606This is the name of the file that holds the data for the directory DIRECTORY.
607This operation exists because a directory is also a file, but its name as
608a directory is different from its name as a file.
7c2fb837 609In Unix-syntax, this function just removes the final slash. */)
5842a27b 610 (Lisp_Object directory)
570d7624
JB
611{
612 char *buf;
c293e30c 613 ptrdiff_t length;
0bf2eed2 614 Lisp_Object handler;
570d7624 615
b7826503 616 CHECK_STRING (directory);
570d7624 617
265a9e55 618 if (NILP (directory))
570d7624 619 return Qnil;
0bf2eed2
RS
620
621 /* If the file name has special constructs in it,
622 call the corresponding file handler. */
49307295 623 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
0bf2eed2 624 if (!NILP (handler))
2375c96a
CY
625 {
626 Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
627 directory);
628 if (STRINGP (handled_name))
629 return handled_name;
630 error ("Invalid handler in `file-name-handler-alist'");
631 }
0bf2eed2 632
e7ac588e
EZ
633#ifdef WINDOWSNT
634 if (!NILP (Vw32_downcase_file_names))
635 directory = Fdowncase (directory);
636#endif
38182d90 637 buf = alloca (SBYTES (directory) + 20);
f5c81c80
EZ
638 length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
639 STRING_MULTIBYTE (directory));
c293e30c 640 return make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
570d7624
JB
641}
642
91433552 643static const char make_temp_name_tbl[64] =
3ce839e4
RS
644{
645 'A','B','C','D','E','F','G','H',
646 'I','J','K','L','M','N','O','P',
647 'Q','R','S','T','U','V','W','X',
648 'Y','Z','a','b','c','d','e','f',
649 'g','h','i','j','k','l','m','n',
650 'o','p','q','r','s','t','u','v',
651 'w','x','y','z','0','1','2','3',
652 '4','5','6','7','8','9','-','_'
653};
cb613bb8 654
3ce839e4
RS
655static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
656
cb613bb8 657/* Value is a temporary file name starting with PREFIX, a string.
efdc16c9 658
cb613bb8
GM
659 The Emacs process number forms part of the result, so there is
660 no danger of generating a name being used by another process.
661 In addition, this function makes an attempt to choose a name
662 which has no existing file. To make this work, PREFIX should be
663 an absolute file name.
efdc16c9 664
f75d7a91 665 BASE64_P means add the pid as 3 characters in base64
cb613bb8
GM
666 encoding. In this case, 6 characters will be added to PREFIX to
667 form the file name. Otherwise, if Emacs is running on a system
668 with long file names, add the pid as a decimal number.
669
670 This function signals an error if no unique file name could be
671 generated. */
672
673Lisp_Object
f75d7a91 674make_temp_name (Lisp_Object prefix, bool base64_p)
570d7624
JB
675{
676 Lisp_Object val;
0cedd530 677 int len, clen;
a81d11a3 678 printmax_t pid;
5976c3fe 679 char *p, *data;
a81d11a3 680 char pidbuf[INT_BUFSIZE_BOUND (printmax_t)];
3ce839e4 681 int pidlen;
efdc16c9 682
b7826503 683 CHECK_STRING (prefix);
3ce839e4
RS
684
685 /* VAL is created by adding 6 characters to PREFIX. The first
686 three are the PID of this process, in base 64, and the second
687 three are incremented if the file already exists. This ensures
688 262144 unique file names per PID per PREFIX. */
689
93f4cf88 690 pid = getpid ();
3ce839e4 691
cb613bb8
GM
692 if (base64_p)
693 {
694 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
695 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
696 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
697 pidlen = 3;
698 }
699 else
700 {
3ce839e4 701#ifdef HAVE_LONG_FILE_NAMES
a81d11a3 702 pidlen = sprintf (pidbuf, "%"pMd, pid);
3a3bfb18 703#else
cb613bb8
GM
704 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
705 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
706 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
707 pidlen = 3;
3ce839e4 708#endif
cb613bb8 709 }
efdc16c9 710
0cedd530
SM
711 len = SBYTES (prefix); clen = SCHARS (prefix);
712 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
713 if (!STRING_MULTIBYTE (prefix))
714 STRING_SET_UNIBYTE (val);
5976c3fe
PE
715 data = SSDATA (val);
716 memcpy (data, SSDATA (prefix), len);
3ce839e4
RS
717 p = data + len;
718
72af86bd 719 memcpy (p, pidbuf, pidlen);
3ce839e4
RS
720 p += pidlen;
721
722 /* Here we try to minimize useless stat'ing when this function is
723 invoked many times successively with the same PREFIX. We achieve
724 this by initializing count to a random value, and incrementing it
f6a492a9
RS
725 afterwards.
726
727 We don't want make-temp-name to be called while dumping,
728 because then make_temp_name_count_initialized_p would get set
729 and then make_temp_name_count would not be set when Emacs starts. */
730
3ce839e4
RS
731 if (!make_temp_name_count_initialized_p)
732 {
327eeec8 733 make_temp_name_count = time (NULL);
3ce839e4
RS
734 make_temp_name_count_initialized_p = 1;
735 }
736
737 while (1)
738 {
8a7777fc 739 unsigned num = make_temp_name_count;
3ce839e4
RS
740
741 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
742 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
743 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
744
8a7777fc
RS
745 /* Poor man's congruential RN generator. Replace with
746 ++make_temp_name_count for debugging. */
747 make_temp_name_count += 25229;
748 make_temp_name_count %= 225307;
749
bb385a92 750 if (!check_existing (data))
3ce839e4
RS
751 {
752 /* We want to return only if errno is ENOENT. */
753 if (errno == ENOENT)
754 return val;
755 else
756 /* The error here is dubious, but there is little else we
757 can do. The alternatives are to return nil, which is
758 as bad as (and in many cases worse than) throwing the
759 error, or to ignore the error, which will likely result
8a7777fc 760 in looping through 225307 stat's, which is not only
410ed5c3
PE
761 dog-slow, but also useless since eventually nil would
762 have to be returned anyway. */
9869bb0b 763 report_file_error ("Cannot create temporary name for prefix",
3ce839e4
RS
764 Fcons (prefix, Qnil));
765 /* not reached */
766 }
767 }
570d7624 768}
3ce839e4 769
cb613bb8
GM
770
771DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
8c1a1077
PJ
772 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
773The Emacs process number forms part of the result,
774so there is no danger of generating a name being used by another process.
775
776In addition, this function makes an attempt to choose a name
777which has no existing file. To make this work,
778PREFIX should be an absolute file name.
779
780There is a race condition between calling `make-temp-name' and creating the
781file which opens all kinds of security holes. For that reason, you should
f9e6f049
RS
782probably use `make-temp-file' instead, except in three circumstances:
783
784* If you are creating the file in the user's home directory.
785* If you are creating a directory rather than an ordinary file.
786* If you are taking special precautions as `make-temp-file' does. */)
5842a27b 787 (Lisp_Object prefix)
cb613bb8
GM
788{
789 return make_temp_name (prefix, 0);
790}
791
792
570d7624 793\f
a7ca3326 794DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
8c1a1077
PJ
795 doc: /* Convert filename NAME to absolute, and canonicalize it.
796Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
78379264 797\(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
a4e03fe5 798the current buffer's value of `default-directory' is used.
1b2a627f
EZ
799NAME should be a string that is a valid file name for the underlying
800filesystem.
8c1a1077
PJ
801File name components that are `.' are removed, and
802so are file name components followed by `..', along with the `..' itself;
803note that these simplifications are done without checking the resulting
804file names in the file system.
15579471
EZ
805Multiple consecutive slashes are collapsed into a single slash,
806except at the beginning of the file name when they are significant (e.g.,
807UNC file names on MS-Windows.)
8c1a1077
PJ
808An initial `~/' expands to your home directory.
809An initial `~USER/' expands to USER's home directory.
07114296
CY
810See also the function `substitute-in-file-name'.
811
812For technical reasons, this function can return correct but
813non-intuitive results for the root directory; for instance,
814\(expand-file-name ".." "/") returns "/..". For this reason, use
15579471 815\(directory-file-name (file-name-directory dirname)) to traverse a
07114296 816filesystem tree, not (expand-file-name ".." dirname). */)
5842a27b 817 (Lisp_Object name, Lisp_Object default_directory)
570d7624 818{
5b5a2ea1
SM
819 /* These point to SDATA and need to be careful with string-relocation
820 during GC (via DECODE_FILE). */
2893f146
PE
821 char *nm;
822 const char *newdir;
5b5a2ea1 823 /* This should only point to alloca'd data. */
5976c3fe 824 char *target;
199607e4 825
93f4cf88 826 ptrdiff_t tlen;
570d7624 827 struct passwd *pw;
5e570b75 828#ifdef DOS_NT
199607e4 829 int drive = 0;
f75d7a91
PE
830 bool collapse_newdir = 1;
831 bool is_escaped = 0;
5e570b75 832#endif /* DOS_NT */
93f4cf88 833 ptrdiff_t length;
2375c96a 834 Lisp_Object handler, result, handled_name;
fce31d69 835 bool multibyte;
9c06a1f3 836 Lisp_Object hdir;
199607e4 837
b7826503 838 CHECK_STRING (name);
570d7624 839
0bf2eed2
RS
840 /* If the file name has special constructs in it,
841 call the corresponding file handler. */
49307295 842 handler = Ffind_file_name_handler (name, Qexpand_file_name);
0bf2eed2 843 if (!NILP (handler))
2375c96a
CY
844 {
845 handled_name = call3 (handler, Qexpand_file_name,
846 name, default_directory);
847 if (STRINGP (handled_name))
848 return handled_name;
849 error ("Invalid handler in `file-name-handler-alist'");
850 }
851
58fc9587 852
3b7f6e60
EN
853 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
854 if (NILP (default_directory))
4b4deea2 855 default_directory = BVAR (current_buffer, directory);
82330e7f 856 if (! STRINGP (default_directory))
dd693537
EZ
857 {
858#ifdef DOS_NT
859 /* "/" is not considered a root directory on DOS_NT, so using "/"
860 here causes an infinite recursion in, e.g., the following:
861
862 (let (default-directory)
863 (expand-file-name "a"))
864
865 To avoid this, we set default_directory to the root of the
866 current drive. */
dd693537
EZ
867 default_directory = build_string (emacs_root_dir ());
868#else
869 default_directory = build_string ("/");
870#endif
871 }
58fc9587 872
3b7f6e60 873 if (!NILP (default_directory))
273e0829 874 {
3b7f6e60 875 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
273e0829 876 if (!NILP (handler))
2375c96a
CY
877 {
878 handled_name = call3 (handler, Qexpand_file_name,
879 name, default_directory);
880 if (STRINGP (handled_name))
881 return handled_name;
882 error ("Invalid handler in `file-name-handler-alist'");
883 }
273e0829 884 }
0bf2eed2 885
5b5a2ea1 886 {
5976c3fe 887 char *o = SSDATA (default_directory);
5b5a2ea1
SM
888
889 /* Make sure DEFAULT_DIRECTORY is properly expanded.
890 It would be better to do this down below where we actually use
891 default_directory. Unfortunately, calling Fexpand_file_name recursively
892 could invoke GC, and the strings might be relocated. This would
893 be annoying because we have pointers into strings lying around
894 that would need adjusting, and people would add new pointers to
895 the code and forget to adjust them, resulting in intermittent bugs.
896 Putting this call here avoids all that crud.
897
898 The EQ test avoids infinite recursion. */
899 if (! NILP (default_directory) && !EQ (default_directory, name)
900 /* Save time in some common cases - as long as default_directory
901 is not relative, it can be canonicalized with name below (if it
902 is needed at all) without requiring it to be expanded now. */
01937013 903#ifdef DOS_NT
5b5a2ea1
SM
904 /* Detect MSDOS file names with drive specifiers. */
905 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
906 && IS_DIRECTORY_SEP (o[2]))
199607e4 907#ifdef WINDOWSNT
5b5a2ea1
SM
908 /* Detect Windows file names in UNC format. */
909 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
01937013 910#endif
199607e4
RS
911#else /* not DOS_NT */
912 /* Detect Unix absolute file names (/... alone is not absolute on
913 DOS or Windows). */
5b5a2ea1 914 && ! (IS_DIRECTORY_SEP (o[0]))
199607e4 915#endif /* not DOS_NT */
5b5a2ea1
SM
916 )
917 {
918 struct gcpro gcpro1;
f14b1c68 919
5b5a2ea1
SM
920 GCPRO1 (name);
921 default_directory = Fexpand_file_name (default_directory, Qnil);
922 UNGCPRO;
923 }
924 }
2b046a72 925 multibyte = STRING_MULTIBYTE (name);
6d060996
KH
926 if (multibyte != STRING_MULTIBYTE (default_directory))
927 {
928 if (multibyte)
929 default_directory = string_to_multibyte (default_directory);
930 else
931 {
932 name = string_to_multibyte (name);
933 multibyte = 1;
934 }
935 }
936
e7ac588e
EZ
937#ifdef WINDOWSNT
938 if (!NILP (Vw32_downcase_file_names))
939 default_directory = Fdowncase (default_directory);
940#endif
941
e8d32c7e 942 /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
38182d90 943 nm = alloca (SBYTES (name) + 1);
5976c3fe 944 memcpy (nm, SSDATA (name), SBYTES (name) + 1);
199607e4 945
565f0b98 946#ifdef DOS_NT
f0f95d31
RS
947 /* Note if special escape prefix is present, but remove for now. */
948 if (nm[0] == '/' && nm[1] == ':')
949 {
950 is_escaped = 1;
951 nm += 2;
952 }
953
199607e4 954 /* Find and remove drive specifier if present; this makes nm absolute
f0f95d31
RS
955 even if the rest of the name appears to be relative. Only look for
956 drive specifier at the beginning. */
957 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
958 {
5976c3fe 959 drive = (unsigned char) nm[0];
f0f95d31
RS
960 nm += 2;
961 }
bb1ff1f4
GV
962
963#ifdef WINDOWSNT
964 /* If we see "c://somedir", we want to strip the first slash after the
965 colon when stripping the drive letter. Otherwise, this expands to
966 "//somedir". */
967 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
968 nm++;
4c3c22f3 969
e8d32c7e 970 /* Discard any previous drive specifier if nm is now in UNC format. */
199607e4
RS
971 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
972 {
973 drive = 0;
974 }
5b5a2ea1
SM
975#endif /* WINDOWSNT */
976#endif /* DOS_NT */
199607e4 977
214378ec
GM
978 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
979 none are found, we can probably return right away. We will avoid
980 allocating a new string if name is already fully expanded. */
570d7624 981 if (
5e570b75 982 IS_DIRECTORY_SEP (nm[0])
199607e4 983#ifdef MSDOS
f0f95d31 984 && drive && !is_escaped
199607e4
RS
985#endif
986#ifdef WINDOWSNT
f0f95d31 987 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
199607e4 988#endif
570d7624
JB
989 )
990 {
f14b1c68
JB
991 /* If it turns out that the filename we want to return is just a
992 suffix of FILENAME, we don't need to go through and edit
993 things; we just need to construct a new string using data
f75d7a91
PE
994 starting at the middle of FILENAME. If we set LOSE, that
995 means we've discovered that we can't do that cool trick. */
996 bool lose = 0;
5976c3fe 997 char *p = nm;
f14b1c68 998
570d7624
JB
999 while (*p)
1000 {
199607e4 1001 /* Since we know the name is absolute, we can assume that each
c77d647e
JB
1002 element starts with a "/". */
1003
c77d647e 1004 /* "." and ".." are hairy. */
5e570b75 1005 if (IS_DIRECTORY_SEP (p[0])
c77d647e 1006 && p[1] == '.'
5e570b75 1007 && (IS_DIRECTORY_SEP (p[2])
c77d647e 1008 || p[2] == 0
5e570b75 1009 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
c77d647e 1010 || p[3] == 0))))
570d7624 1011 lose = 1;
214378ec
GM
1012 /* We want to replace multiple `/' in a row with a single
1013 slash. */
1014 else if (p > nm
1015 && IS_DIRECTORY_SEP (p[0])
1016 && IS_DIRECTORY_SEP (p[1]))
1017 lose = 1;
570d7624
JB
1018 p++;
1019 }
1020 if (!lose)
1021 {
199607e4 1022#ifdef DOS_NT
087fc47a
JB
1023 /* Make sure directories are all separated with /, but
1024 avoid allocation of a new string when not required. */
e7ac588e 1025 dostounix_filename (nm, multibyte);
199607e4
RS
1026#ifdef WINDOWSNT
1027 if (IS_DIRECTORY_SEP (nm[1]))
1028 {
42a5b22f 1029 if (strcmp (nm, SSDATA (name)) != 0)
2b046a72 1030 name = make_specified_string (nm, -1, strlen (nm), multibyte);
199607e4
RS
1031 }
1032 else
1033#endif
e8d32c7e 1034 /* Drive must be set, so this is okay. */
5976c3fe 1035 if (strcmp (nm - 2, SSDATA (name)) != 0)
199607e4 1036 {
3f817c73
KH
1037 char temp[] = " :";
1038
2b046a72 1039 name = make_specified_string (nm, -1, p - nm, multibyte);
3f817c73
KH
1040 temp[0] = DRIVE_LETTER (drive);
1041 name = concat2 (build_string (temp), name);
199607e4 1042 }
e7ac588e
EZ
1043#ifdef WINDOWSNT
1044 if (!NILP (Vw32_downcase_file_names))
1045 name = Fdowncase (name);
1046#endif
199607e4
RS
1047 return name;
1048#else /* not DOS_NT */
42a5b22f 1049 if (strcmp (nm, SSDATA (name)) == 0)
570d7624 1050 return name;
2b046a72 1051 return make_specified_string (nm, -1, strlen (nm), multibyte);
5e570b75 1052#endif /* not DOS_NT */
570d7624
JB
1053 }
1054 }
1055
199607e4
RS
1056 /* At this point, nm might or might not be an absolute file name. We
1057 need to expand ~ or ~user if present, otherwise prefix nm with
1058 default_directory if nm is not absolute, and finally collapse /./
1059 and /foo/../ sequences.
1060
1061 We set newdir to be the appropriate prefix if one is needed:
1062 - the relevant user directory if nm starts with ~ or ~user
1063 - the specified drive's working dir (DOS/NT only) if nm does not
1064 start with /
1065 - the value of default_directory.
1066
1067 Note that these prefixes are not guaranteed to be absolute (except
1068 for the working dir of a drive). Therefore, to ensure we always
1069 return an absolute name, if the final prefix is not absolute we
1070 append it to the current working directory. */
570d7624
JB
1071
1072 newdir = 0;
1073
1074 if (nm[0] == '~') /* prefix ~ */
c77d647e 1075 {
5e570b75 1076 if (IS_DIRECTORY_SEP (nm[1])
c77d647e
JB
1077 || nm[1] == 0) /* ~ by itself */
1078 {
6d557778
EZ
1079 Lisp_Object tem;
1080
5976c3fe
PE
1081 if (!(newdir = egetenv ("HOME")))
1082 newdir = "";
199607e4 1083 nm++;
e8d32c7e 1084 /* `egetenv' may return a unibyte string, which will bite us since
6d557778 1085 we expect the directory to be multibyte. */
9c06a1f3 1086 tem = build_string (newdir);
f5c81c80 1087 if (multibyte && !STRING_MULTIBYTE (tem))
9c06a1f3
EZ
1088 {
1089 hdir = DECODE_FILE (tem);
5976c3fe 1090 newdir = SSDATA (hdir);
9c06a1f3 1091 }
5e570b75 1092#ifdef DOS_NT
9a1dc3be 1093 collapse_newdir = 0;
4c3c22f3 1094#endif
c77d647e
JB
1095 }
1096 else /* ~user/filename */
1097 {
5976c3fe 1098 char *o, *p;
7c2fb837 1099 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)); p++);
5b5a2ea1 1100 o = alloca (p - nm + 1);
72af86bd 1101 memcpy (o, nm, p - nm);
c77d647e
JB
1102 o [p - nm] = 0;
1103
4d7e6e51 1104 block_input ();
350e0088 1105 pw = getpwnam (o + 1);
4d7e6e51 1106 unblock_input ();
c77d647e
JB
1107 if (pw)
1108 {
f5c81c80
EZ
1109 Lisp_Object tem;
1110
5976c3fe 1111 newdir = pw->pw_dir;
f5c81c80
EZ
1112 /* `getpwnam' may return a unibyte string, which will
1113 bite us since we expect the directory to be
1114 multibyte. */
1115 tem = build_string (newdir);
1116 if (multibyte && !STRING_MULTIBYTE (tem))
1117 {
1118 hdir = DECODE_FILE (tem);
1119 newdir = SSDATA (hdir);
1120 }
c77d647e 1121 nm = p;
199607e4 1122#ifdef DOS_NT
9a1dc3be 1123 collapse_newdir = 0;
199607e4 1124#endif
c77d647e 1125 }
e5d77022 1126
c77d647e
JB
1127 /* If we don't find a user of that name, leave the name
1128 unchanged; don't move nm forward to p. */
1129 }
1130 }
570d7624 1131
5e570b75 1132#ifdef DOS_NT
199607e4
RS
1133 /* On DOS and Windows, nm is absolute if a drive name was specified;
1134 use the drive's current directory as the prefix if needed. */
1135 if (!newdir && drive)
1136 {
e8d32c7e 1137 /* Get default directory if needed to make nm absolute. */
2893f146 1138 char *adir = NULL;
199607e4
RS
1139 if (!IS_DIRECTORY_SEP (nm[0]))
1140 {
2893f146 1141 adir = alloca (MAXPATHLEN + 1);
620f13b0 1142 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
2893f146 1143 adir = NULL;
f5c81c80
EZ
1144 else if (multibyte)
1145 {
1146 Lisp_Object tem = build_string (adir);
1147
1148 tem = DECODE_FILE (tem);
1149 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1150 }
199607e4 1151 }
2893f146 1152 if (!adir)
199607e4 1153 {
e8d32c7e 1154 /* Either nm starts with /, or drive isn't mounted. */
2893f146
PE
1155 adir = alloca (4);
1156 adir[0] = DRIVE_LETTER (drive);
1157 adir[1] = ':';
1158 adir[2] = '/';
1159 adir[3] = 0;
199607e4 1160 }
2893f146 1161 newdir = adir;
199607e4 1162 }
5e570b75 1163#endif /* DOS_NT */
199607e4
RS
1164
1165 /* Finally, if no prefix has been specified and nm is not absolute,
e8d32c7e 1166 then it must be expanded relative to default_directory. */
199607e4 1167
34097368 1168 if (1
199607e4 1169#ifndef DOS_NT
e8d32c7e 1170 /* /... alone is not absolute on DOS and Windows. */
34097368 1171 && !IS_DIRECTORY_SEP (nm[0])
199607e4
RS
1172#endif
1173#ifdef WINDOWSNT
34097368 1174 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
199607e4 1175#endif
570d7624
JB
1176 && !newdir)
1177 {
5976c3fe 1178 newdir = SSDATA (default_directory);
f0f95d31
RS
1179#ifdef DOS_NT
1180 /* Note if special escape prefix is present, but remove for now. */
1181 if (newdir[0] == '/' && newdir[1] == ':')
1182 {
1183 is_escaped = 1;
1184 newdir += 2;
1185 }
1186#endif
570d7624
JB
1187 }
1188
5e570b75 1189#ifdef DOS_NT
199607e4
RS
1190 if (newdir)
1191 {
e8d32c7e 1192 /* First ensure newdir is an absolute name. */
199607e4
RS
1193 if (
1194 /* Detect MSDOS file names with drive specifiers. */
1195 ! (IS_DRIVE (newdir[0])
1196 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1197#ifdef WINDOWSNT
1198 /* Detect Windows file names in UNC format. */
1199 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1200#endif
1201 )
1202 {
1203 /* Effectively, let newdir be (expand-file-name newdir cwd).
1204 Because of the admonition against calling expand-file-name
1205 when we have pointers into lisp strings, we accomplish this
1206 indirectly by prepending newdir to nm if necessary, and using
e8d32c7e 1207 cwd (or the wd of newdir's drive) as the new newdir. */
2893f146 1208 char *adir;
f5c81c80 1209
c70a4df6 1210 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
199607e4 1211 {
5976c3fe 1212 drive = (unsigned char) newdir[0];
199607e4
RS
1213 newdir += 2;
1214 }
1215 if (!IS_DIRECTORY_SEP (nm[0]))
1216 {
c293e30c
DA
1217 ptrdiff_t newlen = strlen (newdir);
1218 char *tmp = alloca (newlen + strlen (nm) + 2);
f5c81c80 1219 file_name_as_directory (tmp, newdir, newlen, multibyte);
199607e4
RS
1220 strcat (tmp, nm);
1221 nm = tmp;
1222 }
2893f146 1223 adir = alloca (MAXPATHLEN + 1);
199607e4
RS
1224 if (drive)
1225 {
620f13b0 1226 if (!getdefdir (c_toupper (drive) - 'A' + 1, adir))
f5c81c80 1227 strcpy (adir, "/");
199607e4
RS
1228 }
1229 else
9239d970 1230 getcwd (adir, MAXPATHLEN + 1);
f5c81c80
EZ
1231 if (multibyte)
1232 {
1233 Lisp_Object tem = build_string (adir);
1234
1235 tem = DECODE_FILE (tem);
1236 memcpy (adir, SSDATA (tem), SBYTES (tem) + 1);
1237 }
2893f146 1238 newdir = adir;
199607e4
RS
1239 }
1240
e8d32c7e 1241 /* Strip off drive name from prefix, if present. */
c70a4df6 1242 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
199607e4
RS
1243 {
1244 drive = newdir[0];
1245 newdir += 2;
1246 }
1247
1248 /* Keep only a prefix from newdir if nm starts with slash
82330e7f 1249 (//server/share for UNC, nothing otherwise). */
9a1dc3be 1250 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
199607e4
RS
1251 {
1252#ifdef WINDOWSNT
1253 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1254 {
2893f146
PE
1255 char *adir = strcpy (alloca (strlen (newdir) + 1), newdir);
1256 char *p = adir + 2;
199607e4
RS
1257 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1258 p++;
1259 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1260 *p = 0;
2893f146 1261 newdir = adir;
199607e4
RS
1262 }
1263 else
1264#endif
1265 newdir = "";
1266 }
1267 }
5e570b75 1268#endif /* DOS_NT */
199607e4
RS
1269
1270 if (newdir)
bfb61299 1271 {
57676091 1272 /* Get rid of any slash at the end of newdir, unless newdir is
f0f95d31 1273 just / or // (an incomplete UNC name). */
199607e4 1274 length = strlen (newdir);
c293e30c 1275 tlen = length + 1;
f0f95d31 1276 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
57676091
RS
1277#ifdef WINDOWSNT
1278 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1279#endif
1280 )
bfb61299 1281 {
38182d90 1282 char *temp = alloca (length);
72af86bd 1283 memcpy (temp, newdir, length - 1);
bfb61299 1284 temp[length - 1] = 0;
c293e30c 1285 length--;
bfb61299
JB
1286 newdir = temp;
1287 }
bfb61299
JB
1288 }
1289 else
c293e30c
DA
1290 {
1291 length = 0;
1292 tlen = 0;
1293 }
570d7624 1294
e8d32c7e 1295 /* Now concatenate the directory and name to new space in the stack frame. */
bfb61299 1296 tlen += strlen (nm) + 1;
5e570b75 1297#ifdef DOS_NT
f0f95d31
RS
1298 /* Reserve space for drive specifier and escape prefix, since either
1299 or both may need to be inserted. (The Microsoft x86 compiler
5e570b75 1300 produces incorrect code if the following two lines are combined.) */
38182d90 1301 target = alloca (tlen + 4);
f0f95d31 1302 target += 4;
5e570b75 1303#else /* not DOS_NT */
38182d90 1304 target = alloca (tlen);
5e570b75 1305#endif /* not DOS_NT */
570d7624
JB
1306 *target = 0;
1307
1308 if (newdir)
1309 {
5e570b75 1310 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
f5321b5c 1311 {
3ea2d8b2 1312#ifdef DOS_NT
f5321b5c
RS
1313 /* If newdir is effectively "C:/", then the drive letter will have
1314 been stripped and newdir will be "/". Concatenating with an
1315 absolute directory in nm produces "//", which will then be
1316 incorrectly treated as a network share. Ignore newdir in
1317 this case (keeping the drive letter). */
efdc16c9 1318 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
f5321b5c
RS
1319 && newdir[1] == '\0'))
1320#endif
1321 strcpy (target, newdir);
1322 }
570d7624 1323 else
f5c81c80 1324 file_name_as_directory (target, newdir, length, multibyte);
570d7624
JB
1325 }
1326
1327 strcat (target, nm);
199607e4 1328
214378ec
GM
1329 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1330 appear. */
5b5a2ea1 1331 {
5976c3fe
PE
1332 char *p = target;
1333 char *o = target;
570d7624 1334
5b5a2ea1
SM
1335 while (*p)
1336 {
5b5a2ea1
SM
1337 if (!IS_DIRECTORY_SEP (*p))
1338 {
1339 *o++ = *p++;
1340 }
1341 else if (p[1] == '.'
1342 && (IS_DIRECTORY_SEP (p[2])
1343 || p[2] == 0))
1344 {
1345 /* If "/." is the entire filename, keep the "/". Otherwise,
1346 just delete the whole "/.". */
1347 if (o == target && p[2] == '\0')
1348 *o++ = *p;
1349 p += 2;
1350 }
1351 else if (p[1] == '.' && p[2] == '.'
1352 /* `/../' is the "superroot" on certain file systems.
1353 Turned off on DOS_NT systems because they have no
1354 "superroot" and because this causes us to produce
1355 file names like "d:/../foo" which fail file-related
1356 functions of the underlying OS. (To reproduce, try a
1357 long series of "../../" in default_directory, longer
1358 than the number of levels from the root.) */
aa4060b9 1359#ifndef DOS_NT
5b5a2ea1 1360 && o != target
aa4060b9 1361#endif
5b5a2ea1
SM
1362 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1363 {
972ed246 1364#ifdef WINDOWSNT
5976c3fe 1365 char *prev_o = o;
972ed246 1366#endif
7ba11bee
PE
1367 while (o != target && (--o, !IS_DIRECTORY_SEP (*o)))
1368 continue;
972ed246
JR
1369#ifdef WINDOWSNT
1370 /* Don't go below server level in UNC filenames. */
1371 if (o == target + 1 && IS_DIRECTORY_SEP (*o)
1372 && IS_DIRECTORY_SEP (*target))
1373 o = prev_o;
1374 else
1375#endif
5b5a2ea1
SM
1376 /* Keep initial / only if this is the whole name. */
1377 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1378 ++o;
1379 p += 3;
1380 }
1381 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1382 /* Collapse multiple `/' in a row. */
1383 p++;
1384 else
1385 {
1386 *o++ = *p++;
1387 }
5b5a2ea1 1388 }
570d7624 1389
5e570b75 1390#ifdef DOS_NT
e8d32c7e 1391 /* At last, set drive name. */
5e570b75 1392#ifdef WINDOWSNT
5b5a2ea1
SM
1393 /* Except for network file name. */
1394 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
5e570b75 1395#endif /* WINDOWSNT */
5b5a2ea1 1396 {
1088b922 1397 if (!drive) emacs_abort ();
5b5a2ea1
SM
1398 target -= 2;
1399 target[0] = DRIVE_LETTER (drive);
1400 target[1] = ':';
1401 }
1402 /* Reinsert the escape prefix if required. */
1403 if (is_escaped)
1404 {
1405 target -= 2;
1406 target[0] = '/';
1407 target[1] = ':';
1408 }
5b5a2ea1 1409 result = make_specified_string (target, -1, o - target, multibyte);
e7ac588e
EZ
1410 dostounix_filename (SSDATA (result), multibyte);
1411#ifdef WINDOWSNT
1412 if (!NILP (Vw32_downcase_file_names))
1413 result = Fdowncase (result);
1414#endif
273ac8d1
EZ
1415#else /* !DOS_NT */
1416 result = make_specified_string (target, -1, o - target, multibyte);
1417#endif /* !DOS_NT */
5b5a2ea1 1418 }
beb402de
KG
1419
1420 /* Again look to see if the file name has special constructs in it
1421 and perhaps call the corresponding file handler. This is needed
1422 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1423 the ".." component gives us "/user@host:/bar/../baz" which needs
e8d32c7e 1424 to be expanded again. */
beb402de
KG
1425 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1426 if (!NILP (handler))
2375c96a
CY
1427 {
1428 handled_name = call3 (handler, Qexpand_file_name,
1429 result, default_directory);
1430 if (STRINGP (handled_name))
1431 return handled_name;
1432 error ("Invalid handler in `file-name-handler-alist'");
1433 }
beb402de
KG
1434
1435 return result;
570d7624 1436}
5e570b75 1437
4887597a
EZ
1438#if 0
1439/* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1440 This is the old version of expand-file-name, before it was thoroughly
1441 rewritten for Emacs 10.31. We leave this version here commented-out,
1442 because the code is very complex and likely to have subtle bugs. If
1443 bugs _are_ found, it might be of interest to look at the old code and
1444 see what did it do in the relevant situation.
1445
30f50381
GM
1446 Don't remove this code: it's true that it will be accessible
1447 from the repository, but a few years from deletion, people will
1448 forget it is there. */
4887597a
EZ
1449
1450/* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1451DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1452 "Convert FILENAME to absolute, and canonicalize it.\n\
1453Second arg DEFAULT is directory to start with if FILENAME is relative\n\
c70a4df6 1454\(does not start with slash); if DEFAULT is nil or missing,\n\
4887597a
EZ
1455the current buffer's value of default-directory is used.\n\
1456Filenames containing `.' or `..' as components are simplified;\n\
1457initial `~/' expands to your home directory.\n\
1458See also the function `substitute-in-file-name'.")
1459 (name, defalt)
1460 Lisp_Object name, defalt;
1461{
1462 unsigned char *nm;
1463
1464 register unsigned char *newdir, *p, *o;
93f4cf88 1465 ptrdiff_t tlen;
4887597a
EZ
1466 unsigned char *target;
1467 struct passwd *pw;
4887597a 1468
b7826503 1469 CHECK_STRING (name);
d5db4077 1470 nm = SDATA (name);
4887597a
EZ
1471
1472 /* If nm is absolute, flush ...// and detect /./ and /../.
1473 If no /./ or /../ we can return right away. */
7c2fb837 1474 if (nm[0] == '/')
4887597a 1475 {
f75d7a91 1476 bool lose = 0;
4887597a 1477 p = nm;
4887597a
EZ
1478 while (*p)
1479 {
ce2fe65a 1480 if (p[0] == '/' && p[1] == '/')
4887597a
EZ
1481 nm = p + 1;
1482 if (p[0] == '/' && p[1] == '~')
1483 nm = p + 1, lose = 1;
1484 if (p[0] == '/' && p[1] == '.'
1485 && (p[2] == '/' || p[2] == 0
1486 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1487 lose = 1;
4887597a
EZ
1488 p++;
1489 }
1490 if (!lose)
1491 {
d5db4077 1492 if (nm == SDATA (name))
4887597a
EZ
1493 return name;
1494 return build_string (nm);
1495 }
1496 }
1497
e8d32c7e 1498 /* Now determine directory to start with and put it in NEWDIR. */
4887597a
EZ
1499
1500 newdir = 0;
1501
1502 if (nm[0] == '~') /* prefix ~ */
7c2fb837 1503 if (nm[1] == '/' || nm[1] == 0)/* ~/filename */
4887597a
EZ
1504 {
1505 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1506 newdir = (unsigned char *) "";
1507 nm++;
4887597a
EZ
1508 }
1509 else /* ~user/filename */
1510 {
e8d32c7e 1511 /* Get past ~ to user. */
4887597a 1512 unsigned char *user = nm + 1;
e8d32c7e 1513 /* Find end of name. */
8966b757 1514 unsigned char *ptr = (unsigned char *) strchr (user, '/');
93f4cf88 1515 ptrdiff_t len = ptr ? ptr - user : strlen (user);
e8d32c7e 1516 /* Copy the user name into temp storage. */
38182d90 1517 o = alloca (len + 1);
72af86bd 1518 memcpy (o, user, len);
4887597a
EZ
1519 o[len] = 0;
1520
e8d32c7e 1521 /* Look up the user name. */
4d7e6e51 1522 block_input ();
4887597a 1523 pw = (struct passwd *) getpwnam (o + 1);
4d7e6e51 1524 unblock_input ();
4887597a
EZ
1525 if (!pw)
1526 error ("\"%s\" isn't a registered user", o + 1);
1527
1528 newdir = (unsigned char *) pw->pw_dir;
1529
1530 /* Discard the user name from NM. */
1531 nm += len;
1532 }
1533
7c2fb837 1534 if (nm[0] != '/' && !newdir)
4887597a
EZ
1535 {
1536 if (NILP (defalt))
1537 defalt = current_buffer->directory;
b7826503 1538 CHECK_STRING (defalt);
d5db4077 1539 newdir = SDATA (defalt);
4887597a
EZ
1540 }
1541
e8d32c7e 1542 /* Now concatenate the directory and name to new space in the stack frame. */
4887597a
EZ
1543
1544 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
38182d90 1545 target = alloca (tlen);
4887597a
EZ
1546 *target = 0;
1547
1548 if (newdir)
1549 {
4887597a
EZ
1550 if (nm[0] == 0 || nm[0] == '/')
1551 strcpy (target, newdir);
1552 else
4887597a
EZ
1553 file_name_as_directory (target, newdir);
1554 }
1555
1556 strcat (target, nm);
4887597a 1557
e8d32c7e 1558 /* Now canonicalize by removing /. and /foo/.. if they appear. */
4887597a
EZ
1559
1560 p = target;
1561 o = target;
1562
1563 while (*p)
1564 {
4887597a
EZ
1565 if (*p != '/')
1566 {
1567 *o++ = *p++;
1568 }
1569 else if (!strncmp (p, "//", 2)
4887597a
EZ
1570 )
1571 {
1572 o = target;
1573 p++;
1574 }
994a7262
RS
1575 else if (p[0] == '/' && p[1] == '.'
1576 && (p[2] == '/' || p[2] == 0))
4887597a
EZ
1577 p += 2;
1578 else if (!strncmp (p, "/..", 3)
1579 /* `/../' is the "superroot" on certain file systems. */
1580 && o != target
1581 && (p[3] == '/' || p[3] == 0))
1582 {
1583 while (o != target && *--o != '/')
1584 ;
4887597a
EZ
1585 if (o == target && *o == '/')
1586 ++o;
1587 p += 3;
1588 }
1589 else
1590 {
1591 *o++ = *p++;
1592 }
4887597a
EZ
1593 }
1594
1595 return make_string (target, o - target);
1596}
1597#endif
570d7624 1598\f
c70a4df6 1599/* If /~ or // appears, discard everything through first slash. */
f75d7a91 1600static bool
5976c3fe 1601file_name_absolute_p (const char *filename)
c70a4df6
SM
1602{
1603 return
1604 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
c70a4df6
SM
1605#ifdef DOS_NT
1606 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
1607 && IS_DIRECTORY_SEP (filename[2]))
1608#endif
1609 );
1610}
1611
5976c3fe
PE
1612static char *
1613search_embedded_absfilename (char *nm, char *endp)
c70a4df6 1614{
5976c3fe 1615 char *p, *s;
c70a4df6
SM
1616
1617 for (p = nm + 1; p < endp; p++)
1618 {
ce2fe65a 1619 if (IS_DIRECTORY_SEP (p[-1])
c70a4df6 1620 && file_name_absolute_p (p)
5e617bc2 1621#if defined (WINDOWSNT) || defined (CYGWIN)
c70a4df6
SM
1622 /* // at start of file name is meaningful in Apollo,
1623 WindowsNT and Cygwin systems. */
f34574c6 1624 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
e39a993c 1625#endif /* not (WINDOWSNT || CYGWIN) */
ce2fe65a 1626 )
c70a4df6 1627 {
ce2fe65a 1628 for (s = p; *s && !IS_DIRECTORY_SEP (*s); s++);
e8d32c7e 1629 if (p[0] == '~' && s > p + 1) /* We've got "/~something/". */
c70a4df6 1630 {
5976c3fe 1631 char *o = alloca (s - p + 1);
c70a4df6 1632 struct passwd *pw;
72af86bd 1633 memcpy (o, p, s - p);
c70a4df6
SM
1634 o [s - p] = 0;
1635
1636 /* If we have ~user and `user' exists, discard
1637 everything up to ~. But if `user' does not exist, leave
1638 ~user alone, it might be a literal file name. */
4d7e6e51 1639 block_input ();
67c08d6c 1640 pw = getpwnam (o + 1);
4d7e6e51 1641 unblock_input ();
67c08d6c 1642 if (pw)
c70a4df6 1643 return p;
c70a4df6
SM
1644 }
1645 else
1646 return p;
1647 }
1648 }
1649 return NULL;
1650}
1651
a7ca3326 1652DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
8c1a1077
PJ
1653 Ssubstitute_in_file_name, 1, 1, 0,
1654 doc: /* Substitute environment variables referred to in FILENAME.
1655`$FOO' where FOO is an environment variable name means to substitute
1656the value of that variable. The variable name should be terminated
1657with a character not a letter, digit or underscore; otherwise, enclose
1658the entire variable name in braces.
c68845e0
GM
1659
1660If `/~' appears, all of FILENAME through that `/' is discarded.
1661If `//' appears, everything up to and including the first of
1662those `/' is discarded. */)
5842a27b 1663 (Lisp_Object filename)
570d7624 1664{
f75d7a91 1665 char *nm, *s, *p, *o, *x, *endp;
5976c3fe 1666 char *target = NULL;
5f460827 1667 ptrdiff_t total = 0;
f75d7a91 1668 bool substituted = 0;
fce31d69 1669 bool multibyte;
5976c3fe 1670 char *xnm;
8ce069f5 1671 Lisp_Object handler;
570d7624 1672
b7826503 1673 CHECK_STRING (filename);
570d7624 1674
58aec0d6
JR
1675 multibyte = STRING_MULTIBYTE (filename);
1676
8ce069f5
RS
1677 /* If the file name has special constructs in it,
1678 call the corresponding file handler. */
3b7f6e60 1679 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
8ce069f5 1680 if (!NILP (handler))
2375c96a
CY
1681 {
1682 Lisp_Object handled_name = call2 (handler, Qsubstitute_in_file_name,
1683 filename);
1684 if (STRINGP (handled_name))
1685 return handled_name;
1686 error ("Invalid handler in `file-name-handler-alist'");
1687 }
8ce069f5 1688
58aec0d6
JR
1689 /* Always work on a copy of the string, in case GC happens during
1690 decode of environment variables, causing the original Lisp_String
1691 data to be relocated. */
38182d90 1692 nm = alloca (SBYTES (filename) + 1);
72af86bd 1693 memcpy (nm, SDATA (filename), SBYTES (filename) + 1);
0f3f018c 1694
58aec0d6 1695#ifdef DOS_NT
e7ac588e
EZ
1696 dostounix_filename (nm, multibyte);
1697 substituted = (memcmp (nm, SDATA (filename), SBYTES (filename)) != 0);
a5a1cc06 1698#endif
d5db4077 1699 endp = nm + SBYTES (filename);
570d7624 1700
82330e7f 1701 /* If /~ or // appears, discard everything through first slash. */
c70a4df6
SM
1702 p = search_embedded_absfilename (nm, endp);
1703 if (p)
1704 /* Start over with the new string, so we check the file-name-handler
1705 again. Important with filenames like "/home/foo//:/hello///there"
ee7683eb 1706 which would substitute to "/:/hello///there" rather than "/there". */
c70a4df6 1707 return Fsubstitute_in_file_name
58aec0d6 1708 (make_specified_string (p, -1, endp - p, multibyte));
570d7624
JB
1709
1710 /* See if any variables are substituted into the string
e8d32c7e 1711 and find the total length of their values in `total'. */
570d7624
JB
1712
1713 for (p = nm; p != endp;)
1714 if (*p != '$')
1715 p++;
1716 else
1717 {
1718 p++;
1719 if (p == endp)
1720 goto badsubst;
1721 else if (*p == '$')
1722 {
e8d32c7e 1723 /* "$$" means a single "$". */
570d7624
JB
1724 p++;
1725 total -= 1;
1726 substituted = 1;
1727 continue;
1728 }
1729 else if (*p == '{')
1730 {
1731 o = ++p;
a84b7c53
PE
1732 p = memchr (p, '}', endp - p);
1733 if (! p)
1734 goto missingclose;
570d7624
JB
1735 s = p;
1736 }
1737 else
1738 {
1739 o = p;
620f13b0 1740 while (p != endp && (c_isalnum (*p) || *p == '_')) p++;
570d7624
JB
1741 s = p;
1742 }
1743
e8d32c7e 1744 /* Copy out the variable name. */
38182d90 1745 target = alloca (s - o + 1);
e99a530f 1746 memcpy (target, o, s - o);
570d7624 1747 target[s - o] = 0;
5e570b75 1748#ifdef DOS_NT
4c3c22f3 1749 strupr (target); /* $home == $HOME etc. */
5e570b75 1750#endif /* DOS_NT */
570d7624 1751
e8d32c7e 1752 /* Get variable value. */
5976c3fe 1753 o = egetenv (target);
8d2ced53 1754 if (o)
58aec0d6
JR
1755 {
1756 /* Don't try to guess a maximum length - UTF8 can use up to
1757 four bytes per character. This code is unlikely to run
1758 in a situation that requires performance, so decoding the
1759 env variables twice should be acceptable. Note that
1760 decoding may cause a garbage collect. */
1761 Lisp_Object orig, decoded;
d7ea76b4 1762 orig = build_unibyte_string (o);
58aec0d6
JR
1763 decoded = DECODE_FILE (orig);
1764 total += SBYTES (decoded);
8d2ced53
SM
1765 substituted = 1;
1766 }
1767 else if (*p == '}')
1768 goto badvar;
570d7624
JB
1769 }
1770
1771 if (!substituted)
e7ac588e
EZ
1772 {
1773#ifdef WINDOWSNT
1774 if (!NILP (Vw32_downcase_file_names))
1775 filename = Fdowncase (filename);
1776#endif
1777 return filename;
1778 }
570d7624 1779
e8d32c7e
SM
1780 /* If substitution required, recopy the string and do it. */
1781 /* Make space in stack frame for the new copy. */
38182d90 1782 xnm = alloca (SBYTES (filename) + total + 1);
570d7624
JB
1783 x = xnm;
1784
e8d32c7e 1785 /* Copy the rest of the name through, replacing $ constructs with values. */
570d7624
JB
1786 for (p = nm; *p;)
1787 if (*p != '$')
1788 *x++ = *p++;
1789 else
1790 {
1791 p++;
1792 if (p == endp)
1793 goto badsubst;
1794 else if (*p == '$')
1795 {
1796 *x++ = *p++;
1797 continue;
1798 }
1799 else if (*p == '{')
1800 {
1801 o = ++p;
a84b7c53
PE
1802 p = memchr (p, '}', endp - p);
1803 if (! p)
1804 goto missingclose;
570d7624
JB
1805 s = p++;
1806 }
1807 else
1808 {
1809 o = p;
620f13b0 1810 while (p != endp && (c_isalnum (*p) || *p == '_')) p++;
570d7624
JB
1811 s = p;
1812 }
1813
e8d32c7e 1814 /* Copy out the variable name. */
38182d90 1815 target = alloca (s - o + 1);
e99a530f 1816 memcpy (target, o, s - o);
570d7624
JB
1817 target[s - o] = 0;
1818
e8d32c7e 1819 /* Get variable value. */
5976c3fe 1820 o = egetenv (target);
570d7624 1821 if (!o)
8d2ced53
SM
1822 {
1823 *x++ = '$';
1824 strcpy (x, target); x+= strlen (target);
1825 }
60d67b83
RS
1826 else
1827 {
58aec0d6 1828 Lisp_Object orig, decoded;
93f4cf88 1829 ptrdiff_t orig_length, decoded_length;
58aec0d6
JR
1830 orig_length = strlen (o);
1831 orig = make_unibyte_string (o, orig_length);
1832 decoded = DECODE_FILE (orig);
1833 decoded_length = SBYTES (decoded);
e99a530f 1834 memcpy (x, SDATA (decoded), decoded_length);
58aec0d6
JR
1835 x += decoded_length;
1836
1837 /* If environment variable needed decoding, return value
1838 needs to be multibyte. */
1839 if (decoded_length != orig_length
e99a530f 1840 || memcmp (SDATA (decoded), o, orig_length))
58aec0d6 1841 multibyte = 1;
60d67b83 1842 }
570d7624
JB
1843 }
1844
1845 *x = 0;
1846
82330e7f 1847 /* If /~ or // appears, discard everything through first slash. */
ce2fe65a 1848 while ((p = search_embedded_absfilename (xnm, x)) != NULL)
c70a4df6
SM
1849 /* This time we do not start over because we've already expanded envvars
1850 and replaced $$ with $. Maybe we should start over as well, but we'd
1851 need to quote some $ to $$ first. */
1852 xnm = p;
570d7624 1853
e7ac588e
EZ
1854#ifdef WINDOWSNT
1855 if (!NILP (Vw32_downcase_file_names))
1856 {
1857 Lisp_Object xname = make_specified_string (xnm, -1, x - xnm, multibyte);
1858
1859 xname = Fdowncase (xname);
1860 return xname;
1861 }
1862 else
1863#endif
58aec0d6 1864 return make_specified_string (xnm, -1, x - xnm, multibyte);
570d7624
JB
1865
1866 badsubst:
1867 error ("Bad format environment-variable substitution");
1868 missingclose:
1869 error ("Missing \"}\" in environment-variable substitution");
1870 badvar:
1871 error ("Substituting nonexistent environment variable \"%s\"", target);
570d7624
JB
1872}
1873\f
067ffa38 1874/* A slightly faster and more convenient way to get
298b760e 1875 (directory-file-name (expand-file-name FOO)). */
067ffa38 1876
570d7624 1877Lisp_Object
971de7fb 1878expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
570d7624 1879{
199607e4 1880 register Lisp_Object absname;
570d7624 1881
199607e4 1882 absname = Fexpand_file_name (filename, defdir);
7c2fb837 1883
199607e4 1884 /* Remove final slash, if any (unless this is the root dir).
570d7624 1885 stat behaves differently depending! */
d5db4077
KR
1886 if (SCHARS (absname) > 1
1887 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
e8d32c7e 1888 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname) - 2)))
ddc61f46 1889 /* We cannot take shortcuts; they might be wrong for magic file names. */
199607e4 1890 absname = Fdirectory_file_name (absname);
199607e4 1891 return absname;
570d7624
JB
1892}
1893\f
3ed15d97 1894/* Signal an error if the file ABSNAME already exists.
f75d7a91 1895 If INTERACTIVE, ask the user whether to proceed,
3ed15d97
RS
1896 and bypass the error if the user says to go ahead.
1897 QUERYSTRING is a name for the action that is being considered
1898 to alter the file.
de1d0127 1899
3ed15d97 1900 *STATPTR is used to store the stat information if the file exists.
de1d0127 1901 If the file does not exist, STATPTR->st_mode is set to 0.
b8b29dc9
RS
1902 If STATPTR is null, we don't store into it.
1903
f75d7a91 1904 If QUICK, ask for y or n, not yes or no. */
3ed15d97 1905
f14b7e14 1906static void
5976c3fe 1907barf_or_query_if_file_exists (Lisp_Object absname, const char *querystring,
f75d7a91
PE
1908 bool interactive, struct stat *statptr,
1909 bool quick)
570d7624 1910{
f75d7a91 1911 Lisp_Object tem, encoded_filename;
4018b5ef 1912 struct stat statbuf;
570d7624
JB
1913 struct gcpro gcpro1;
1914
643c73b9
RS
1915 encoded_filename = ENCODE_FILE (absname);
1916
e8d32c7e 1917 /* `stat' is a good way to tell whether the file exists,
4018b5ef 1918 regardless of what access permissions it has. */
42a5b22f 1919 if (lstat (SSDATA (encoded_filename), &statbuf) >= 0)
570d7624 1920 {
6e9b2be9 1921 if (S_ISDIR (statbuf.st_mode))
c4f2d8d4 1922 xsignal2 (Qfile_error,
ad637907 1923 build_string ("File is a directory"), absname);
c4f2d8d4 1924
570d7624 1925 if (! interactive)
24b1ddad
KS
1926 xsignal2 (Qfile_already_exists,
1927 build_string ("File already exists"), absname);
570d7624 1928 GCPRO1 (absname);
67e8e2b8
RS
1929 tem = format2 ("File %s already exists; %s anyway? ",
1930 absname, build_string (querystring));
b8b29dc9 1931 if (quick)
5616cc54 1932 tem = call1 (intern ("y-or-n-p"), tem);
b8b29dc9
RS
1933 else
1934 tem = do_yes_or_no_p (tem);
570d7624 1935 UNGCPRO;
265a9e55 1936 if (NILP (tem))
24b1ddad
KS
1937 xsignal2 (Qfile_already_exists,
1938 build_string ("File already exists"), absname);
3ed15d97
RS
1939 if (statptr)
1940 *statptr = statbuf;
1941 }
1942 else
1943 {
1944 if (statptr)
1945 statptr->st_mode = 0;
570d7624
JB
1946 }
1947 return;
1948}
1949
574c05e2 1950DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 6,
7c0f6118 1951 "fCopy file: \nGCopy %s to file: \np\nP",
8c1a1077
PJ
1952 doc: /* Copy FILE to NEWNAME. Both args must be strings.
1953If NEWNAME names a directory, copy FILE there.
795c20df
CY
1954
1955This function always sets the file modes of the output file to match
1956the input file.
1957
1958The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
1959if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
1960signal a `file-already-exists' error without overwriting. If
1961OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
1962about overwriting; this is what happens in interactive use with M-x.
1963Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
1964existing file.
c50f15d0 1965
7f08b80e 1966Fourth arg KEEP-TIME non-nil means give the output file the same
8c1a1077 1967last-modified time as the old one. (This works on only some systems.)
c50f15d0 1968
7fce7dfe
EZ
1969A prefix arg makes KEEP-TIME non-nil.
1970
586702ce 1971If PRESERVE-UID-GID is non-nil, we try to transfer the
574c05e2
KK
1972uid and gid of FILE to NEWNAME.
1973
7c3d167f
RF
1974If PRESERVE-EXTENDED-ATTRIBUTES is non-nil, we try to copy additional
1975attributes of FILE to NEWNAME, such as its SELinux context and ACL
1976entries (depending on how Emacs was built). */)
1977 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists, Lisp_Object keep_time, Lisp_Object preserve_uid_gid, Lisp_Object preserve_extended_attributes)
570d7624 1978{
8a2cbd72 1979 int ifd, ofd;
d311d28c 1980 int n;
570d7624 1981 char buf[16 * 1024];
3ed15d97 1982 struct stat st, out_st;
32f4334d 1983 Lisp_Object handler;
b1d1b865 1984 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
d311d28c 1985 ptrdiff_t count = SPECPDL_INDEX ();
b1d1b865 1986 Lisp_Object encoded_file, encoded_newname;
574c05e2
KK
1987#if HAVE_LIBSELINUX
1988 security_context_t con;
f75d7a91 1989 int conlength = 0;
574c05e2 1990#endif
7c3d167f
RF
1991#ifdef HAVE_POSIX_ACL
1992 acl_t acl = NULL;
1993#endif
570d7624 1994
b1d1b865
RS
1995 encoded_file = encoded_newname = Qnil;
1996 GCPRO4 (file, newname, encoded_file, encoded_newname);
b7826503
PJ
1997 CHECK_STRING (file);
1998 CHECK_STRING (newname);
b1d1b865 1999
a9d14e54 2000 if (!NILP (Ffile_directory_p (newname)))
6b61353c 2001 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
a9d14e54
GM
2002 else
2003 newname = Fexpand_file_name (newname, Qnil);
2004
3b7f6e60 2005 file = Fexpand_file_name (file, Qnil);
32f4334d 2006
0bf2eed2 2007 /* If the input file name has special constructs in it,
32f4334d 2008 call the corresponding file handler. */
3b7f6e60 2009 handler = Ffind_file_name_handler (file, Qcopy_file);
0bf2eed2 2010 /* Likewise for output file name. */
51cf6d37 2011 if (NILP (handler))
49307295 2012 handler = Ffind_file_name_handler (newname, Qcopy_file);
32f4334d 2013 if (!NILP (handler))
574c05e2
KK
2014 RETURN_UNGCPRO (call7 (handler, Qcopy_file, file, newname,
2015 ok_if_already_exists, keep_time, preserve_uid_gid,
7c3d167f 2016 preserve_extended_attributes));
32f4334d 2017
b1d1b865
RS
2018 encoded_file = ENCODE_FILE (file);
2019 encoded_newname = ENCODE_FILE (newname);
2020
265a9e55 2021 if (NILP (ok_if_already_exists)
93c30b5f 2022 || INTEGERP (ok_if_already_exists))
2f868094 2023 barf_or_query_if_file_exists (newname, "copy to it",
b8b29dc9 2024 INTEGERP (ok_if_already_exists), &out_st, 0);
42a5b22f 2025 else if (stat (SSDATA (encoded_newname), &out_st) < 0)
3ed15d97 2026 out_st.st_mode = 0;
570d7624 2027
e8691c59 2028#ifdef WINDOWSNT
66447e07
EZ
2029 if (!NILP (preserve_extended_attributes))
2030 {
2031#ifdef HAVE_POSIX_ACL
2032 acl = acl_get_file (SDATA (encoded_file), ACL_TYPE_ACCESS);
5406cfd9 2033 if (acl == NULL && !ACL_NOT_WELL_SUPPORTED (errno))
66447e07
EZ
2034 report_file_error ("Getting ACL", Fcons (file, Qnil));
2035#endif
2036 }
d5db4077 2037 if (!CopyFile (SDATA (encoded_file),
efdc16c9 2038 SDATA (encoded_newname),
e8691c59 2039 FALSE))
8d23a331
EZ
2040 {
2041 /* CopyFile doesn't set errno when it fails. By far the most
2042 "popular" reason is that the target is read-only. */
2043 if (GetLastError () == 5)
2044 errno = EACCES;
2045 else
2046 errno = EPERM;
2047 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
2048 }
8b53dc06
JR
2049 /* CopyFile retains the timestamp by default. */
2050 else if (NILP (keep_time))
e8691c59
GM
2051 {
2052 EMACS_TIME now;
ad497129
JR
2053 DWORD attributes;
2054 char * filename;
2055
d5db4077 2056 filename = SDATA (encoded_newname);
ad497129
JR
2057
2058 /* Ensure file is writable while its modified time is set. */
2059 attributes = GetFileAttributes (filename);
02cca86b 2060 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
e9a9ae03 2061 now = current_emacs_time ();
d35af63c 2062 if (set_file_times (-1, filename, now, now))
ad497129
JR
2063 {
2064 /* Restore original attributes. */
2065 SetFileAttributes (filename, attributes);
24b1ddad
KS
2066 xsignal2 (Qfile_date_error,
2067 build_string ("Cannot set file date"), newname);
ad497129
JR
2068 }
2069 /* Restore original attributes. */
2070 SetFileAttributes (filename, attributes);
e8691c59 2071 }
66447e07
EZ
2072#ifdef HAVE_POSIX_ACL
2073 if (acl != NULL)
2074 {
2075 bool fail =
2076 acl_set_file (SDATA (encoded_newname), ACL_TYPE_ACCESS, acl) != 0;
5406cfd9 2077 if (fail && !ACL_NOT_WELL_SUPPORTED (errno))
66447e07
EZ
2078 report_file_error ("Setting ACL", Fcons (newname, Qnil));
2079
2080 acl_free (acl);
2081 }
2082#endif
e8691c59 2083#else /* not WINDOWSNT */
13336908 2084 immediate_quit = 1;
42a5b22f 2085 ifd = emacs_open (SSDATA (encoded_file), O_RDONLY, 0);
13336908
RS
2086 immediate_quit = 0;
2087
570d7624 2088 if (ifd < 0)
3b7f6e60 2089 report_file_error ("Opening input file", Fcons (file, Qnil));
570d7624 2090
b5148e85
RS
2091 record_unwind_protect (close_file_unwind, make_number (ifd));
2092
d20704ef
PE
2093 if (fstat (ifd, &st) != 0)
2094 report_file_error ("Input file status", Fcons (file, Qnil));
f73b0ada 2095
7c3d167f 2096 if (!NILP (preserve_extended_attributes))
574c05e2 2097 {
7c3d167f
RF
2098#if HAVE_LIBSELINUX
2099 if (is_selinux_enabled ())
2100 {
2101 conlength = fgetfilecon (ifd, &con);
2102 if (conlength == -1)
2103 report_file_error ("Doing fgetfilecon", Fcons (file, Qnil));
2104 }
2105#endif
2106
2107#ifdef HAVE_POSIX_ACL
2108 acl = acl_get_fd (ifd);
5406cfd9 2109 if (acl == NULL && !ACL_NOT_WELL_SUPPORTED (errno))
7c3d167f 2110 report_file_error ("Getting ACL", Fcons (file, Qnil));
574c05e2 2111#endif
7c3d167f 2112 }
574c05e2 2113
3ed15d97
RS
2114 if (out_st.st_mode != 0
2115 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2116 {
2117 errno = 0;
2118 report_file_error ("Input and output files are the same",
3b7f6e60 2119 Fcons (file, Fcons (newname, Qnil)));
3ed15d97 2120 }
3ed15d97 2121
d20704ef
PE
2122 /* We can copy only regular files. */
2123 if (!S_ISREG (st.st_mode))
f73b0ada 2124 {
d20704ef
PE
2125 /* Get a better looking error message. */
2126 errno = S_ISDIR (st.st_mode) ? EISDIR : EINVAL;
2127 report_file_error ("Non-regular file", Fcons (file, Qnil));
f73b0ada 2128 }
f73b0ada 2129
4c3c22f3
RS
2130#ifdef MSDOS
2131 /* System's default file type was set to binary by _fmode in emacs.c. */
c50f15d0 2132 ofd = emacs_open (SDATA (encoded_newname),
7fce7dfe 2133 O_WRONLY | O_TRUNC | O_CREAT
795c20df 2134 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
c50f15d0
RS
2135 S_IREAD | S_IWRITE);
2136#else /* not MSDOS */
15e3a074 2137 {
d20704ef
PE
2138 mode_t new_mask = !NILP (preserve_uid_gid) ? 0600 : 0666;
2139 new_mask &= st.st_mode;
15e3a074
PE
2140 ofd = emacs_open (SSDATA (encoded_newname),
2141 (O_WRONLY | O_TRUNC | O_CREAT
2142 | (NILP (ok_if_already_exists) ? O_EXCL : 0)),
2143 new_mask);
2144 }
4c3c22f3 2145#endif /* not MSDOS */
570d7624 2146 if (ofd < 0)
3ed15d97 2147 report_file_error ("Opening output file", Fcons (newname, Qnil));
b5148e85
RS
2148
2149 record_unwind_protect (close_file_unwind, make_number (ofd));
570d7624 2150
b5148e85
RS
2151 immediate_quit = 1;
2152 QUIT;
68c45bf0
PE
2153 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2154 if (emacs_write (ofd, buf, n) != n)
3ed15d97 2155 report_file_error ("I/O error", Fcons (newname, Qnil));
b5148e85 2156 immediate_quit = 0;
570d7624 2157
b016179b
EZ
2158#ifndef MSDOS
2159 /* Preserve the original file modes, and if requested, also its
2160 owner and group. */
d20704ef
PE
2161 {
2162 mode_t mode_mask = 07777;
2163 if (!NILP (preserve_uid_gid))
2164 {
2165 /* Attempt to change owner and group. If that doesn't work
2166 attempt to change just the group, as that is sometimes allowed.
2167 Adjust the mode mask to eliminate setuid or setgid bits
2168 that are inappropriate if the owner and group are wrong. */
2169 if (fchown (ofd, st.st_uid, st.st_gid) != 0)
2170 {
2171 mode_mask &= ~06000;
2172 if (fchown (ofd, -1, st.st_gid) == 0)
2173 mode_mask |= 02000;
2174 }
2175 }
2176 if (fchmod (ofd, st.st_mode & mode_mask) != 0)
2177 report_file_error ("Doing chmod", Fcons (newname, Qnil));
2178 }
b016179b 2179#endif /* not MSDOS */
586702ce 2180
574c05e2
KK
2181#if HAVE_LIBSELINUX
2182 if (conlength > 0)
2183 {
24c51a09 2184 /* Set the modified context back to the file. */
f75d7a91 2185 bool fail = fsetfilecon (ofd, con) != 0;
24c51a09
GM
2186 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
2187 if (fail && errno != ENOTSUP)
574c05e2
KK
2188 report_file_error ("Doing fsetfilecon", Fcons (newname, Qnil));
2189
2190 freecon (con);
2191 }
2192#endif
2193
7c3d167f
RF
2194#ifdef HAVE_POSIX_ACL
2195 if (acl != NULL)
2196 {
2197 bool fail = acl_set_fd (ofd, acl) != 0;
5406cfd9 2198 if (fail && !ACL_NOT_WELL_SUPPORTED (errno))
7c3d167f
RF
2199 report_file_error ("Setting ACL", Fcons (newname, Qnil));
2200
2201 acl_free (acl);
2202 }
2203#endif
2204
d20704ef 2205 if (!NILP (keep_time))
570d7624 2206 {
d20704ef
PE
2207 EMACS_TIME atime = get_stat_atime (&st);
2208 EMACS_TIME mtime = get_stat_mtime (&st);
2209 if (set_file_times (ofd, SSDATA (encoded_newname), atime, mtime))
2210 xsignal2 (Qfile_date_error,
2211 build_string ("Cannot set file date"), newname);
570d7624
JB
2212 }
2213
d35af63c
PE
2214 if (emacs_close (ofd) < 0)
2215 report_file_error ("I/O error", Fcons (newname, Qnil));
2216
68c45bf0 2217 emacs_close (ifd);
b016179b 2218
ed68db4d 2219#ifdef MSDOS
d20704ef
PE
2220 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2221 and if it can't, it tells so. Otherwise, under MSDOS we usually
2222 get only the READ bit, which will make the copied file read-only,
2223 so it's better not to chmod at all. */
2224 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2225 chmod (SDATA (encoded_newname), st.st_mode & 07777);
ed68db4d 2226#endif /* MSDOS */
b016179b 2227#endif /* not WINDOWSNT */
5acac34e 2228
b5148e85
RS
2229 /* Discard the unwind protects. */
2230 specpdl_ptr = specpdl + count;
2231
570d7624
JB
2232 UNGCPRO;
2233 return Qnil;
2234}
385b6cc7 2235\f
9bbe01fb 2236DEFUN ("make-directory-internal", Fmake_directory_internal,
353cfc19 2237 Smake_directory_internal, 1, 1, 0,
8c1a1077 2238 doc: /* Create a new directory named DIRECTORY. */)
5842a27b 2239 (Lisp_Object directory)
570d7624 2240{
5976c3fe 2241 const char *dir;
32f4334d 2242 Lisp_Object handler;
b1d1b865 2243 Lisp_Object encoded_dir;
570d7624 2244
b7826503 2245 CHECK_STRING (directory);
3b7f6e60 2246 directory = Fexpand_file_name (directory, Qnil);
32f4334d 2247
3b7f6e60 2248 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
32f4334d 2249 if (!NILP (handler))
3b7f6e60 2250 return call2 (handler, Qmake_directory_internal, directory);
9bbe01fb 2251
b1d1b865
RS
2252 encoded_dir = ENCODE_FILE (directory);
2253
5976c3fe 2254 dir = SSDATA (encoded_dir);
570d7624 2255
5e570b75
RS
2256#ifdef WINDOWSNT
2257 if (mkdir (dir) != 0)
2258#else
09450bae 2259 if (mkdir (dir, 0777 & ~auto_saving_dir_umask) != 0)
5e570b75 2260#endif
a9f2aeae 2261 report_file_error ("Creating directory", list1 (directory));
570d7624 2262
32f4334d 2263 return Qnil;
570d7624
JB
2264}
2265
9d8f3bd9
MA
2266DEFUN ("delete-directory-internal", Fdelete_directory_internal,
2267 Sdelete_directory_internal, 1, 1, 0,
efdc16c9 2268 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
5842a27b 2269 (Lisp_Object directory)
570d7624 2270{
5976c3fe 2271 const char *dir;
b1d1b865 2272 Lisp_Object encoded_dir;
570d7624 2273
b7826503 2274 CHECK_STRING (directory);
3b7f6e60 2275 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
b1d1b865 2276 encoded_dir = ENCODE_FILE (directory);
5976c3fe 2277 dir = SSDATA (encoded_dir);
b1d1b865 2278
570d7624 2279 if (rmdir (dir) != 0)
a9f2aeae 2280 report_file_error ("Removing directory", list1 (directory));
570d7624
JB
2281
2282 return Qnil;
2283}
2284
2e2bbddb 2285DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 2,
f1a5d776
CY
2286 "(list (read-file-name \
2287 (if (and delete-by-moving-to-trash (null current-prefix-arg)) \
2288 \"Move file to trash: \" \"Delete file: \") \
2289 nil default-directory (confirm-nonexistent-file-or-buffer)) \
2290 (null current-prefix-arg))",
efdc16c9 2291 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
53967e09 2292If file has multiple names, it continues to exist with the other names.
f1a5d776
CY
2293TRASH non-nil means to trash the file instead of deleting, provided
2294`delete-by-moving-to-trash' is non-nil.
53967e09 2295
f1a5d776
CY
2296When called interactively, TRASH is t if no prefix argument is given.
2297With a prefix argument, TRASH is nil. */)
5842a27b 2298 (Lisp_Object filename, Lisp_Object trash)
570d7624 2299{
32f4334d 2300 Lisp_Object handler;
b1d1b865 2301 Lisp_Object encoded_file;
efdc16c9 2302 struct gcpro gcpro1;
b1d1b865 2303
efdc16c9 2304 GCPRO1 (filename);
b4bd27c5
RS
2305 if (!NILP (Ffile_directory_p (filename))
2306 && NILP (Ffile_symlink_p (filename)))
24b1ddad
KS
2307 xsignal2 (Qfile_error,
2308 build_string ("Removing old name: is a directory"),
2309 filename);
efdc16c9 2310 UNGCPRO;
570d7624 2311 filename = Fexpand_file_name (filename, Qnil);
32f4334d 2312
49307295 2313 handler = Ffind_file_name_handler (filename, Qdelete_file);
32f4334d 2314 if (!NILP (handler))
f5783df3 2315 return call3 (handler, Qdelete_file, filename, trash);
32f4334d 2316
f1a5d776 2317 if (delete_by_moving_to_trash && !NILP (trash))
6cf29fe8
JR
2318 return call1 (Qmove_file_to_trash, filename);
2319
b1d1b865
RS
2320 encoded_file = ENCODE_FILE (filename);
2321
ce2fe65a 2322 if (unlink (SSDATA (encoded_file)) < 0)
a9f2aeae 2323 report_file_error ("Removing old name", list1 (filename));
8a9b0da9 2324 return Qnil;
570d7624
JB
2325}
2326
385b6cc7 2327static Lisp_Object
971de7fb 2328internal_delete_file_1 (Lisp_Object ignore)
385b6cc7
RS
2329{
2330 return Qt;
2331}
2332
7d80ea23 2333/* Delete file FILENAME, returning true if successful.
f1a5d776 2334 This ignores `delete-by-moving-to-trash'. */
385b6cc7 2335
7d80ea23 2336bool
f1a5d776 2337internal_delete_file (Lisp_Object filename)
385b6cc7 2338{
b0728617
EZ
2339 Lisp_Object tem;
2340
2341 tem = internal_condition_case_2 (Fdelete_file, filename, Qnil,
2342 Qt, internal_delete_file_1);
2343 return NILP (tem);
385b6cc7
RS
2344}
2345\f
570d7624 2346DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
7c0f6118 2347 "fRename file: \nGRename %s to file: \np",
a4e03fe5 2348 doc: /* Rename FILE as NEWNAME. Both args must be strings.
8c1a1077
PJ
2349If file has names other than FILE, it continues to have those names.
2350Signals a `file-already-exists' error if a file NEWNAME already exists
2351unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2352A number as third arg means request confirmation if NEWNAME already exists.
2353This is what happens in interactive use with M-x. */)
5842a27b 2354 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
570d7624 2355{
32f4334d 2356 Lisp_Object handler;
f72b5416
JD
2357 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2358 Lisp_Object encoded_file, encoded_newname, symlink_target;
570d7624 2359
f72b5416
JD
2360 symlink_target = encoded_file = encoded_newname = Qnil;
2361 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
b7826503
PJ
2362 CHECK_STRING (file);
2363 CHECK_STRING (newname);
3b7f6e60 2364 file = Fexpand_file_name (file, Qnil);
1ffc5c90 2365
f83caf70
EZ
2366 if ((!NILP (Ffile_directory_p (newname)))
2367#ifdef DOS_NT
2368 /* If the file names are identical but for the case,
2369 don't attempt to move directory to itself. */
2370 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2371#endif
2372 )
8719abec 2373 {
ce2fe65a
AS
2374 Lisp_Object fname = (NILP (Ffile_directory_p (file))
2375 ? file : Fdirectory_file_name (file));
8719abec
CY
2376 newname = Fexpand_file_name (Ffile_name_nondirectory (fname), newname);
2377 }
1ffc5c90
RS
2378 else
2379 newname = Fexpand_file_name (newname, Qnil);
32f4334d
RS
2380
2381 /* If the file name has special constructs in it,
2382 call the corresponding file handler. */
3b7f6e60 2383 handler = Ffind_file_name_handler (file, Qrename_file);
51cf6d37 2384 if (NILP (handler))
49307295 2385 handler = Ffind_file_name_handler (newname, Qrename_file);
32f4334d 2386 if (!NILP (handler))
36712b0a 2387 RETURN_UNGCPRO (call4 (handler, Qrename_file,
3b7f6e60 2388 file, newname, ok_if_already_exists));
32f4334d 2389
b1d1b865
RS
2390 encoded_file = ENCODE_FILE (file);
2391 encoded_newname = ENCODE_FILE (newname);
2392
bc77278f
EZ
2393#ifdef DOS_NT
2394 /* If the file names are identical but for the case, don't ask for
2395 confirmation: they simply want to change the letter-case of the
2396 file name. */
2397 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2398#endif
265a9e55 2399 if (NILP (ok_if_already_exists)
93c30b5f 2400 || INTEGERP (ok_if_already_exists))
2f868094 2401 barf_or_query_if_file_exists (newname, "rename to it",
b8b29dc9 2402 INTEGERP (ok_if_already_exists), 0, 0);
ce2fe65a 2403 if (rename (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
570d7624
JB
2404 {
2405 if (errno == EXDEV)
2406 {
d311d28c 2407 ptrdiff_t count;
f72b5416 2408 symlink_target = Ffile_symlink_p (file);
440c7d00
JD
2409 if (! NILP (symlink_target))
2410 Fmake_symbolic_link (symlink_target, newname,
f59abab9 2411 NILP (ok_if_already_exists) ? Qnil : Qt);
ae0d7250 2412 else if (!NILP (Ffile_directory_p (file)))
8719abec
CY
2413 call4 (Qcopy_directory, file, newname, Qt, Qnil);
2414 else
2415 /* We have already prompted if it was an integer, so don't
2416 have copy-file prompt again. */
586702ce 2417 Fcopy_file (file, newname,
586702ce 2418 NILP (ok_if_already_exists) ? Qnil : Qt,
574c05e2 2419 Qt, Qt, Qt);
d550c425 2420
6bddfc97 2421 count = SPECPDL_INDEX ();
d2b66acf 2422 specbind (Qdelete_by_moving_to_trash, Qnil);
8fab2362 2423
ae0d7250 2424 if (!NILP (Ffile_directory_p (file)) && NILP (symlink_target))
8719abec
CY
2425 call2 (Qdelete_directory, file, Qt);
2426 else
f1a5d776 2427 Fdelete_file (file, Qnil);
6bddfc97 2428 unbind_to (count, Qnil);
570d7624
JB
2429 }
2430 else
a9f2aeae 2431 report_file_error ("Renaming", list2 (file, newname));
570d7624
JB
2432 }
2433 UNGCPRO;
2434 return Qnil;
2435}
2436
2437DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
7c0f6118 2438 "fAdd name to file: \nGName to add to %s: \np",
a4e03fe5 2439 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
8c1a1077
PJ
2440Signals a `file-already-exists' error if a file NEWNAME already exists
2441unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2442A number as third arg means request confirmation if NEWNAME already exists.
2443This is what happens in interactive use with M-x. */)
5842a27b 2444 (Lisp_Object file, Lisp_Object newname, Lisp_Object ok_if_already_exists)
570d7624 2445{
32f4334d 2446 Lisp_Object handler;
b1d1b865
RS
2447 Lisp_Object encoded_file, encoded_newname;
2448 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
570d7624 2449
b1d1b865
RS
2450 GCPRO4 (file, newname, encoded_file, encoded_newname);
2451 encoded_file = encoded_newname = Qnil;
b7826503
PJ
2452 CHECK_STRING (file);
2453 CHECK_STRING (newname);
3b7f6e60 2454 file = Fexpand_file_name (file, Qnil);
1ffc5c90
RS
2455
2456 if (!NILP (Ffile_directory_p (newname)))
2457 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2458 else
2459 newname = Fexpand_file_name (newname, Qnil);
32f4334d
RS
2460
2461 /* If the file name has special constructs in it,
2462 call the corresponding file handler. */
3b7f6e60 2463 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
32f4334d 2464 if (!NILP (handler))
3b7f6e60 2465 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
36712b0a 2466 newname, ok_if_already_exists));
32f4334d 2467
adc6741c
RS
2468 /* If the new name has special constructs in it,
2469 call the corresponding file handler. */
2470 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2471 if (!NILP (handler))
3b7f6e60 2472 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
adc6741c
RS
2473 newname, ok_if_already_exists));
2474
b1d1b865
RS
2475 encoded_file = ENCODE_FILE (file);
2476 encoded_newname = ENCODE_FILE (newname);
2477
265a9e55 2478 if (NILP (ok_if_already_exists)
93c30b5f 2479 || INTEGERP (ok_if_already_exists))
2f868094 2480 barf_or_query_if_file_exists (newname, "make it a new name",
b8b29dc9 2481 INTEGERP (ok_if_already_exists), 0, 0);
5e570b75 2482
42a5b22f 2483 unlink (SSDATA (newname));
ce2fe65a 2484 if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) < 0)
a9f2aeae 2485 report_file_error ("Adding new name", list2 (file, newname));
570d7624
JB
2486
2487 UNGCPRO;
2488 return Qnil;
2489}
2490
570d7624 2491DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
7c0f6118 2492 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
68780e2a
RS
2493 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2494Both args must be strings.
8c1a1077
PJ
2495Signals a `file-already-exists' error if a file LINKNAME already exists
2496unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2497A number as third arg means request confirmation if LINKNAME already exists.
2498This happens for interactive use with M-x. */)
5842a27b 2499 (Lisp_Object filename, Lisp_Object linkname, Lisp_Object ok_if_already_exists)
570d7624 2500{
32f4334d 2501 Lisp_Object handler;
b1d1b865
RS
2502 Lisp_Object encoded_filename, encoded_linkname;
2503 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
570d7624 2504
b1d1b865
RS
2505 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2506 encoded_filename = encoded_linkname = Qnil;
b7826503
PJ
2507 CHECK_STRING (filename);
2508 CHECK_STRING (linkname);
d9bc1c99
RS
2509 /* If the link target has a ~, we must expand it to get
2510 a truly valid file name. Otherwise, do not expand;
2511 we want to permit links to relative file names. */
d5db4077 2512 if (SREF (filename, 0) == '~')
d9bc1c99 2513 filename = Fexpand_file_name (filename, Qnil);
1ffc5c90
RS
2514
2515 if (!NILP (Ffile_directory_p (linkname)))
dac24db4 2516 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
1ffc5c90
RS
2517 else
2518 linkname = Fexpand_file_name (linkname, Qnil);
32f4334d
RS
2519
2520 /* If the file name has special constructs in it,
2521 call the corresponding file handler. */
49307295 2522 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
32f4334d 2523 if (!NILP (handler))
36712b0a
KH
2524 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2525 linkname, ok_if_already_exists));
32f4334d 2526
adc6741c
RS
2527 /* If the new link name has special constructs in it,
2528 call the corresponding file handler. */
2529 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2530 if (!NILP (handler))
2531 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2532 linkname, ok_if_already_exists));
2533
b1d1b865
RS
2534 encoded_filename = ENCODE_FILE (filename);
2535 encoded_linkname = ENCODE_FILE (linkname);
2536
265a9e55 2537 if (NILP (ok_if_already_exists)
93c30b5f 2538 || INTEGERP (ok_if_already_exists))
2f868094 2539 barf_or_query_if_file_exists (linkname, "make it a link",
b8b29dc9 2540 INTEGERP (ok_if_already_exists), 0, 0);
ce2fe65a 2541 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname)) < 0)
570d7624
JB
2542 {
2543 /* If we didn't complain already, silently delete existing file. */
2544 if (errno == EEXIST)
2545 {
42a5b22f 2546 unlink (SSDATA (encoded_linkname));
ce2fe65a
AS
2547 if (symlink (SSDATA (encoded_filename), SSDATA (encoded_linkname))
2548 >= 0)
1a04498e
KH
2549 {
2550 UNGCPRO;
2551 return Qnil;
2552 }
570d7624 2553 }
d9d0d182
PE
2554 if (errno == ENOSYS)
2555 {
2556 UNGCPRO;
2557 xsignal1 (Qfile_error,
2558 build_string ("Symbolic links are not supported"));
2559 }
570d7624 2560
a9f2aeae 2561 report_file_error ("Making symbolic link", list2 (filename, linkname));
570d7624
JB
2562 }
2563 UNGCPRO;
2564 return Qnil;
e89b536d 2565}
570d7624 2566
570d7624 2567\f
a7ca3326 2568DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
570d7624 2569 1, 1, 0,
8c1a1077
PJ
2570 doc: /* Return t if file FILENAME specifies an absolute file name.
2571On Unix, this is a name starting with a `/' or a `~'. */)
5842a27b 2572 (Lisp_Object filename)
570d7624 2573{
b7826503 2574 CHECK_STRING (filename);
5976c3fe 2575 return file_name_absolute_p (SSDATA (filename)) ? Qt : Qnil;
570d7624 2576}
3beeedfe 2577\f
bb385a92
EZ
2578/* Return true if FILENAME exists. */
2579bool
2580check_existing (const char *filename)
2581{
73dcdb9f 2582 return faccessat (AT_FDCWD, filename, F_OK, AT_EACCESS) == 0;
bb385a92
EZ
2583}
2584
f75d7a91 2585/* Return true if file FILENAME exists and can be executed. */
3beeedfe 2586
f75d7a91 2587static bool
971de7fb 2588check_executable (char *filename)
3beeedfe 2589{
73dcdb9f 2590 return faccessat (AT_FDCWD, filename, X_OK, AT_EACCESS) == 0;
3beeedfe
RS
2591}
2592
73dcdb9f
PE
2593/* Return true if file FILENAME exists and can be accessed
2594 according to AMODE, which should include W_OK.
2595 On failure, return false and set errno. */
3beeedfe 2596
f75d7a91 2597static bool
73dcdb9f 2598check_writable (const char *filename, int amode)
3beeedfe 2599{
3be3c08e 2600#ifdef MSDOS
73dcdb9f
PE
2601 /* FIXME: an faccessat implementation should be added to the
2602 DOS/Windows ports and this #ifdef branch should be removed. */
3be3c08e
RS
2603 struct stat st;
2604 if (stat (filename, &st) < 0)
2605 return 0;
73dcdb9f 2606 errno = EPERM;
f68c809d 2607 return (st.st_mode & S_IWRITE || S_ISDIR (st.st_mode));
3be3c08e 2608#else /* not MSDOS */
73dcdb9f 2609 bool res = faccessat (AT_FDCWD, filename, amode, AT_EACCESS) == 0;
e1b01a3a 2610#ifdef CYGWIN
73dcdb9f 2611 /* faccessat may have returned failure because Cygwin couldn't
e1b01a3a
KB
2612 determine the file's UID or GID; if so, we return success. */
2613 if (!res)
2614 {
73dcdb9f 2615 int faccessat_errno = errno;
e1b01a3a
KB
2616 struct stat st;
2617 if (stat (filename, &st) < 0)
2618 return 0;
2619 res = (st.st_uid == -1 || st.st_gid == -1);
73dcdb9f 2620 errno = faccessat_errno;
e1b01a3a
KB
2621 }
2622#endif /* CYGWIN */
2623 return res;
3be3c08e 2624#endif /* not MSDOS */
3beeedfe 2625}
570d7624 2626
a7ca3326 2627DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
68780e2a
RS
2628 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
2629See also `file-readable-p' and `file-attributes'.
2630This returns nil for a symlink to a nonexistent file.
2631Use `file-symlink-p' to test for such links. */)
5842a27b 2632 (Lisp_Object filename)
570d7624 2633{
199607e4 2634 Lisp_Object absname;
32f4334d 2635 Lisp_Object handler;
570d7624 2636
b7826503 2637 CHECK_STRING (filename);
199607e4 2638 absname = Fexpand_file_name (filename, Qnil);
32f4334d
RS
2639
2640 /* If the file name has special constructs in it,
2641 call the corresponding file handler. */
199607e4 2642 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
32f4334d 2643 if (!NILP (handler))
199607e4 2644 return call2 (handler, Qfile_exists_p, absname);
32f4334d 2645
b1d1b865
RS
2646 absname = ENCODE_FILE (absname);
2647
bb385a92 2648 return (check_existing (SSDATA (absname))) ? Qt : Qnil;
570d7624
JB
2649}
2650
2651DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
8c1a1077
PJ
2652 doc: /* Return t if FILENAME can be executed by you.
2653For a directory, this means you can access files in that directory. */)
5842a27b 2654 (Lisp_Object filename)
570d7624 2655{
199607e4 2656 Lisp_Object absname;
32f4334d 2657 Lisp_Object handler;
570d7624 2658
b7826503 2659 CHECK_STRING (filename);
199607e4 2660 absname = Fexpand_file_name (filename, Qnil);
32f4334d
RS
2661
2662 /* If the file name has special constructs in it,
2663 call the corresponding file handler. */
199607e4 2664 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
32f4334d 2665 if (!NILP (handler))
199607e4 2666 return call2 (handler, Qfile_executable_p, absname);
32f4334d 2667
b1d1b865
RS
2668 absname = ENCODE_FILE (absname);
2669
42a5b22f 2670 return (check_executable (SSDATA (absname)) ? Qt : Qnil);
570d7624
JB
2671}
2672
a7ca3326 2673DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
8c1a1077
PJ
2674 doc: /* Return t if file FILENAME exists and you can read it.
2675See also `file-exists-p' and `file-attributes'. */)
5842a27b 2676 (Lisp_Object filename)
570d7624 2677{
199607e4 2678 Lisp_Object absname;
32f4334d 2679 Lisp_Object handler;
570d7624 2680
b7826503 2681 CHECK_STRING (filename);
199607e4 2682 absname = Fexpand_file_name (filename, Qnil);
32f4334d
RS
2683
2684 /* If the file name has special constructs in it,
2685 call the corresponding file handler. */
199607e4 2686 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
32f4334d 2687 if (!NILP (handler))
199607e4 2688 return call2 (handler, Qfile_readable_p, absname);
32f4334d 2689
b1d1b865 2690 absname = ENCODE_FILE (absname);
73dcdb9f
PE
2691 return (faccessat (AT_FDCWD, SSDATA (absname), R_OK, AT_EACCESS) == 0
2692 ? Qt : Qnil);
570d7624
JB
2693}
2694
f793dc6c 2695DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
8c1a1077 2696 doc: /* Return t if file FILENAME can be written or created by you. */)
5842a27b 2697 (Lisp_Object filename)
f793dc6c 2698{
b1d1b865 2699 Lisp_Object absname, dir, encoded;
f793dc6c 2700 Lisp_Object handler;
f793dc6c 2701
b7826503 2702 CHECK_STRING (filename);
199607e4 2703 absname = Fexpand_file_name (filename, Qnil);
f793dc6c
RS
2704
2705 /* If the file name has special constructs in it,
2706 call the corresponding file handler. */
199607e4 2707 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
f793dc6c 2708 if (!NILP (handler))
199607e4 2709 return call2 (handler, Qfile_writable_p, absname);
f793dc6c 2710
b1d1b865 2711 encoded = ENCODE_FILE (absname);
73dcdb9f
PE
2712 if (check_writable (SSDATA (encoded), W_OK))
2713 return Qt;
2714 if (errno != ENOENT)
2715 return Qnil;
b1d1b865 2716
199607e4 2717 dir = Ffile_name_directory (absname);
73dcdb9f 2718 eassert (!NILP (dir));
f793dc6c 2719#ifdef MSDOS
73dcdb9f 2720 dir = Fdirectory_file_name (dir);
f793dc6c 2721#endif /* MSDOS */
b1d1b865
RS
2722
2723 dir = ENCODE_FILE (dir);
e3e8a75a
GM
2724#ifdef WINDOWSNT
2725 /* The read-only attribute of the parent directory doesn't affect
2726 whether a file or directory can be created within it. Some day we
2727 should check ACLs though, which do affect this. */
73dcdb9f 2728 return file_directory_p (SDATA (dir)) ? Qt : Qnil;
e3e8a75a 2729#else
73dcdb9f 2730 return check_writable (SSDATA (dir), W_OK | X_OK) ? Qt : Qnil;
e3e8a75a 2731#endif
f793dc6c
RS
2732}
2733\f
1f8653eb 2734DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
8c1a1077
PJ
2735 doc: /* Access file FILENAME, and get an error if that does not work.
2736The second argument STRING is used in the error message.
a4e03fe5 2737If there is no error, returns nil. */)
5842a27b 2738 (Lisp_Object filename, Lisp_Object string)
1f8653eb 2739{
49475635 2740 Lisp_Object handler, encoded_filename, absname;
1f8653eb
RS
2741 int fd;
2742
b7826503 2743 CHECK_STRING (filename);
49475635
EZ
2744 absname = Fexpand_file_name (filename, Qnil);
2745
b7826503 2746 CHECK_STRING (string);
1f8653eb
RS
2747
2748 /* If the file name has special constructs in it,
2749 call the corresponding file handler. */
49475635 2750 handler = Ffind_file_name_handler (absname, Qaccess_file);
1f8653eb 2751 if (!NILP (handler))
49475635 2752 return call3 (handler, Qaccess_file, absname, string);
1f8653eb 2753
49475635 2754 encoded_filename = ENCODE_FILE (absname);
b1d1b865 2755
42a5b22f 2756 fd = emacs_open (SSDATA (encoded_filename), O_RDONLY, 0);
1f8653eb 2757 if (fd < 0)
42a5b22f 2758 report_file_error (SSDATA (string), Fcons (filename, Qnil));
68c45bf0 2759 emacs_close (fd);
1f8653eb
RS
2760
2761 return Qnil;
2762}
2763\f
8654f9d7
PE
2764/* Relative to directory FD, return the symbolic link value of FILENAME.
2765 On failure, return nil. */
2766Lisp_Object
2767emacs_readlinkat (int fd, char const *filename)
2768{
2769 static struct allocator const emacs_norealloc_allocator =
2770 { xmalloc, NULL, xfree, memory_full };
2771 Lisp_Object val;
2772 char readlink_buf[1024];
2773 char *buf = careadlinkat (fd, filename, readlink_buf, sizeof readlink_buf,
2774 &emacs_norealloc_allocator, readlinkat);
2775 if (!buf)
2776 return Qnil;
2777
2778 val = build_string (buf);
2779 if (buf[0] == '/' && strchr (buf, ':'))
2780 val = concat2 (build_string ("/:"), val);
2781 if (buf != readlink_buf)
2782 xfree (buf);
2783 val = DECODE_FILE (val);
2784 return val;
2785}
2786
a7ca3326 2787DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
8c1a1077 2788 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
1c353c74 2789The value is the link target, as a string.
68780e2a
RS
2790Otherwise it returns nil.
2791
2792This function returns t when given the name of a symlink that
2793points to a nonexistent file. */)
5842a27b 2794 (Lisp_Object filename)
570d7624 2795{
32f4334d 2796 Lisp_Object handler;
570d7624 2797
b7826503 2798 CHECK_STRING (filename);
570d7624
JB
2799 filename = Fexpand_file_name (filename, Qnil);
2800
32f4334d
RS
2801 /* If the file name has special constructs in it,
2802 call the corresponding file handler. */
49307295 2803 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
32f4334d
RS
2804 if (!NILP (handler))
2805 return call2 (handler, Qfile_symlink_p, filename);
2806
b1d1b865
RS
2807 filename = ENCODE_FILE (filename);
2808
8654f9d7 2809 return emacs_readlinkat (AT_FDCWD, SSDATA (filename));
570d7624
JB
2810}
2811
a7ca3326 2812DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
8c1a1077
PJ
2813 doc: /* Return t if FILENAME names an existing directory.
2814Symbolic links to directories count as directories.
2815See `file-symlink-p' to distinguish symlinks. */)
5842a27b 2816 (Lisp_Object filename)
570d7624 2817{
73dcdb9f 2818 Lisp_Object absname;
32f4334d 2819 Lisp_Object handler;
570d7624 2820
4b4deea2 2821 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
570d7624 2822
32f4334d
RS
2823 /* If the file name has special constructs in it,
2824 call the corresponding file handler. */
199607e4 2825 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
32f4334d 2826 if (!NILP (handler))
199607e4 2827 return call2 (handler, Qfile_directory_p, absname);
32f4334d 2828
b1d1b865
RS
2829 absname = ENCODE_FILE (absname);
2830
73dcdb9f
PE
2831 return file_directory_p (SSDATA (absname)) ? Qt : Qnil;
2832}
2833
2834/* Return true if FILE is a directory or a symlink to a directory. */
2835bool
2836file_directory_p (char const *file)
2837{
2838#ifdef WINDOWSNT
2839 /* This is cheaper than 'stat'. */
2840 return faccessat (AT_FDCWD, file, D_OK, AT_EACCESS) == 0;
2841#else
2842 struct stat st;
2843 return stat (file, &st) == 0 && S_ISDIR (st.st_mode);
2844#endif
570d7624
JB
2845}
2846
a7ca3326 2847DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p,
16a97296 2848 Sfile_accessible_directory_p, 1, 1, 0,
e385ec41
RS
2849 doc: /* Return t if file FILENAME names a directory you can open.
2850For the value to be t, FILENAME must specify the name of a directory as a file,
2851and the directory must allow you to open files in it. In order to use a
8c1a1077
PJ
2852directory as a buffer's current directory, this predicate must return true.
2853A directory name spec may be given instead; then the value is t
2854if the directory so specified exists and really is a readable and
2855searchable directory. */)
5842a27b 2856 (Lisp_Object filename)
b72dea2a 2857{
73dcdb9f 2858 Lisp_Object absname;
32f4334d 2859 Lisp_Object handler;
73dcdb9f
PE
2860
2861 CHECK_STRING (filename);
2862 absname = Fexpand_file_name (filename, Qnil);
32f4334d
RS
2863
2864 /* If the file name has special constructs in it,
2865 call the corresponding file handler. */
73dcdb9f 2866 handler = Ffind_file_name_handler (absname, Qfile_accessible_directory_p);
32f4334d 2867 if (!NILP (handler))
73dcdb9f 2868 return call2 (handler, Qfile_accessible_directory_p, absname);
32f4334d 2869
73dcdb9f
PE
2870 absname = ENCODE_FILE (absname);
2871 return file_accessible_directory_p (SSDATA (absname)) ? Qt : Qnil;
2872}
2873
2874/* If FILE is a searchable directory or a symlink to a
2875 searchable directory, return true. Otherwise return
2876 false and set errno to an error number. */
2877bool
2878file_accessible_directory_p (char const *file)
2879{
2880#ifdef DOS_NT
2881 /* There's no need to test whether FILE is searchable, as the
2882 searchable/executable bit is invented on DOS_NT platforms. */
2883 return file_directory_p (file);
2884#else
2885 /* On POSIXish platforms, use just one system call; this avoids a
2886 race and is typically faster. */
2887 ptrdiff_t len = strlen (file);
2888 char const *dir;
2889 bool ok;
2890 int saved_errno;
2891 USE_SAFE_ALLOCA;
2892
2893 /* Normally a file "FOO" is an accessible directory if "FOO/." exists.
2894 There are three exceptions: "", "/", and "//". Leave "" alone,
2895 as it's invalid. Append only "." to the other two exceptions as
2896 "/" and "//" are distinct on some platforms, whereas "/", "///",
2897 "////", etc. are all equivalent. */
2898 if (! len)
2899 dir = file;
2900 else
2901 {
2902 /* Just check for trailing '/' when deciding whether to append '/'.
2903 That's simpler than testing the two special cases "/" and "//",
2904 and it's a safe optimization here. */
2905 char *buf = SAFE_ALLOCA (len + 3);
2906 memcpy (buf, file, len);
2907 strcpy (buf + len, "/." + (file[len - 1] == '/'));
2908 dir = buf;
2909 }
2910
2911 ok = check_existing (dir);
2912 saved_errno = errno;
2913 SAFE_FREE ();
2914 errno = saved_errno;
2915 return ok;
2916#endif
b72dea2a
JB
2917}
2918
f793dc6c 2919DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
19a9c3b7
LH
2920 doc: /* Return t if FILENAME names a regular file.
2921This is the sort of file that holds an ordinary stream of data bytes.
2922Symbolic links to regular files count as regular files.
2923See `file-symlink-p' to distinguish symlinks. */)
5842a27b 2924 (Lisp_Object filename)
f793dc6c 2925{
199607e4 2926 register Lisp_Object absname;
f793dc6c
RS
2927 struct stat st;
2928 Lisp_Object handler;
2929
4b4deea2 2930 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
f793dc6c
RS
2931
2932 /* If the file name has special constructs in it,
2933 call the corresponding file handler. */
199607e4 2934 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
f793dc6c 2935 if (!NILP (handler))
199607e4 2936 return call2 (handler, Qfile_regular_p, absname);
f793dc6c 2937
b1d1b865
RS
2938 absname = ENCODE_FILE (absname);
2939
c1c4693e
RS
2940#ifdef WINDOWSNT
2941 {
2942 int result;
2943 Lisp_Object tem = Vw32_get_true_file_attributes;
2944
2945 /* Tell stat to use expensive method to get accurate info. */
2946 Vw32_get_true_file_attributes = Qt;
d5db4077 2947 result = stat (SDATA (absname), &st);
c1c4693e
RS
2948 Vw32_get_true_file_attributes = tem;
2949
2950 if (result < 0)
2951 return Qnil;
f68c809d 2952 return S_ISREG (st.st_mode) ? Qt : Qnil;
c1c4693e
RS
2953 }
2954#else
42a5b22f 2955 if (stat (SSDATA (absname), &st) < 0)
f793dc6c 2956 return Qnil;
f68c809d 2957 return S_ISREG (st.st_mode) ? Qt : Qnil;
c1c4693e 2958#endif
f793dc6c
RS
2959}
2960\f
574c05e2
KK
2961DEFUN ("file-selinux-context", Ffile_selinux_context,
2962 Sfile_selinux_context, 1, 1, 0,
fa74b241
CY
2963 doc: /* Return SELinux context of file named FILENAME.
2964The return value is a list (USER ROLE TYPE RANGE), where the list
2965elements are strings naming the user, role, type, and range of the
2966file's SELinux security context.
2967
2968Return (nil nil nil nil) if the file is nonexistent or inaccessible,
2969or if SELinux is disabled, or if Emacs lacks SELinux support. */)
5842a27b 2970 (Lisp_Object filename)
574c05e2
KK
2971{
2972 Lisp_Object absname;
2973 Lisp_Object values[4];
2974 Lisp_Object handler;
2975#if HAVE_LIBSELINUX
2976 security_context_t con;
2977 int conlength;
2978 context_t context;
2979#endif
2980
4b4deea2 2981 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
574c05e2
KK
2982
2983 /* If the file name has special constructs in it,
2984 call the corresponding file handler. */
2985 handler = Ffind_file_name_handler (absname, Qfile_selinux_context);
2986 if (!NILP (handler))
2987 return call2 (handler, Qfile_selinux_context, absname);
2988
2989 absname = ENCODE_FILE (absname);
2990
2991 values[0] = Qnil;
2992 values[1] = Qnil;
2993 values[2] = Qnil;
2994 values[3] = Qnil;
2995#if HAVE_LIBSELINUX
2996 if (is_selinux_enabled ())
2997 {
b14aac08 2998 conlength = lgetfilecon (SSDATA (absname), &con);
574c05e2
KK
2999 if (conlength > 0)
3000 {
3001 context = context_new (con);
45841e65
KK
3002 if (context_user_get (context))
3003 values[0] = build_string (context_user_get (context));
3004 if (context_role_get (context))
3005 values[1] = build_string (context_role_get (context));
3006 if (context_type_get (context))
3007 values[2] = build_string (context_type_get (context));
3008 if (context_range_get (context))
3009 values[3] = build_string (context_range_get (context));
574c05e2 3010 context_free (context);
c6ba4138 3011 freecon (con);
574c05e2 3012 }
574c05e2
KK
3013 }
3014#endif
3015
5e617bc2 3016 return Flist (sizeof (values) / sizeof (values[0]), values);
574c05e2
KK
3017}
3018\f
3019DEFUN ("set-file-selinux-context", Fset_file_selinux_context,
3020 Sset_file_selinux_context, 2, 2, 0,
fa74b241
CY
3021 doc: /* Set SELinux context of file named FILENAME to CONTEXT.
3022CONTEXT should be a list (USER ROLE TYPE RANGE), where the list
3023elements are strings naming the components of a SELinux context.
3024
ccad023b
EZ
3025Value is t if setting of SELinux context was successful, nil otherwise.
3026
3027This function does nothing and returns nil if SELinux is disabled,
3028or if Emacs was not compiled with SELinux support. */)
5842a27b 3029 (Lisp_Object filename, Lisp_Object context)
574c05e2 3030{
0f4a96b5 3031 Lisp_Object absname;
574c05e2 3032 Lisp_Object handler;
0f4a96b5
JB
3033#if HAVE_LIBSELINUX
3034 Lisp_Object encoded_absname;
574c05e2
KK
3035 Lisp_Object user = CAR_SAFE (context);
3036 Lisp_Object role = CAR_SAFE (CDR_SAFE (context));
3037 Lisp_Object type = CAR_SAFE (CDR_SAFE (CDR_SAFE (context)));
3038 Lisp_Object range = CAR_SAFE (CDR_SAFE (CDR_SAFE (CDR_SAFE (context))));
574c05e2 3039 security_context_t con;
f75d7a91
PE
3040 bool fail;
3041 int conlength;
574c05e2
KK
3042 context_t parsed_con;
3043#endif
3044
4b4deea2 3045 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
574c05e2
KK
3046
3047 /* If the file name has special constructs in it,
3048 call the corresponding file handler. */
3049 handler = Ffind_file_name_handler (absname, Qset_file_selinux_context);
3050 if (!NILP (handler))
3051 return call3 (handler, Qset_file_selinux_context, absname, context);
3052
0f4a96b5 3053#if HAVE_LIBSELINUX
574c05e2
KK
3054 if (is_selinux_enabled ())
3055 {
3056 /* Get current file context. */
a9b53ad3 3057 encoded_absname = ENCODE_FILE (absname);
b14aac08 3058 conlength = lgetfilecon (SSDATA (encoded_absname), &con);
574c05e2
KK
3059 if (conlength > 0)
3060 {
3061 parsed_con = context_new (con);
3062 /* Change the parts defined in the parameter.*/
3063 if (STRINGP (user))
3064 {
b14aac08 3065 if (context_user_set (parsed_con, SSDATA (user)))
574c05e2
KK
3066 error ("Doing context_user_set");
3067 }
3068 if (STRINGP (role))
3069 {
b14aac08 3070 if (context_role_set (parsed_con, SSDATA (role)))
574c05e2
KK
3071 error ("Doing context_role_set");
3072 }
3073 if (STRINGP (type))
3074 {
b14aac08 3075 if (context_type_set (parsed_con, SSDATA (type)))
574c05e2
KK
3076 error ("Doing context_type_set");
3077 }
3078 if (STRINGP (range))
3079 {
b14aac08 3080 if (context_range_set (parsed_con, SSDATA (range)))
574c05e2
KK
3081 error ("Doing context_range_set");
3082 }
3083
24c51a09 3084 /* Set the modified context back to the file. */
f75d7a91
PE
3085 fail = (lsetfilecon (SSDATA (encoded_absname),
3086 context_str (parsed_con))
3087 != 0);
24c51a09
GM
3088 /* See http://debbugs.gnu.org/11245 for ENOTSUP. */
3089 if (fail && errno != ENOTSUP)
574c05e2
KK
3090 report_file_error ("Doing lsetfilecon", Fcons (absname, Qnil));
3091
3092 context_free (parsed_con);
c6ba4138 3093 freecon (con);
c1fea2c0 3094 return fail ? Qnil : Qt;
574c05e2
KK
3095 }
3096 else
5e617bc2 3097 report_file_error ("Doing lgetfilecon", Fcons (absname, Qnil));
574c05e2
KK
3098 }
3099#endif
3100
3101 return Qnil;
3102}
3103\f
7c3d167f 3104DEFUN ("file-acl", Ffile_acl, Sfile_acl, 1, 1, 0,
553081a5
SM
3105 doc: /* Return ACL entries of file named FILENAME.
3106The entries are returned in a format suitable for use in `set-file-acl'
3107but is otherwise undocumented and subject to change.
7c3d167f 3108Return nil if file does not exist or is not accessible, or if Emacs
553081a5 3109was unable to determine the ACL entries. */)
7c3d167f
RF
3110 (Lisp_Object filename)
3111{
3112 Lisp_Object absname;
3113 Lisp_Object handler;
3114#ifdef HAVE_POSIX_ACL
3115 acl_t acl;
3116 Lisp_Object acl_string;
3117 char *str;
3118#endif
3119
3120 absname = expand_and_dir_to_file (filename,
3121 BVAR (current_buffer, directory));
3122
3123 /* If the file name has special constructs in it,
3124 call the corresponding file handler. */
3125 handler = Ffind_file_name_handler (absname, Qfile_acl);
3126 if (!NILP (handler))
3127 return call2 (handler, Qfile_acl, absname);
3128
3129#ifdef HAVE_POSIX_ACL
3130 absname = ENCODE_FILE (absname);
3131
3132 acl = acl_get_file (SSDATA (absname), ACL_TYPE_ACCESS);
3133 if (acl == NULL)
3134 return Qnil;
3135
3136 str = acl_to_text (acl, NULL);
3137 if (str == NULL)
3138 {
3139 acl_free (acl);
3140 return Qnil;
3141 }
3142
3143 acl_string = build_string (str);
3144 acl_free (str);
3145 acl_free (acl);
3146
3147 return acl_string;
3148#endif
3149
3150 return Qnil;
3151}
3152
3153DEFUN ("set-file-acl", Fset_file_acl, Sset_file_acl,
3154 2, 2, 0,
3155 doc: /* Set ACL of file named FILENAME to ACL-STRING.
3156ACL-STRING should contain the textual representation of the ACL
3157entries in a format suitable for the platform.
3158
ccad023b
EZ
3159Value is t if setting of ACL was successful, nil otherwise.
3160
7c3d167f
RF
3161Setting ACL for local files requires Emacs to be built with ACL
3162support. */)
3163 (Lisp_Object filename, Lisp_Object acl_string)
3164{
3165 Lisp_Object absname;
3166 Lisp_Object handler;
3167#ifdef HAVE_POSIX_ACL
3168 Lisp_Object encoded_absname;
3169 acl_t acl;
3170 bool fail;
3171#endif
3172
3173 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
3174
3175 /* If the file name has special constructs in it,
3176 call the corresponding file handler. */
3177 handler = Ffind_file_name_handler (absname, Qset_file_acl);
3178 if (!NILP (handler))
3179 return call3 (handler, Qset_file_acl, absname, acl_string);
3180
3181#ifdef HAVE_POSIX_ACL
3182 if (STRINGP (acl_string))
3183 {
3184 acl = acl_from_text (SSDATA (acl_string));
3185 if (acl == NULL)
3186 {
3187 report_file_error ("Converting ACL", Fcons (absname, Qnil));
3188 return Qnil;
3189 }
3190
3191 encoded_absname = ENCODE_FILE (absname);
3192
3193 fail = (acl_set_file (SSDATA (encoded_absname), ACL_TYPE_ACCESS,
3194 acl)
3195 != 0);
5406cfd9 3196 if (fail && !ACL_NOT_WELL_SUPPORTED (errno))
7c3d167f
RF
3197 report_file_error ("Setting ACL", Fcons (absname, Qnil));
3198
3199 acl_free (acl);
c1fea2c0 3200 return fail ? Qnil : Qt;
7c3d167f
RF
3201 }
3202#endif
3203
3204 return Qnil;
3205}
3206\f
570d7624 3207DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
d4a42098
KS
3208 doc: /* Return mode bits of file named FILENAME, as an integer.
3209Return nil, if file does not exist or is not accessible. */)
5842a27b 3210 (Lisp_Object filename)
570d7624 3211{
199607e4 3212 Lisp_Object absname;
570d7624 3213 struct stat st;
32f4334d 3214 Lisp_Object handler;
570d7624 3215
4b4deea2 3216 absname = expand_and_dir_to_file (filename, BVAR (current_buffer, directory));
570d7624 3217
32f4334d
RS
3218 /* If the file name has special constructs in it,
3219 call the corresponding file handler. */
199607e4 3220 handler = Ffind_file_name_handler (absname, Qfile_modes);
32f4334d 3221 if (!NILP (handler))
199607e4 3222 return call2 (handler, Qfile_modes, absname);
32f4334d 3223
b1d1b865
RS
3224 absname = ENCODE_FILE (absname);
3225
42a5b22f 3226 if (stat (SSDATA (absname), &st) < 0)
570d7624 3227 return Qnil;
3ace87e3 3228
570d7624
JB
3229 return make_number (st.st_mode & 07777);
3230}
3231
09fbdf6c
MC
3232DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2,
3233 "(let ((file (read-file-name \"File: \"))) \
3234 (list file (read-file-modes nil file)))",
8c1a1077 3235 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
ea429250
EZ
3236Only the 12 low bits of MODE are used.
3237
3238Interactively, mode bits are read by `read-file-modes', which accepts
712adc82 3239symbolic notation, like the `chmod' command from GNU Coreutils. */)
5842a27b 3240 (Lisp_Object filename, Lisp_Object mode)
570d7624 3241{
b1d1b865 3242 Lisp_Object absname, encoded_absname;
32f4334d 3243 Lisp_Object handler;
570d7624 3244
4b4deea2 3245 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
b7826503 3246 CHECK_NUMBER (mode);
570d7624 3247
32f4334d
RS
3248 /* If the file name has special constructs in it,
3249 call the corresponding file handler. */
199607e4 3250 handler = Ffind_file_name_handler (absname, Qset_file_modes);
32f4334d 3251 if (!NILP (handler))
199607e4 3252 return call3 (handler, Qset_file_modes, absname, mode);
32f4334d 3253
b1d1b865
RS
3254 encoded_absname = ENCODE_FILE (absname);
3255
18c52557 3256 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
199607e4 3257 report_file_error ("Doing chmod", Fcons (absname, Qnil));
570d7624
JB
3258
3259 return Qnil;
3260}
3261
c24e9a53 3262DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
8c1a1077
PJ
3263 doc: /* Set the file permission bits for newly created files.
3264The argument MODE should be an integer; only the low 9 bits are used.
3265This setting is inherited by subprocesses. */)
5842a27b 3266 (Lisp_Object mode)
36a8c287 3267{
b7826503 3268 CHECK_NUMBER (mode);
199607e4 3269
5f85ea58 3270 umask ((~ XINT (mode)) & 0777);
36a8c287
JB
3271
3272 return Qnil;
3273}
3274
c24e9a53 3275DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
8c1a1077
PJ
3276 doc: /* Return the default file protection for created files.
3277The value is an integer. */)
5842a27b 3278 (void)
36a8c287 3279{
f75d7a91 3280 mode_t realmask;
5f85ea58 3281 Lisp_Object value;
36a8c287 3282
4d7e6e51 3283 block_input ();
5f85ea58
RS
3284 realmask = umask (0);
3285 umask (realmask);
4d7e6e51 3286 unblock_input ();
36a8c287 3287
46283abe 3288 XSETINT (value, (~ realmask) & 0777);
5f85ea58 3289 return value;
36a8c287 3290}
819da85b 3291\f
819da85b
EZ
3292
3293DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
f839df0c 3294 doc: /* Set times of file FILENAME to TIMESTAMP.
819da85b
EZ
3295Set both access and modification times.
3296Return t on success, else nil.
f839df0c 3297Use the current time if TIMESTAMP is nil. TIMESTAMP is in the format of
819da85b 3298`current-time'. */)
f839df0c 3299 (Lisp_Object filename, Lisp_Object timestamp)
819da85b
EZ
3300{
3301 Lisp_Object absname, encoded_absname;
3302 Lisp_Object handler;
31571fd7 3303 EMACS_TIME t = lisp_time_argument (timestamp);
819da85b 3304
4b4deea2 3305 absname = Fexpand_file_name (filename, BVAR (current_buffer, directory));
819da85b
EZ
3306
3307 /* If the file name has special constructs in it,
3308 call the corresponding file handler. */
3309 handler = Ffind_file_name_handler (absname, Qset_file_times);
3310 if (!NILP (handler))
f839df0c 3311 return call3 (handler, Qset_file_times, absname, timestamp);
819da85b
EZ
3312
3313 encoded_absname = ENCODE_FILE (absname);
5df5e07c 3314
819da85b 3315 {
d35af63c 3316 if (set_file_times (-1, SSDATA (encoded_absname), t, t))
819da85b 3317 {
0d9f584b 3318#ifdef MSDOS
819da85b 3319 /* Setting times on a directory always fails. */
73dcdb9f 3320 if (file_directory_p (SSDATA (encoded_absname)))
819da85b
EZ
3321 return Qnil;
3322#endif
3323 report_file_error ("Setting file times", Fcons (absname, Qnil));
819da85b
EZ
3324 }
3325 }
5df5e07c 3326
819da85b
EZ
3327 return Qt;
3328}
f793dc6c 3329\f
697c17a2 3330#ifdef HAVE_SYNC
85ffea93 3331DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
8c1a1077 3332 doc: /* Tell Unix to finish all pending disk updates. */)
5842a27b 3333 (void)
85ffea93
RS
3334{
3335 sync ();
3336 return Qnil;
3337}
3338
697c17a2 3339#endif /* HAVE_SYNC */
85ffea93 3340
570d7624 3341DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
8c1a1077
PJ
3342 doc: /* Return t if file FILE1 is newer than file FILE2.
3343If FILE1 does not exist, the answer is nil;
3344otherwise, if FILE2 does not exist, the answer is t. */)
5842a27b 3345 (Lisp_Object file1, Lisp_Object file2)
570d7624 3346{
199607e4 3347 Lisp_Object absname1, absname2;
39adff0d 3348 struct stat st1, st2;
32f4334d 3349 Lisp_Object handler;
09121adc 3350 struct gcpro gcpro1, gcpro2;
570d7624 3351
b7826503
PJ
3352 CHECK_STRING (file1);
3353 CHECK_STRING (file2);
570d7624 3354
199607e4
RS
3355 absname1 = Qnil;
3356 GCPRO2 (absname1, file2);
4b4deea2
TT
3357 absname1 = expand_and_dir_to_file (file1, BVAR (current_buffer, directory));
3358 absname2 = expand_and_dir_to_file (file2, BVAR (current_buffer, directory));
09121adc 3359 UNGCPRO;
570d7624 3360
32f4334d
RS
3361 /* If the file name has special constructs in it,
3362 call the corresponding file handler. */
199607e4 3363 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
51cf6d37 3364 if (NILP (handler))
199607e4 3365 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
32f4334d 3366 if (!NILP (handler))
199607e4 3367 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
32f4334d 3368
b1d1b865
RS
3369 GCPRO2 (absname1, absname2);
3370 absname1 = ENCODE_FILE (absname1);
3371 absname2 = ENCODE_FILE (absname2);
3372 UNGCPRO;
3373
39adff0d 3374 if (stat (SSDATA (absname1), &st1) < 0)
570d7624
JB
3375 return Qnil;
3376
39adff0d 3377 if (stat (SSDATA (absname2), &st2) < 0)
570d7624
JB
3378 return Qt;
3379
39adff0d
PE
3380 return (EMACS_TIME_GT (get_stat_mtime (&st1), get_stat_mtime (&st2))
3381 ? Qt : Qnil);
570d7624
JB
3382}
3383\f
6fdaa9a0
KH
3384#ifndef READ_BUF_SIZE
3385#define READ_BUF_SIZE (64 << 10)
3386#endif
d311d28c
PE
3387/* Some buffer offsets are stored in 'int' variables. */
3388verify (READ_BUF_SIZE <= INT_MAX);
6fdaa9a0 3389
98a7d268
KH
3390/* This function is called after Lisp functions to decide a coding
3391 system are called, or when they cause an error. Before they are
3392 called, the current buffer is set unibyte and it contains only a
3393 newly inserted text (thus the buffer was empty before the
3394 insertion).
3395
3396 The functions may set markers, overlays, text properties, or even
3397 alter the buffer contents, change the current buffer.
3398
3399 Here, we reset all those changes by:
3400 o set back the current buffer.
3401 o move all markers and overlays to BEG.
3402 o remove all text properties.
3403 o set back the buffer multibyteness. */
f736ffbf
KH
3404
3405static Lisp_Object
971de7fb 3406decide_coding_unwind (Lisp_Object unwind_data)
f736ffbf 3407{
98a7d268 3408 Lisp_Object multibyte, undo_list, buffer;
f736ffbf 3409
98a7d268
KH
3410 multibyte = XCAR (unwind_data);
3411 unwind_data = XCDR (unwind_data);
3412 undo_list = XCAR (unwind_data);
3413 buffer = XCDR (unwind_data);
3414
a3d794a1 3415 set_buffer_internal (XBUFFER (buffer));
98a7d268
KH
3416 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3417 adjust_overlays_for_delete (BEG, Z - BEG);
0c94c8d6 3418 set_buffer_intervals (current_buffer, NULL);
98a7d268
KH
3419 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3420
3421 /* Now we are safe to change the buffer's multibyteness directly. */
39eb03f1
PE
3422 bset_enable_multibyte_characters (current_buffer, multibyte);
3423 bset_undo_list (current_buffer, undo_list);
f736ffbf
KH
3424
3425 return Qnil;
3426}
3427
2ef88fd4 3428/* Read from a non-regular file. STATE is a Lisp_Save_Value
3346c1d0
DA
3429 object where slot 0 is the file descriptor, slot 1 specifies
3430 an offset to put the read bytes, and slot 2 is the maximum
3431 amount of bytes to read. Value is the number of bytes read. */
55587f8a
GM
3432
3433static Lisp_Object
2ef88fd4 3434read_non_regular (Lisp_Object state)
55587f8a 3435{
d311d28c 3436 int nbytes;
efdc16c9 3437
1b978129
GM
3438 immediate_quit = 1;
3439 QUIT;
3346c1d0 3440 nbytes = emacs_read (XSAVE_INTEGER (state, 0),
5976c3fe 3441 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
3346c1d0
DA
3442 + XSAVE_INTEGER (state, 1)),
3443 XSAVE_INTEGER (state, 2));
1b978129 3444 immediate_quit = 0;
e07469fa
DA
3445 /* Fast recycle this object for the likely next call. */
3446 free_misc (state);
1b978129
GM
3447 return make_number (nbytes);
3448}
55587f8a 3449
2ef88fd4
DA
3450
3451/* Condition-case handler used when reading from non-regular files
3452 in insert-file-contents. */
1b978129
GM
3453
3454static Lisp_Object
2ef88fd4 3455read_non_regular_quit (Lisp_Object ignore)
1b978129 3456{
55587f8a
GM
3457 return Qnil;
3458}
3459
b3fbb395
PE
3460/* Return the file offset that VAL represents, checking for type
3461 errors and overflow. */
e69dafad 3462static off_t
b3fbb395 3463file_offset (Lisp_Object val)
e69dafad 3464{
b3fbb395
PE
3465 if (RANGED_INTEGERP (0, val, TYPE_MAXIMUM (off_t)))
3466 return XINT (val);
3467
3468 if (FLOATP (val))
e69dafad 3469 {
b3fbb395 3470 double v = XFLOAT_DATA (val);
7216e43b 3471 if (0 <= v
b3fbb395
PE
3472 && (sizeof (off_t) < sizeof v
3473 ? v <= TYPE_MAXIMUM (off_t)
3474 : v < TYPE_MAXIMUM (off_t)))
3475 return v;
e69dafad 3476 }
b3fbb395
PE
3477
3478 wrong_type_argument (intern ("file-offset"), val);
e69dafad
PE
3479}
3480
f0941253 3481/* Return a special time value indicating the error number ERRNUM. */
dbeed9a6 3482static EMACS_TIME
f0941253 3483time_error_value (int errnum)
dbeed9a6 3484{
0497dc44 3485 int ns = (errnum == ENOENT || errnum == EACCES || errnum == ENOTDIR
dbeed9a6
PE
3486 ? NONEXISTENT_MODTIME_NSECS
3487 : UNKNOWN_MODTIME_NSECS);
e9a9ae03 3488 return make_emacs_time (0, ns);
dbeed9a6 3489}
55587f8a 3490
570d7624 3491DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
8c1a1077
PJ
3492 1, 5, 0,
3493 doc: /* Insert contents of file FILENAME after point.
cf6d2357 3494Returns list of absolute file name and number of characters inserted.
6f2528d8
MR
3495If second argument VISIT is non-nil, the buffer's visited filename and
3496last save file modtime are set, and it is marked unmodified. If
3497visiting and the file does not exist, visiting is completed before the
3498error is signaled.
3499
3500The optional third and fourth arguments BEG and END specify what portion
3501of the file to insert. These arguments count bytes in the file, not
3502characters in the buffer. If VISIT is non-nil, BEG and END must be nil.
3503
3504If optional fifth argument REPLACE is non-nil, replace the current
3505buffer contents (in the accessible portion) with the file contents.
3506This is better than simply deleting and inserting the whole thing
3507because (1) it preserves some marker positions and (2) it puts less data
3508in the undo list. When REPLACE is non-nil, the second return value is
3509the number of characters that replace previous buffer contents.
3510
3511This function does code conversion according to the value of
3512`coding-system-for-read' or `file-coding-system-alist', and sets the
bb085aed
EZ
3513variable `last-coding-system-used' to the coding system actually used.
3514
3515In addition, this function decodes the inserted text from known formats
3516by calling `format-decode', which see. */)
5842a27b 3517 (Lisp_Object filename, Lisp_Object visit, Lisp_Object beg, Lisp_Object end, Lisp_Object replace)
570d7624
JB
3518{
3519 struct stat st;
dbeed9a6 3520 EMACS_TIME mtime;
f75d7a91 3521 int fd;
d311d28c 3522 ptrdiff_t inserted = 0;
f75d7a91
PE
3523 bool nochange = 0;
3524 ptrdiff_t how_much;
728f8f0a 3525 off_t beg_offset, end_offset;
f75d7a91 3526 int unprocessed;
d311d28c 3527 ptrdiff_t count = SPECPDL_INDEX ();
6f2528d8
MR
3528 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
3529 Lisp_Object handler, val, insval, orig_filename, old_undo;
d6a3cc15 3530 Lisp_Object p;
d311d28c 3531 ptrdiff_t total = 0;
f75d7a91 3532 bool not_regular = 0;
2ef88fd4 3533 int save_errno = 0;
5976c3fe 3534 char read_buf[READ_BUF_SIZE];
6fdaa9a0 3535 struct coding_system coding;
f75d7a91
PE
3536 bool replace_handled = 0;
3537 bool set_coding_system = 0;
db327c7e 3538 Lisp_Object coding_system;
f75d7a91 3539 bool read_quit = 0;
490ee853 3540 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
f75d7a91
PE
3541 bool we_locked_file = 0;
3542 bool deferred_remove_unwind_protect = 0;
32f4334d 3543
95385625
RS
3544 if (current_buffer->base_buffer && ! NILP (visit))
3545 error ("Cannot do file visiting in an indirect buffer");
3546
4b4deea2 3547 if (!NILP (BVAR (current_buffer, read_only)))
95385625
RS
3548 Fbarf_if_buffer_read_only ();
3549
32f4334d 3550 val = Qnil;
d6a3cc15 3551 p = Qnil;
b1d1b865 3552 orig_filename = Qnil;
6f2528d8 3553 old_undo = Qnil;
32f4334d 3554
6f2528d8 3555 GCPRO5 (filename, val, p, orig_filename, old_undo);
570d7624 3556
b7826503 3557 CHECK_STRING (filename);
570d7624
JB
3558 filename = Fexpand_file_name (filename, Qnil);
3559
1c157f8d
KH
3560 /* The value Qnil means that the coding system is not yet
3561 decided. */
3562 coding_system = Qnil;
3563
32f4334d
RS
3564 /* If the file name has special constructs in it,
3565 call the corresponding file handler. */
49307295 3566 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
32f4334d
RS
3567 if (!NILP (handler))
3568 {
3d0387c0
RS
3569 val = call6 (handler, Qinsert_file_contents, filename,
3570 visit, beg, end, replace);
d311d28c
PE
3571 if (CONSP (val) && CONSP (XCDR (val))
3572 && RANGED_INTEGERP (0, XCAR (XCDR (val)), ZV - PT))
03699b14 3573 inserted = XINT (XCAR (XCDR (val)));
32f4334d
RS
3574 goto handled;
3575 }
3576
b1d1b865
RS
3577 orig_filename = filename;
3578 filename = ENCODE_FILE (filename);
3579
67722112
PE
3580 fd = emacs_open (SSDATA (filename), O_RDONLY, 0);
3581 if (fd < 0)
570d7624 3582 {
e5e9d610 3583 save_errno = errno;
265a9e55 3584 if (NILP (visit))
b1d1b865 3585 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
f0941253 3586 mtime = time_error_value (save_errno);
b885bf36 3587 st.st_size = -1;
0de6b8f4 3588 if (!NILP (Vcoding_system_for_read))
22d92d6b 3589 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
570d7624
JB
3590 goto notfound;
3591 }
3592
67722112
PE
3593 /* Replacement should preserve point as it preserves markers. */
3594 if (!NILP (replace))
3595 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3596
3597 record_unwind_protect (close_file_unwind, make_number (fd));
3598
3599 if (fstat (fd, &st) != 0)
fa705c99 3600 report_file_error ("Input file status", Fcons (orig_filename, Qnil));
67722112
PE
3601 mtime = get_stat_mtime (&st);
3602
be53b411
JB
3603 /* This code will need to be changed in order to work on named
3604 pipes, and it's probably just not worth it. So we should at
3605 least signal an error. */
99bc28f4 3606 if (!S_ISREG (st.st_mode))
330bfe57 3607 {
d4b8687b
RS
3608 not_regular = 1;
3609
3610 if (! NILP (visit))
3611 goto notfound;
3612
3613 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
24b1ddad
KS
3614 xsignal2 (Qfile_error,
3615 build_string ("not a regular file"), orig_filename);
330bfe57 3616 }
be53b411 3617
9f57b6b4
KH
3618 if (!NILP (visit))
3619 {
3620 if (!NILP (beg) || !NILP (end))
3621 error ("Attempt to visit less than an entire file");
3622 if (BEG < Z && NILP (replace))
3623 error ("Cannot do file visiting in a non-empty buffer");
3624 }
7fded690
JB
3625
3626 if (!NILP (beg))
b3fbb395 3627 beg_offset = file_offset (beg);
7fded690 3628 else
728f8f0a 3629 beg_offset = 0;
7fded690
JB
3630
3631 if (!NILP (end))
b3fbb395 3632 end_offset = file_offset (end);
7fded690
JB
3633 else
3634 {
728f8f0a
PE
3635 if (not_regular)
3636 end_offset = TYPE_MAXIMUM (off_t);
3637 else
d4b8687b 3638 {
728f8f0a
PE
3639 end_offset = st.st_size;
3640
3641 /* A negative size can happen on a platform that allows file
3642 sizes greater than the maximum off_t value. */
3643 if (end_offset < 0)
3644 buffer_overflow ();
68c45bf0 3645
d21dd12d
GM
3646 /* The file size returned from stat may be zero, but data
3647 may be readable nonetheless, for example when this is a
3648 file in the /proc filesystem. */
728f8f0a
PE
3649 if (end_offset == 0)
3650 end_offset = READ_BUF_SIZE;
d4b8687b 3651 }
7fded690
JB
3652 }
3653
728f8f0a
PE
3654 /* Check now whether the buffer will become too large,
3655 in the likely case where the file's length is not changing.
3656 This saves a lot of needless work before a buffer overflow. */
3657 if (! not_regular)
3658 {
3659 /* The likely offset where we will stop reading. We could read
3660 more (or less), if the file grows (or shrinks) as we read it. */
3661 off_t likely_end = min (end_offset, st.st_size);
3662
3663 if (beg_offset < likely_end)
3664 {
ce2fe65a
AS
3665 ptrdiff_t buf_bytes
3666 = Z_BYTE - (!NILP (replace) ? ZV_BYTE - BEGV_BYTE : 0);
728f8f0a
PE
3667 ptrdiff_t buf_growth_max = BUF_BYTES_MAX - buf_bytes;
3668 off_t likely_growth = likely_end - beg_offset;
3669 if (buf_growth_max < likely_growth)
3670 buffer_overflow ();
3671 }
3672 }
3673
3674 /* Prevent redisplay optimizations. */
3675 current_buffer->clip_changed = 1;
3676
356a6224 3677 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
5560aecd 3678 {
75421805 3679 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
5560aecd
KH
3680 setup_coding_system (coding_system, &coding);
3681 /* Ensure we set Vlast_coding_system_used. */
3682 set_coding_system = 1;
3683 }
356a6224 3684 else if (BEG < Z)
f736ffbf
KH
3685 {
3686 /* Decide the coding system to use for reading the file now
3687 because we can't use an optimized method for handling
3688 `coding:' tag if the current buffer is not empty. */
f736ffbf 3689 if (!NILP (Vcoding_system_for_read))
db327c7e 3690 coding_system = Vcoding_system_for_read;
f736ffbf
KH
3691 else
3692 {
3693 /* Don't try looking inside a file for a coding system
3694 specification if it is not seekable. */
3695 if (! not_regular && ! NILP (Vset_auto_coding_function))
3696 {
3697 /* Find a coding system specified in the heading two
3698 lines or in the tailing several lines of the file.
3699 We assume that the 1K-byte and 3K-byte for heading
003a7eaa 3700 and tailing respectively are sufficient for this
f736ffbf 3701 purpose. */
d311d28c 3702 int nread;
f736ffbf
KH
3703
3704 if (st.st_size <= (1024 * 4))
68c45bf0 3705 nread = emacs_read (fd, read_buf, 1024 * 4);
f736ffbf
KH
3706 else
3707 {
68c45bf0 3708 nread = emacs_read (fd, read_buf, 1024);
4c95c9a5 3709 if (nread == 1024)
f736ffbf 3710 {
4c95c9a5
PE
3711 int ntail;
3712 if (lseek (fd, - (1024 * 3), SEEK_END) < 0)
f736ffbf
KH
3713 report_file_error ("Setting file position",
3714 Fcons (orig_filename, Qnil));
4c95c9a5
PE
3715 ntail = emacs_read (fd, read_buf + nread, 1024 * 3);
3716 nread = ntail < 0 ? ntail : nread + ntail;
f736ffbf
KH
3717 }
3718 }
feb9dc27 3719
f736ffbf
KH
3720 if (nread < 0)
3721 error ("IO error reading %s: %s",
d5db4077 3722 SDATA (orig_filename), emacs_strerror (errno));
f736ffbf
KH
3723 else if (nread > 0)
3724 {
f736ffbf 3725 struct buffer *prev = current_buffer;
f839df0c 3726 Lisp_Object workbuf;
685fc579 3727 struct buffer *buf;
f736ffbf 3728
66322887 3729 record_unwind_current_buffer ();
1d92afcd 3730
f839df0c
PE
3731 workbuf = Fget_buffer_create (build_string (" *code-converting-work*"));
3732 buf = XBUFFER (workbuf);
685fc579 3733
29ea8ae9 3734 delete_all_overlays (buf);
39eb03f1
PE
3735 bset_directory (buf, BVAR (current_buffer, directory));
3736 bset_read_only (buf, Qnil);
3737 bset_filename (buf, Qnil);
3738 bset_undo_list (buf, Qt);
fd318b54
DA
3739 eassert (buf->overlays_before == NULL);
3740 eassert (buf->overlays_after == NULL);
efdc16c9 3741
685fc579
RS
3742 set_buffer_internal (buf);
3743 Ferase_buffer ();
39eb03f1 3744 bset_enable_multibyte_characters (buf, Qnil);
685fc579 3745
b68864e5 3746 insert_1_both ((char *) read_buf, nread, nread, 0, 0, 0);
f736ffbf 3747 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
db327c7e 3748 coding_system = call2 (Vset_auto_coding_function,
8f924df7 3749 filename, make_number (nread));
f736ffbf 3750 set_buffer_internal (prev);
efdc16c9 3751
f736ffbf
KH
3752 /* Discard the unwind protect for recovering the
3753 current buffer. */
3754 specpdl_ptr--;
3755
3756 /* Rewind the file for the actual read done later. */
e69dafad 3757 if (lseek (fd, 0, SEEK_SET) < 0)
f736ffbf
KH
3758 report_file_error ("Setting file position",
3759 Fcons (orig_filename, Qnil));
3760 }
3761 }
feb9dc27 3762
db327c7e 3763 if (NILP (coding_system))
f736ffbf
KH
3764 {
3765 /* If we have not yet decided a coding system, check
3766 file-coding-system-alist. */
8f924df7 3767 Lisp_Object args[6];
f736ffbf
KH
3768
3769 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3770 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
8f924df7
KH
3771 coding_system = Ffind_operation_coding_system (6, args);
3772 if (CONSP (coding_system))
3773 coding_system = XCAR (coding_system);
f736ffbf
KH
3774 }
3775 }
c9e82392 3776
db327c7e
KH
3777 if (NILP (coding_system))
3778 coding_system = Qundecided;
3779 else
3780 CHECK_CODING_SYSTEM (coding_system);
c8a6d68a 3781
4b4deea2 3782 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
237a6fd2
RS
3783 /* We must suppress all character code conversion except for
3784 end-of-line conversion. */
db327c7e 3785 coding_system = raw_text_coding_system (coding_system);
54369368 3786
db327c7e
KH
3787 setup_coding_system (coding_system, &coding);
3788 /* Ensure we set Vlast_coding_system_used. */
3789 set_coding_system = 1;
f736ffbf 3790 }
6cf71bf1 3791
3d0387c0
RS
3792 /* If requested, replace the accessible part of the buffer
3793 with the file contents. Avoid replacing text at the
3794 beginning or end of the buffer that matches the file contents;
3dbcf3f6
RS
3795 that preserves markers pointing to the unchanged parts.
3796
3797 Here we implement this feature in an optimized way
3798 for the case where code conversion is NOT needed.
3799 The following if-statement handles the case of conversion
727a0b4a
RS
3800 in a less optimal way.
3801
3802 If the code conversion is "automatic" then we try using this
3803 method and hope for the best.
3804 But if we discover the need for conversion, we give up on this method
3805 and let the following if-statement handle the replace job. */
3dbcf3f6 3806 if (!NILP (replace)
f736ffbf 3807 && BEGV < ZV
db327c7e
KH
3808 && (NILP (coding_system)
3809 || ! CODING_REQUIRE_DECODING (&coding)))
3d0387c0 3810 {
ec7adf26
RS
3811 /* same_at_start and same_at_end count bytes,
3812 because file access counts bytes
3813 and BEG and END count bytes. */
d311d28c
PE
3814 ptrdiff_t same_at_start = BEGV_BYTE;
3815 ptrdiff_t same_at_end = ZV_BYTE;
3816 ptrdiff_t overlap;
6fdaa9a0 3817 /* There is still a possibility we will find the need to do code
f75d7a91 3818 conversion. If that happens, set this variable to
727a0b4a 3819 give up on handling REPLACE in the optimized way. */
f75d7a91 3820 bool giveup_match_end = 0;
9c28748f 3821
728f8f0a 3822 if (beg_offset != 0)
4d2a0879 3823 {
728f8f0a 3824 if (lseek (fd, beg_offset, SEEK_SET) < 0)
4d2a0879 3825 report_file_error ("Setting file position",
b1d1b865 3826 Fcons (orig_filename, Qnil));
4d2a0879
RS
3827 }
3828
3d0387c0
RS
3829 immediate_quit = 1;
3830 QUIT;
3831 /* Count how many chars at the start of the file
3832 match the text at the beginning of the buffer. */
3833 while (1)
3834 {
d311d28c 3835 int nread, bufpos;
3d0387c0 3836
2ef88fd4 3837 nread = emacs_read (fd, read_buf, sizeof read_buf);
3d0387c0
RS
3838 if (nread < 0)
3839 error ("IO error reading %s: %s",
5976c3fe 3840 SSDATA (orig_filename), emacs_strerror (errno));
3d0387c0
RS
3841 else if (nread == 0)
3842 break;
6fdaa9a0 3843
db327c7e 3844 if (CODING_REQUIRE_DETECTION (&coding))
727a0b4a 3845 {
2ef88fd4 3846 coding_system = detect_coding_system ((unsigned char *) read_buf,
5976c3fe 3847 nread, nread, 1, 0,
db327c7e
KH
3848 coding_system);
3849 setup_coding_system (coding_system, &coding);
727a0b4a
RS
3850 }
3851
db327c7e
KH
3852 if (CODING_REQUIRE_DECODING (&coding))
3853 /* We found that the file should be decoded somehow.
727a0b4a
RS
3854 Let's give up here. */
3855 {
3856 giveup_match_end = 1;
3857 break;
3858 }
3859
3d0387c0 3860 bufpos = 0;
ec7adf26 3861 while (bufpos < nread && same_at_start < ZV_BYTE
2ef88fd4 3862 && FETCH_BYTE (same_at_start) == read_buf[bufpos])
3d0387c0
RS
3863 same_at_start++, bufpos++;
3864 /* If we found a discrepancy, stop the scan.
8e6208c5 3865 Otherwise loop around and scan the next bufferful. */
3d0387c0
RS
3866 if (bufpos != nread)
3867 break;
3868 }
3869 immediate_quit = 0;
3870 /* If the file matches the buffer completely,
3871 there's no need to replace anything. */
2ba8e008 3872 if (same_at_start - BEGV_BYTE == end_offset - beg_offset)
3d0387c0 3873 {
68c45bf0 3874 emacs_close (fd);
a1d2b64a 3875 specpdl_ptr--;
1051b3b3 3876 /* Truncate the buffer to the size of the file. */
7dae4502 3877 del_range_1 (same_at_start, same_at_end, 0, 0);
3d0387c0
RS
3878 goto handled;
3879 }
3880 immediate_quit = 1;
3881 QUIT;
3882 /* Count how many chars at the end of the file
6fdaa9a0
KH
3883 match the text at the end of the buffer. But, if we have
3884 already found that decoding is necessary, don't waste time. */
3885 while (!giveup_match_end)
3d0387c0 3886 {
728f8f0a
PE
3887 int total_read, nread, bufpos, trial;
3888 off_t curpos;
3d0387c0
RS
3889
3890 /* At what file position are we now scanning? */
728f8f0a 3891 curpos = end_offset - (ZV_BYTE - same_at_end);
fc81fa9e
KH
3892 /* If the entire file matches the buffer tail, stop the scan. */
3893 if (curpos == 0)
3894 break;
3d0387c0 3895 /* How much can we scan in the next step? */
2ef88fd4 3896 trial = min (curpos, sizeof read_buf);
728f8f0a 3897 if (lseek (fd, curpos - trial, SEEK_SET) < 0)
3d0387c0 3898 report_file_error ("Setting file position",
b1d1b865 3899 Fcons (orig_filename, Qnil));
3d0387c0 3900
b02439c8 3901 total_read = nread = 0;
3d0387c0
RS
3902 while (total_read < trial)
3903 {
2ef88fd4 3904 nread = emacs_read (fd, read_buf + total_read, trial - total_read);
2bd2273e 3905 if (nread < 0)
3d0387c0 3906 error ("IO error reading %s: %s",
d5db4077 3907 SDATA (orig_filename), emacs_strerror (errno));
2bd2273e
GM
3908 else if (nread == 0)
3909 break;
3d0387c0
RS
3910 total_read += nread;
3911 }
efdc16c9 3912
8e6208c5 3913 /* Scan this bufferful from the end, comparing with
3d0387c0
RS
3914 the Emacs buffer. */
3915 bufpos = total_read;
efdc16c9 3916
3d0387c0
RS
3917 /* Compare with same_at_start to avoid counting some buffer text
3918 as matching both at the file's beginning and at the end. */
3919 while (bufpos > 0 && same_at_end > same_at_start
2ef88fd4 3920 && FETCH_BYTE (same_at_end - 1) == read_buf[bufpos - 1])
3d0387c0 3921 same_at_end--, bufpos--;
727a0b4a 3922
3d0387c0 3923 /* If we found a discrepancy, stop the scan.
8e6208c5 3924 Otherwise loop around and scan the preceding bufferful. */
3d0387c0 3925 if (bufpos != 0)
727a0b4a
RS
3926 {
3927 /* If this discrepancy is because of code conversion,
3928 we cannot use this method; giveup and try the other. */
3929 if (same_at_end > same_at_start
3930 && FETCH_BYTE (same_at_end - 1) >= 0200
4b4deea2 3931 && ! NILP (BVAR (current_buffer, enable_multibyte_characters))
c8a6d68a 3932 && (CODING_MAY_REQUIRE_DECODING (&coding)))
727a0b4a
RS
3933 giveup_match_end = 1;
3934 break;
3935 }
b02439c8
GM
3936
3937 if (nread == 0)
3938 break;
3d0387c0
RS
3939 }
3940 immediate_quit = 0;
9c28748f 3941
727a0b4a
RS
3942 if (! giveup_match_end)
3943 {
d311d28c 3944 ptrdiff_t temp;
ec7adf26 3945
727a0b4a 3946 /* We win! We can handle REPLACE the optimized way. */
9c28748f 3947
20f6783d
RS
3948 /* Extend the start of non-matching text area to multibyte
3949 character boundary. */
4b4deea2 3950 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
20f6783d
RS
3951 while (same_at_start > BEGV_BYTE
3952 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3953 same_at_start--;
3954
3955 /* Extend the end of non-matching text area to multibyte
71312b68 3956 character boundary. */
4b4deea2 3957 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
ec7adf26
RS
3958 while (same_at_end < ZV_BYTE
3959 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
71312b68
RS
3960 same_at_end++;
3961
727a0b4a 3962 /* Don't try to reuse the same piece of text twice. */
ec7adf26 3963 overlap = (same_at_start - BEGV_BYTE
728f8f0a
PE
3964 - (same_at_end
3965 + (! NILP (end) ? end_offset : st.st_size) - ZV_BYTE));
727a0b4a
RS
3966 if (overlap > 0)
3967 same_at_end += overlap;
9c28748f 3968
727a0b4a 3969 /* Arrange to read only the nonmatching middle part of the file. */
728f8f0a
PE
3970 beg_offset += same_at_start - BEGV_BYTE;
3971 end_offset -= ZV_BYTE - same_at_end;
3dbcf3f6 3972
ec7adf26 3973 del_range_byte (same_at_start, same_at_end, 0);
727a0b4a 3974 /* Insert from the file at the proper position. */
ec7adf26
RS
3975 temp = BYTE_TO_CHAR (same_at_start);
3976 SET_PT_BOTH (temp, same_at_start);
727a0b4a
RS
3977
3978 /* If display currently starts at beginning of line,
3979 keep it that way. */
e74aeda8 3980 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
c98ff5dd 3981 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
727a0b4a
RS
3982
3983 replace_handled = 1;
3984 }
3dbcf3f6
RS
3985 }
3986
3987 /* If requested, replace the accessible part of the buffer
3988 with the file contents. Avoid replacing text at the
3989 beginning or end of the buffer that matches the file contents;
3990 that preserves markers pointing to the unchanged parts.
3991
3992 Here we implement this feature for the case where code conversion
3993 is needed, in a simple way that needs a lot of memory.
3994 The preceding if-statement handles the case of no conversion
3995 in a more optimized way. */
f736ffbf 3996 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3dbcf3f6 3997 {
d311d28c
PE
3998 ptrdiff_t same_at_start = BEGV_BYTE;
3999 ptrdiff_t same_at_end = ZV_BYTE;
4000 ptrdiff_t same_at_start_charpos;
4001 ptrdiff_t inserted_chars;
4002 ptrdiff_t overlap;
4003 ptrdiff_t bufpos;
db327c7e 4004 unsigned char *decoded;
d311d28c
PE
4005 ptrdiff_t temp;
4006 ptrdiff_t this = 0;
4007 ptrdiff_t this_count = SPECPDL_INDEX ();
f10fe38f
PE
4008 bool multibyte
4009 = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
5b359650 4010 Lisp_Object conversion_buffer;
83aca1cb 4011 struct gcpro gcpro1;
db327c7e 4012
5b359650 4013 conversion_buffer = code_conversion_save (1, multibyte);
3dbcf3f6
RS
4014
4015 /* First read the whole file, performing code conversion into
4016 CONVERSION_BUFFER. */
4017
728f8f0a 4018 if (lseek (fd, beg_offset, SEEK_SET) < 0)
8f924df7
KH
4019 report_file_error ("Setting file position",
4020 Fcons (orig_filename, Qnil));
727a0b4a 4021
3dbcf3f6
RS
4022 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
4023 unprocessed = 0; /* Bytes not processed in previous loop. */
4024
2ba48777 4025 GCPRO1 (conversion_buffer);
b41b8a7e 4026 while (1)
3dbcf3f6 4027 {
b41b8a7e
PE
4028 /* Read at most READ_BUF_SIZE bytes at a time, to allow
4029 quitting while reading a huge file. */
3dbcf3f6
RS
4030
4031 /* Allow quitting out of the actual I/O. */
4032 immediate_quit = 1;
4033 QUIT;
b41b8a7e
PE
4034 this = emacs_read (fd, read_buf + unprocessed,
4035 READ_BUF_SIZE - unprocessed);
3dbcf3f6
RS
4036 immediate_quit = 0;
4037
db327c7e 4038 if (this <= 0)
43aae36e 4039 break;
3dbcf3f6 4040
bf1c0f27
SM
4041 BUF_TEMP_SET_PT (XBUFFER (conversion_buffer),
4042 BUF_Z (XBUFFER (conversion_buffer)));
5976c3fe
PE
4043 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4044 unprocessed + this, conversion_buffer);
db327c7e
KH
4045 unprocessed = coding.carryover_bytes;
4046 if (coding.carryover_bytes > 0)
72af86bd 4047 memcpy (read_buf, coding.carryover, unprocessed);
3dbcf3f6 4048 }
2ba48777 4049 UNGCPRO;
db327c7e 4050 emacs_close (fd);
3dbcf3f6 4051
db65a627
CY
4052 /* We should remove the unwind_protect calling
4053 close_file_unwind, but other stuff has been added the stack,
4054 so defer the removal till we reach the `handled' label. */
4055 deferred_remove_unwind_protect = 1;
4056
43aae36e 4057 if (this < 0)
4ed925c6
MB
4058 error ("IO error reading %s: %s",
4059 SDATA (orig_filename), emacs_strerror (errno));
3dbcf3f6 4060
db327c7e
KH
4061 if (unprocessed > 0)
4062 {
4063 coding.mode |= CODING_MODE_LAST_BLOCK;
5976c3fe
PE
4064 decode_coding_c_string (&coding, (unsigned char *) read_buf,
4065 unprocessed, conversion_buffer);
db327c7e
KH
4066 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4067 }
4068
50b06221 4069 coding_system = CODING_ID_NAME (coding.id);
f6a07420 4070 set_coding_system = 1;
db327c7e 4071 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
50342b35
KH
4072 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4073 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
db327c7e
KH
4074
4075 /* Compare the beginning of the converted string with the buffer
4076 text. */
3dbcf3f6
RS
4077
4078 bufpos = 0;
4079 while (bufpos < inserted && same_at_start < same_at_end
db327c7e 4080 && FETCH_BYTE (same_at_start) == decoded[bufpos])
3dbcf3f6
RS
4081 same_at_start++, bufpos++;
4082
db327c7e 4083 /* If the file matches the head of buffer completely,
3dbcf3f6
RS
4084 there's no need to replace anything. */
4085
4086 if (bufpos == inserted)
4087 {
3dbcf3f6 4088 /* Truncate the buffer to the size of the file. */
18a9f8d9
SM
4089 if (same_at_start == same_at_end)
4090 nochange = 1;
4091 else
4092 del_range_byte (same_at_start, same_at_end, 0);
427f5aab 4093 inserted = 0;
e8553dd1
KH
4094
4095 unbind_to (this_count, Qnil);
3dbcf3f6
RS
4096 goto handled;
4097 }
4098
db327c7e
KH
4099 /* Extend the start of non-matching text area to the previous
4100 multibyte character boundary. */
4b4deea2 4101 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
20f6783d
RS
4102 while (same_at_start > BEGV_BYTE
4103 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4104 same_at_start--;
4105
3dbcf3f6
RS
4106 /* Scan this bufferful from the end, comparing with
4107 the Emacs buffer. */
4108 bufpos = inserted;
4109
4110 /* Compare with same_at_start to avoid counting some buffer text
4111 as matching both at the file's beginning and at the end. */
4112 while (bufpos > 0 && same_at_end > same_at_start
db327c7e 4113 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
3dbcf3f6
RS
4114 same_at_end--, bufpos--;
4115
db327c7e
KH
4116 /* Extend the end of non-matching text area to the next
4117 multibyte character boundary. */
4b4deea2 4118 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
20f6783d
RS
4119 while (same_at_end < ZV_BYTE
4120 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4121 same_at_end++;
4122
3dbcf3f6 4123 /* Don't try to reuse the same piece of text twice. */
ec7adf26 4124 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3dbcf3f6
RS
4125 if (overlap > 0)
4126 same_at_end += overlap;
4127
727a0b4a
RS
4128 /* If display currently starts at beginning of line,
4129 keep it that way. */
e74aeda8 4130 if (XBUFFER (XWINDOW (selected_window)->contents) == current_buffer)
c98ff5dd 4131 XWINDOW (selected_window)->start_at_line_beg = !NILP (Fbolp ());
727a0b4a 4132
3dbcf3f6
RS
4133 /* Replace the chars that we need to replace,
4134 and update INSERTED to equal the number of bytes
db327c7e 4135 we are taking from the decoded string. */
4b70e2c9 4136 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
427f5aab 4137
643c73b9 4138 if (same_at_end != same_at_start)
427f5aab
KH
4139 {
4140 del_range_byte (same_at_start, same_at_end, 0);
4141 temp = GPT;
4142 same_at_start = GPT_BYTE;
4143 }
643c73b9
RS
4144 else
4145 {
643c73b9 4146 temp = BYTE_TO_CHAR (same_at_start);
643c73b9 4147 }
427f5aab
KH
4148 /* Insert from the file at the proper position. */
4149 SET_PT_BOTH (temp, same_at_start);
50342b35
KH
4150 same_at_start_charpos
4151 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
7f5d2c72
SM
4152 same_at_start - BEGV_BYTE
4153 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
50342b35
KH
4154 inserted_chars
4155 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
7f5d2c72
SM
4156 same_at_start + inserted - BEGV_BYTE
4157 + BUF_BEG_BYTE (XBUFFER (conversion_buffer)))
50342b35 4158 - same_at_start_charpos);
d07af40d
KH
4159 /* This binding is to avoid ask-user-about-supersession-threat
4160 being called in insert_from_buffer (via in
4161 prepare_to_modify_buffer). */
4162 specbind (intern ("buffer-file-name"), Qnil);
db327c7e 4163 insert_from_buffer (XBUFFER (conversion_buffer),
50342b35 4164 same_at_start_charpos, inserted_chars, 0);
427f5aab
KH
4165 /* Set `inserted' to the number of inserted characters. */
4166 inserted = PT - temp;
77343e1d
KH
4167 /* Set point before the inserted characters. */
4168 SET_PT_BOTH (temp, same_at_start);
3dbcf3f6 4169
db327c7e 4170 unbind_to (this_count, Qnil);
3dbcf3f6 4171
3dbcf3f6 4172 goto handled;
3d0387c0
RS
4173 }
4174
d4b8687b 4175 if (! not_regular)
728f8f0a 4176 total = end_offset - beg_offset;
d4b8687b
RS
4177 else
4178 /* For a special file, all we can do is guess. */
4179 total = READ_BUF_SIZE;
570d7624 4180
8b913b57 4181 if (NILP (visit) && total > 0)
68780e2a
RS
4182 {
4183#ifdef CLASH_DETECTION
4b4deea2 4184 if (!NILP (BVAR (current_buffer, file_truename))
68780e2a 4185 /* Make binding buffer-file-name to nil effective. */
4b4deea2 4186 && !NILP (BVAR (current_buffer, filename))
68780e2a
RS
4187 && SAVE_MODIFF >= MODIFF)
4188 we_locked_file = 1;
4189#endif /* CLASH_DETECTION */
4190 prepare_to_modify_buffer (GPT, GPT, NULL);
4191 }
570d7624 4192
13002885 4193 move_gap_both (PT, PT_BYTE);
7fded690
JB
4194 if (GAP_SIZE < total)
4195 make_gap (total - GAP_SIZE);
4196
728f8f0a 4197 if (beg_offset != 0 || !NILP (replace))
7fded690 4198 {
728f8f0a 4199 if (lseek (fd, beg_offset, SEEK_SET) < 0)
b1d1b865
RS
4200 report_file_error ("Setting file position",
4201 Fcons (orig_filename, Qnil));
7fded690
JB
4202 }
4203
2ef88fd4
DA
4204 /* In the following loop, HOW_MUCH contains the total bytes read so
4205 far for a regular file, and not changed for a special file. But,
4206 before exiting the loop, it is set to a negative value if I/O
4207 error occurs. */
a1d2b64a 4208 how_much = 0;
efdc16c9 4209
6fdaa9a0
KH
4210 /* Total bytes inserted. */
4211 inserted = 0;
efdc16c9 4212
2ef88fd4
DA
4213 /* Here, we don't do code conversion in the loop. It is done by
4214 decode_coding_gap after all data are read into the buffer. */
4215 {
4216 ptrdiff_t gap_size = GAP_SIZE;
1b978129 4217
2ef88fd4
DA
4218 while (how_much < total)
4219 {
4220 /* try is reserved in some compilers (Microsoft C) */
4221 ptrdiff_t trytry = min (total - how_much, READ_BUF_SIZE);
4222 ptrdiff_t this;
1b978129 4223
2ef88fd4
DA
4224 if (not_regular)
4225 {
4226 Lisp_Object nbytes;
4227
4228 /* Maybe make more room. */
4229 if (gap_size < trytry)
4230 {
4231 make_gap (trytry - gap_size);
4232 gap_size = GAP_SIZE - inserted;
4233 }
4234
4235 /* Read from the file, capturing `quit'. When an
4236 error occurs, end the loop, and arrange for a quit
4237 to be signaled after decoding the text we read. */
4238 nbytes = internal_condition_case_1
4239 (read_non_regular,
7b1123d8
PE
4240 make_save_value (SAVE_TYPE_INT_INT_INT, (ptrdiff_t) fd,
4241 inserted, trytry),
2ef88fd4
DA
4242 Qerror, read_non_regular_quit);
4243
4244 if (NILP (nbytes))
4245 {
4246 read_quit = 1;
4247 break;
4248 }
4249
4250 this = XINT (nbytes);
4251 }
4252 else
4253 {
4254 /* Allow quitting out of the actual I/O. We don't make text
4255 part of the buffer until all the reading is done, so a C-g
4256 here doesn't do any harm. */
4257 immediate_quit = 1;
4258 QUIT;
4259 this = emacs_read (fd,
4260 ((char *) BEG_ADDR + PT_BYTE - BEG_BYTE
4261 + inserted),
4262 trytry);
4263 immediate_quit = 0;
4264 }
4265
4266 if (this <= 0)
4267 {
4268 how_much = this;
4269 break;
4270 }
4271
4272 gap_size -= this;
4273
4274 /* For a regular file, where TOTAL is the real size,
4275 count HOW_MUCH to compare with it.
4276 For a special file, where TOTAL is just a buffer size,
4277 so don't bother counting in HOW_MUCH.
4278 (INSERTED is where we count the number of characters inserted.) */
4279 if (! not_regular)
4280 how_much += this;
4281 inserted += this;
4282 }
4283 }
1b978129 4284
e07469fa
DA
4285 /* Now we have either read all the file data into the gap,
4286 or stop reading on I/O error or quit. If nothing was
4287 read, undo marking the buffer modified. */
68780e2a
RS
4288
4289 if (inserted == 0)
4290 {
6840d350 4291#ifdef CLASH_DETECTION
68780e2a 4292 if (we_locked_file)
4b4deea2 4293 unlock_file (BVAR (current_buffer, file_truename));
6840d350 4294#endif
68780e2a
RS
4295 Vdeactivate_mark = old_Vdeactivate_mark;
4296 }
83c1cf6d
RS
4297 else
4298 Vdeactivate_mark = Qt;
68780e2a 4299
68c45bf0 4300 emacs_close (fd);
6fdaa9a0 4301
c8a6d68a
KH
4302 /* Discard the unwind protect for closing the file. */
4303 specpdl_ptr--;
6fdaa9a0 4304
2ef88fd4
DA
4305 if (how_much < 0)
4306 error ("IO error reading %s: %s",
4307 SDATA (orig_filename), emacs_strerror (errno));
4308
4309 /* Make the text read part of the buffer. */
4310 GAP_SIZE -= inserted;
4311 GPT += inserted;
4312 GPT_BYTE += inserted;
4313 ZV += inserted;
4314 ZV_BYTE += inserted;
4315 Z += inserted;
4316 Z_BYTE += inserted;
4317
4318 if (GAP_SIZE > 0)
4319 /* Put an anchor to ensure multi-byte form ends at gap. */
4320 *GPT_ADDR = 0;
4321
f8569325
DL
4322 notfound:
4323
db327c7e 4324 if (NILP (coding_system))
c8a6d68a 4325 {
2df42e09 4326 /* The coding system is not yet decided. Decide it by an
dfe35e7b
RS
4327 optimized method for handling `coding:' tag.
4328
4329 Note that we can get here only if the buffer was empty
4330 before the insertion. */
f736ffbf 4331
2df42e09 4332 if (!NILP (Vcoding_system_for_read))
db327c7e 4333 coding_system = Vcoding_system_for_read;
2df42e09
KH
4334 else
4335 {
98a7d268
KH
4336 /* Since we are sure that the current buffer was empty
4337 before the insertion, we can toggle
4338 enable-multibyte-characters directly here without taking
9a7f80aa
KH
4339 care of marker adjustment. By this way, we can run Lisp
4340 program safely before decoding the inserted text. */
98a7d268 4341 Lisp_Object unwind_data;
d311d28c 4342 ptrdiff_t count1 = SPECPDL_INDEX ();
2df42e09 4343
4b4deea2
TT
4344 unwind_data = Fcons (BVAR (current_buffer, enable_multibyte_characters),
4345 Fcons (BVAR (current_buffer, undo_list),
98a7d268 4346 Fcurrent_buffer ()));
39eb03f1
PE
4347 bset_enable_multibyte_characters (current_buffer, Qnil);
4348 bset_undo_list (current_buffer, Qt);
98a7d268
KH
4349 record_unwind_protect (decide_coding_unwind, unwind_data);
4350
4351 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4352 {
db327c7e 4353 coding_system = call2 (Vset_auto_coding_function,
8f924df7 4354 filename, make_number (inserted));
2df42e09 4355 }
f736ffbf 4356
db327c7e 4357 if (NILP (coding_system))
2df42e09
KH
4358 {
4359 /* If the coding system is not yet decided, check
4360 file-coding-system-alist. */
8f924df7 4361 Lisp_Object args[6];
f736ffbf 4362
2df42e09
KH
4363 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4364 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
8f924df7
KH
4365 coding_system = Ffind_operation_coding_system (6, args);
4366 if (CONSP (coding_system))
4367 coding_system = XCAR (coding_system);
f736ffbf 4368 }
f839df0c 4369 unbind_to (count1, Qnil);
98a7d268 4370 inserted = Z_BYTE - BEG_BYTE;
2df42e09 4371 }
f736ffbf 4372
db327c7e
KH
4373 if (NILP (coding_system))
4374 coding_system = Qundecided;
4375 else
4376 CHECK_CODING_SYSTEM (coding_system);
f736ffbf 4377
4b4deea2 4378 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
237a6fd2 4379 /* We must suppress all character code conversion except for
2df42e09 4380 end-of-line conversion. */
db327c7e 4381 coding_system = raw_text_coding_system (coding_system);
db327c7e
KH
4382 setup_coding_system (coding_system, &coding);
4383 /* Ensure we set Vlast_coding_system_used. */
4384 set_coding_system = 1;
2df42e09 4385 }
f736ffbf 4386
db327c7e 4387 if (!NILP (visit))
8c3b9441 4388 {
db327c7e 4389 /* When we visit a file by raw-text, we change the buffer to
9a7f80aa 4390 unibyte. */
db327c7e
KH
4391 if (CODING_FOR_UNIBYTE (&coding)
4392 /* Can't do this if part of the buffer might be preserved. */
4393 && NILP (replace))
4394 /* Visiting a file with these coding system makes the buffer
4395 unibyte. */
39eb03f1 4396 bset_enable_multibyte_characters (current_buffer, Qnil);
8c3b9441
KH
4397 }
4398
4b4deea2 4399 coding.dst_multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
5b359650 4400 if (CODING_MAY_REQUIRE_DECODING (&coding)
1c157f8d 4401 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
2df42e09 4402 {
db327c7e
KH
4403 move_gap_both (PT, PT_BYTE);
4404 GAP_SIZE += inserted;
4405 ZV_BYTE -= inserted;
4406 Z_BYTE -= inserted;
4407 ZV -= inserted;
4408 Z -= inserted;
4409 decode_coding_gap (&coding, inserted, inserted);
4410 inserted = coding.produced_char;
5b359650 4411 coding_system = CODING_ID_NAME (coding.id);
2df42e09 4412 }
db327c7e
KH
4413 else if (inserted > 0)
4414 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4415 inserted);
570d7624 4416
0068070e
SM
4417 /* Call after-change hooks for the inserted text, aside from the case
4418 of normal visiting (not with REPLACE), which is done in a new buffer
4419 "before" the buffer is changed. */
4420 if (inserted > 0 && total > 0
4421 && (NILP (visit) || !NILP (replace)))
4422 {
4423 signal_after_change (PT, 0, inserted);
4424 update_compositions (PT, PT, CHECK_BORDER);
4425 }
4426
cf6d2357
RS
4427 /* Now INSERTED is measured in characters. */
4428
32f4334d 4429 handled:
570d7624 4430
db65a627
CY
4431 if (deferred_remove_unwind_protect)
4432 /* If requested above, discard the unwind protect for closing the
4433 file. */
4434 specpdl_ptr--;
4435
265a9e55 4436 if (!NILP (visit))
570d7624 4437 {
4b4deea2 4438 if (!EQ (BVAR (current_buffer, undo_list), Qt) && !nochange)
39eb03f1 4439 bset_undo_list (current_buffer, Qnil);
62bcf009 4440
a7e82472
RS
4441 if (NILP (handler))
4442 {
dbeed9a6 4443 current_buffer->modtime = mtime;
58b963f7 4444 current_buffer->modtime_size = st.st_size;
39eb03f1 4445 bset_filename (current_buffer, orig_filename);
a7e82472 4446 }
62bcf009 4447
95385625 4448 SAVE_MODIFF = MODIFF;
0b5397c2 4449 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4b4deea2 4450 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
570d7624 4451#ifdef CLASH_DETECTION
32f4334d
RS
4452 if (NILP (handler))
4453 {
4b4deea2
TT
4454 if (!NILP (BVAR (current_buffer, file_truename)))
4455 unlock_file (BVAR (current_buffer, file_truename));
32f4334d
RS
4456 unlock_file (filename);
4457 }
570d7624 4458#endif /* CLASH_DETECTION */
330bfe57 4459 if (not_regular)
24b1ddad
KS
4460 xsignal2 (Qfile_error,
4461 build_string ("not a regular file"), orig_filename);
570d7624
JB
4462 }
4463
b6426b03 4464 if (set_coding_system)
8f924df7 4465 Vlast_coding_system_used = coding_system;
b6426b03 4466
2080470e 4467 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
b6426b03 4468 {
37a3c774
KH
4469 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4470 visit);
b6426b03
KH
4471 if (! NILP (insval))
4472 {
d311d28c
PE
4473 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4474 wrong_type_argument (intern ("inserted-chars"), insval);
b6426b03
KH
4475 inserted = XFASTINT (insval);
4476 }
4477 }
4478
6420e80c 4479 /* Decode file format. */
c8a6d68a 4480 if (inserted > 0)
0d420e88 4481 {
6420e80c 4482 /* Don't run point motion or modification hooks when decoding. */
d311d28c
PE
4483 ptrdiff_t count1 = SPECPDL_INDEX ();
4484 ptrdiff_t old_inserted = inserted;
6f2528d8
MR
4485 specbind (Qinhibit_point_motion_hooks, Qt);
4486 specbind (Qinhibit_modification_hooks, Qt);
4487
6420e80c 4488 /* Save old undo list and don't record undo for decoding. */
4b4deea2 4489 old_undo = BVAR (current_buffer, undo_list);
39eb03f1 4490 bset_undo_list (current_buffer, Qt);
efdc16c9 4491
6f2528d8 4492 if (NILP (replace))
ed8e506f 4493 {
6f2528d8
MR
4494 insval = call3 (Qformat_decode,
4495 Qnil, make_number (inserted), visit);
d311d28c
PE
4496 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4497 wrong_type_argument (intern ("inserted-chars"), insval);
6f2528d8
MR
4498 inserted = XFASTINT (insval);
4499 }
4500 else
4501 {
4502 /* If REPLACE is non-nil and we succeeded in not replacing the
6420e80c
AS
4503 beginning or end of the buffer text with the file's contents,
4504 call format-decode with `point' positioned at the beginning
fa463103 4505 of the buffer and `inserted' equaling the number of
6420e80c
AS
4506 characters in the buffer. Otherwise, format-decode might
4507 fail to correctly analyze the beginning or end of the buffer.
4508 Hence we temporarily save `point' and `inserted' here and
4509 restore `point' iff format-decode did not insert or delete
4510 any text. Otherwise we leave `point' at point-min. */
d311d28c
PE
4511 ptrdiff_t opoint = PT;
4512 ptrdiff_t opoint_byte = PT_BYTE;
4513 ptrdiff_t oinserted = ZV - BEGV;
4514 EMACS_INT ochars_modiff = CHARS_MODIFF;
1f163f28
MA
4515
4516 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
6f2528d8
MR
4517 insval = call3 (Qformat_decode,
4518 Qnil, make_number (oinserted), visit);
d311d28c
PE
4519 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4520 wrong_type_argument (intern ("inserted-chars"), insval);
cac4219c
MR
4521 if (ochars_modiff == CHARS_MODIFF)
4522 /* format_decode didn't modify buffer's characters => move
4523 point back to position before inserted text and leave
6420e80c 4524 value of inserted alone. */
6f2528d8 4525 SET_PT_BOTH (opoint, opoint_byte);
cac4219c
MR
4526 else
4527 /* format_decode modified buffer's characters => consider
6420e80c 4528 entire buffer changed and leave point at point-min. */
cac4219c 4529 inserted = XFASTINT (insval);
ed8e506f 4530 }
efdc16c9 4531
6f2528d8 4532 /* For consistency with format-decode call these now iff inserted > 0
6420e80c 4533 (martin 2007-06-28). */
6f2528d8
MR
4534 p = Vafter_insert_file_functions;
4535 while (CONSP (p))
4536 {
4537 if (NILP (replace))
4538 {
4539 insval = call1 (XCAR (p), make_number (inserted));
4540 if (!NILP (insval))
4541 {
d311d28c
PE
4542 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4543 wrong_type_argument (intern ("inserted-chars"), insval);
6f2528d8
MR
4544 inserted = XFASTINT (insval);
4545 }
4546 }
4547 else
4548 {
6420e80c
AS
4549 /* For the rationale of this see the comment on
4550 format-decode above. */
d311d28c
PE
4551 ptrdiff_t opoint = PT;
4552 ptrdiff_t opoint_byte = PT_BYTE;
4553 ptrdiff_t oinserted = ZV - BEGV;
4554 EMACS_INT ochars_modiff = CHARS_MODIFF;
1f163f28 4555
6f2528d8
MR
4556 TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
4557 insval = call1 (XCAR (p), make_number (oinserted));
4558 if (!NILP (insval))
4559 {
d311d28c
PE
4560 if (! RANGED_INTEGERP (0, insval, ZV - PT))
4561 wrong_type_argument (intern ("inserted-chars"), insval);
cac4219c
MR
4562 if (ochars_modiff == CHARS_MODIFF)
4563 /* after_insert_file_functions didn't modify
4564 buffer's characters => move point back to
4565 position before inserted text and leave value of
6420e80c 4566 inserted alone. */
6f2528d8 4567 SET_PT_BOTH (opoint, opoint_byte);
cac4219c
MR
4568 else
4569 /* after_insert_file_functions did modify buffer's
4570 characters => consider entire buffer changed and
6420e80c 4571 leave point at point-min. */
cac4219c 4572 inserted = XFASTINT (insval);
6f2528d8
MR
4573 }
4574 }
4575
4576 QUIT;
4577 p = XCDR (p);
ed8e506f 4578 }
efdc16c9 4579
6f2528d8
MR
4580 if (NILP (visit))
4581 {
39eb03f1 4582 bset_undo_list (current_buffer, old_undo);
6420e80c 4583 if (CONSP (old_undo) && inserted != old_inserted)
6f2528d8 4584 {
6420e80c
AS
4585 /* Adjust the last undo record for the size change during
4586 the format conversion. */
6f2528d8 4587 Lisp_Object tem = XCAR (old_undo);
6420e80c
AS
4588 if (CONSP (tem) && INTEGERP (XCAR (tem))
4589 && INTEGERP (XCDR (tem))
4590 && XFASTINT (XCDR (tem)) == PT + old_inserted)
4591 XSETCDR (tem, make_number (PT + inserted));
6f2528d8
MR
4592 }
4593 }
6f2528d8 4594 else
1bc99c9c 4595 /* If undo_list was Qt before, keep it that way.
6420e80c 4596 Otherwise start with an empty undo_list. */
39eb03f1 4597 bset_undo_list (current_buffer, EQ (old_undo, Qt) ? Qt : Qnil);
efdc16c9 4598
f839df0c 4599 unbind_to (count1, Qnil);
0d420e88
BG
4600 }
4601
f8569325 4602 if (!NILP (visit)
d35af63c 4603 && EMACS_NSECS (current_buffer->modtime) == NONEXISTENT_MODTIME_NSECS)
f8569325
DL
4604 {
4605 /* If visiting nonexistent file, return nil. */
e5e9d610 4606 errno = save_errno;
f8569325 4607 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
d6a3cc15
RS
4608 }
4609
1b978129
GM
4610 if (read_quit)
4611 Fsignal (Qquit, Qnil);
4612
2ef88fd4 4613 /* Retval needs to be dealt with in all cases consistently. */
a1d2b64a 4614 if (NILP (val))
e07469fa 4615 val = list2 (orig_filename, make_number (inserted));
a1d2b64a
RS
4616
4617 RETURN_UNGCPRO (unbind_to (count, val));
570d7624 4618}
7fded690 4619\f
f57e2426 4620static Lisp_Object build_annotations (Lisp_Object, Lisp_Object);
d6a3cc15 4621
199607e4 4622static Lisp_Object
971de7fb 4623build_annotations_unwind (Lisp_Object arg)
6fc6f94b 4624{
67fbc0cb 4625 Vwrite_region_annotation_buffers = arg;
6fc6f94b
RS
4626 return Qnil;
4627}
4628
7c82a4a9
SM
4629/* Decide the coding-system to encode the data with. */
4630
9dbda100
GM
4631DEFUN ("choose-write-coding-system", Fchoose_write_coding_system,
4632 Schoose_write_coding_system, 3, 6, 0,
4633 doc: /* Choose the coding system for writing a file.
4634Arguments are as for `write-region'.
4635This function is for internal use only. It may prompt the user. */ )
4636 (Lisp_Object start, Lisp_Object end, Lisp_Object filename,
4637 Lisp_Object append, Lisp_Object visit, Lisp_Object lockname)
7c82a4a9
SM
4638{
4639 Lisp_Object val;
75421805 4640 Lisp_Object eol_parent = Qnil;
7c82a4a9 4641
9dbda100
GM
4642 /* Mimic write-region behavior. */
4643 if (NILP (start))
4644 {
4645 XSETFASTINT (start, BEGV);
4646 XSETFASTINT (end, ZV);
4647 }
4648
6b61353c 4649 if (auto_saving
4b4deea2
TT
4650 && NILP (Fstring_equal (BVAR (current_buffer, filename),
4651 BVAR (current_buffer, auto_save_file_name))))
75421805
KH
4652 {
4653 val = Qutf_8_emacs;
4654 eol_parent = Qunix;
4655 }
7c82a4a9 4656 else if (!NILP (Vcoding_system_for_write))
42b01e1e
KH
4657 {
4658 val = Vcoding_system_for_write;
4659 if (coding_system_require_warning
4660 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4661 /* Confirm that VAL can surely encode the current region. */
4662 val = call5 (Vselect_safe_coding_system_function,
4663 start, end, Fcons (Qt, Fcons (val, Qnil)),
4664 Qnil, filename);
4665 }
7c82a4a9
SM
4666 else
4667 {
4668 /* If the variable `buffer-file-coding-system' is set locally,
4669 it means that the file was read with some kind of code
4670 conversion or the variable is explicitly set by users. We
4671 had better write it out with the same coding system even if
4672 `enable-multibyte-characters' is nil.
4673
4674 If it is not set locally, we anyway have to convert EOL
4675 format if the default value of `buffer-file-coding-system'
4676 tells that it is not Unix-like (LF only) format. */
f75d7a91
PE
4677 bool using_default_coding = 0;
4678 bool force_raw_text = 0;
7c82a4a9 4679
4b4deea2 4680 val = BVAR (current_buffer, buffer_file_coding_system);
7c82a4a9
SM
4681 if (NILP (val)
4682 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4683 {
4684 val = Qnil;
4b4deea2 4685 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7c82a4a9
SM
4686 force_raw_text = 1;
4687 }
efdc16c9 4688
7c82a4a9
SM
4689 if (NILP (val))
4690 {
4691 /* Check file-coding-system-alist. */
4692 Lisp_Object args[7], coding_systems;
4693
4694 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4695 args[3] = filename; args[4] = append; args[5] = visit;
4696 args[6] = lockname;
4697 coding_systems = Ffind_operation_coding_system (7, args);
4698 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4699 val = XCDR (coding_systems);
4700 }
4701
c934586d 4702 if (NILP (val))
7c82a4a9
SM
4703 {
4704 /* If we still have not decided a coding system, use the
4705 default value of buffer-file-coding-system. */
4b4deea2 4706 val = BVAR (current_buffer, buffer_file_coding_system);
7c82a4a9
SM
4707 using_default_coding = 1;
4708 }
efdc16c9 4709
db327c7e
KH
4710 if (! NILP (val) && ! force_raw_text)
4711 {
4712 Lisp_Object spec, attrs;
4713
4714 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4715 attrs = AREF (spec, 0);
4716 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4717 force_raw_text = 1;
4718 }
4719
7c82a4a9
SM
4720 if (!force_raw_text
4721 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4722 /* Confirm that VAL can surely encode the current region. */
905a4276
PJ
4723 val = call5 (Vselect_safe_coding_system_function,
4724 start, end, val, Qnil, filename);
7c82a4a9 4725
db327c7e
KH
4726 /* If the decided coding-system doesn't specify end-of-line
4727 format, we use that of
4728 `default-buffer-file-coding-system'. */
c934586d 4729 if (! using_default_coding
4b4deea2 4730 && ! NILP (BVAR (&buffer_defaults, buffer_file_coding_system)))
db327c7e 4731 val = (coding_inherit_eol_type
4b4deea2 4732 (val, BVAR (&buffer_defaults, buffer_file_coding_system)));
7c82a4a9 4733
db327c7e
KH
4734 /* If we decide not to encode text, use `raw-text' or one of its
4735 subsidiaries. */
7c82a4a9 4736 if (force_raw_text)
db327c7e 4737 val = raw_text_coding_system (val);
7c82a4a9
SM
4738 }
4739
75421805 4740 val = coding_inherit_eol_type (val, eol_parent);
c934586d 4741 return val;
7c82a4a9
SM
4742}
4743
a7ca3326 4744DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
8c1a1077
PJ
4745 "r\nFWrite region to file: \ni\ni\ni\np",
4746 doc: /* Write current region into specified file.
c2efea25
RS
4747When called from a program, requires three arguments:
4748START, END and FILENAME. START and END are normally buffer positions
4749specifying the part of the buffer to write.
4750If START is nil, that means to use the entire buffer contents.
4751If START is a string, then output that string to the file
4752instead of any buffer contents; END is ignored.
4753
8c1a1077 4754Optional fourth argument APPEND if non-nil means
b3fbb395 4755 append to existing file contents (if any). If it is a number,
8c1a1077 4756 seek to that offset in the file before writing.
36e50520 4757Optional fifth argument VISIT, if t or a string, means
8c1a1077
PJ
4758 set the last-save-file-modtime of buffer to this file's modtime
4759 and mark buffer not modified.
4760If VISIT is a string, it is a second file name;
4761 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4762 VISIT is also the file name to lock and unlock for clash detection.
4763If VISIT is neither t nor nil nor a string,
5f4e6aa9 4764 that means do not display the \"Wrote file\" message.
8c1a1077
PJ
4765The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4766 use for locking and unlocking, overriding FILENAME and VISIT.
4767The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4768 for an existing file with the same name. If MUSTBENEW is `excl',
4769 that means to get an error if the file already exists; never overwrite.
4770 If MUSTBENEW is neither nil nor `excl', that means ask for
4771 confirmation before overwriting, but do go ahead and overwrite the file
4772 if the user confirms.
8c1a1077
PJ
4773
4774This does code conversion according to the value of
4775`coding-system-for-write', `buffer-file-coding-system', or
4776`file-coding-system-alist', and sets the variable
aacd8ba1
GM
4777`last-coding-system-used' to the coding system actually used.
4778
4779This calls `write-region-annotate-functions' at the start, and
4780`write-region-post-annotation-function' at the end. */)
5842a27b 4781 (Lisp_Object start, Lisp_Object end, Lisp_Object filename, Lisp_Object append, Lisp_Object visit, Lisp_Object lockname, Lisp_Object mustbenew)
570d7624 4782{
f75d7a91 4783 int desc;
3a955a1f
PE
4784 int open_flags;
4785 int mode;
4786 off_t offset IF_LINT (= 0);
f75d7a91 4787 bool ok;
6bbd7a29 4788 int save_errno = 0;
5976c3fe 4789 const char *fn;
570d7624 4790 struct stat st;
d6453ce4 4791 EMACS_TIME modtime;
d311d28c 4792 ptrdiff_t count = SPECPDL_INDEX ();
6fc6f94b 4793 int count1;
3eac9910 4794 Lisp_Object handler;
4ad827c5 4795 Lisp_Object visit_file;
65b7d3e7 4796 Lisp_Object annotations;
b1d1b865 4797 Lisp_Object encoded_filename;
f75d7a91
PE
4798 bool visiting = (EQ (visit, Qt) || STRINGP (visit));
4799 bool quietly = !NILP (visit);
7204a979 4800 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
6fc6f94b 4801 struct buffer *given_buffer;
6fdaa9a0 4802 struct coding_system coding;
570d7624 4803
d3a67486 4804 if (current_buffer->base_buffer && visiting)
95385625
RS
4805 error ("Cannot do file visiting in an indirect buffer");
4806
561cb8e1 4807 if (!NILP (start) && !STRINGP (start))
570d7624
JB
4808 validate_region (&start, &end);
4809
95c1c901 4810 visit_file = Qnil;
59fac292 4811 GCPRO5 (start, filename, visit, visit_file, lockname);
b56567b5 4812
570d7624 4813 filename = Fexpand_file_name (filename, Qnil);
de1d0127 4814
236a12f2 4815 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
b8b29dc9 4816 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
de1d0127 4817
561cb8e1 4818 if (STRINGP (visit))
e5176bae 4819 visit_file = Fexpand_file_name (visit, Qnil);
4ad827c5
RS
4820 else
4821 visit_file = filename;
4822
7204a979
RS
4823 if (NILP (lockname))
4824 lockname = visit_file;
4825
65b7d3e7
RS
4826 annotations = Qnil;
4827
32f4334d
RS
4828 /* If the file name has special constructs in it,
4829 call the corresponding file handler. */
49307295 4830 handler = Ffind_file_name_handler (filename, Qwrite_region);
b56ad927 4831 /* If FILENAME has no handler, see if VISIT has one. */
93c30b5f 4832 if (NILP (handler) && STRINGP (visit))
199607e4 4833 handler = Ffind_file_name_handler (visit, Qwrite_region);
3eac9910 4834
32f4334d
RS
4835 if (!NILP (handler))
4836 {
32f4334d 4837 Lisp_Object val;
51cf6d37
RS
4838 val = call6 (handler, Qwrite_region, start, end,
4839 filename, append, visit);
32f4334d 4840
d6a3cc15 4841 if (visiting)
32f4334d 4842 {
95385625 4843 SAVE_MODIFF = MODIFF;
4b4deea2 4844 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
39eb03f1 4845 bset_filename (current_buffer, visit_file);
32f4334d 4846 }
09121adc 4847 UNGCPRO;
32f4334d
RS
4848 return val;
4849 }
4850
4a38de71
KH
4851 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4852
561cb8e1
RS
4853 /* Special kludge to simplify auto-saving. */
4854 if (NILP (start))
4855 {
6b3d752c
SM
4856 /* Do it later, so write-region-annotate-function can work differently
4857 if we save "the buffer" vs "a region".
4858 This is useful in tar-mode. --Stef
2acfd7ae 4859 XSETFASTINT (start, BEG);
6b3d752c 4860 XSETFASTINT (end, Z); */
4a38de71 4861 Fwiden ();
561cb8e1
RS
4862 }
4863
67fbc0cb
CY
4864 record_unwind_protect (build_annotations_unwind,
4865 Vwrite_region_annotation_buffers);
4866 Vwrite_region_annotation_buffers = Fcons (Fcurrent_buffer (), Qnil);
aed13378 4867 count1 = SPECPDL_INDEX ();
6fc6f94b
RS
4868
4869 given_buffer = current_buffer;
bf3428a1
RS
4870
4871 if (!STRINGP (start))
236a12f2 4872 {
bf3428a1
RS
4873 annotations = build_annotations (start, end);
4874
4875 if (current_buffer != given_buffer)
4876 {
4877 XSETFASTINT (start, BEGV);
4878 XSETFASTINT (end, ZV);
4879 }
236a12f2
SM
4880 }
4881
6b3d752c
SM
4882 if (NILP (start))
4883 {
4884 XSETFASTINT (start, BEGV);
4885 XSETFASTINT (end, ZV);
4886 }
4887
236a12f2
SM
4888 UNGCPRO;
4889
4890 GCPRO5 (start, filename, annotations, visit_file, lockname);
4891
59fac292
SM
4892 /* Decide the coding-system to encode the data with.
4893 We used to make this choice before calling build_annotations, but that
4894 leads to problems when a write-annotate-function takes care of
4895 unsavable chars (as was the case with X-Symbol). */
538f3845 4896 Vlast_coding_system_used =
9dbda100 4897 Fchoose_write_coding_system (start, end, filename,
538f3845 4898 append, visit, lockname);
9dbda100
GM
4899
4900 setup_coding_system (Vlast_coding_system_used, &coding);
4901
4902 if (!STRINGP (start) && !NILP (BVAR (current_buffer, selective_display)))
4903 coding.mode |= CODING_MODE_SELECTIVE_DISPLAY;
d6a3cc15 4904
570d7624
JB
4905#ifdef CLASH_DETECTION
4906 if (!auto_saving)
67fbc0cb 4907 lock_file (lockname);
570d7624
JB
4908#endif /* CLASH_DETECTION */
4909
b1d1b865 4910 encoded_filename = ENCODE_FILE (filename);
5976c3fe 4911 fn = SSDATA (encoded_filename);
3a955a1f
PE
4912 open_flags = O_WRONLY | O_BINARY | O_CREAT;
4913 open_flags |= EQ (mustbenew, Qexcl) ? O_EXCL : !NILP (append) ? 0 : O_TRUNC;
4914 if (NUMBERP (append))
4915 offset = file_offset (append);
4916 else if (!NILP (append))
4917 open_flags |= O_APPEND;
5e570b75 4918#ifdef DOS_NT
3a955a1f
PE
4919 mode = S_IREAD | S_IWRITE;
4920#else
4921 mode = auto_saving ? auto_save_mode_bits : 0666;
4922#endif
4923
4924 desc = emacs_open (fn, open_flags, mode);
570d7624
JB
4925
4926 if (desc < 0)
4927 {
4928#ifdef CLASH_DETECTION
4929 save_errno = errno;
7204a979 4930 if (!auto_saving) unlock_file (lockname);
570d7624
JB
4931 errno = save_errno;
4932#endif /* CLASH_DETECTION */
43fb7d9a 4933 UNGCPRO;
570d7624
JB
4934 report_file_error ("Opening output file", Fcons (filename, Qnil));
4935 }
4936
4937 record_unwind_protect (close_file_unwind, make_number (desc));
4938
3a955a1f 4939 if (NUMBERP (append))
43fb7d9a 4940 {
3a955a1f 4941 off_t ret = lseek (desc, offset, SEEK_SET);
43fb7d9a
DL
4942 if (ret < 0)
4943 {
570d7624 4944#ifdef CLASH_DETECTION
e5e9d610 4945 save_errno = errno;
43fb7d9a 4946 if (!auto_saving) unlock_file (lockname);
e5e9d610 4947 errno = save_errno;
570d7624 4948#endif /* CLASH_DETECTION */
43fb7d9a
DL
4949 UNGCPRO;
4950 report_file_error ("Lseek error", Fcons (filename, Qnil));
4951 }
4952 }
efdc16c9 4953
43fb7d9a 4954 UNGCPRO;
570d7624 4955
570d7624
JB
4956 immediate_quit = 1;
4957
561cb8e1 4958 if (STRINGP (start))
f75d7a91 4959 ok = a_write (desc, start, 0, SCHARS (start), &annotations, &coding);
570d7624 4960 else if (XINT (start) != XINT (end))
f75d7a91
PE
4961 ok = a_write (desc, Qnil, XINT (start), XINT (end) - XINT (start),
4962 &annotations, &coding);
69f6e679
RS
4963 else
4964 {
f75d7a91 4965 /* If file was empty, still need to write the annotations. */
c8a6d68a 4966 coding.mode |= CODING_MODE_LAST_BLOCK;
f75d7a91 4967 ok = a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
6fdaa9a0 4968 }
f75d7a91 4969 save_errno = errno;
6fdaa9a0 4970
f75d7a91
PE
4971 if (ok && CODING_REQUIRE_FLUSHING (&coding)
4972 && !(coding.mode & CODING_MODE_LAST_BLOCK))
6fdaa9a0
KH
4973 {
4974 /* We have to flush out a data. */
c8a6d68a 4975 coding.mode |= CODING_MODE_LAST_BLOCK;
f75d7a91 4976 ok = e_write (desc, Qnil, 1, 1, &coding);
69f6e679 4977 save_errno = errno;
570d7624
JB
4978 }
4979
4980 immediate_quit = 0;
4981
cbee2131
PE
4982 /* fsync is not crucial for auto-save files, since they might lose
4983 some work anyway. */
47d7532e 4984 if (!auto_saving && !write_region_inhibit_fsync)
cb33c142 4985 {
cbee2131
PE
4986 /* Transfer data and metadata to disk, retrying if interrupted.
4987 fsync can report a write failure here, e.g., due to disk full
4988 under NFS. But ignore EINVAL, which means fsync is not
4989 supported on this file. */
47d7532e
PE
4990 while (fsync (desc) != 0)
4991 if (errno != EINTR)
4992 {
4993 if (errno != EINVAL)
4994 ok = 0, save_errno = errno;
4995 break;
4996 }
cb33c142 4997 }
570d7624 4998
d6453ce4
PE
4999 modtime = invalid_emacs_time ();
5000 if (visiting)
5001 {
5002 if (fstat (desc, &st) == 0)
5003 modtime = get_stat_mtime (&st);
5004 else
5005 ok = 0, save_errno = errno;
5006 }
5007
570d7624 5008 /* NFS can report a write failure now. */
68c45bf0 5009 if (emacs_close (desc) < 0)
f75d7a91 5010 ok = 0, save_errno = errno;
570d7624 5011
6fc6f94b
RS
5012 /* Discard the unwind protect for close_file_unwind. */
5013 specpdl_ptr = specpdl + count1;
67fbc0cb 5014
9fe43ff6
PE
5015 /* Some file systems have a bug where st_mtime is not updated
5016 properly after a write. For example, CIFS might not see the
5017 st_mtime change until after the file is opened again.
5018
5019 Attempt to detect this file system bug, and update MODTIME to the
5020 newer st_mtime if the bug appears to be present. This introduces
5021 a race condition, so to avoid most instances of the race condition
5022 on non-buggy file systems, skip this check if the most recently
5023 encountered non-buggy file system was the current file system.
5024
5025 A race condition can occur if some other process modifies the
5026 file between the fstat above and the fstat below, but the race is
5027 unlikely and a similar race between the last write and the fstat
5028 above cannot possibly be closed anyway. */
5029
5030 if (EMACS_TIME_VALID_P (modtime)
5031 && ! (valid_timestamp_file_system && st.st_dev == timestamp_file_system))
5032 {
21cd50b8 5033 int desc1 = emacs_open (fn, O_WRONLY | O_BINARY, 0);
908589fd 5034 if (desc1 >= 0)
9fe43ff6
PE
5035 {
5036 struct stat st1;
5037 if (fstat (desc1, &st1) == 0
5038 && st.st_dev == st1.st_dev && st.st_ino == st1.st_ino)
5039 {
8ea41ea9
PE
5040 /* Use the heuristic if it appears to be valid. With neither
5041 O_EXCL nor O_TRUNC, if Emacs happened to write nothing to the
5042 file, the time stamp won't change. Also, some non-POSIX
5043 systems don't update an empty file's time stamp when
5044 truncating it. Finally, file systems with 100 ns or worse
5045 resolution sometimes seem to have bugs: on a system with ns
5046 resolution, checking ns % 100 incorrectly avoids the heuristic
5047 1% of the time, but the problem should be temporary as we will
5048 try again on the next time stamp. */
5049 bool use_heuristic
5050 = ((open_flags & (O_EXCL | O_TRUNC)) != 0
5051 && st.st_size != 0
5052 && EMACS_NSECS (modtime) % 100 != 0);
5053
9fe43ff6 5054 EMACS_TIME modtime1 = get_stat_mtime (&st1);
8ea41ea9 5055 if (use_heuristic
35e85499 5056 && EMACS_TIME_EQ (modtime, modtime1)
9fe43ff6
PE
5057 && st.st_size == st1.st_size)
5058 {
5059 timestamp_file_system = st.st_dev;
5060 valid_timestamp_file_system = 1;
5061 }
5062 else
5063 {
5064 st.st_size = st1.st_size;
5065 modtime = modtime1;
5066 }
5067 }
5068 emacs_close (desc1);
5069 }
5070 }
5071
67fbc0cb 5072 /* Call write-region-post-annotation-function. */
294fa707 5073 while (CONSP (Vwrite_region_annotation_buffers))
67fbc0cb
CY
5074 {
5075 Lisp_Object buf = XCAR (Vwrite_region_annotation_buffers);
5076 if (!NILP (Fbuffer_live_p (buf)))
5077 {
5078 Fset_buffer (buf);
5079 if (FUNCTIONP (Vwrite_region_post_annotation_function))
5080 call0 (Vwrite_region_post_annotation_function);
5081 }
5082 Vwrite_region_annotation_buffers
5083 = XCDR (Vwrite_region_annotation_buffers);
5084 }
5085
5086 unbind_to (count, Qnil);
570d7624
JB
5087
5088#ifdef CLASH_DETECTION
5089 if (!auto_saving)
7204a979 5090 unlock_file (lockname);
570d7624
JB
5091#endif /* CLASH_DETECTION */
5092
5093 /* Do this before reporting IO error
5094 to avoid a "file has changed on disk" warning on
5095 next attempt to save. */
d6453ce4 5096 if (EMACS_TIME_VALID_P (modtime))
58b963f7 5097 {
d6453ce4 5098 current_buffer->modtime = modtime;
58b963f7
SM
5099 current_buffer->modtime_size = st.st_size;
5100 }
570d7624 5101
f75d7a91 5102 if (! ok)
d5db4077 5103 error ("IO error writing %s: %s", SDATA (filename),
68c45bf0 5104 emacs_strerror (save_errno));
570d7624 5105
d6a3cc15 5106 if (visiting)
570d7624 5107 {
95385625 5108 SAVE_MODIFF = MODIFF;
4b4deea2 5109 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
39eb03f1 5110 bset_filename (current_buffer, visit_file);
f4226e89 5111 update_mode_lines++;
570d7624 5112 }
d6a3cc15 5113 else if (quietly)
6b61353c
KH
5114 {
5115 if (auto_saving
4b4deea2
TT
5116 && ! NILP (Fstring_equal (BVAR (current_buffer, filename),
5117 BVAR (current_buffer, auto_save_file_name))))
6b61353c
KH
5118 SAVE_MODIFF = MODIFF;
5119
5120 return Qnil;
5121 }
570d7624
JB
5122
5123 if (!auto_saving)
3908c576 5124 message_with_string ((NUMBERP (append)
0c328a0e
RS
5125 ? "Updated %s"
5126 : ! NILP (append)
5127 ? "Added to %s"
5128 : "Wrote %s"),
5129 visit_file, 1);
570d7624
JB
5130
5131 return Qnil;
5132}
ec7adf26 5133\f
dd4c5104 5134Lisp_Object merge (Lisp_Object, Lisp_Object, Lisp_Object);
d6a3cc15
RS
5135
5136DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
8c1a1077 5137 doc: /* Return t if (car A) is numerically less than (car B). */)
5842a27b 5138 (Lisp_Object a, Lisp_Object b)
d6a3cc15
RS
5139{
5140 return Flss (Fcar (a), Fcar (b));
5141}
5142
5143/* Build the complete list of annotations appropriate for writing out
5144 the text between START and END, by calling all the functions in
6fc6f94b
RS
5145 write-region-annotate-functions and merging the lists they return.
5146 If one of these functions switches to a different buffer, we assume
5147 that buffer contains altered text. Therefore, the caller must
5148 make sure to restore the current buffer in all cases,
5149 as save-excursion would do. */
d6a3cc15
RS
5150
5151static Lisp_Object
971de7fb 5152build_annotations (Lisp_Object start, Lisp_Object end)
d6a3cc15
RS
5153{
5154 Lisp_Object annotations;
5155 Lisp_Object p, res;
5156 struct gcpro gcpro1, gcpro2;
0a20b684 5157 Lisp_Object original_buffer;
f75d7a91
PE
5158 int i;
5159 bool used_global = 0;
0a20b684
RS
5160
5161 XSETBUFFER (original_buffer, current_buffer);
d6a3cc15
RS
5162
5163 annotations = Qnil;
5164 p = Vwrite_region_annotate_functions;
5165 GCPRO2 (annotations, p);
28c3eb5a 5166 while (CONSP (p))
d6a3cc15 5167 {
6fc6f94b 5168 struct buffer *given_buffer = current_buffer;
bd235610
SM
5169 if (EQ (Qt, XCAR (p)) && !used_global)
5170 { /* Use the global value of the hook. */
5171 Lisp_Object arg[2];
5172 used_global = 1;
5173 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
5174 arg[1] = XCDR (p);
5175 p = Fappend (2, arg);
5176 continue;
5177 }
6fc6f94b 5178 Vwrite_region_annotations_so_far = annotations;
28c3eb5a 5179 res = call2 (XCAR (p), start, end);
6fc6f94b
RS
5180 /* If the function makes a different buffer current,
5181 assume that means this buffer contains altered text to be output.
5182 Reset START and END from the buffer bounds
5183 and discard all previous annotations because they should have
5184 been dealt with by this function. */
5185 if (current_buffer != given_buffer)
5186 {
67fbc0cb
CY
5187 Vwrite_region_annotation_buffers
5188 = Fcons (Fcurrent_buffer (),
5189 Vwrite_region_annotation_buffers);
3cf29f61
RS
5190 XSETFASTINT (start, BEGV);
5191 XSETFASTINT (end, ZV);
6fc6f94b
RS
5192 annotations = Qnil;
5193 }
d6a3cc15
RS
5194 Flength (res); /* Check basic validity of return value */
5195 annotations = merge (annotations, res, Qcar_less_than_car);
28c3eb5a 5196 p = XCDR (p);
d6a3cc15 5197 }
0d420e88
BG
5198
5199 /* Now do the same for annotation functions implied by the file-format */
4b4deea2
TT
5200 if (auto_saving && (!EQ (BVAR (current_buffer, auto_save_file_format), Qt)))
5201 p = BVAR (current_buffer, auto_save_file_format);
0d420e88 5202 else
4b4deea2 5203 p = BVAR (current_buffer, file_format);
28c3eb5a 5204 for (i = 0; CONSP (p); p = XCDR (p), ++i)
0d420e88
BG
5205 {
5206 struct buffer *given_buffer = current_buffer;
efdc16c9 5207
0d420e88 5208 Vwrite_region_annotations_so_far = annotations;
532ed661
GM
5209
5210 /* Value is either a list of annotations or nil if the function
5211 has written annotations to a temporary buffer, which is now
5212 current. */
28c3eb5a 5213 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
532ed661 5214 original_buffer, make_number (i));
0d420e88
BG
5215 if (current_buffer != given_buffer)
5216 {
3cf29f61
RS
5217 XSETFASTINT (start, BEGV);
5218 XSETFASTINT (end, ZV);
0d420e88
BG
5219 annotations = Qnil;
5220 }
efdc16c9 5221
532ed661
GM
5222 if (CONSP (res))
5223 annotations = merge (annotations, res, Qcar_less_than_car);
0d420e88 5224 }
6fdaa9a0 5225
236a12f2
SM
5226 UNGCPRO;
5227 return annotations;
5228}
5229
ec7adf26 5230\f
ce51c54c
KH
5231/* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5232 If STRING is nil, POS is the character position in the current buffer.
d6a3cc15 5233 Intersperse with them the annotations from *ANNOT
ce51c54c 5234 which fall within the range of POS to POS + NCHARS,
d6a3cc15
RS
5235 each at its appropriate position.
5236
ec7adf26
RS
5237 We modify *ANNOT by discarding elements as we use them up.
5238
f75d7a91 5239 Return true if successful. */
d6a3cc15 5240
f75d7a91 5241static bool
d311d28c 5242a_write (int desc, Lisp_Object string, ptrdiff_t pos,
f75d7a91 5243 ptrdiff_t nchars, Lisp_Object *annot,
8a2cbd72 5244 struct coding_system *coding)
d6a3cc15
RS
5245{
5246 Lisp_Object tem;
d311d28c
PE
5247 ptrdiff_t nextpos;
5248 ptrdiff_t lastpos = pos + nchars;
d6a3cc15 5249
eb15aa18 5250 while (NILP (*annot) || CONSP (*annot))
d6a3cc15
RS
5251 {
5252 tem = Fcar_safe (Fcar (*annot));
ce51c54c 5253 nextpos = pos - 1;
ec7adf26 5254 if (INTEGERP (tem))
ce51c54c 5255 nextpos = XFASTINT (tem);
ec7adf26
RS
5256
5257 /* If there are no more annotations in this range,
5258 output the rest of the range all at once. */
ce51c54c
KH
5259 if (! (nextpos >= pos && nextpos <= lastpos))
5260 return e_write (desc, string, pos, lastpos, coding);
ec7adf26
RS
5261
5262 /* Output buffer text up to the next annotation's position. */
ce51c54c 5263 if (nextpos > pos)
d6a3cc15 5264 {
f75d7a91
PE
5265 if (!e_write (desc, string, pos, nextpos, coding))
5266 return 0;
ce51c54c 5267 pos = nextpos;
d6a3cc15 5268 }
ec7adf26 5269 /* Output the annotation. */
d6a3cc15
RS
5270 tem = Fcdr (Fcar (*annot));
5271 if (STRINGP (tem))
5272 {
f75d7a91
PE
5273 if (!e_write (desc, tem, 0, SCHARS (tem), coding))
5274 return 0;
d6a3cc15
RS
5275 }
5276 *annot = Fcdr (*annot);
5277 }
f75d7a91 5278 return 1;
d6a3cc15
RS
5279}
5280
6fdaa9a0 5281
ce51c54c
KH
5282/* Write text in the range START and END into descriptor DESC,
5283 encoding them with coding system CODING. If STRING is nil, START
5284 and END are character positions of the current buffer, else they
f75d7a91 5285 are indexes to the string STRING. Return true if successful. */
ec7adf26 5286
f75d7a91 5287static bool
d311d28c 5288e_write (int desc, Lisp_Object string, ptrdiff_t start, ptrdiff_t end,
8a2cbd72 5289 struct coding_system *coding)
570d7624 5290{
ce51c54c
KH
5291 if (STRINGP (string))
5292 {
db327c7e 5293 start = 0;
8f924df7 5294 end = SCHARS (string);
ce51c54c 5295 }
570d7624 5296
6fdaa9a0
KH
5297 /* We used to have a code for handling selective display here. But,
5298 now it is handled within encode_coding. */
01ca97a2
KH
5299
5300 while (start < end)
570d7624 5301 {
01ca97a2 5302 if (STRINGP (string))
6ad568dd 5303 {
01ca97a2
KH
5304 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5305 if (CODING_REQUIRE_ENCODING (coding))
5306 {
5307 encode_coding_object (coding, string,
5308 start, string_char_to_byte (string, start),
5309 end, string_char_to_byte (string, end), Qt);
5310 }
5311 else
5312 {
5313 coding->dst_object = string;
5314 coding->consumed_char = SCHARS (string);
5315 coding->produced = SBYTES (string);
5316 }
6ad568dd 5317 }
db327c7e 5318 else
6ad568dd 5319 {
d311d28c
PE
5320 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
5321 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
b4132433 5322
01ca97a2
KH
5323 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5324 if (CODING_REQUIRE_ENCODING (coding))
5325 {
5326 encode_coding_object (coding, Fcurrent_buffer (),
5327 start, start_byte, end, end_byte, Qt);
5328 }
5329 else
5330 {
5331 coding->dst_object = Qnil;
5332 coding->dst_pos_byte = start_byte;
5333 if (start >= GPT || end <= GPT)
5334 {
5335 coding->consumed_char = end - start;
5336 coding->produced = end_byte - start_byte;
5337 }
5338 else
5339 {
5340 coding->consumed_char = GPT - start;
5341 coding->produced = GPT_BYTE - start_byte;
5342 }
5343 }
c185d744 5344 }
01ca97a2
KH
5345
5346 if (coding->produced > 0)
c185d744 5347 {
ce2fe65a
AS
5348 coding->produced
5349 -= emacs_write (desc,
5350 STRINGP (coding->dst_object)
5351 ? SSDATA (coding->dst_object)
5352 : (char *) BYTE_POS_ADDR (coding->dst_pos_byte),
5353 coding->produced);
01ca97a2
KH
5354
5355 if (coding->produced)
f75d7a91 5356 return 0;
570d7624 5357 }
01ca97a2 5358 start += coding->consumed_char;
c185d744
KH
5359 }
5360
f75d7a91 5361 return 1;
570d7624 5362}
ec7adf26 5363\f
a7ca3326 5364DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
ec1b9b17 5365 Sverify_visited_file_modtime, 0, 1, 0,
8c1a1077 5366 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
6b61353c 5367This means that the file has not been changed since it was visited or saved.
ec1b9b17 5368If BUF is omitted or nil, it defaults to the current buffer.
6b61353c 5369See Info node `(elisp)Modification Time' for more details. */)
5842a27b 5370 (Lisp_Object buf)
570d7624
JB
5371{
5372 struct buffer *b;
5373 struct stat st;
32f4334d 5374 Lisp_Object handler;
b1d1b865 5375 Lisp_Object filename;
b95a9c0c 5376 EMACS_TIME mtime;
570d7624 5377
ec1b9b17
GM
5378 if (NILP (buf))
5379 b = current_buffer;
5380 else
5381 {
5382 CHECK_BUFFER (buf);
5383 b = XBUFFER (buf);
5384 }
570d7624 5385
4b4deea2 5386 if (!STRINGP (BVAR (b, filename))) return Qt;
d35af63c 5387 if (EMACS_NSECS (b->modtime) == UNKNOWN_MODTIME_NSECS) return Qt;
570d7624 5388
32f4334d
RS
5389 /* If the file name has special constructs in it,
5390 call the corresponding file handler. */
4b4deea2 5391 handler = Ffind_file_name_handler (BVAR (b, filename),
49307295 5392 Qverify_visited_file_modtime);
32f4334d 5393 if (!NILP (handler))
09121adc 5394 return call2 (handler, Qverify_visited_file_modtime, buf);
32f4334d 5395
4b4deea2 5396 filename = ENCODE_FILE (BVAR (b, filename));
b1d1b865 5397
dbeed9a6
PE
5398 mtime = (stat (SSDATA (filename), &st) == 0
5399 ? get_stat_mtime (&st)
f0941253 5400 : time_error_value (errno));
b95a9c0c 5401 if (EMACS_TIME_EQ (mtime, b->modtime)
645c6a30
PE
5402 && (b->modtime_size < 0
5403 || st.st_size == b->modtime_size))
570d7624
JB
5404 return Qt;
5405 return Qnil;
5406}
5407
5408DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
8c1a1077
PJ
5409 Sclear_visited_file_modtime, 0, 0, 0,
5410 doc: /* Clear out records of last mod time of visited file.
5411Next attempt to save will certainly not complain of a discrepancy. */)
5842a27b 5412 (void)
570d7624 5413{
e9a9ae03 5414 current_buffer->modtime = make_emacs_time (0, UNKNOWN_MODTIME_NSECS);
58b963f7 5415 current_buffer->modtime_size = -1;
570d7624
JB
5416 return Qnil;
5417}
5418
f5d5eccf 5419DEFUN ("visited-file-modtime", Fvisited_file_modtime,
8c1a1077
PJ
5420 Svisited_file_modtime, 0, 0, 0,
5421 doc: /* Return the current buffer's recorded visited file modification time.
d35af63c 5422The value is a list of the form (HIGH LOW USEC PSEC), like the time values that
1c4d7f3d
LMI
5423`file-attributes' returns. If the current buffer has no recorded file
5424modification time, this function returns 0. If the visited file
9d1d6e68 5425doesn't exist, HIGH will be -1.
6b61353c 5426See Info node `(elisp)Modification Time' for more details. */)
5842a27b 5427 (void)
f5d5eccf 5428{
d35af63c 5429 if (EMACS_NSECS (current_buffer->modtime) < 0)
184246df
PE
5430 {
5431 if (EMACS_NSECS (current_buffer->modtime) == NONEXISTENT_MODTIME_NSECS)
5432 {
5433 /* make_lisp_time won't work here if time_t is unsigned. */
3de717bd 5434 return list4i (-1, 65535, 0, 0);
184246df
PE
5435 }
5436 return make_number (0);
5437 }
d35af63c 5438 return make_lisp_time (current_buffer->modtime);
f5d5eccf
RS
5439}
5440
570d7624 5441DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
8c1a1077
PJ
5442 Sset_visited_file_modtime, 0, 1, 0,
5443 doc: /* Update buffer's recorded modification time from the visited file's time.
5444Useful if the buffer was not read from the file normally
5445or if the file itself has been changed for some known benign reason.
5446An argument specifies the modification time value to use
5447\(instead of that of the visited file), in the form of a list
d35af63c 5448\(HIGH LOW USEC PSEC) as returned by `current-time'. */)
5842a27b 5449 (Lisp_Object time_list)
570d7624 5450{
f5d5eccf 5451 if (!NILP (time_list))
58b963f7 5452 {
31571fd7 5453 current_buffer->modtime = lisp_time_argument (time_list);
58b963f7
SM
5454 current_buffer->modtime_size = -1;
5455 }
f5d5eccf
RS
5456 else
5457 {
5458 register Lisp_Object filename;
5459 struct stat st;
5460 Lisp_Object handler;
570d7624 5461
4b4deea2 5462 filename = Fexpand_file_name (BVAR (current_buffer, filename), Qnil);
32f4334d 5463
f5d5eccf
RS
5464 /* If the file name has special constructs in it,
5465 call the corresponding file handler. */
49307295 5466 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
f5d5eccf 5467 if (!NILP (handler))
caf3c431 5468 /* The handler can find the file name the same way we did. */
76c881b0 5469 return call2 (handler, Qset_visited_file_modtime, Qnil);
b1d1b865
RS
5470
5471 filename = ENCODE_FILE (filename);
5472
42a5b22f 5473 if (stat (SSDATA (filename), &st) >= 0)
58b963f7 5474 {
d35af63c 5475 current_buffer->modtime = get_stat_mtime (&st);
58b963f7
SM
5476 current_buffer->modtime_size = st.st_size;
5477 }
f5d5eccf 5478 }
570d7624
JB
5479
5480 return Qnil;
5481}
5482\f
f14b7e14 5483static Lisp_Object
f839df0c 5484auto_save_error (Lisp_Object error_val)
570d7624 5485{
d7f31e22 5486 Lisp_Object args[3], msg;
b09cca6a 5487 int i;
d7f31e22 5488 struct gcpro gcpro1;
efdc16c9 5489
ca730bf0
CY
5490 auto_save_error_occurred = 1;
5491
385ed61f 5492 ring_bell (XFRAME (selected_frame));
efdc16c9 5493
d7f31e22 5494 args[0] = build_string ("Auto-saving %s: %s");
4b4deea2 5495 args[1] = BVAR (current_buffer, name);
f839df0c 5496 args[2] = Ferror_message_string (error_val);
d7f31e22
GM
5497 msg = Fformat (3, args);
5498 GCPRO1 (msg);
d7f31e22
GM
5499
5500 for (i = 0; i < 3; ++i)
5501 {
5502 if (i == 0)
b09cca6a 5503 message3 (msg);
d7f31e22 5504 else
b09cca6a 5505 message3_nolog (msg);
d7f31e22
GM
5506 Fsleep_for (make_number (1), Qnil);
5507 }
5508
5509 UNGCPRO;
570d7624
JB
5510 return Qnil;
5511}
5512
f14b7e14 5513static Lisp_Object
971de7fb 5514auto_save_1 (void)
570d7624 5515{
570d7624 5516 struct stat st;
d4a42098
KS
5517 Lisp_Object modes;
5518
5519 auto_save_mode_bits = 0666;
570d7624
JB
5520
5521 /* Get visited file's mode to become the auto save file's mode. */
4b4deea2 5522 if (! NILP (BVAR (current_buffer, filename)))
d4a42098 5523 {
4b4deea2 5524 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
d4a42098 5525 /* But make sure we can overwrite it later! */
18c52557 5526 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
ce2fe65a
AS
5527 else if (modes = Ffile_modes (BVAR (current_buffer, filename)),
5528 INTEGERP (modes))
d4a42098 5529 /* Remote files don't cooperate with stat. */
18c52557 5530 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
d4a42098 5531 }
570d7624
JB
5532
5533 return
4b4deea2 5534 Fwrite_region (Qnil, Qnil, BVAR (current_buffer, auto_save_file_name), Qnil,
699b53bc
CY
5535 NILP (Vauto_save_visited_file_name) ? Qlambda : Qt,
5536 Qnil, Qnil);
570d7624
JB
5537}
5538
e54d3b5d 5539static Lisp_Object
971de7fb 5540do_auto_save_unwind (Lisp_Object arg) /* used as unwind-protect function */
410ed5c3 5541
e54d3b5d 5542{
2b30549c 5543 FILE *stream = XSAVE_POINTER (arg, 0);
3be3c08e 5544 auto_saving = 0;
fff7e982 5545 if (stream != NULL)
aab12958 5546 {
4d7e6e51 5547 block_input ();
aab12958 5548 fclose (stream);
4d7e6e51 5549 unblock_input ();
aab12958 5550 }
e54d3b5d
RS
5551 return Qnil;
5552}
5553
a8c828be 5554static Lisp_Object
971de7fb 5555do_auto_save_unwind_1 (Lisp_Object value) /* used as unwind-protect function */
410ed5c3 5556
a8c828be
RS
5557{
5558 minibuffer_auto_raise = XINT (value);
5559 return Qnil;
5560}
5561
5794dd61 5562static Lisp_Object
971de7fb 5563do_auto_save_make_dir (Lisp_Object dir)
5794dd61 5564{
09450bae 5565 Lisp_Object result;
26816cbf 5566
09450bae
PE
5567 auto_saving_dir_umask = 077;
5568 result = call2 (Qmake_directory, dir, Qt);
5569 auto_saving_dir_umask = 0;
5570 return result;
5794dd61
RS
5571}
5572
5573static Lisp_Object
971de7fb 5574do_auto_save_eh (Lisp_Object ignore)
5794dd61 5575{
09450bae 5576 auto_saving_dir_umask = 0;
5794dd61
RS
5577 return Qnil;
5578}
5579
a7ca3326 5580DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
8c1a1077
PJ
5581 doc: /* Auto-save all buffers that need it.
5582This is all buffers that have auto-saving enabled
5583and are changed since last auto-saved.
5584Auto-saving writes the buffer into a file
5585so that your editing is not lost if the system crashes.
5586This file is not the file you visited; that changes only when you save.
5587Normally we run the normal hook `auto-save-hook' before saving.
5588
5589A non-nil NO-MESSAGE argument means do not print any message if successful.
5590A non-nil CURRENT-ONLY argument means save only current buffer. */)
5842a27b 5591 (Lisp_Object no_message, Lisp_Object current_only)
570d7624
JB
5592{
5593 struct buffer *old = current_buffer, *b;
dee091a3 5594 Lisp_Object tail, buf, hook;
f75d7a91 5595 bool auto_saved = 0;
f14b1c68 5596 int do_handled_files;
ff4c9993 5597 Lisp_Object oquit;
fff7e982 5598 FILE *stream = NULL;
d311d28c 5599 ptrdiff_t count = SPECPDL_INDEX ();
f75d7a91 5600 bool orig_minibuffer_auto_raise = minibuffer_auto_raise;
fce31d69 5601 bool old_message_p = 0;
d57563b6 5602 struct gcpro gcpro1, gcpro2;
38da540d
RS
5603
5604 if (max_specpdl_size < specpdl_size + 40)
5605 max_specpdl_size = specpdl_size + 40;
5606
5607 if (minibuf_level)
5608 no_message = Qt;
5609
5794dd61
RS
5610 if (NILP (no_message))
5611 {
5612 old_message_p = push_message ();
5613 record_unwind_protect (pop_message_unwind, Qnil);
5614 }
efdc16c9 5615
ff4c9993
RS
5616 /* Ordinarily don't quit within this function,
5617 but don't make it impossible to quit (in case we get hung in I/O). */
5618 oquit = Vquit_flag;
5619 Vquit_flag = Qnil;
570d7624
JB
5620
5621 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5622 point to non-strings reached from Vbuffer_alist. */
5623
dee091a3
JD
5624 hook = intern ("auto-save-hook");
5625 Frun_hooks (1, &hook);
570d7624 5626
e54d3b5d
RS
5627 if (STRINGP (Vauto_save_list_file_name))
5628 {
0894672f 5629 Lisp_Object listfile;
efdc16c9 5630
258fd2cb 5631 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
0894672f
GM
5632
5633 /* Don't try to create the directory when shutting down Emacs,
5634 because creating the directory might signal an error, and
5635 that would leave Emacs in a strange state. */
5636 if (!NILP (Vrun_hooks))
5637 {
5638 Lisp_Object dir;
d57563b6
RS
5639 dir = Qnil;
5640 GCPRO2 (dir, listfile);
0894672f
GM
5641 dir = Ffile_name_directory (listfile);
5642 if (NILP (Ffile_directory_p (dir)))
5794dd61 5643 internal_condition_case_1 (do_auto_save_make_dir,
09450bae 5644 dir, Qt,
5794dd61 5645 do_auto_save_eh);
d57563b6 5646 UNGCPRO;
0894672f 5647 }
efdc16c9 5648
42a5b22f 5649 stream = fopen (SSDATA (listfile), "w");
1b335d29 5650 }
199607e4 5651
fff7e982 5652 record_unwind_protect (do_auto_save_unwind,
468afbac 5653 make_save_pointer (stream));
a8c828be
RS
5654 record_unwind_protect (do_auto_save_unwind_1,
5655 make_number (minibuffer_auto_raise));
5656 minibuffer_auto_raise = 0;
3be3c08e 5657 auto_saving = 1;
ca730bf0 5658 auto_save_error_occurred = 0;
3be3c08e 5659
6b61353c
KH
5660 /* On first pass, save all files that don't have handlers.
5661 On second pass, save all files that do have handlers.
5662
5663 If Emacs is crashing, the handlers may tweak what is causing
5664 Emacs to crash in the first place, and it would be a shame if
5665 Emacs failed to autosave perfectly ordinary files because it
5666 couldn't handle some ange-ftp'd file. */
5667
f14b1c68 5668 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
8e50cc2d 5669 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
f14b1c68 5670 {
03699b14 5671 buf = XCDR (XCAR (tail));
f14b1c68 5672 b = XBUFFER (buf);
199607e4 5673
e54d3b5d 5674 /* Record all the buffers that have auto save mode
258fd2cb
RS
5675 in the special file that lists them. For each of these buffers,
5676 Record visited name (if any) and auto save name. */
4b4deea2 5677 if (STRINGP (BVAR (b, auto_save_file_name))
1b335d29 5678 && stream != NULL && do_handled_files == 0)
e54d3b5d 5679 {
4d7e6e51 5680 block_input ();
4b4deea2 5681 if (!NILP (BVAR (b, filename)))
258fd2cb 5682 {
4b4deea2
TT
5683 fwrite (SDATA (BVAR (b, filename)), 1,
5684 SBYTES (BVAR (b, filename)), stream);
258fd2cb 5685 }
1b335d29 5686 putc ('\n', stream);
4b4deea2
TT
5687 fwrite (SDATA (BVAR (b, auto_save_file_name)), 1,
5688 SBYTES (BVAR (b, auto_save_file_name)), stream);
1b335d29 5689 putc ('\n', stream);
4d7e6e51 5690 unblock_input ();
e54d3b5d 5691 }
17857782 5692
f14b1c68
JB
5693 if (!NILP (current_only)
5694 && b != current_buffer)
5695 continue;
e54d3b5d 5696
95385625
RS
5697 /* Don't auto-save indirect buffers.
5698 The base buffer takes care of it. */
5699 if (b->base_buffer)
5700 continue;
5701
f14b1c68
JB
5702 /* Check for auto save enabled
5703 and file changed since last auto save
5704 and file changed since last real save. */
4b4deea2 5705 if (STRINGP (BVAR (b, auto_save_file_name))
95385625 5706 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
0b5397c2 5707 && BUF_AUTOSAVE_MODIFF (b) < BUF_MODIFF (b)
82c2d839 5708 /* -1 means we've turned off autosaving for a while--see below. */
4b4deea2 5709 && XINT (BVAR (b, save_length)) >= 0
f14b1c68 5710 && (do_handled_files
4b4deea2 5711 || NILP (Ffind_file_name_handler (BVAR (b, auto_save_file_name),
49307295 5712 Qwrite_region))))
f14b1c68 5713 {
e9a9ae03
PE
5714 EMACS_TIME before_time = current_emacs_time ();
5715 EMACS_TIME after_time;
b60247d9
RS
5716
5717 /* If we had a failure, don't try again for 20 minutes. */
d311d28c 5718 if (b->auto_save_failure_time > 0
b60247d9
RS
5719 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5720 continue;
5721
090101cf
CY
5722 set_buffer_internal (b);
5723 if (NILP (Vauto_save_include_big_deletions)
4b4deea2 5724 && (XFASTINT (BVAR (b, save_length)) * 10
4be941e3 5725 > (BUF_Z (b) - BUF_BEG (b)) * 13)
f14b1c68
JB
5726 /* A short file is likely to change a large fraction;
5727 spare the user annoying messages. */
4b4deea2 5728 && XFASTINT (BVAR (b, save_length)) > 5000
f14b1c68 5729 /* These messages are frequent and annoying for `*mail*'. */
4b4deea2 5730 && !EQ (BVAR (b, filename), Qnil)
f14b1c68
JB
5731 && NILP (no_message))
5732 {
5733 /* It has shrunk too much; turn off auto-saving here. */
a8c828be 5734 minibuffer_auto_raise = orig_minibuffer_auto_raise;
fd91d0d4 5735 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
4b4deea2 5736 BVAR (b, name), 1);
a8c828be 5737 minibuffer_auto_raise = 0;
82c2d839
RS
5738 /* Turn off auto-saving until there's a real save,
5739 and prevent any more warnings. */
4b4deea2 5740 XSETINT (BVAR (b, save_length), -1);
f14b1c68
JB
5741 Fsleep_for (make_number (1), Qnil);
5742 continue;
5743 }
f14b1c68
JB
5744 if (!auto_saved && NILP (no_message))
5745 message1 ("Auto-saving...");
5746 internal_condition_case (auto_save_1, Qt, auto_save_error);
f75d7a91 5747 auto_saved = 1;
0b5397c2 5748 BUF_AUTOSAVE_MODIFF (b) = BUF_MODIFF (b);
4b4deea2 5749 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
f14b1c68 5750 set_buffer_internal (old);
b60247d9 5751
e9a9ae03 5752 after_time = current_emacs_time ();
b60247d9
RS
5753
5754 /* If auto-save took more than 60 seconds,
5755 assume it was an NFS failure that got a timeout. */
5756 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5757 b->auto_save_failure_time = EMACS_SECS (after_time);
f14b1c68
JB
5758 }
5759 }
570d7624 5760
b67f2ca5
RS
5761 /* Prevent another auto save till enough input events come in. */
5762 record_auto_save ();
570d7624 5763
17857782 5764 if (auto_saved && NILP (no_message))
f05b275b 5765 {
5794dd61 5766 if (old_message_p)
31f3d831 5767 {
5794dd61
RS
5768 /* If we are going to restore an old message,
5769 give time to read ours. */
83f8d903 5770 sit_for (make_number (1), 0, 0);
c71106e5 5771 restore_message ();
31f3d831 5772 }
ca730bf0 5773 else if (!auto_save_error_occurred)
31e31a15
CY
5774 /* Don't overwrite the error message if an error occurred.
5775 If we displayed a message and then restored a state
5794dd61 5776 with no message, leave a "done" message on the screen. */
f05b275b
KH
5777 message1 ("Auto-saving...done");
5778 }
570d7624 5779
ff4c9993
RS
5780 Vquit_flag = oquit;
5781
5794dd61 5782 /* This restores the message-stack status. */
e54d3b5d 5783 unbind_to (count, Qnil);
570d7624
JB
5784 return Qnil;
5785}
5786
5787DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
8c1a1077
PJ
5788 Sset_buffer_auto_saved, 0, 0, 0,
5789 doc: /* Mark current buffer as auto-saved with its current text.
5790No auto-save file will be written until the buffer changes again. */)
5842a27b 5791 (void)
570d7624 5792{
0b5397c2
SM
5793 /* FIXME: This should not be called in indirect buffers, since
5794 they're not autosaved. */
5795 BUF_AUTOSAVE_MODIFF (current_buffer) = MODIFF;
4b4deea2 5796 XSETFASTINT (BVAR (current_buffer, save_length), Z - BEG);
d311d28c 5797 current_buffer->auto_save_failure_time = 0;
b60247d9
RS
5798 return Qnil;
5799}
5800
5801DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
8c1a1077
PJ
5802 Sclear_buffer_auto_save_failure, 0, 0, 0,
5803 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5842a27b 5804 (void)
b60247d9 5805{
d311d28c 5806 current_buffer->auto_save_failure_time = 0;
570d7624
JB
5807 return Qnil;
5808}
5809
5810DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
8c1a1077 5811 0, 0, 0,
68780e2a
RS
5812 doc: /* Return t if current buffer has been auto-saved recently.
5813More precisely, if it has been auto-saved since last read from or saved
5814in the visited file. If the buffer has no visited file,
5815then any auto-save counts as "recent". */)
5842a27b 5816 (void)
570d7624 5817{
0b5397c2
SM
5818 /* FIXME: maybe we should return nil for indirect buffers since
5819 they're never autosaved. */
5820 return (SAVE_MODIFF < BUF_AUTOSAVE_MODIFF (current_buffer) ? Qt : Qnil);
570d7624
JB
5821}
5822\f
5823/* Reading and completing file names */
6e710ae5 5824
88208bb8
JD
5825DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
5826 Snext_read_file_uses_dialog_p, 0, 0, 0,
5827 doc: /* Return t if a call to `read-file-name' will use a dialog.
5828The return value is only relevant for a call to `read-file-name' that happens
1a0de25c 5829before any other event (mouse or keypress) is handled. */)
5842a27b 5830 (void)
88208bb8 5831{
d7e642cc
JD
5832#if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) \
5833 || defined (HAVE_NS)
88208bb8
JD
5834 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5835 && use_dialog_box
5836 && use_file_dialog
7452b7bd 5837 && window_system_available (SELECTED_FRAME ()))
88208bb8
JD
5838 return Qt;
5839#endif
5840 return Qnil;
5841}
d4a42098 5842
dbd50d4b 5843Lisp_Object
971de7fb 5844Fread_file_name (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object initial, Lisp_Object predicate)
570d7624 5845{
fd4ead52 5846 struct gcpro gcpro1;
dbd50d4b 5847 Lisp_Object args[7];
a79485af 5848
71e1f69d 5849 GCPRO1 (default_filename);
dbd50d4b
SM
5850 args[0] = intern ("read-file-name");
5851 args[1] = prompt;
5852 args[2] = dir;
5853 args[3] = default_filename;
5854 args[4] = mustmatch;
5855 args[5] = initial;
5856 args[6] = predicate;
5857 RETURN_UNGCPRO (Ffuncall (7, args));
570d7624 5858}
9c856db9 5859
570d7624 5860\f
9fe43ff6
PE
5861void
5862init_fileio (void)
5863{
5864 valid_timestamp_file_system = 0;
5865}
5866
dfcf069d 5867void
971de7fb 5868syms_of_fileio (void)
570d7624 5869{
cd3520a4
JB
5870 DEFSYM (Qoperations, "operations");
5871 DEFSYM (Qexpand_file_name, "expand-file-name");
5872 DEFSYM (Qsubstitute_in_file_name, "substitute-in-file-name");
5873 DEFSYM (Qdirectory_file_name, "directory-file-name");
5874 DEFSYM (Qfile_name_directory, "file-name-directory");
5875 DEFSYM (Qfile_name_nondirectory, "file-name-nondirectory");
5876 DEFSYM (Qunhandled_file_name_directory, "unhandled-file-name-directory");
5877 DEFSYM (Qfile_name_as_directory, "file-name-as-directory");
5878 DEFSYM (Qcopy_file, "copy-file");
5879 DEFSYM (Qmake_directory_internal, "make-directory-internal");
5880 DEFSYM (Qmake_directory, "make-directory");
5881 DEFSYM (Qdelete_directory_internal, "delete-directory-internal");
5882 DEFSYM (Qdelete_file, "delete-file");
5883 DEFSYM (Qrename_file, "rename-file");
5884 DEFSYM (Qadd_name_to_file, "add-name-to-file");
5885 DEFSYM (Qmake_symbolic_link, "make-symbolic-link");
5886 DEFSYM (Qfile_exists_p, "file-exists-p");
5887 DEFSYM (Qfile_executable_p, "file-executable-p");
5888 DEFSYM (Qfile_readable_p, "file-readable-p");
5889 DEFSYM (Qfile_writable_p, "file-writable-p");
5890 DEFSYM (Qfile_symlink_p, "file-symlink-p");
5891 DEFSYM (Qaccess_file, "access-file");
5892 DEFSYM (Qfile_directory_p, "file-directory-p");
5893 DEFSYM (Qfile_regular_p, "file-regular-p");
5894 DEFSYM (Qfile_accessible_directory_p, "file-accessible-directory-p");
5895 DEFSYM (Qfile_modes, "file-modes");
5896 DEFSYM (Qset_file_modes, "set-file-modes");
5897 DEFSYM (Qset_file_times, "set-file-times");
5898 DEFSYM (Qfile_selinux_context, "file-selinux-context");
5899 DEFSYM (Qset_file_selinux_context, "set-file-selinux-context");
7c3d167f
RF
5900 DEFSYM (Qfile_acl, "file-acl");
5901 DEFSYM (Qset_file_acl, "set-file-acl");
cd3520a4
JB
5902 DEFSYM (Qfile_newer_than_file_p, "file-newer-than-file-p");
5903 DEFSYM (Qinsert_file_contents, "insert-file-contents");
9dbda100 5904 DEFSYM (Qchoose_write_coding_system, "choose-write-coding-system");
cd3520a4
JB
5905 DEFSYM (Qwrite_region, "write-region");
5906 DEFSYM (Qverify_visited_file_modtime, "verify-visited-file-modtime");
5907 DEFSYM (Qset_visited_file_modtime, "set-visited-file-modtime");
5908 DEFSYM (Qauto_save_coding, "auto-save-coding");
5909
5910 DEFSYM (Qfile_name_history, "file-name-history");
642ef245 5911 Fset (Qfile_name_history, Qnil);
15c65264 5912
cd3520a4
JB
5913 DEFSYM (Qfile_error, "file-error");
5914 DEFSYM (Qfile_already_exists, "file-already-exists");
5915 DEFSYM (Qfile_date_error, "file-date-error");
5916 DEFSYM (Qexcl, "excl");
570d7624 5917
29208e82 5918 DEFVAR_LISP ("file-name-coding-system", Vfile_name_coding_system,
fb7ada5f 5919 doc: /* Coding system for encoding file names.
346ebf53 5920If it is nil, `default-file-name-coding-system' (which see) is used. */);
b1d1b865
RS
5921 Vfile_name_coding_system = Qnil;
5922
cd913586 5923 DEFVAR_LISP ("default-file-name-coding-system",
29208e82 5924 Vdefault_file_name_coding_system,
8c1a1077 5925 doc: /* Default coding system for encoding file names.
346ebf53 5926This variable is used only when `file-name-coding-system' is nil.
8c1a1077 5927
346ebf53 5928This variable is set/changed by the command `set-language-environment'.
8c1a1077 5929User should not set this variable manually,
346ebf53 5930instead use `file-name-coding-system' to get a constant encoding
8c1a1077 5931of file names regardless of the current language environment. */);
cd913586
KH
5932 Vdefault_file_name_coding_system = Qnil;
5933
cd3520a4
JB
5934 DEFSYM (Qformat_decode, "format-decode");
5935 DEFSYM (Qformat_annotate_function, "format-annotate-function");
5936 DEFSYM (Qafter_insert_file_set_coding, "after-insert-file-set-coding");
5937 DEFSYM (Qcar_less_than_car, "car-less-than-car");
d6a3cc15 5938
570d7624 5939 Fput (Qfile_error, Qerror_conditions,
d67b4f80 5940 Fpurecopy (list2 (Qfile_error, Qerror)));
570d7624 5941 Fput (Qfile_error, Qerror_message,
2a0213a6 5942 build_pure_c_string ("File error"));
570d7624
JB
5943
5944 Fput (Qfile_already_exists, Qerror_conditions,
d67b4f80 5945 Fpurecopy (list3 (Qfile_already_exists, Qfile_error, Qerror)));
570d7624 5946 Fput (Qfile_already_exists, Qerror_message,
2a0213a6 5947 build_pure_c_string ("File already exists"));
570d7624 5948
c0b7b21c 5949 Fput (Qfile_date_error, Qerror_conditions,
d67b4f80 5950 Fpurecopy (list3 (Qfile_date_error, Qfile_error, Qerror)));
c0b7b21c 5951 Fput (Qfile_date_error, Qerror_message,
2a0213a6 5952 build_pure_c_string ("Cannot set file date"));
c0b7b21c 5953
29208e82 5954 DEFVAR_LISP ("file-name-handler-alist", Vfile_name_handler_alist,
a59225b1
CY
5955 doc: /* Alist of elements (REGEXP . HANDLER) for file names handled specially.
5956If a file name matches REGEXP, all I/O on that file is done by calling
5957HANDLER. If a file name matches more than one handler, the handler
5958whose match starts last in the file name gets precedence. The
5959function `find-file-name-handler' checks this list for a handler for
5960its argument.
5961
5962HANDLER should be a function. The first argument given to it is the
5963name of the I/O primitive to be handled; the remaining arguments are
5964the arguments that were passed to that primitive. For example, if you
5965do (file-exists-p FILENAME) and FILENAME is handled by HANDLER, then
5966HANDLER is called like this:
5967
5968 (funcall HANDLER 'file-exists-p FILENAME)
5969
5970Note that HANDLER must be able to handle all I/O primitives; if it has
5971nothing special to do for a primitive, it should reinvoke the
5972primitive to handle the operation \"the usual way\".
5973See Info node `(elisp)Magic File Names' for more details. */);
09121adc
RS
5974 Vfile_name_handler_alist = Qnil;
5975
0414b394 5976 DEFVAR_LISP ("set-auto-coding-function",
29208e82 5977 Vset_auto_coding_function,
8c1a1077
PJ
5978 doc: /* If non-nil, a function to call to decide a coding system of file.
5979Two arguments are passed to this function: the file name
5980and the length of a file contents following the point.
5981This function should return a coding system to decode the file contents.
5982It should check the file name against `auto-coding-alist'.
5983If no coding system is decided, it should check a coding system
5984specified in the heading lines with the format:
5985 -*- ... coding: CODING-SYSTEM; ... -*-
5986or local variable spec of the tailing lines with `coding:' tag. */);
0414b394 5987 Vset_auto_coding_function = Qnil;
c9e82392 5988
29208e82 5989 DEFVAR_LISP ("after-insert-file-functions", Vafter_insert_file_functions,
8c1a1077 5990 doc: /* A list of functions to be called at the end of `insert-file-contents'.
0cf9f5b5
RS
5991Each is passed one argument, the number of characters inserted,
5992with point at the start of the inserted text. Each function
5993should leave point the same, and return the new character count.
cf6d2357
RS
5994If `insert-file-contents' is intercepted by a handler from
5995`file-name-handler-alist', that handler is responsible for calling the
5996functions in `after-insert-file-functions' if appropriate. */);
d6a3cc15
RS
5997 Vafter_insert_file_functions = Qnil;
5998
29208e82 5999 DEFVAR_LISP ("write-region-annotate-functions", Vwrite_region_annotate_functions,
8c1a1077
PJ
6000 doc: /* A list of functions to be called at the start of `write-region'.
6001Each is passed two arguments, START and END as for `write-region'.
6002These are usually two numbers but not always; see the documentation
6003for `write-region'. The function should return a list of pairs
6004of the form (POSITION . STRING), consisting of strings to be effectively
6005inserted at the specified positions of the file being written (1 means to
6006insert before the first byte written). The POSITIONs must be sorted into
67fbc0cb
CY
6007increasing order.
6008
6009If there are several annotation functions, the lists returned by these
6010functions are merged destructively. As each annotation function runs,
6011the variable `write-region-annotations-so-far' contains a list of all
6012annotations returned by previous annotation functions.
6013
6014An annotation function can return with a different buffer current.
6015Doing so removes the annotations returned by previous functions, and
6016resets START and END to `point-min' and `point-max' of the new buffer.
6017
6018After `write-region' completes, Emacs calls the function stored in
6019`write-region-post-annotation-function', once for each buffer that was
6020current when building the annotations (i.e., at least once), with that
6021buffer current. */);
d6a3cc15 6022 Vwrite_region_annotate_functions = Qnil;
cd3520a4 6023 DEFSYM (Qwrite_region_annotate_functions, "write-region-annotate-functions");
d6a3cc15 6024
67fbc0cb 6025 DEFVAR_LISP ("write-region-post-annotation-function",
29208e82 6026 Vwrite_region_post_annotation_function,
67fbc0cb
CY
6027 doc: /* Function to call after `write-region' completes.
6028The function is called with no arguments. If one or more of the
6029annotation functions in `write-region-annotate-functions' changed the
6030current buffer, the function stored in this variable is called for
6031each of those additional buffers as well, in addition to the original
6032buffer. The relevant buffer is current during each function call. */);
6033 Vwrite_region_post_annotation_function = Qnil;
6034 staticpro (&Vwrite_region_annotation_buffers);
6035
6fc6f94b 6036 DEFVAR_LISP ("write-region-annotations-so-far",
29208e82 6037 Vwrite_region_annotations_so_far,
8c1a1077
PJ
6038 doc: /* When an annotation function is called, this holds the previous annotations.
6039These are the annotations made by other annotation functions
6040that were already called. See also `write-region-annotate-functions'. */);
6fc6f94b
RS
6041 Vwrite_region_annotations_so_far = Qnil;
6042
29208e82 6043 DEFVAR_LISP ("inhibit-file-name-handlers", Vinhibit_file_name_handlers,
8c1a1077
PJ
6044 doc: /* A list of file name handlers that temporarily should not be used.
6045This applies only to the operation `inhibit-file-name-operation'. */);
82c2d839
RS
6046 Vinhibit_file_name_handlers = Qnil;
6047
29208e82 6048 DEFVAR_LISP ("inhibit-file-name-operation", Vinhibit_file_name_operation,
8c1a1077 6049 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
a65970a0
RS
6050 Vinhibit_file_name_operation = Qnil;
6051
29208e82 6052 DEFVAR_LISP ("auto-save-list-file-name", Vauto_save_list_file_name,
8c1a1077
PJ
6053 doc: /* File name in which we write a list of all auto save file names.
6054This variable is initialized automatically from `auto-save-list-file-prefix'
a2458031 6055shortly after Emacs reads your init file, if you have not yet given it
8c1a1077 6056a non-nil value. */);
e54d3b5d
RS
6057 Vauto_save_list_file_name = Qnil;
6058
29208e82 6059 DEFVAR_LISP ("auto-save-visited-file-name", Vauto_save_visited_file_name,
699b53bc
CY
6060 doc: /* Non-nil says auto-save a buffer in the file it is visiting, when practical.
6061Normally auto-save files are written under other names. */);
6062 Vauto_save_visited_file_name = Qnil;
6063
29208e82 6064 DEFVAR_LISP ("auto-save-include-big-deletions", Vauto_save_include_big_deletions,
090101cf
CY
6065 doc: /* If non-nil, auto-save even if a large part of the text is deleted.
6066If nil, deleting a substantial portion of the text disables auto-save
6067in the buffer; this is the default behavior, because the auto-save
6068file is usually more useful if it contains the deleted text. */);
6069 Vauto_save_include_big_deletions = Qnil;
6070
cbee2131
PE
6071 /* fsync can be a significant performance hit. Often it doesn't
6072 suffice to make the file-save operation survive a crash. For
6073 batch scripts, which are typically part of larger shell commands
6074 that don't fsync other files, its effect on performance can be
6075 significant so its utility is particularly questionable.
6076 Hence, for now by default fsync is used only when interactive.
6077
6078 For more on why fsync often fails to work on today's hardware, see:
6079 Zheng M, Tucek J, Qin F, Lillibridge M. Understanding the
6080 robustness of SSDs under power fault. 11th USENIX Conference on
6081 File and Storage Technologies, 2013 (FAST '13), 271-84
6082 http://www.usenix.org/system/files/conference/fast13/fast13-final80.pdf
6083
6084 For more on why fsync does not suffice even if it works properly, see:
6085 Roche X. Necessary step(s) to synchronize filename operations on disk.
6086 Austin Group Defect 672, 2013-03-19
6087 http://austingroupbugs.net/view.php?id=672 */
29208e82 6088 DEFVAR_BOOL ("write-region-inhibit-fsync", write_region_inhibit_fsync,
fb7ada5f 6089 doc: /* Non-nil means don't call fsync in `write-region'.
e3f509dd 6090This variable affects calls to `write-region' as well as save commands.
cbee2131
PE
6091Setting this to nil may avoid data loss if the system loses power or
6092the operating system crashes. */);
6093 write_region_inhibit_fsync = noninteractive;
ccf61795 6094
29208e82 6095 DEFVAR_BOOL ("delete-by-moving-to-trash", delete_by_moving_to_trash,
6cf29fe8 6096 doc: /* Specifies whether to use the system's trash can.
f1a5d776
CY
6097When non-nil, certain file deletion commands use the function
6098`move-file-to-trash' instead of deleting files outright.
6099This includes interactive calls to `delete-file' and
6100`delete-directory' and the Dired deletion commands. */);
6cf29fe8 6101 delete_by_moving_to_trash = 0;
d67b4f80 6102 Qdelete_by_moving_to_trash = intern_c_string ("delete-by-moving-to-trash");
cd3520a4
JB
6103
6104 DEFSYM (Qmove_file_to_trash, "move-file-to-trash");
6105 DEFSYM (Qcopy_directory, "copy-directory");
6106 DEFSYM (Qdelete_directory, "delete-directory");
6cf29fe8 6107
642ef245 6108 defsubr (&Sfind_file_name_handler);
570d7624
JB
6109 defsubr (&Sfile_name_directory);
6110 defsubr (&Sfile_name_nondirectory);
642ef245 6111 defsubr (&Sunhandled_file_name_directory);
570d7624
JB
6112 defsubr (&Sfile_name_as_directory);
6113 defsubr (&Sdirectory_file_name);
6114 defsubr (&Smake_temp_name);
6115 defsubr (&Sexpand_file_name);
6116 defsubr (&Ssubstitute_in_file_name);
6117 defsubr (&Scopy_file);
9bbe01fb 6118 defsubr (&Smake_directory_internal);
9d8f3bd9 6119 defsubr (&Sdelete_directory_internal);
570d7624
JB
6120 defsubr (&Sdelete_file);
6121 defsubr (&Srename_file);
6122 defsubr (&Sadd_name_to_file);
570d7624 6123 defsubr (&Smake_symbolic_link);
570d7624
JB
6124 defsubr (&Sfile_name_absolute_p);
6125 defsubr (&Sfile_exists_p);
6126 defsubr (&Sfile_executable_p);
6127 defsubr (&Sfile_readable_p);
6128 defsubr (&Sfile_writable_p);
1f8653eb 6129 defsubr (&Saccess_file);
570d7624
JB
6130 defsubr (&Sfile_symlink_p);
6131 defsubr (&Sfile_directory_p);
b72dea2a 6132 defsubr (&Sfile_accessible_directory_p);
f793dc6c 6133 defsubr (&Sfile_regular_p);
570d7624
JB
6134 defsubr (&Sfile_modes);
6135 defsubr (&Sset_file_modes);
819da85b 6136 defsubr (&Sset_file_times);
574c05e2 6137 defsubr (&Sfile_selinux_context);
7c3d167f
RF
6138 defsubr (&Sfile_acl);
6139 defsubr (&Sset_file_acl);
574c05e2 6140 defsubr (&Sset_file_selinux_context);
c24e9a53
RS
6141 defsubr (&Sset_default_file_modes);
6142 defsubr (&Sdefault_file_modes);
570d7624
JB
6143 defsubr (&Sfile_newer_than_file_p);
6144 defsubr (&Sinsert_file_contents);
9dbda100 6145 defsubr (&Schoose_write_coding_system);
570d7624 6146 defsubr (&Swrite_region);
d6a3cc15 6147 defsubr (&Scar_less_than_car);
570d7624
JB
6148 defsubr (&Sverify_visited_file_modtime);
6149 defsubr (&Sclear_visited_file_modtime);
f5d5eccf 6150 defsubr (&Svisited_file_modtime);
570d7624
JB
6151 defsubr (&Sset_visited_file_modtime);
6152 defsubr (&Sdo_auto_save);
6153 defsubr (&Sset_buffer_auto_saved);
b60247d9 6154 defsubr (&Sclear_buffer_auto_save_failure);
570d7624
JB
6155 defsubr (&Srecent_auto_save_p);
6156
88208bb8 6157 defsubr (&Snext_read_file_uses_dialog_p);
85ffea93 6158
697c17a2 6159#ifdef HAVE_SYNC
85ffea93 6160 defsubr (&Sunix_sync);
483a2e10 6161#endif
570d7624 6162}