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