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