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