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