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