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