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