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