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