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