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