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