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