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