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