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