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