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