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