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