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