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