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