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