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