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