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