(Fmake_temp_name): forgot the \n\ in the docstring
[emacs.git] / src / fileio.c
blob39927008d57fe8c9a7d6364f5a78ea92a2b5f44a
1 /* File IO for GNU Emacs.
2 Copyright (C) 1985,86,87,88,93,94,95,96,97,1998 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include <config.h>
23 #if defined (USG5) || defined (BSD_SYSTEM) || defined (LINUX)
24 #include <fcntl.h>
25 #endif
27 #include <stdio.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
35 #ifdef STDC_HEADERS
36 #include <stdlib.h>
37 #endif
39 #if !defined (S_ISLNK) && defined (S_IFLNK)
40 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
41 #endif
43 #if !defined (S_ISFIFO) && defined (S_IFIFO)
44 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
45 #endif
47 #if !defined (S_ISREG) && defined (S_IFREG)
48 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
49 #endif
51 #ifdef VMS
52 #include "vms-pwd.h"
53 #else
54 #include <pwd.h>
55 #endif
57 #include <ctype.h>
59 #ifdef VMS
60 #include "vmsdir.h"
61 #include <perror.h>
62 #include <stddef.h>
63 #include <string.h>
64 #endif
66 #include <errno.h>
68 #ifndef vax11c
69 extern int errno;
70 #endif
72 extern char *strerror ();
74 #ifdef APOLLO
75 #include <sys/time.h>
76 #endif
78 #ifndef USG
79 #ifndef VMS
80 #ifndef BSD4_1
81 #ifndef WINDOWSNT
82 #define HAVE_FSYNC
83 #endif
84 #endif
85 #endif
86 #endif
88 #include "lisp.h"
89 #include "intervals.h"
90 #include "buffer.h"
91 #include "charset.h"
92 #include "coding.h"
93 #include "window.h"
95 #ifdef WINDOWSNT
96 #define NOMINMAX 1
97 #include <windows.h>
98 #include <stdlib.h>
99 #include <fcntl.h>
100 #endif /* not WINDOWSNT */
102 #ifdef MSDOS
103 #include "msdos.h"
104 #include <sys/param.h>
105 #if __DJGPP__ >= 2
106 #include <fcntl.h>
107 #include <string.h>
108 #endif
109 #endif
111 #ifdef DOS_NT
112 #define CORRECT_DIR_SEPS(s) \
113 do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
114 else unixtodos_filename (s); \
115 } while (0)
116 /* On Windows, drive letters must be alphabetic - on DOS, the Netware
117 redirector allows the six letters between 'Z' and 'a' as well. */
118 #ifdef MSDOS
119 #define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
120 #endif
121 #ifdef WINDOWSNT
122 #define IS_DRIVE(x) isalpha (x)
123 #endif
124 /* Need to lower-case the drive letter, or else expanded
125 filenames will sometimes compare inequal, because
126 `expand-file-name' doesn't always down-case the drive letter. */
127 #define DRIVE_LETTER(x) (tolower (x))
128 #endif
130 #ifdef VMS
131 #include <file.h>
132 #include <rmsdef.h>
133 #include <fab.h>
134 #include <nam.h>
135 #endif
137 #include "systime.h"
139 #ifdef HPUX
140 #include <netio.h>
141 #ifndef HPUX8
142 #ifndef HPUX9
143 #include <errnet.h>
144 #endif
145 #endif
146 #endif
148 #include "commands.h"
149 extern int use_dialog_box;
151 #ifndef O_WRONLY
152 #define O_WRONLY 1
153 #endif
155 #ifndef O_RDONLY
156 #define O_RDONLY 0
157 #endif
159 #ifndef S_ISLNK
160 # define lstat stat
161 #endif
163 #define min(a, b) ((a) < (b) ? (a) : (b))
164 #define max(a, b) ((a) > (b) ? (a) : (b))
166 /* Nonzero during writing of auto-save files */
167 int auto_saving;
169 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
170 a new file with the same mode as the original */
171 int auto_save_mode_bits;
173 /* Coding system for file names, or nil if none. */
174 Lisp_Object Vfile_name_coding_system;
176 /* Coding system for file names used only when
177 Vfile_name_coding_system is nil. */
178 Lisp_Object Vdefault_file_name_coding_system;
180 /* Alist of elements (REGEXP . HANDLER) for file names
181 whose I/O is done with a special handler. */
182 Lisp_Object Vfile_name_handler_alist;
184 /* Format for auto-save files */
185 Lisp_Object Vauto_save_file_format;
187 /* Lisp functions for translating file formats */
188 Lisp_Object Qformat_decode, Qformat_annotate_function;
190 /* Function to be called to decide a coding system of a reading file. */
191 Lisp_Object Vset_auto_coding_function;
193 /* Functions to be called to process text properties in inserted file. */
194 Lisp_Object Vafter_insert_file_functions;
196 /* Functions to be called to create text property annotations for file. */
197 Lisp_Object Vwrite_region_annotate_functions;
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;
203 /* File name in which we write a list of all our auto save files. */
204 Lisp_Object Vauto_save_list_file_name;
206 /* Nonzero means, when reading a filename in the minibuffer,
207 start out by inserting the default directory into the minibuffer. */
208 int insert_default_directory;
210 /* On VMS, nonzero means write new files with record format stmlf.
211 Zero means use var format. */
212 int vms_stmlf_recfm;
214 /* On NT, specifies the directory separator character, used (eg.) when
215 expanding file names. This can be bound to / or \. */
216 Lisp_Object Vdirectory_sep_char;
218 extern Lisp_Object Vuser_login_name;
220 #ifdef WINDOWSNT
221 extern Lisp_Object Vw32_get_true_file_attributes;
222 #endif
224 extern int minibuf_level;
226 extern int minibuffer_auto_raise;
228 /* These variables describe handlers that have "already" had a chance
229 to handle the current operation.
231 Vinhibit_file_name_handlers is a list of file name handlers.
232 Vinhibit_file_name_operation is the operation being handled.
233 If we try to handle that operation, we ignore those handlers. */
235 static Lisp_Object Vinhibit_file_name_handlers;
236 static Lisp_Object Vinhibit_file_name_operation;
238 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
239 Lisp_Object Qexcl;
240 Lisp_Object Qfile_name_history;
242 Lisp_Object Qcar_less_than_car;
244 static int a_write P_ ((int, char *, int, int,
245 Lisp_Object *, struct coding_system *));
246 static int e_write P_ ((int, char *, int, struct coding_system *));
248 void
249 report_file_error (string, data)
250 char *string;
251 Lisp_Object data;
253 Lisp_Object errstring;
254 int errorno = errno;
256 errstring = build_string (strerror (errno));
257 while (1)
258 switch (errorno)
260 case EEXIST:
261 Fsignal (Qfile_already_exists, Fcons (errstring, data));
262 break;
263 default:
264 /* System error messages are capitalized. Downcase the initial
265 unless it is followed by a slash. */
266 if (XSTRING (errstring)->data[1] != '/')
267 XSTRING (errstring)->data[0] = DOWNCASE (XSTRING (errstring)->data[0]);
269 Fsignal (Qfile_error,
270 Fcons (build_string (string), Fcons (errstring, data)));
274 Lisp_Object
275 close_file_unwind (fd)
276 Lisp_Object fd;
278 close (XFASTINT (fd));
279 return Qnil;
282 /* Restore point, having saved it as a marker. */
284 static Lisp_Object
285 restore_point_unwind (location)
286 Lisp_Object location;
288 Fgoto_char (location);
289 Fset_marker (location, Qnil, Qnil);
290 return Qnil;
293 Lisp_Object Qexpand_file_name;
294 Lisp_Object Qsubstitute_in_file_name;
295 Lisp_Object Qdirectory_file_name;
296 Lisp_Object Qfile_name_directory;
297 Lisp_Object Qfile_name_nondirectory;
298 Lisp_Object Qunhandled_file_name_directory;
299 Lisp_Object Qfile_name_as_directory;
300 Lisp_Object Qcopy_file;
301 Lisp_Object Qmake_directory_internal;
302 Lisp_Object Qdelete_directory;
303 Lisp_Object Qdelete_file;
304 Lisp_Object Qrename_file;
305 Lisp_Object Qadd_name_to_file;
306 Lisp_Object Qmake_symbolic_link;
307 Lisp_Object Qfile_exists_p;
308 Lisp_Object Qfile_executable_p;
309 Lisp_Object Qfile_readable_p;
310 Lisp_Object Qfile_writable_p;
311 Lisp_Object Qfile_symlink_p;
312 Lisp_Object Qaccess_file;
313 Lisp_Object Qfile_directory_p;
314 Lisp_Object Qfile_regular_p;
315 Lisp_Object Qfile_accessible_directory_p;
316 Lisp_Object Qfile_modes;
317 Lisp_Object Qset_file_modes;
318 Lisp_Object Qfile_newer_than_file_p;
319 Lisp_Object Qinsert_file_contents;
320 Lisp_Object Qwrite_region;
321 Lisp_Object Qverify_visited_file_modtime;
322 Lisp_Object Qset_visited_file_modtime;
324 DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
325 "Return FILENAME's handler function for OPERATION, if it has one.\n\
326 Otherwise, return nil.\n\
327 A file name is handled if one of the regular expressions in\n\
328 `file-name-handler-alist' matches it.\n\n\
329 If OPERATION equals `inhibit-file-name-operation', then we ignore\n\
330 any handlers that are members of `inhibit-file-name-handlers',\n\
331 but we still do run any other handlers. This lets handlers\n\
332 use the standard functions without calling themselves recursively.")
333 (filename, operation)
334 Lisp_Object filename, operation;
336 /* This function must not munge the match data. */
337 Lisp_Object chain, inhibited_handlers;
339 CHECK_STRING (filename, 0);
341 if (EQ (operation, Vinhibit_file_name_operation))
342 inhibited_handlers = Vinhibit_file_name_handlers;
343 else
344 inhibited_handlers = Qnil;
346 for (chain = Vfile_name_handler_alist; CONSP (chain);
347 chain = XCDR (chain))
349 Lisp_Object elt;
350 elt = XCAR (chain);
351 if (CONSP (elt))
353 Lisp_Object string;
354 string = XCAR (elt);
355 if (STRINGP (string) && fast_string_match (string, filename) >= 0)
357 Lisp_Object handler, tem;
359 handler = XCDR (elt);
360 tem = Fmemq (handler, inhibited_handlers);
361 if (NILP (tem))
362 return handler;
366 QUIT;
368 return Qnil;
371 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
372 1, 1, 0,
373 "Return the directory component in file name FILENAME.\n\
374 Return nil if FILENAME does not include a directory.\n\
375 Otherwise return a directory spec.\n\
376 Given a Unix syntax file name, returns a string ending in slash;\n\
377 on VMS, perhaps instead a string ending in `:', `]' or `>'.")
378 (filename)
379 Lisp_Object filename;
381 register unsigned char *beg;
382 register unsigned char *p;
383 Lisp_Object handler;
385 CHECK_STRING (filename, 0);
387 /* If the file name has special constructs in it,
388 call the corresponding file handler. */
389 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
390 if (!NILP (handler))
391 return call2 (handler, Qfile_name_directory, filename);
393 #ifdef FILE_SYSTEM_CASE
394 filename = FILE_SYSTEM_CASE (filename);
395 #endif
396 beg = XSTRING (filename)->data;
397 #ifdef DOS_NT
398 beg = strcpy (alloca (strlen (beg) + 1), beg);
399 #endif
400 p = beg + STRING_BYTES (XSTRING (filename));
402 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
403 #ifdef VMS
404 && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
405 #endif /* VMS */
406 #ifdef DOS_NT
407 /* only recognise drive specifier at the beginning */
408 && !(p[-1] == ':'
409 /* handle the "/:d:foo" and "/:foo" cases correctly */
410 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
411 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
412 #endif
413 ) p--;
415 if (p == beg)
416 return Qnil;
417 #ifdef DOS_NT
418 /* Expansion of "c:" to drive and default directory. */
419 if (p[-1] == ':')
421 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
422 unsigned char *res = alloca (MAXPATHLEN + 1);
423 unsigned char *r = res;
425 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
427 strncpy (res, beg, 2);
428 beg += 2;
429 r += 2;
432 if (getdefdir (toupper (*beg) - 'A' + 1, r))
434 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
435 strcat (res, "/");
436 beg = res;
437 p = beg + strlen (beg);
440 CORRECT_DIR_SEPS (beg);
441 #endif /* DOS_NT */
443 if (STRING_MULTIBYTE (filename))
444 return make_string (beg, p - beg);
445 return make_unibyte_string (beg, p - beg);
448 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
449 Sfile_name_nondirectory, 1, 1, 0,
450 "Return file name FILENAME sans its directory.\n\
451 For example, in a Unix-syntax file name,\n\
452 this is everything after the last slash,\n\
453 or the entire name if it contains no slash.")
454 (filename)
455 Lisp_Object filename;
457 register unsigned char *beg, *p, *end;
458 Lisp_Object handler;
460 CHECK_STRING (filename, 0);
462 /* If the file name has special constructs in it,
463 call the corresponding file handler. */
464 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
465 if (!NILP (handler))
466 return call2 (handler, Qfile_name_nondirectory, filename);
468 beg = XSTRING (filename)->data;
469 end = p = beg + STRING_BYTES (XSTRING (filename));
471 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
472 #ifdef VMS
473 && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
474 #endif /* VMS */
475 #ifdef DOS_NT
476 /* only recognise drive specifier at beginning */
477 && !(p[-1] == ':'
478 /* handle the "/:d:foo" case correctly */
479 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
480 #endif
482 p--;
484 if (STRING_MULTIBYTE (filename))
485 return make_string (p, end - p);
486 return make_unibyte_string (p, end - p);
489 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
490 Sunhandled_file_name_directory, 1, 1, 0,
491 "Return a directly usable directory name somehow associated with FILENAME.\n\
492 A `directly usable' directory name is one that may be used without the\n\
493 intervention of any file handler.\n\
494 If FILENAME is a directly usable file itself, return\n\
495 \(file-name-directory FILENAME).\n\
496 The `call-process' and `start-process' functions use this function to\n\
497 get a current directory to run processes in.")
498 (filename)
499 Lisp_Object filename;
501 Lisp_Object handler;
503 /* If the file name has special constructs in it,
504 call the corresponding file handler. */
505 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
506 if (!NILP (handler))
507 return call2 (handler, Qunhandled_file_name_directory, filename);
509 return Ffile_name_directory (filename);
513 char *
514 file_name_as_directory (out, in)
515 char *out, *in;
517 int size = strlen (in) - 1;
519 strcpy (out, in);
521 if (size < 0)
523 out[0] = '.';
524 out[1] = '/';
525 out[2] = 0;
526 return out;
529 #ifdef VMS
530 /* Is it already a directory string? */
531 if (in[size] == ':' || in[size] == ']' || in[size] == '>')
532 return out;
533 /* Is it a VMS directory file name? If so, hack VMS syntax. */
534 else if (! index (in, '/')
535 && ((size > 3 && ! strcmp (&in[size - 3], ".DIR"))
536 || (size > 3 && ! strcmp (&in[size - 3], ".dir"))
537 || (size > 5 && (! strncmp (&in[size - 5], ".DIR", 4)
538 || ! strncmp (&in[size - 5], ".dir", 4))
539 && (in[size - 1] == '.' || in[size - 1] == ';')
540 && in[size] == '1')))
542 register char *p, *dot;
543 char brack;
545 /* x.dir -> [.x]
546 dir:x.dir --> dir:[x]
547 dir:[x]y.dir --> dir:[x.y] */
548 p = in + size;
549 while (p != in && *p != ':' && *p != '>' && *p != ']') p--;
550 if (p != in)
552 strncpy (out, in, p - in);
553 out[p - in] = '\0';
554 if (*p == ':')
556 brack = ']';
557 strcat (out, ":[");
559 else
561 brack = *p;
562 strcat (out, ".");
564 p++;
566 else
568 brack = ']';
569 strcpy (out, "[.");
571 dot = index (p, '.');
572 if (dot)
574 /* blindly remove any extension */
575 size = strlen (out) + (dot - p);
576 strncat (out, p, dot - p);
578 else
580 strcat (out, p);
581 size = strlen (out);
583 out[size++] = brack;
584 out[size] = '\0';
586 #else /* not VMS */
587 /* For Unix syntax, Append a slash if necessary */
588 if (!IS_DIRECTORY_SEP (out[size]))
590 out[size + 1] = DIRECTORY_SEP;
591 out[size + 2] = '\0';
593 #ifdef DOS_NT
594 CORRECT_DIR_SEPS (out);
595 #endif
596 #endif /* not VMS */
597 return out;
600 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
601 Sfile_name_as_directory, 1, 1, 0,
602 "Return a string representing file FILENAME interpreted as a directory.\n\
603 This operation exists because a directory is also a file, but its name as\n\
604 a directory is different from its name as a file.\n\
605 The result can be used as the value of `default-directory'\n\
606 or passed as second argument to `expand-file-name'.\n\
607 For a Unix-syntax file name, just appends a slash.\n\
608 On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc.")
609 (file)
610 Lisp_Object file;
612 char *buf;
613 Lisp_Object handler;
615 CHECK_STRING (file, 0);
616 if (NILP (file))
617 return Qnil;
619 /* If the file name has special constructs in it,
620 call the corresponding file handler. */
621 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
622 if (!NILP (handler))
623 return call2 (handler, Qfile_name_as_directory, file);
625 buf = (char *) alloca (STRING_BYTES (XSTRING (file)) + 10);
626 return build_string (file_name_as_directory (buf, XSTRING (file)->data));
630 * Convert from directory name to filename.
631 * On VMS:
632 * xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
633 * xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
634 * On UNIX, it's simple: just make sure there isn't a terminating /
636 * Value is nonzero if the string output is different from the input.
640 directory_file_name (src, dst)
641 char *src, *dst;
643 long slen;
644 #ifdef VMS
645 long rlen;
646 char * ptr, * rptr;
647 char bracket;
648 struct FAB fab = cc$rms_fab;
649 struct NAM nam = cc$rms_nam;
650 char esa[NAM$C_MAXRSS];
651 #endif /* VMS */
653 slen = strlen (src);
654 #ifdef VMS
655 if (! index (src, '/')
656 && (src[slen - 1] == ']'
657 || src[slen - 1] == ':'
658 || src[slen - 1] == '>'))
660 /* VMS style - convert [x.y.z] to [x.y]z, [x] to [000000]x */
661 fab.fab$l_fna = src;
662 fab.fab$b_fns = slen;
663 fab.fab$l_nam = &nam;
664 fab.fab$l_fop = FAB$M_NAM;
666 nam.nam$l_esa = esa;
667 nam.nam$b_ess = sizeof esa;
668 nam.nam$b_nop |= NAM$M_SYNCHK;
670 /* We call SYS$PARSE to handle such things as [--] for us. */
671 if (SYS$PARSE (&fab, 0, 0) == RMS$_NORMAL)
673 slen = nam.nam$b_esl;
674 if (esa[slen - 1] == ';' && esa[slen - 2] == '.')
675 slen -= 2;
676 esa[slen] = '\0';
677 src = esa;
679 if (src[slen - 1] != ']' && src[slen - 1] != '>')
681 /* what about when we have logical_name:???? */
682 if (src[slen - 1] == ':')
683 { /* Xlate logical name and see what we get */
684 ptr = strcpy (dst, src); /* upper case for getenv */
685 while (*ptr)
687 if ('a' <= *ptr && *ptr <= 'z')
688 *ptr -= 040;
689 ptr++;
691 dst[slen - 1] = 0; /* remove colon */
692 if (!(src = egetenv (dst)))
693 return 0;
694 /* should we jump to the beginning of this procedure?
695 Good points: allows us to use logical names that xlate
696 to Unix names,
697 Bad points: can be a problem if we just translated to a device
698 name...
699 For now, I'll punt and always expect VMS names, and hope for
700 the best! */
701 slen = strlen (src);
702 if (src[slen - 1] != ']' && src[slen - 1] != '>')
703 { /* no recursion here! */
704 strcpy (dst, src);
705 return 0;
708 else
709 { /* not a directory spec */
710 strcpy (dst, src);
711 return 0;
714 bracket = src[slen - 1];
716 /* If bracket is ']' or '>', bracket - 2 is the corresponding
717 opening bracket. */
718 ptr = index (src, bracket - 2);
719 if (ptr == 0)
720 { /* no opening bracket */
721 strcpy (dst, src);
722 return 0;
724 if (!(rptr = rindex (src, '.')))
725 rptr = ptr;
726 slen = rptr - src;
727 strncpy (dst, src, slen);
728 dst[slen] = '\0';
729 if (*rptr == '.')
731 dst[slen++] = bracket;
732 dst[slen] = '\0';
734 else
736 /* If we have the top-level of a rooted directory (i.e. xx:[000000]),
737 then translate the device and recurse. */
738 if (dst[slen - 1] == ':'
739 && dst[slen - 2] != ':' /* skip decnet nodes */
740 && strcmp (src + slen, "[000000]") == 0)
742 dst[slen - 1] = '\0';
743 if ((ptr = egetenv (dst))
744 && (rlen = strlen (ptr) - 1) > 0
745 && (ptr[rlen] == ']' || ptr[rlen] == '>')
746 && ptr[rlen - 1] == '.')
748 char * buf = (char *) alloca (strlen (ptr) + 1);
749 strcpy (buf, ptr);
750 buf[rlen - 1] = ']';
751 buf[rlen] = '\0';
752 return directory_file_name (buf, dst);
754 else
755 dst[slen - 1] = ':';
757 strcat (dst, "[000000]");
758 slen += 8;
760 rptr++;
761 rlen = strlen (rptr) - 1;
762 strncat (dst, rptr, rlen);
763 dst[slen + rlen] = '\0';
764 strcat (dst, ".DIR.1");
765 return 1;
767 #endif /* VMS */
768 /* Process as Unix format: just remove any final slash.
769 But leave "/" unchanged; do not change it to "". */
770 strcpy (dst, src);
771 #ifdef APOLLO
772 /* Handle // as root for apollo's. */
773 if ((slen > 2 && dst[slen - 1] == '/')
774 || (slen > 1 && dst[0] != '/' && dst[slen - 1] == '/'))
775 dst[slen - 1] = 0;
776 #else
777 if (slen > 1
778 && IS_DIRECTORY_SEP (dst[slen - 1])
779 #ifdef DOS_NT
780 && !IS_ANY_SEP (dst[slen - 2])
781 #endif
783 dst[slen - 1] = 0;
784 #endif
785 #ifdef DOS_NT
786 CORRECT_DIR_SEPS (dst);
787 #endif
788 return 1;
791 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
792 1, 1, 0,
793 "Returns the file name of the directory named DIRECTORY.\n\
794 This is the name of the file that holds the data for the directory DIRECTORY.\n\
795 This operation exists because a directory is also a file, but its name as\n\
796 a directory is different from its name as a file.\n\
797 In Unix-syntax, this function just removes the final slash.\n\
798 On VMS, given a VMS-syntax directory name such as \"[X.Y]\",\n\
799 it returns a file name such as \"[X]Y.DIR.1\".")
800 (directory)
801 Lisp_Object directory;
803 char *buf;
804 Lisp_Object handler;
806 CHECK_STRING (directory, 0);
808 if (NILP (directory))
809 return Qnil;
811 /* If the file name has special constructs in it,
812 call the corresponding file handler. */
813 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
814 if (!NILP (handler))
815 return call2 (handler, Qdirectory_file_name, directory);
817 #ifdef VMS
818 /* 20 extra chars is insufficient for VMS, since we might perform a
819 logical name translation. an equivalence string can be up to 255
820 chars long, so grab that much extra space... - sss */
821 buf = (char *) alloca (STRING_BYTES (XSTRING (directory)) + 20 + 255);
822 #else
823 buf = (char *) alloca (STRING_BYTES (XSTRING (directory)) + 20);
824 #endif
825 directory_file_name (XSTRING (directory)->data, buf);
826 return build_string (buf);
829 static char make_temp_name_tbl[64] =
831 'A','B','C','D','E','F','G','H',
832 'I','J','K','L','M','N','O','P',
833 'Q','R','S','T','U','V','W','X',
834 'Y','Z','a','b','c','d','e','f',
835 'g','h','i','j','k','l','m','n',
836 'o','p','q','r','s','t','u','v',
837 'w','x','y','z','0','1','2','3',
838 '4','5','6','7','8','9','-','_'
840 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
842 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
843 "Generate temporary file name (string) starting with PREFIX (a string).\n\
844 The Emacs process number forms part of the result,\n\
845 so there is no danger of generating a name being used by another process.\n\
847 In addition, this function makes an attempt to choose a name\n\
848 which has no existing file. To make this work,\n\
849 PREFIX should be an absolute file name.\n\
851 There is a race condition between calling `make-temp-name' and creating the\n\
852 file which opens all kinds of security holes. For that reason, you should\n\
853 probably use `make-temp-file' instead.")
854 (prefix)
855 Lisp_Object prefix;
857 Lisp_Object val;
858 int len;
859 int pid;
860 unsigned char *p, *data;
861 char pidbuf[20];
862 int pidlen;
864 CHECK_STRING (prefix, 0);
866 /* VAL is created by adding 6 characters to PREFIX. The first
867 three are the PID of this process, in base 64, and the second
868 three are incremented if the file already exists. This ensures
869 262144 unique file names per PID per PREFIX. */
871 pid = (int) getpid ();
873 #ifdef HAVE_LONG_FILE_NAMES
874 sprintf (pidbuf, "%d", pid);
875 pidlen = strlen (pidbuf);
876 #else
877 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
878 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
879 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
880 pidlen = 3;
881 #endif
883 len = XSTRING (prefix)->size;
884 val = make_uninit_string (len + 3 + pidlen);
885 data = XSTRING (val)->data;
886 bcopy(XSTRING (prefix)->data, data, len);
887 p = data + len;
889 bcopy (pidbuf, p, pidlen);
890 p += pidlen;
892 /* Here we try to minimize useless stat'ing when this function is
893 invoked many times successively with the same PREFIX. We achieve
894 this by initializing count to a random value, and incrementing it
895 afterwards.
897 We don't want make-temp-name to be called while dumping,
898 because then make_temp_name_count_initialized_p would get set
899 and then make_temp_name_count would not be set when Emacs starts. */
901 if (!make_temp_name_count_initialized_p)
903 make_temp_name_count = (unsigned) time (NULL);
904 make_temp_name_count_initialized_p = 1;
907 while (1)
909 struct stat ignored;
910 unsigned num = make_temp_name_count;
912 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
913 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
914 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
916 /* Poor man's congruential RN generator. Replace with
917 ++make_temp_name_count for debugging. */
918 make_temp_name_count += 25229;
919 make_temp_name_count %= 225307;
921 if (stat (data, &ignored) < 0)
923 /* We want to return only if errno is ENOENT. */
924 if (errno == ENOENT)
925 return val;
926 else
927 /* The error here is dubious, but there is little else we
928 can do. The alternatives are to return nil, which is
929 as bad as (and in many cases worse than) throwing the
930 error, or to ignore the error, which will likely result
931 in looping through 225307 stat's, which is not only
932 dog-slow, but also useless since it will fallback to
933 the errow below, anyway. */
934 report_file_error ("Cannot create temporary name for prefix `%s'",
935 Fcons (prefix, Qnil));
936 /* not reached */
940 error ("Cannot create temporary name for prefix `%s'",
941 XSTRING (prefix)->data);
942 return Qnil;
946 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
947 "Convert filename NAME to absolute, and canonicalize it.\n\
948 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative\n\
949 (does not start with slash); if DEFAULT-DIRECTORY is nil or missing,\n\
950 the current buffer's value of default-directory is used.\n\
951 File name components that are `.' are removed, and \n\
952 so are file name components followed by `..', along with the `..' itself;\n\
953 note that these simplifications are done without checking the resulting\n\
954 file names in the file system.\n\
955 An initial `~/' expands to your home directory.\n\
956 An initial `~USER/' expands to USER's home directory.\n\
957 See also the function `substitute-in-file-name'.")
958 (name, default_directory)
959 Lisp_Object name, default_directory;
961 unsigned char *nm;
963 register unsigned char *newdir, *p, *o;
964 int tlen;
965 unsigned char *target;
966 struct passwd *pw;
967 #ifdef VMS
968 unsigned char * colon = 0;
969 unsigned char * close = 0;
970 unsigned char * slash = 0;
971 unsigned char * brack = 0;
972 int lbrack = 0, rbrack = 0;
973 int dots = 0;
974 #endif /* VMS */
975 #ifdef DOS_NT
976 int drive = 0;
977 int collapse_newdir = 1;
978 int is_escaped = 0;
979 #endif /* DOS_NT */
980 int length;
981 Lisp_Object handler;
983 CHECK_STRING (name, 0);
985 /* If the file name has special constructs in it,
986 call the corresponding file handler. */
987 handler = Ffind_file_name_handler (name, Qexpand_file_name);
988 if (!NILP (handler))
989 return call3 (handler, Qexpand_file_name, name, default_directory);
991 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
992 if (NILP (default_directory))
993 default_directory = current_buffer->directory;
994 if (! STRINGP (default_directory))
995 default_directory = build_string ("/");
997 if (!NILP (default_directory))
999 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
1000 if (!NILP (handler))
1001 return call3 (handler, Qexpand_file_name, name, default_directory);
1004 o = XSTRING (default_directory)->data;
1006 /* Make sure DEFAULT_DIRECTORY is properly expanded.
1007 It would be better to do this down below where we actually use
1008 default_directory. Unfortunately, calling Fexpand_file_name recursively
1009 could invoke GC, and the strings might be relocated. This would
1010 be annoying because we have pointers into strings lying around
1011 that would need adjusting, and people would add new pointers to
1012 the code and forget to adjust them, resulting in intermittent bugs.
1013 Putting this call here avoids all that crud.
1015 The EQ test avoids infinite recursion. */
1016 if (! NILP (default_directory) && !EQ (default_directory, name)
1017 /* Save time in some common cases - as long as default_directory
1018 is not relative, it can be canonicalized with name below (if it
1019 is needed at all) without requiring it to be expanded now. */
1020 #ifdef DOS_NT
1021 /* Detect MSDOS file names with drive specifiers. */
1022 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1]) && IS_DIRECTORY_SEP (o[2]))
1023 #ifdef WINDOWSNT
1024 /* Detect Windows file names in UNC format. */
1025 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
1026 #endif
1027 #else /* not DOS_NT */
1028 /* Detect Unix absolute file names (/... alone is not absolute on
1029 DOS or Windows). */
1030 && ! (IS_DIRECTORY_SEP (o[0]))
1031 #endif /* not DOS_NT */
1034 struct gcpro gcpro1;
1036 GCPRO1 (name);
1037 default_directory = Fexpand_file_name (default_directory, Qnil);
1038 UNGCPRO;
1041 #ifdef VMS
1042 /* Filenames on VMS are always upper case. */
1043 name = Fupcase (name);
1044 #endif
1045 #ifdef FILE_SYSTEM_CASE
1046 name = FILE_SYSTEM_CASE (name);
1047 #endif
1049 nm = XSTRING (name)->data;
1051 #ifdef DOS_NT
1052 /* We will force directory separators to be either all \ or /, so make
1053 a local copy to modify, even if there ends up being no change. */
1054 nm = strcpy (alloca (strlen (nm) + 1), nm);
1056 /* Note if special escape prefix is present, but remove for now. */
1057 if (nm[0] == '/' && nm[1] == ':')
1059 is_escaped = 1;
1060 nm += 2;
1063 /* Find and remove drive specifier if present; this makes nm absolute
1064 even if the rest of the name appears to be relative. Only look for
1065 drive specifier at the beginning. */
1066 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
1068 drive = nm[0];
1069 nm += 2;
1072 #ifdef WINDOWSNT
1073 /* If we see "c://somedir", we want to strip the first slash after the
1074 colon when stripping the drive letter. Otherwise, this expands to
1075 "//somedir". */
1076 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1077 nm++;
1078 #endif /* WINDOWSNT */
1079 #endif /* DOS_NT */
1081 #ifdef WINDOWSNT
1082 /* Discard any previous drive specifier if nm is now in UNC format. */
1083 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1085 drive = 0;
1087 #endif
1089 /* If nm is absolute, look for /./ or /../ sequences; if none are
1090 found, we can probably return right away. We will avoid allocating
1091 a new string if name is already fully expanded. */
1092 if (
1093 IS_DIRECTORY_SEP (nm[0])
1094 #ifdef MSDOS
1095 && drive && !is_escaped
1096 #endif
1097 #ifdef WINDOWSNT
1098 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
1099 #endif
1100 #ifdef VMS
1101 || index (nm, ':')
1102 #endif /* VMS */
1105 /* If it turns out that the filename we want to return is just a
1106 suffix of FILENAME, we don't need to go through and edit
1107 things; we just need to construct a new string using data
1108 starting at the middle of FILENAME. If we set lose to a
1109 non-zero value, that means we've discovered that we can't do
1110 that cool trick. */
1111 int lose = 0;
1113 p = nm;
1114 while (*p)
1116 /* Since we know the name is absolute, we can assume that each
1117 element starts with a "/". */
1119 /* "." and ".." are hairy. */
1120 if (IS_DIRECTORY_SEP (p[0])
1121 && p[1] == '.'
1122 && (IS_DIRECTORY_SEP (p[2])
1123 || p[2] == 0
1124 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1125 || p[3] == 0))))
1126 lose = 1;
1127 #ifdef VMS
1128 if (p[0] == '\\')
1129 lose = 1;
1130 if (p[0] == '/') {
1131 /* if dev:[dir]/, move nm to / */
1132 if (!slash && p > nm && (brack || colon)) {
1133 nm = (brack ? brack + 1 : colon + 1);
1134 lbrack = rbrack = 0;
1135 brack = 0;
1136 colon = 0;
1138 slash = p;
1140 if (p[0] == '-')
1141 #ifndef VMS4_4
1142 /* VMS pre V4.4,convert '-'s in filenames. */
1143 if (lbrack == rbrack)
1145 if (dots < 2) /* this is to allow negative version numbers */
1146 p[0] = '_';
1148 else
1149 #endif /* VMS4_4 */
1150 if (lbrack > rbrack &&
1151 ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<') &&
1152 (p[1] == '.' || p[1] == ']' || p[1] == '>')))
1153 lose = 1;
1154 #ifndef VMS4_4
1155 else
1156 p[0] = '_';
1157 #endif /* VMS4_4 */
1158 /* count open brackets, reset close bracket pointer */
1159 if (p[0] == '[' || p[0] == '<')
1160 lbrack++, brack = 0;
1161 /* count close brackets, set close bracket pointer */
1162 if (p[0] == ']' || p[0] == '>')
1163 rbrack++, brack = p;
1164 /* detect ][ or >< */
1165 if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
1166 lose = 1;
1167 if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
1168 nm = p + 1, lose = 1;
1169 if (p[0] == ':' && (colon || slash))
1170 /* if dev1:[dir]dev2:, move nm to dev2: */
1171 if (brack)
1173 nm = brack + 1;
1174 brack = 0;
1176 /* if /name/dev:, move nm to dev: */
1177 else if (slash)
1178 nm = slash + 1;
1179 /* if node::dev:, move colon following dev */
1180 else if (colon && colon[-1] == ':')
1181 colon = p;
1182 /* if dev1:dev2:, move nm to dev2: */
1183 else if (colon && colon[-1] != ':')
1185 nm = colon + 1;
1186 colon = 0;
1188 if (p[0] == ':' && !colon)
1190 if (p[1] == ':')
1191 p++;
1192 colon = p;
1194 if (lbrack == rbrack)
1195 if (p[0] == ';')
1196 dots = 2;
1197 else if (p[0] == '.')
1198 dots++;
1199 #endif /* VMS */
1200 p++;
1202 if (!lose)
1204 #ifdef VMS
1205 if (index (nm, '/'))
1206 return build_string (sys_translate_unix (nm));
1207 #endif /* VMS */
1208 #ifdef DOS_NT
1209 /* Make sure directories are all separated with / or \ as
1210 desired, but avoid allocation of a new string when not
1211 required. */
1212 CORRECT_DIR_SEPS (nm);
1213 #ifdef WINDOWSNT
1214 if (IS_DIRECTORY_SEP (nm[1]))
1216 if (strcmp (nm, XSTRING (name)->data) != 0)
1217 name = build_string (nm);
1219 else
1220 #endif
1221 /* drive must be set, so this is okay */
1222 if (strcmp (nm - 2, XSTRING (name)->data) != 0)
1224 name = make_string (nm - 2, p - nm + 2);
1225 XSTRING (name)->data[0] = DRIVE_LETTER (drive);
1226 XSTRING (name)->data[1] = ':';
1228 return name;
1229 #else /* not DOS_NT */
1230 if (nm == XSTRING (name)->data)
1231 return name;
1232 return build_string (nm);
1233 #endif /* not DOS_NT */
1237 /* At this point, nm might or might not be an absolute file name. We
1238 need to expand ~ or ~user if present, otherwise prefix nm with
1239 default_directory if nm is not absolute, and finally collapse /./
1240 and /foo/../ sequences.
1242 We set newdir to be the appropriate prefix if one is needed:
1243 - the relevant user directory if nm starts with ~ or ~user
1244 - the specified drive's working dir (DOS/NT only) if nm does not
1245 start with /
1246 - the value of default_directory.
1248 Note that these prefixes are not guaranteed to be absolute (except
1249 for the working dir of a drive). Therefore, to ensure we always
1250 return an absolute name, if the final prefix is not absolute we
1251 append it to the current working directory. */
1253 newdir = 0;
1255 if (nm[0] == '~') /* prefix ~ */
1257 if (IS_DIRECTORY_SEP (nm[1])
1258 #ifdef VMS
1259 || nm[1] == ':'
1260 #endif /* VMS */
1261 || nm[1] == 0) /* ~ by itself */
1263 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1264 newdir = (unsigned char *) "";
1265 nm++;
1266 #ifdef DOS_NT
1267 collapse_newdir = 0;
1268 #endif
1269 #ifdef VMS
1270 nm++; /* Don't leave the slash in nm. */
1271 #endif /* VMS */
1273 else /* ~user/filename */
1275 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)
1276 #ifdef VMS
1277 && *p != ':'
1278 #endif /* VMS */
1279 ); p++);
1280 o = (unsigned char *) alloca (p - nm + 1);
1281 bcopy ((char *) nm, o, p - nm);
1282 o [p - nm] = 0;
1284 pw = (struct passwd *) getpwnam (o + 1);
1285 if (pw)
1287 newdir = (unsigned char *) pw -> pw_dir;
1288 #ifdef VMS
1289 nm = p + 1; /* skip the terminator */
1290 #else
1291 nm = p;
1292 #ifdef DOS_NT
1293 collapse_newdir = 0;
1294 #endif
1295 #endif /* VMS */
1298 /* If we don't find a user of that name, leave the name
1299 unchanged; don't move nm forward to p. */
1303 #ifdef DOS_NT
1304 /* On DOS and Windows, nm is absolute if a drive name was specified;
1305 use the drive's current directory as the prefix if needed. */
1306 if (!newdir && drive)
1308 /* Get default directory if needed to make nm absolute. */
1309 if (!IS_DIRECTORY_SEP (nm[0]))
1311 newdir = alloca (MAXPATHLEN + 1);
1312 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1313 newdir = NULL;
1315 if (!newdir)
1317 /* Either nm starts with /, or drive isn't mounted. */
1318 newdir = alloca (4);
1319 newdir[0] = DRIVE_LETTER (drive);
1320 newdir[1] = ':';
1321 newdir[2] = '/';
1322 newdir[3] = 0;
1325 #endif /* DOS_NT */
1327 /* Finally, if no prefix has been specified and nm is not absolute,
1328 then it must be expanded relative to default_directory. */
1330 if (1
1331 #ifndef DOS_NT
1332 /* /... alone is not absolute on DOS and Windows. */
1333 && !IS_DIRECTORY_SEP (nm[0])
1334 #endif
1335 #ifdef WINDOWSNT
1336 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1337 #endif
1338 #ifdef VMS
1339 && !index (nm, ':')
1340 #endif
1341 && !newdir)
1343 newdir = XSTRING (default_directory)->data;
1344 #ifdef DOS_NT
1345 /* Note if special escape prefix is present, but remove for now. */
1346 if (newdir[0] == '/' && newdir[1] == ':')
1348 is_escaped = 1;
1349 newdir += 2;
1351 #endif
1354 #ifdef DOS_NT
1355 if (newdir)
1357 /* First ensure newdir is an absolute name. */
1358 if (
1359 /* Detect MSDOS file names with drive specifiers. */
1360 ! (IS_DRIVE (newdir[0])
1361 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1362 #ifdef WINDOWSNT
1363 /* Detect Windows file names in UNC format. */
1364 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1365 #endif
1368 /* Effectively, let newdir be (expand-file-name newdir cwd).
1369 Because of the admonition against calling expand-file-name
1370 when we have pointers into lisp strings, we accomplish this
1371 indirectly by prepending newdir to nm if necessary, and using
1372 cwd (or the wd of newdir's drive) as the new newdir. */
1374 if (IS_DRIVE (newdir[0]) && newdir[1] == ':')
1376 drive = newdir[0];
1377 newdir += 2;
1379 if (!IS_DIRECTORY_SEP (nm[0]))
1381 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1382 file_name_as_directory (tmp, newdir);
1383 strcat (tmp, nm);
1384 nm = tmp;
1386 newdir = alloca (MAXPATHLEN + 1);
1387 if (drive)
1389 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1390 newdir = "/";
1392 else
1393 getwd (newdir);
1396 /* Strip off drive name from prefix, if present. */
1397 if (IS_DRIVE (newdir[0]) && newdir[1] == ':')
1399 drive = newdir[0];
1400 newdir += 2;
1403 /* Keep only a prefix from newdir if nm starts with slash
1404 (//server/share for UNC, nothing otherwise). */
1405 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1407 #ifdef WINDOWSNT
1408 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1410 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1411 p = newdir + 2;
1412 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1413 p++;
1414 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1415 *p = 0;
1417 else
1418 #endif
1419 newdir = "";
1422 #endif /* DOS_NT */
1424 if (newdir)
1426 /* Get rid of any slash at the end of newdir, unless newdir is
1427 just / or // (an incomplete UNC name). */
1428 length = strlen (newdir);
1429 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1430 #ifdef WINDOWSNT
1431 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1432 #endif
1435 unsigned char *temp = (unsigned char *) alloca (length);
1436 bcopy (newdir, temp, length - 1);
1437 temp[length - 1] = 0;
1438 newdir = temp;
1440 tlen = length + 1;
1442 else
1443 tlen = 0;
1445 /* Now concatenate the directory and name to new space in the stack frame */
1446 tlen += strlen (nm) + 1;
1447 #ifdef DOS_NT
1448 /* Reserve space for drive specifier and escape prefix, since either
1449 or both may need to be inserted. (The Microsoft x86 compiler
1450 produces incorrect code if the following two lines are combined.) */
1451 target = (unsigned char *) alloca (tlen + 4);
1452 target += 4;
1453 #else /* not DOS_NT */
1454 target = (unsigned char *) alloca (tlen);
1455 #endif /* not DOS_NT */
1456 *target = 0;
1458 if (newdir)
1460 #ifndef VMS
1461 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1463 #ifdef DOS_NT
1464 /* If newdir is effectively "C:/", then the drive letter will have
1465 been stripped and newdir will be "/". Concatenating with an
1466 absolute directory in nm produces "//", which will then be
1467 incorrectly treated as a network share. Ignore newdir in
1468 this case (keeping the drive letter). */
1469 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1470 && newdir[1] == '\0'))
1471 #endif
1472 strcpy (target, newdir);
1474 else
1475 #endif
1476 file_name_as_directory (target, newdir);
1479 strcat (target, nm);
1480 #ifdef VMS
1481 if (index (target, '/'))
1482 strcpy (target, sys_translate_unix (target));
1483 #endif /* VMS */
1485 /* ASSERT (IS_DIRECTORY_SEP (target[0])) if not VMS */
1487 /* Now canonicalize by removing /. and /foo/.. if they appear. */
1489 p = target;
1490 o = target;
1492 while (*p)
1494 #ifdef VMS
1495 if (*p != ']' && *p != '>' && *p != '-')
1497 if (*p == '\\')
1498 p++;
1499 *o++ = *p++;
1501 else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
1502 /* brackets are offset from each other by 2 */
1504 p += 2;
1505 if (*p != '.' && *p != '-' && o[-1] != '.')
1506 /* convert [foo][bar] to [bar] */
1507 while (o[-1] != '[' && o[-1] != '<')
1508 o--;
1509 else if (*p == '-' && *o != '.')
1510 *--p = '.';
1512 else if (p[0] == '-' && o[-1] == '.' &&
1513 (p[1] == '.' || p[1] == ']' || p[1] == '>'))
1514 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1517 o--;
1518 while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
1519 if (p[1] == '.') /* foo.-.bar ==> bar. */
1520 p += 2;
1521 else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
1522 p++, o--;
1523 /* else [foo.-] ==> [-] */
1525 else
1527 #ifndef VMS4_4
1528 if (*p == '-' &&
1529 o[-1] != '[' && o[-1] != '<' && o[-1] != '.' &&
1530 p[1] != ']' && p[1] != '>' && p[1] != '.')
1531 *p = '_';
1532 #endif /* VMS4_4 */
1533 *o++ = *p++;
1535 #else /* not VMS */
1536 if (!IS_DIRECTORY_SEP (*p))
1538 *o++ = *p++;
1540 else if (IS_DIRECTORY_SEP (p[0])
1541 && p[1] == '.'
1542 && (IS_DIRECTORY_SEP (p[2])
1543 || p[2] == 0))
1545 /* If "/." is the entire filename, keep the "/". Otherwise,
1546 just delete the whole "/.". */
1547 if (o == target && p[2] == '\0')
1548 *o++ = *p;
1549 p += 2;
1551 else if (IS_DIRECTORY_SEP (p[0]) && p[1] == '.' && p[2] == '.'
1552 /* `/../' is the "superroot" on certain file systems. */
1553 && o != target
1554 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1556 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1558 /* Keep initial / only if this is the whole name. */
1559 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1560 ++o;
1561 p += 3;
1563 else
1565 *o++ = *p++;
1567 #endif /* not VMS */
1570 #ifdef DOS_NT
1571 /* At last, set drive name. */
1572 #ifdef WINDOWSNT
1573 /* Except for network file name. */
1574 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1575 #endif /* WINDOWSNT */
1577 if (!drive) abort ();
1578 target -= 2;
1579 target[0] = DRIVE_LETTER (drive);
1580 target[1] = ':';
1582 /* Reinsert the escape prefix if required. */
1583 if (is_escaped)
1585 target -= 2;
1586 target[0] = '/';
1587 target[1] = ':';
1589 CORRECT_DIR_SEPS (target);
1590 #endif /* DOS_NT */
1592 return make_string (target, o - target);
1595 #if 0
1596 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1597 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1598 "Convert FILENAME to absolute, and canonicalize it.\n\
1599 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1600 (does not start with slash); if DEFAULT is nil or missing,\n\
1601 the current buffer's value of default-directory is used.\n\
1602 Filenames containing `.' or `..' as components are simplified;\n\
1603 initial `~/' expands to your home directory.\n\
1604 See also the function `substitute-in-file-name'.")
1605 (name, defalt)
1606 Lisp_Object name, defalt;
1608 unsigned char *nm;
1610 register unsigned char *newdir, *p, *o;
1611 int tlen;
1612 unsigned char *target;
1613 struct passwd *pw;
1614 int lose;
1615 #ifdef VMS
1616 unsigned char * colon = 0;
1617 unsigned char * close = 0;
1618 unsigned char * slash = 0;
1619 unsigned char * brack = 0;
1620 int lbrack = 0, rbrack = 0;
1621 int dots = 0;
1622 #endif /* VMS */
1624 CHECK_STRING (name, 0);
1626 #ifdef VMS
1627 /* Filenames on VMS are always upper case. */
1628 name = Fupcase (name);
1629 #endif
1631 nm = XSTRING (name)->data;
1633 /* If nm is absolute, flush ...// and detect /./ and /../.
1634 If no /./ or /../ we can return right away. */
1635 if (
1636 nm[0] == '/'
1637 #ifdef VMS
1638 || index (nm, ':')
1639 #endif /* VMS */
1642 p = nm;
1643 lose = 0;
1644 while (*p)
1646 if (p[0] == '/' && p[1] == '/'
1647 #ifdef APOLLO
1648 /* // at start of filename is meaningful on Apollo system. */
1649 && nm != p
1650 #endif /* APOLLO */
1652 nm = p + 1;
1653 if (p[0] == '/' && p[1] == '~')
1654 nm = p + 1, lose = 1;
1655 if (p[0] == '/' && p[1] == '.'
1656 && (p[2] == '/' || p[2] == 0
1657 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1658 lose = 1;
1659 #ifdef VMS
1660 if (p[0] == '\\')
1661 lose = 1;
1662 if (p[0] == '/') {
1663 /* if dev:[dir]/, move nm to / */
1664 if (!slash && p > nm && (brack || colon)) {
1665 nm = (brack ? brack + 1 : colon + 1);
1666 lbrack = rbrack = 0;
1667 brack = 0;
1668 colon = 0;
1670 slash = p;
1672 if (p[0] == '-')
1673 #ifndef VMS4_4
1674 /* VMS pre V4.4,convert '-'s in filenames. */
1675 if (lbrack == rbrack)
1677 if (dots < 2) /* this is to allow negative version numbers */
1678 p[0] = '_';
1680 else
1681 #endif /* VMS4_4 */
1682 if (lbrack > rbrack &&
1683 ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<') &&
1684 (p[1] == '.' || p[1] == ']' || p[1] == '>')))
1685 lose = 1;
1686 #ifndef VMS4_4
1687 else
1688 p[0] = '_';
1689 #endif /* VMS4_4 */
1690 /* count open brackets, reset close bracket pointer */
1691 if (p[0] == '[' || p[0] == '<')
1692 lbrack++, brack = 0;
1693 /* count close brackets, set close bracket pointer */
1694 if (p[0] == ']' || p[0] == '>')
1695 rbrack++, brack = p;
1696 /* detect ][ or >< */
1697 if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
1698 lose = 1;
1699 if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
1700 nm = p + 1, lose = 1;
1701 if (p[0] == ':' && (colon || slash))
1702 /* if dev1:[dir]dev2:, move nm to dev2: */
1703 if (brack)
1705 nm = brack + 1;
1706 brack = 0;
1708 /* If /name/dev:, move nm to dev: */
1709 else if (slash)
1710 nm = slash + 1;
1711 /* If node::dev:, move colon following dev */
1712 else if (colon && colon[-1] == ':')
1713 colon = p;
1714 /* If dev1:dev2:, move nm to dev2: */
1715 else if (colon && colon[-1] != ':')
1717 nm = colon + 1;
1718 colon = 0;
1720 if (p[0] == ':' && !colon)
1722 if (p[1] == ':')
1723 p++;
1724 colon = p;
1726 if (lbrack == rbrack)
1727 if (p[0] == ';')
1728 dots = 2;
1729 else if (p[0] == '.')
1730 dots++;
1731 #endif /* VMS */
1732 p++;
1734 if (!lose)
1736 #ifdef VMS
1737 if (index (nm, '/'))
1738 return build_string (sys_translate_unix (nm));
1739 #endif /* VMS */
1740 if (nm == XSTRING (name)->data)
1741 return name;
1742 return build_string (nm);
1746 /* Now determine directory to start with and put it in NEWDIR */
1748 newdir = 0;
1750 if (nm[0] == '~') /* prefix ~ */
1751 if (nm[1] == '/'
1752 #ifdef VMS
1753 || nm[1] == ':'
1754 #endif /* VMS */
1755 || nm[1] == 0)/* ~/filename */
1757 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1758 newdir = (unsigned char *) "";
1759 nm++;
1760 #ifdef VMS
1761 nm++; /* Don't leave the slash in nm. */
1762 #endif /* VMS */
1764 else /* ~user/filename */
1766 /* Get past ~ to user */
1767 unsigned char *user = nm + 1;
1768 /* Find end of name. */
1769 unsigned char *ptr = (unsigned char *) index (user, '/');
1770 int len = ptr ? ptr - user : strlen (user);
1771 #ifdef VMS
1772 unsigned char *ptr1 = index (user, ':');
1773 if (ptr1 != 0 && ptr1 - user < len)
1774 len = ptr1 - user;
1775 #endif /* VMS */
1776 /* Copy the user name into temp storage. */
1777 o = (unsigned char *) alloca (len + 1);
1778 bcopy ((char *) user, o, len);
1779 o[len] = 0;
1781 /* Look up the user name. */
1782 pw = (struct passwd *) getpwnam (o + 1);
1783 if (!pw)
1784 error ("\"%s\" isn't a registered user", o + 1);
1786 newdir = (unsigned char *) pw->pw_dir;
1788 /* Discard the user name from NM. */
1789 nm += len;
1792 if (nm[0] != '/'
1793 #ifdef VMS
1794 && !index (nm, ':')
1795 #endif /* not VMS */
1796 && !newdir)
1798 if (NILP (defalt))
1799 defalt = current_buffer->directory;
1800 CHECK_STRING (defalt, 1);
1801 newdir = XSTRING (defalt)->data;
1804 /* Now concatenate the directory and name to new space in the stack frame */
1806 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1807 target = (unsigned char *) alloca (tlen);
1808 *target = 0;
1810 if (newdir)
1812 #ifndef VMS
1813 if (nm[0] == 0 || nm[0] == '/')
1814 strcpy (target, newdir);
1815 else
1816 #endif
1817 file_name_as_directory (target, newdir);
1820 strcat (target, nm);
1821 #ifdef VMS
1822 if (index (target, '/'))
1823 strcpy (target, sys_translate_unix (target));
1824 #endif /* VMS */
1826 /* Now canonicalize by removing /. and /foo/.. if they appear */
1828 p = target;
1829 o = target;
1831 while (*p)
1833 #ifdef VMS
1834 if (*p != ']' && *p != '>' && *p != '-')
1836 if (*p == '\\')
1837 p++;
1838 *o++ = *p++;
1840 else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
1841 /* brackets are offset from each other by 2 */
1843 p += 2;
1844 if (*p != '.' && *p != '-' && o[-1] != '.')
1845 /* convert [foo][bar] to [bar] */
1846 while (o[-1] != '[' && o[-1] != '<')
1847 o--;
1848 else if (*p == '-' && *o != '.')
1849 *--p = '.';
1851 else if (p[0] == '-' && o[-1] == '.' &&
1852 (p[1] == '.' || p[1] == ']' || p[1] == '>'))
1853 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1856 o--;
1857 while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
1858 if (p[1] == '.') /* foo.-.bar ==> bar. */
1859 p += 2;
1860 else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
1861 p++, o--;
1862 /* else [foo.-] ==> [-] */
1864 else
1866 #ifndef VMS4_4
1867 if (*p == '-' &&
1868 o[-1] != '[' && o[-1] != '<' && o[-1] != '.' &&
1869 p[1] != ']' && p[1] != '>' && p[1] != '.')
1870 *p = '_';
1871 #endif /* VMS4_4 */
1872 *o++ = *p++;
1874 #else /* not VMS */
1875 if (*p != '/')
1877 *o++ = *p++;
1879 else if (!strncmp (p, "//", 2)
1880 #ifdef APOLLO
1881 /* // at start of filename is meaningful in Apollo system. */
1882 && o != target
1883 #endif /* APOLLO */
1886 o = target;
1887 p++;
1889 else if (p[0] == '/' && p[1] == '.' &&
1890 (p[2] == '/' || p[2] == 0))
1891 p += 2;
1892 else if (!strncmp (p, "/..", 3)
1893 /* `/../' is the "superroot" on certain file systems. */
1894 && o != target
1895 && (p[3] == '/' || p[3] == 0))
1897 while (o != target && *--o != '/')
1899 #ifdef APOLLO
1900 if (o == target + 1 && o[-1] == '/' && o[0] == '/')
1901 ++o;
1902 else
1903 #endif /* APOLLO */
1904 if (o == target && *o == '/')
1905 ++o;
1906 p += 3;
1908 else
1910 *o++ = *p++;
1912 #endif /* not VMS */
1915 return make_string (target, o - target);
1917 #endif
1919 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
1920 Ssubstitute_in_file_name, 1, 1, 0,
1921 "Substitute environment variables referred to in FILENAME.\n\
1922 `$FOO' where FOO is an environment variable name means to substitute\n\
1923 the value of that variable. The variable name should be terminated\n\
1924 with a character not a letter, digit or underscore; otherwise, enclose\n\
1925 the entire variable name in braces.\n\
1926 If `/~' appears, all of FILENAME through that `/' is discarded.\n\n\
1927 On VMS, `$' substitution is not done; this function does little and only\n\
1928 duplicates what `expand-file-name' does.")
1929 (filename)
1930 Lisp_Object filename;
1932 unsigned char *nm;
1934 register unsigned char *s, *p, *o, *x, *endp;
1935 unsigned char *target;
1936 int total = 0;
1937 int substituted = 0;
1938 unsigned char *xnm;
1939 Lisp_Object handler;
1941 CHECK_STRING (filename, 0);
1943 /* If the file name has special constructs in it,
1944 call the corresponding file handler. */
1945 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
1946 if (!NILP (handler))
1947 return call2 (handler, Qsubstitute_in_file_name, filename);
1949 nm = XSTRING (filename)->data;
1950 #ifdef DOS_NT
1951 nm = strcpy (alloca (strlen (nm) + 1), nm);
1952 CORRECT_DIR_SEPS (nm);
1953 substituted = (strcmp (nm, XSTRING (filename)->data) != 0);
1954 #endif
1955 endp = nm + STRING_BYTES (XSTRING (filename));
1957 /* If /~ or // appears, discard everything through first slash. */
1959 for (p = nm; p != endp; p++)
1961 if ((p[0] == '~'
1962 #if defined (APOLLO) || defined (WINDOWSNT)
1963 /* // at start of file name is meaningful in Apollo and
1964 WindowsNT systems. */
1965 || (IS_DIRECTORY_SEP (p[0]) && p - 1 != nm)
1966 #else /* not (APOLLO || WINDOWSNT) */
1967 || IS_DIRECTORY_SEP (p[0])
1968 #endif /* not (APOLLO || WINDOWSNT) */
1970 && p != nm
1971 && (0
1972 #ifdef VMS
1973 || p[-1] == ':' || p[-1] == ']' || p[-1] == '>'
1974 #endif /* VMS */
1975 || IS_DIRECTORY_SEP (p[-1])))
1977 nm = p;
1978 substituted = 1;
1980 #ifdef DOS_NT
1981 /* see comment in expand-file-name about drive specifiers */
1982 else if (IS_DRIVE (p[0]) && p[1] == ':'
1983 && p > nm && IS_DIRECTORY_SEP (p[-1]))
1985 nm = p;
1986 substituted = 1;
1988 #endif /* DOS_NT */
1991 #ifdef VMS
1992 return build_string (nm);
1993 #else
1995 /* See if any variables are substituted into the string
1996 and find the total length of their values in `total' */
1998 for (p = nm; p != endp;)
1999 if (*p != '$')
2000 p++;
2001 else
2003 p++;
2004 if (p == endp)
2005 goto badsubst;
2006 else if (*p == '$')
2008 /* "$$" means a single "$" */
2009 p++;
2010 total -= 1;
2011 substituted = 1;
2012 continue;
2014 else if (*p == '{')
2016 o = ++p;
2017 while (p != endp && *p != '}') p++;
2018 if (*p != '}') goto missingclose;
2019 s = p;
2021 else
2023 o = p;
2024 while (p != endp && (isalnum (*p) || *p == '_')) p++;
2025 s = p;
2028 /* Copy out the variable name */
2029 target = (unsigned char *) alloca (s - o + 1);
2030 strncpy (target, o, s - o);
2031 target[s - o] = 0;
2032 #ifdef DOS_NT
2033 strupr (target); /* $home == $HOME etc. */
2034 #endif /* DOS_NT */
2036 /* Get variable value */
2037 o = (unsigned char *) egetenv (target);
2038 if (!o) goto badvar;
2039 total += strlen (o);
2040 substituted = 1;
2043 if (!substituted)
2044 return filename;
2046 /* If substitution required, recopy the string and do it */
2047 /* Make space in stack frame for the new copy */
2048 xnm = (unsigned char *) alloca (STRING_BYTES (XSTRING (filename)) + total + 1);
2049 x = xnm;
2051 /* Copy the rest of the name through, replacing $ constructs with values */
2052 for (p = nm; *p;)
2053 if (*p != '$')
2054 *x++ = *p++;
2055 else
2057 p++;
2058 if (p == endp)
2059 goto badsubst;
2060 else if (*p == '$')
2062 *x++ = *p++;
2063 continue;
2065 else if (*p == '{')
2067 o = ++p;
2068 while (p != endp && *p != '}') p++;
2069 if (*p != '}') goto missingclose;
2070 s = p++;
2072 else
2074 o = p;
2075 while (p != endp && (isalnum (*p) || *p == '_')) p++;
2076 s = p;
2079 /* Copy out the variable name */
2080 target = (unsigned char *) alloca (s - o + 1);
2081 strncpy (target, o, s - o);
2082 target[s - o] = 0;
2083 #ifdef DOS_NT
2084 strupr (target); /* $home == $HOME etc. */
2085 #endif /* DOS_NT */
2087 /* Get variable value */
2088 o = (unsigned char *) egetenv (target);
2089 if (!o)
2090 goto badvar;
2092 if (STRING_MULTIBYTE (filename))
2094 /* If the original string is multibyte,
2095 convert what we substitute into multibyte. */
2096 unsigned char workbuf[4], *str;
2097 int len;
2099 while (*o)
2101 int c = *o++;
2102 c = unibyte_char_to_multibyte (c);
2103 if (! SINGLE_BYTE_CHAR_P (c))
2105 len = CHAR_STRING (c, workbuf, str);
2106 bcopy (str, x, len);
2107 x += len;
2109 else
2110 *x++ = c;
2113 else
2115 strcpy (x, o);
2116 x += strlen (o);
2120 *x = 0;
2122 /* If /~ or // appears, discard everything through first slash. */
2124 for (p = xnm; p != x; p++)
2125 if ((p[0] == '~'
2126 #if defined (APOLLO) || defined (WINDOWSNT)
2127 || (IS_DIRECTORY_SEP (p[0]) && p - 1 != xnm)
2128 #else /* not (APOLLO || WINDOWSNT) */
2129 || IS_DIRECTORY_SEP (p[0])
2130 #endif /* not (APOLLO || WINDOWSNT) */
2132 && p != xnm && IS_DIRECTORY_SEP (p[-1]))
2133 xnm = p;
2134 #ifdef DOS_NT
2135 else if (IS_DRIVE (p[0]) && p[1] == ':'
2136 && p > xnm && IS_DIRECTORY_SEP (p[-1]))
2137 xnm = p;
2138 #endif
2140 if (STRING_MULTIBYTE (filename))
2141 return make_string (xnm, x - xnm);
2142 return make_unibyte_string (xnm, x - xnm);
2144 badsubst:
2145 error ("Bad format environment-variable substitution");
2146 missingclose:
2147 error ("Missing \"}\" in environment-variable substitution");
2148 badvar:
2149 error ("Substituting nonexistent environment variable \"%s\"", target);
2151 /* NOTREACHED */
2152 #endif /* not VMS */
2155 /* A slightly faster and more convenient way to get
2156 (directory-file-name (expand-file-name FOO)). */
2158 Lisp_Object
2159 expand_and_dir_to_file (filename, defdir)
2160 Lisp_Object filename, defdir;
2162 register Lisp_Object absname;
2164 absname = Fexpand_file_name (filename, defdir);
2165 #ifdef VMS
2167 register int c = XSTRING (absname)->data[STRING_BYTES (XSTRING (absname)) - 1];
2168 if (c == ':' || c == ']' || c == '>')
2169 absname = Fdirectory_file_name (absname);
2171 #else
2172 /* Remove final slash, if any (unless this is the root dir).
2173 stat behaves differently depending! */
2174 if (XSTRING (absname)->size > 1
2175 && IS_DIRECTORY_SEP (XSTRING (absname)->data[STRING_BYTES (XSTRING (absname)) - 1])
2176 && !IS_DEVICE_SEP (XSTRING (absname)->data[STRING_BYTES (XSTRING (absname))-2]))
2177 /* We cannot take shortcuts; they might be wrong for magic file names. */
2178 absname = Fdirectory_file_name (absname);
2179 #endif
2180 return absname;
2183 /* Signal an error if the file ABSNAME already exists.
2184 If INTERACTIVE is nonzero, ask the user whether to proceed,
2185 and bypass the error if the user says to go ahead.
2186 QUERYSTRING is a name for the action that is being considered
2187 to alter the file.
2189 *STATPTR is used to store the stat information if the file exists.
2190 If the file does not exist, STATPTR->st_mode is set to 0.
2191 If STATPTR is null, we don't store into it.
2193 If QUICK is nonzero, we ask for y or n, not yes or no. */
2195 void
2196 barf_or_query_if_file_exists (absname, querystring, interactive, statptr, quick)
2197 Lisp_Object absname;
2198 unsigned char *querystring;
2199 int interactive;
2200 struct stat *statptr;
2201 int quick;
2203 register Lisp_Object tem, encoded_filename;
2204 struct stat statbuf;
2205 struct gcpro gcpro1;
2207 encoded_filename = ENCODE_FILE (absname);
2209 /* stat is a good way to tell whether the file exists,
2210 regardless of what access permissions it has. */
2211 if (stat (XSTRING (encoded_filename)->data, &statbuf) >= 0)
2213 if (! interactive)
2214 Fsignal (Qfile_already_exists,
2215 Fcons (build_string ("File already exists"),
2216 Fcons (absname, Qnil)));
2217 GCPRO1 (absname);
2218 tem = format1 ("File %s already exists; %s anyway? ",
2219 XSTRING (absname)->data, querystring);
2220 if (quick)
2221 tem = Fy_or_n_p (tem);
2222 else
2223 tem = do_yes_or_no_p (tem);
2224 UNGCPRO;
2225 if (NILP (tem))
2226 Fsignal (Qfile_already_exists,
2227 Fcons (build_string ("File already exists"),
2228 Fcons (absname, Qnil)));
2229 if (statptr)
2230 *statptr = statbuf;
2232 else
2234 if (statptr)
2235 statptr->st_mode = 0;
2237 return;
2240 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 4,
2241 "fCopy file: \nFCopy %s to file: \np\nP",
2242 "Copy FILE to NEWNAME. Both args must be strings.\n\
2243 Signals a `file-already-exists' error if file NEWNAME already exists,\n\
2244 unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.\n\
2245 A number as third arg means request confirmation if NEWNAME already exists.\n\
2246 This is what happens in interactive use with M-x.\n\
2247 Fourth arg KEEP-TIME non-nil means give the new file the same\n\
2248 last-modified time as the old one. (This works on only some systems.)\n\
2249 A prefix arg makes KEEP-TIME non-nil.")
2250 (file, newname, ok_if_already_exists, keep_date)
2251 Lisp_Object file, newname, ok_if_already_exists, keep_date;
2253 int ifd, ofd, n;
2254 char buf[16 * 1024];
2255 struct stat st, out_st;
2256 Lisp_Object handler;
2257 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2258 int count = specpdl_ptr - specpdl;
2259 int input_file_statable_p;
2260 Lisp_Object encoded_file, encoded_newname;
2262 encoded_file = encoded_newname = Qnil;
2263 GCPRO4 (file, newname, encoded_file, encoded_newname);
2264 CHECK_STRING (file, 0);
2265 CHECK_STRING (newname, 1);
2267 file = Fexpand_file_name (file, Qnil);
2268 newname = Fexpand_file_name (newname, Qnil);
2270 /* If the input file name has special constructs in it,
2271 call the corresponding file handler. */
2272 handler = Ffind_file_name_handler (file, Qcopy_file);
2273 /* Likewise for output file name. */
2274 if (NILP (handler))
2275 handler = Ffind_file_name_handler (newname, Qcopy_file);
2276 if (!NILP (handler))
2277 RETURN_UNGCPRO (call5 (handler, Qcopy_file, file, newname,
2278 ok_if_already_exists, keep_date));
2280 encoded_file = ENCODE_FILE (file);
2281 encoded_newname = ENCODE_FILE (newname);
2283 if (NILP (ok_if_already_exists)
2284 || INTEGERP (ok_if_already_exists))
2285 barf_or_query_if_file_exists (encoded_newname, "copy to it",
2286 INTEGERP (ok_if_already_exists), &out_st, 0);
2287 else if (stat (XSTRING (encoded_newname)->data, &out_st) < 0)
2288 out_st.st_mode = 0;
2290 ifd = open (XSTRING (encoded_file)->data, O_RDONLY);
2291 if (ifd < 0)
2292 report_file_error ("Opening input file", Fcons (file, Qnil));
2294 record_unwind_protect (close_file_unwind, make_number (ifd));
2296 /* We can only copy regular files and symbolic links. Other files are not
2297 copyable by us. */
2298 input_file_statable_p = (fstat (ifd, &st) >= 0);
2300 #if !defined (DOS_NT) || __DJGPP__ > 1
2301 if (out_st.st_mode != 0
2302 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2304 errno = 0;
2305 report_file_error ("Input and output files are the same",
2306 Fcons (file, Fcons (newname, Qnil)));
2308 #endif
2310 #if defined (S_ISREG) && defined (S_ISLNK)
2311 if (input_file_statable_p)
2313 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
2315 #if defined (EISDIR)
2316 /* Get a better looking error message. */
2317 errno = EISDIR;
2318 #endif /* EISDIR */
2319 report_file_error ("Non-regular file", Fcons (file, Qnil));
2322 #endif /* S_ISREG && S_ISLNK */
2324 #ifdef VMS
2325 /* Create the copy file with the same record format as the input file */
2326 ofd = sys_creat (XSTRING (encoded_newname)->data, 0666, ifd);
2327 #else
2328 #ifdef MSDOS
2329 /* System's default file type was set to binary by _fmode in emacs.c. */
2330 ofd = creat (XSTRING (encoded_newname)->data, S_IREAD | S_IWRITE);
2331 #else /* not MSDOS */
2332 ofd = creat (XSTRING (encoded_newname)->data, 0666);
2333 #endif /* not MSDOS */
2334 #endif /* VMS */
2335 if (ofd < 0)
2336 report_file_error ("Opening output file", Fcons (newname, Qnil));
2338 record_unwind_protect (close_file_unwind, make_number (ofd));
2340 immediate_quit = 1;
2341 QUIT;
2342 while ((n = read (ifd, buf, sizeof buf)) > 0)
2343 if (write (ofd, buf, n) != n)
2344 report_file_error ("I/O error", Fcons (newname, Qnil));
2345 immediate_quit = 0;
2347 /* Closing the output clobbers the file times on some systems. */
2348 if (close (ofd) < 0)
2349 report_file_error ("I/O error", Fcons (newname, Qnil));
2351 if (input_file_statable_p)
2353 if (!NILP (keep_date))
2355 EMACS_TIME atime, mtime;
2356 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2357 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2358 if (set_file_times (XSTRING (encoded_newname)->data,
2359 atime, mtime))
2360 Fsignal (Qfile_date_error,
2361 Fcons (build_string ("Cannot set file date"),
2362 Fcons (newname, Qnil)));
2364 #ifndef MSDOS
2365 chmod (XSTRING (encoded_newname)->data, st.st_mode & 07777);
2366 #else /* MSDOS */
2367 #if defined (__DJGPP__) && __DJGPP__ > 1
2368 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2369 and if it can't, it tells so. Otherwise, under MSDOS we usually
2370 get only the READ bit, which will make the copied file read-only,
2371 so it's better not to chmod at all. */
2372 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2373 chmod (XSTRING (encoded_newname)->data, st.st_mode & 07777);
2374 #endif /* DJGPP version 2 or newer */
2375 #endif /* MSDOS */
2378 close (ifd);
2380 /* Discard the unwind protects. */
2381 specpdl_ptr = specpdl + count;
2383 UNGCPRO;
2384 return Qnil;
2387 DEFUN ("make-directory-internal", Fmake_directory_internal,
2388 Smake_directory_internal, 1, 1, 0,
2389 "Create a new directory named DIRECTORY.")
2390 (directory)
2391 Lisp_Object directory;
2393 unsigned char *dir;
2394 Lisp_Object handler;
2395 Lisp_Object encoded_dir;
2397 CHECK_STRING (directory, 0);
2398 directory = Fexpand_file_name (directory, Qnil);
2400 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2401 if (!NILP (handler))
2402 return call2 (handler, Qmake_directory_internal, directory);
2404 encoded_dir = ENCODE_FILE (directory);
2406 dir = XSTRING (encoded_dir)->data;
2408 #ifdef WINDOWSNT
2409 if (mkdir (dir) != 0)
2410 #else
2411 if (mkdir (dir, 0777) != 0)
2412 #endif
2413 report_file_error ("Creating directory", Flist (1, &directory));
2415 return Qnil;
2418 DEFUN ("delete-directory", Fdelete_directory, Sdelete_directory, 1, 1, "FDelete directory: ",
2419 "Delete the directory named DIRECTORY.")
2420 (directory)
2421 Lisp_Object directory;
2423 unsigned char *dir;
2424 Lisp_Object handler;
2425 Lisp_Object encoded_dir;
2427 CHECK_STRING (directory, 0);
2428 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2430 handler = Ffind_file_name_handler (directory, Qdelete_directory);
2431 if (!NILP (handler))
2432 return call2 (handler, Qdelete_directory, directory);
2434 encoded_dir = ENCODE_FILE (directory);
2436 dir = XSTRING (encoded_dir)->data;
2438 if (rmdir (dir) != 0)
2439 report_file_error ("Removing directory", Flist (1, &directory));
2441 return Qnil;
2444 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 1, "fDelete file: ",
2445 "Delete file named FILENAME.\n\
2446 If file has multiple names, it continues to exist with the other names.")
2447 (filename)
2448 Lisp_Object filename;
2450 Lisp_Object handler;
2451 Lisp_Object encoded_file;
2453 CHECK_STRING (filename, 0);
2454 filename = Fexpand_file_name (filename, Qnil);
2456 handler = Ffind_file_name_handler (filename, Qdelete_file);
2457 if (!NILP (handler))
2458 return call2 (handler, Qdelete_file, filename);
2460 encoded_file = ENCODE_FILE (filename);
2462 if (0 > unlink (XSTRING (encoded_file)->data))
2463 report_file_error ("Removing old name", Flist (1, &filename));
2464 return Qnil;
2467 static Lisp_Object
2468 internal_delete_file_1 (ignore)
2469 Lisp_Object ignore;
2471 return Qt;
2474 /* Delete file FILENAME, returning 1 if successful and 0 if failed. */
2477 internal_delete_file (filename)
2478 Lisp_Object filename;
2480 return NILP (internal_condition_case_1 (Fdelete_file, filename,
2481 Qt, internal_delete_file_1));
2484 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2485 "fRename file: \nFRename %s to file: \np",
2486 "Rename FILE as NEWNAME. Both args strings.\n\
2487 If file has names other than FILE, it continues to have those names.\n\
2488 Signals a `file-already-exists' error if a file NEWNAME already exists\n\
2489 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
2490 A number as third arg means request confirmation if NEWNAME already exists.\n\
2491 This is what happens in interactive use with M-x.")
2492 (file, newname, ok_if_already_exists)
2493 Lisp_Object file, newname, ok_if_already_exists;
2495 #ifdef NO_ARG_ARRAY
2496 Lisp_Object args[2];
2497 #endif
2498 Lisp_Object handler;
2499 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2500 Lisp_Object encoded_file, encoded_newname;
2502 encoded_file = encoded_newname = Qnil;
2503 GCPRO4 (file, newname, encoded_file, encoded_newname);
2504 CHECK_STRING (file, 0);
2505 CHECK_STRING (newname, 1);
2506 file = Fexpand_file_name (file, Qnil);
2507 newname = Fexpand_file_name (newname, Qnil);
2509 /* If the file name has special constructs in it,
2510 call the corresponding file handler. */
2511 handler = Ffind_file_name_handler (file, Qrename_file);
2512 if (NILP (handler))
2513 handler = Ffind_file_name_handler (newname, Qrename_file);
2514 if (!NILP (handler))
2515 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2516 file, newname, ok_if_already_exists));
2518 encoded_file = ENCODE_FILE (file);
2519 encoded_newname = ENCODE_FILE (newname);
2521 if (NILP (ok_if_already_exists)
2522 || INTEGERP (ok_if_already_exists))
2523 barf_or_query_if_file_exists (encoded_newname, "rename to it",
2524 INTEGERP (ok_if_already_exists), 0, 0);
2525 #ifndef BSD4_1
2526 if (0 > rename (XSTRING (encoded_file)->data, XSTRING (encoded_newname)->data))
2527 #else
2528 if (0 > link (XSTRING (encoded_file)->data, XSTRING (encoded_newname)->data)
2529 || 0 > unlink (XSTRING (encoded_file)->data))
2530 #endif
2532 if (errno == EXDEV)
2534 Fcopy_file (file, newname,
2535 /* We have already prompted if it was an integer,
2536 so don't have copy-file prompt again. */
2537 NILP (ok_if_already_exists) ? Qnil : Qt, Qt);
2538 Fdelete_file (file);
2540 else
2541 #ifdef NO_ARG_ARRAY
2543 args[0] = file;
2544 args[1] = newname;
2545 report_file_error ("Renaming", Flist (2, args));
2547 #else
2548 report_file_error ("Renaming", Flist (2, &file));
2549 #endif
2551 UNGCPRO;
2552 return Qnil;
2555 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2556 "fAdd name to file: \nFName to add to %s: \np",
2557 "Give FILE additional name NEWNAME. Both args strings.\n\
2558 Signals a `file-already-exists' error if a file NEWNAME already exists\n\
2559 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
2560 A number as third arg means request confirmation if NEWNAME already exists.\n\
2561 This is what happens in interactive use with M-x.")
2562 (file, newname, ok_if_already_exists)
2563 Lisp_Object file, newname, ok_if_already_exists;
2565 #ifdef NO_ARG_ARRAY
2566 Lisp_Object args[2];
2567 #endif
2568 Lisp_Object handler;
2569 Lisp_Object encoded_file, encoded_newname;
2570 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2572 GCPRO4 (file, newname, encoded_file, encoded_newname);
2573 encoded_file = encoded_newname = Qnil;
2574 CHECK_STRING (file, 0);
2575 CHECK_STRING (newname, 1);
2576 file = Fexpand_file_name (file, Qnil);
2577 newname = Fexpand_file_name (newname, Qnil);
2579 /* If the file name has special constructs in it,
2580 call the corresponding file handler. */
2581 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2582 if (!NILP (handler))
2583 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2584 newname, ok_if_already_exists));
2586 /* If the new name has special constructs in it,
2587 call the corresponding file handler. */
2588 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2589 if (!NILP (handler))
2590 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2591 newname, ok_if_already_exists));
2593 encoded_file = ENCODE_FILE (file);
2594 encoded_newname = ENCODE_FILE (newname);
2596 if (NILP (ok_if_already_exists)
2597 || INTEGERP (ok_if_already_exists))
2598 barf_or_query_if_file_exists (encoded_newname, "make it a new name",
2599 INTEGERP (ok_if_already_exists), 0, 0);
2601 unlink (XSTRING (newname)->data);
2602 if (0 > link (XSTRING (encoded_file)->data, XSTRING (encoded_newname)->data))
2604 #ifdef NO_ARG_ARRAY
2605 args[0] = file;
2606 args[1] = newname;
2607 report_file_error ("Adding new name", Flist (2, args));
2608 #else
2609 report_file_error ("Adding new name", Flist (2, &file));
2610 #endif
2613 UNGCPRO;
2614 return Qnil;
2617 #ifdef S_IFLNK
2618 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2619 "FMake symbolic link to file: \nFMake symbolic link to file %s: \np",
2620 "Make a symbolic link to FILENAME, named LINKNAME. Both args strings.\n\
2621 Signals a `file-already-exists' error if a file LINKNAME already exists\n\
2622 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
2623 A number as third arg means request confirmation if LINKNAME already exists.\n\
2624 This happens for interactive use with M-x.")
2625 (filename, linkname, ok_if_already_exists)
2626 Lisp_Object filename, linkname, ok_if_already_exists;
2628 #ifdef NO_ARG_ARRAY
2629 Lisp_Object args[2];
2630 #endif
2631 Lisp_Object handler;
2632 Lisp_Object encoded_filename, encoded_linkname;
2633 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2635 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2636 encoded_filename = encoded_linkname = Qnil;
2637 CHECK_STRING (filename, 0);
2638 CHECK_STRING (linkname, 1);
2639 /* If the link target has a ~, we must expand it to get
2640 a truly valid file name. Otherwise, do not expand;
2641 we want to permit links to relative file names. */
2642 if (XSTRING (filename)->data[0] == '~')
2643 filename = Fexpand_file_name (filename, Qnil);
2644 linkname = Fexpand_file_name (linkname, Qnil);
2646 /* If the file name has special constructs in it,
2647 call the corresponding file handler. */
2648 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2649 if (!NILP (handler))
2650 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2651 linkname, ok_if_already_exists));
2653 /* If the new link name has special constructs in it,
2654 call the corresponding file handler. */
2655 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2656 if (!NILP (handler))
2657 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2658 linkname, ok_if_already_exists));
2660 encoded_filename = ENCODE_FILE (filename);
2661 encoded_linkname = ENCODE_FILE (linkname);
2663 if (NILP (ok_if_already_exists)
2664 || INTEGERP (ok_if_already_exists))
2665 barf_or_query_if_file_exists (encoded_linkname, "make it a link",
2666 INTEGERP (ok_if_already_exists), 0, 0);
2667 if (0 > symlink (XSTRING (encoded_filename)->data,
2668 XSTRING (encoded_linkname)->data))
2670 /* If we didn't complain already, silently delete existing file. */
2671 if (errno == EEXIST)
2673 unlink (XSTRING (encoded_linkname)->data);
2674 if (0 <= symlink (XSTRING (encoded_filename)->data,
2675 XSTRING (encoded_linkname)->data))
2677 UNGCPRO;
2678 return Qnil;
2682 #ifdef NO_ARG_ARRAY
2683 args[0] = filename;
2684 args[1] = linkname;
2685 report_file_error ("Making symbolic link", Flist (2, args));
2686 #else
2687 report_file_error ("Making symbolic link", Flist (2, &filename));
2688 #endif
2690 UNGCPRO;
2691 return Qnil;
2693 #endif /* S_IFLNK */
2695 #ifdef VMS
2697 DEFUN ("define-logical-name", Fdefine_logical_name, Sdefine_logical_name,
2698 2, 2, "sDefine logical name: \nsDefine logical name %s as: ",
2699 "Define the job-wide logical name NAME to have the value STRING.\n\
2700 If STRING is nil or a null string, the logical name NAME is deleted.")
2701 (name, string)
2702 Lisp_Object name;
2703 Lisp_Object string;
2705 CHECK_STRING (name, 0);
2706 if (NILP (string))
2707 delete_logical_name (XSTRING (name)->data);
2708 else
2710 CHECK_STRING (string, 1);
2712 if (XSTRING (string)->size == 0)
2713 delete_logical_name (XSTRING (name)->data);
2714 else
2715 define_logical_name (XSTRING (name)->data, XSTRING (string)->data);
2718 return string;
2720 #endif /* VMS */
2722 #ifdef HPUX_NET
2724 DEFUN ("sysnetunam", Fsysnetunam, Ssysnetunam, 2, 2, 0,
2725 "Open a network connection to PATH using LOGIN as the login string.")
2726 (path, login)
2727 Lisp_Object path, login;
2729 int netresult;
2731 CHECK_STRING (path, 0);
2732 CHECK_STRING (login, 0);
2734 netresult = netunam (XSTRING (path)->data, XSTRING (login)->data);
2736 if (netresult == -1)
2737 return Qnil;
2738 else
2739 return Qt;
2741 #endif /* HPUX_NET */
2743 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2744 1, 1, 0,
2745 "Return t if file FILENAME specifies an absolute file name.\n\
2746 On Unix, this is a name starting with a `/' or a `~'.")
2747 (filename)
2748 Lisp_Object filename;
2750 unsigned char *ptr;
2752 CHECK_STRING (filename, 0);
2753 ptr = XSTRING (filename)->data;
2754 if (IS_DIRECTORY_SEP (*ptr) || *ptr == '~'
2755 #ifdef VMS
2756 /* ??? This criterion is probably wrong for '<'. */
2757 || index (ptr, ':') || index (ptr, '<')
2758 || (*ptr == '[' && (ptr[1] != '-' || (ptr[2] != '.' && ptr[2] != ']'))
2759 && ptr[1] != '.')
2760 #endif /* VMS */
2761 #ifdef DOS_NT
2762 || (IS_DRIVE (*ptr) && ptr[1] == ':' && IS_DIRECTORY_SEP (ptr[2]))
2763 #endif
2765 return Qt;
2766 else
2767 return Qnil;
2770 /* Return nonzero if file FILENAME exists and can be executed. */
2772 static int
2773 check_executable (filename)
2774 char *filename;
2776 #ifdef DOS_NT
2777 int len = strlen (filename);
2778 char *suffix;
2779 struct stat st;
2780 if (stat (filename, &st) < 0)
2781 return 0;
2782 #if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
2783 return ((st.st_mode & S_IEXEC) != 0);
2784 #else
2785 return (S_ISREG (st.st_mode)
2786 && len >= 5
2787 && (stricmp ((suffix = filename + len-4), ".com") == 0
2788 || stricmp (suffix, ".exe") == 0
2789 || stricmp (suffix, ".bat") == 0)
2790 || (st.st_mode & S_IFMT) == S_IFDIR);
2791 #endif /* not WINDOWSNT */
2792 #else /* not DOS_NT */
2793 #ifdef HAVE_EUIDACCESS
2794 return (euidaccess (filename, 1) >= 0);
2795 #else
2796 /* Access isn't quite right because it uses the real uid
2797 and we really want to test with the effective uid.
2798 But Unix doesn't give us a right way to do it. */
2799 return (access (filename, 1) >= 0);
2800 #endif
2801 #endif /* not DOS_NT */
2804 /* Return nonzero if file FILENAME exists and can be written. */
2806 static int
2807 check_writable (filename)
2808 char *filename;
2810 #ifdef MSDOS
2811 struct stat st;
2812 if (stat (filename, &st) < 0)
2813 return 0;
2814 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
2815 #else /* not MSDOS */
2816 #ifdef HAVE_EUIDACCESS
2817 return (euidaccess (filename, 2) >= 0);
2818 #else
2819 /* Access isn't quite right because it uses the real uid
2820 and we really want to test with the effective uid.
2821 But Unix doesn't give us a right way to do it.
2822 Opening with O_WRONLY could work for an ordinary file,
2823 but would lose for directories. */
2824 return (access (filename, 2) >= 0);
2825 #endif
2826 #endif /* not MSDOS */
2829 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
2830 "Return t if file FILENAME exists. (This does not mean you can read it.)\n\
2831 See also `file-readable-p' and `file-attributes'.")
2832 (filename)
2833 Lisp_Object filename;
2835 Lisp_Object absname;
2836 Lisp_Object handler;
2837 struct stat statbuf;
2839 CHECK_STRING (filename, 0);
2840 absname = Fexpand_file_name (filename, Qnil);
2842 /* If the file name has special constructs in it,
2843 call the corresponding file handler. */
2844 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
2845 if (!NILP (handler))
2846 return call2 (handler, Qfile_exists_p, absname);
2848 absname = ENCODE_FILE (absname);
2850 return (stat (XSTRING (absname)->data, &statbuf) >= 0) ? Qt : Qnil;
2853 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
2854 "Return t if FILENAME can be executed by you.\n\
2855 For a directory, this means you can access files in that directory.")
2856 (filename)
2857 Lisp_Object filename;
2860 Lisp_Object absname;
2861 Lisp_Object handler;
2863 CHECK_STRING (filename, 0);
2864 absname = Fexpand_file_name (filename, Qnil);
2866 /* If the file name has special constructs in it,
2867 call the corresponding file handler. */
2868 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
2869 if (!NILP (handler))
2870 return call2 (handler, Qfile_executable_p, absname);
2872 absname = ENCODE_FILE (absname);
2874 return (check_executable (XSTRING (absname)->data) ? Qt : Qnil);
2877 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
2878 "Return t if file FILENAME exists and you can read it.\n\
2879 See also `file-exists-p' and `file-attributes'.")
2880 (filename)
2881 Lisp_Object filename;
2883 Lisp_Object absname;
2884 Lisp_Object handler;
2885 int desc;
2886 int flags;
2887 struct stat statbuf;
2889 CHECK_STRING (filename, 0);
2890 absname = Fexpand_file_name (filename, Qnil);
2892 /* If the file name has special constructs in it,
2893 call the corresponding file handler. */
2894 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
2895 if (!NILP (handler))
2896 return call2 (handler, Qfile_readable_p, absname);
2898 absname = ENCODE_FILE (absname);
2900 #ifdef DOS_NT
2901 /* Under MS-DOS and Windows, open does not work for directories. */
2902 if (access (XSTRING (absname)->data, 0) == 0)
2903 return Qt;
2904 return Qnil;
2905 #else /* not DOS_NT */
2906 flags = O_RDONLY;
2907 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
2908 /* Opening a fifo without O_NONBLOCK can wait.
2909 We don't want to wait. But we don't want to mess wth O_NONBLOCK
2910 except in the case of a fifo, on a system which handles it. */
2911 desc = stat (XSTRING (absname)->data, &statbuf);
2912 if (desc < 0)
2913 return Qnil;
2914 if (S_ISFIFO (statbuf.st_mode))
2915 flags |= O_NONBLOCK;
2916 #endif
2917 desc = open (XSTRING (absname)->data, flags);
2918 if (desc < 0)
2919 return Qnil;
2920 close (desc);
2921 return Qt;
2922 #endif /* not DOS_NT */
2925 /* Having this before file-symlink-p mysteriously caused it to be forgotten
2926 on the RT/PC. */
2927 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
2928 "Return t if file FILENAME can be written or created by you.")
2929 (filename)
2930 Lisp_Object filename;
2932 Lisp_Object absname, dir, encoded;
2933 Lisp_Object handler;
2934 struct stat statbuf;
2936 CHECK_STRING (filename, 0);
2937 absname = Fexpand_file_name (filename, Qnil);
2939 /* If the file name has special constructs in it,
2940 call the corresponding file handler. */
2941 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
2942 if (!NILP (handler))
2943 return call2 (handler, Qfile_writable_p, absname);
2945 encoded = ENCODE_FILE (absname);
2946 if (stat (XSTRING (encoded)->data, &statbuf) >= 0)
2947 return (check_writable (XSTRING (encoded)->data)
2948 ? Qt : Qnil);
2950 dir = Ffile_name_directory (absname);
2951 #ifdef VMS
2952 if (!NILP (dir))
2953 dir = Fdirectory_file_name (dir);
2954 #endif /* VMS */
2955 #ifdef MSDOS
2956 if (!NILP (dir))
2957 dir = Fdirectory_file_name (dir);
2958 #endif /* MSDOS */
2960 dir = ENCODE_FILE (dir);
2961 return (check_writable (!NILP (dir) ? (char *) XSTRING (dir)->data : "")
2962 ? Qt : Qnil);
2965 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
2966 "Access file FILENAME, and get an error if that does not work.\n\
2967 The second argument STRING is used in the error message.\n\
2968 If there is no error, we return nil.")
2969 (filename, string)
2970 Lisp_Object filename, string;
2972 Lisp_Object handler, encoded_filename;
2973 int fd;
2975 CHECK_STRING (filename, 0);
2976 CHECK_STRING (string, 1);
2978 /* If the file name has special constructs in it,
2979 call the corresponding file handler. */
2980 handler = Ffind_file_name_handler (filename, Qaccess_file);
2981 if (!NILP (handler))
2982 return call3 (handler, Qaccess_file, filename, string);
2984 encoded_filename = ENCODE_FILE (filename);
2986 fd = open (XSTRING (encoded_filename)->data, O_RDONLY);
2987 if (fd < 0)
2988 report_file_error (XSTRING (string)->data, Fcons (filename, Qnil));
2989 close (fd);
2991 return Qnil;
2994 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
2995 "Return non-nil if file FILENAME is the name of a symbolic link.\n\
2996 The value is the name of the file to which it is linked.\n\
2997 Otherwise returns nil.")
2998 (filename)
2999 Lisp_Object filename;
3001 #ifdef S_IFLNK
3002 char *buf;
3003 int bufsize;
3004 int valsize;
3005 Lisp_Object val;
3006 Lisp_Object handler;
3008 CHECK_STRING (filename, 0);
3009 filename = Fexpand_file_name (filename, Qnil);
3011 /* If the file name has special constructs in it,
3012 call the corresponding file handler. */
3013 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
3014 if (!NILP (handler))
3015 return call2 (handler, Qfile_symlink_p, filename);
3017 filename = ENCODE_FILE (filename);
3019 bufsize = 100;
3020 while (1)
3022 buf = (char *) xmalloc (bufsize);
3023 bzero (buf, bufsize);
3024 valsize = readlink (XSTRING (filename)->data, buf, bufsize);
3025 if (valsize < bufsize) break;
3026 /* Buffer was not long enough */
3027 xfree (buf);
3028 bufsize *= 2;
3030 if (valsize == -1)
3032 xfree (buf);
3033 return Qnil;
3035 val = make_string (buf, valsize);
3036 xfree (buf);
3037 val = DECODE_FILE (val);
3038 return val;
3039 #else /* not S_IFLNK */
3040 return Qnil;
3041 #endif /* not S_IFLNK */
3044 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
3045 "Return t if FILENAME names an existing directory.\n\
3046 Symbolic links to directories count as directories.\n\
3047 See `file-symlink-p' to distinguish symlinks.")
3048 (filename)
3049 Lisp_Object filename;
3051 register Lisp_Object absname;
3052 struct stat st;
3053 Lisp_Object handler;
3055 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3057 /* If the file name has special constructs in it,
3058 call the corresponding file handler. */
3059 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
3060 if (!NILP (handler))
3061 return call2 (handler, Qfile_directory_p, absname);
3063 absname = ENCODE_FILE (absname);
3065 if (stat (XSTRING (absname)->data, &st) < 0)
3066 return Qnil;
3067 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
3070 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
3071 "Return t if file FILENAME is the name of a directory as a file,\n\
3072 and files in that directory can be opened by you. In order to use a\n\
3073 directory as a buffer's current directory, this predicate must return true.\n\
3074 A directory name spec may be given instead; then the value is t\n\
3075 if the directory so specified exists and really is a readable and\n\
3076 searchable directory.")
3077 (filename)
3078 Lisp_Object filename;
3080 Lisp_Object handler;
3081 int tem;
3082 struct gcpro gcpro1;
3084 /* If the file name has special constructs in it,
3085 call the corresponding file handler. */
3086 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
3087 if (!NILP (handler))
3088 return call2 (handler, Qfile_accessible_directory_p, filename);
3090 /* It's an unlikely combination, but yes we really do need to gcpro:
3091 Suppose that file-accessible-directory-p has no handler, but
3092 file-directory-p does have a handler; this handler causes a GC which
3093 relocates the string in `filename'; and finally file-directory-p
3094 returns non-nil. Then we would end up passing a garbaged string
3095 to file-executable-p. */
3096 GCPRO1 (filename);
3097 tem = (NILP (Ffile_directory_p (filename))
3098 || NILP (Ffile_executable_p (filename)));
3099 UNGCPRO;
3100 return tem ? Qnil : Qt;
3103 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
3104 "Return t if file FILENAME is the name of a regular file.\n\
3105 This is the sort of file that holds an ordinary stream of data bytes.")
3106 (filename)
3107 Lisp_Object filename;
3109 register Lisp_Object absname;
3110 struct stat st;
3111 Lisp_Object handler;
3113 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3115 /* If the file name has special constructs in it,
3116 call the corresponding file handler. */
3117 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
3118 if (!NILP (handler))
3119 return call2 (handler, Qfile_regular_p, absname);
3121 absname = ENCODE_FILE (absname);
3123 #ifdef WINDOWSNT
3125 int result;
3126 Lisp_Object tem = Vw32_get_true_file_attributes;
3128 /* Tell stat to use expensive method to get accurate info. */
3129 Vw32_get_true_file_attributes = Qt;
3130 result = stat (XSTRING (absname)->data, &st);
3131 Vw32_get_true_file_attributes = tem;
3133 if (result < 0)
3134 return Qnil;
3135 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
3137 #else
3138 if (stat (XSTRING (absname)->data, &st) < 0)
3139 return Qnil;
3140 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
3141 #endif
3144 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3145 "Return mode bits of file named FILENAME, as an integer.")
3146 (filename)
3147 Lisp_Object filename;
3149 Lisp_Object absname;
3150 struct stat st;
3151 Lisp_Object handler;
3153 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3155 /* If the file name has special constructs in it,
3156 call the corresponding file handler. */
3157 handler = Ffind_file_name_handler (absname, Qfile_modes);
3158 if (!NILP (handler))
3159 return call2 (handler, Qfile_modes, absname);
3161 absname = ENCODE_FILE (absname);
3163 if (stat (XSTRING (absname)->data, &st) < 0)
3164 return Qnil;
3165 #if defined (MSDOS) && __DJGPP__ < 2
3166 if (check_executable (XSTRING (absname)->data))
3167 st.st_mode |= S_IEXEC;
3168 #endif /* MSDOS && __DJGPP__ < 2 */
3170 return make_number (st.st_mode & 07777);
3173 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2, 0,
3174 "Set mode bits of file named FILENAME to MODE (an integer).\n\
3175 Only the 12 low bits of MODE are used.")
3176 (filename, mode)
3177 Lisp_Object filename, mode;
3179 Lisp_Object absname, encoded_absname;
3180 Lisp_Object handler;
3182 absname = Fexpand_file_name (filename, current_buffer->directory);
3183 CHECK_NUMBER (mode, 1);
3185 /* If the file name has special constructs in it,
3186 call the corresponding file handler. */
3187 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3188 if (!NILP (handler))
3189 return call3 (handler, Qset_file_modes, absname, mode);
3191 encoded_absname = ENCODE_FILE (absname);
3193 if (chmod (XSTRING (encoded_absname)->data, XINT (mode)) < 0)
3194 report_file_error ("Doing chmod", Fcons (absname, Qnil));
3196 return Qnil;
3199 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3200 "Set the file permission bits for newly created files.\n\
3201 The argument MODE should be an integer; only the low 9 bits are used.\n\
3202 This setting is inherited by subprocesses.")
3203 (mode)
3204 Lisp_Object mode;
3206 CHECK_NUMBER (mode, 0);
3208 umask ((~ XINT (mode)) & 0777);
3210 return Qnil;
3213 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3214 "Return the default file protection for created files.\n\
3215 The value is an integer.")
3218 int realmask;
3219 Lisp_Object value;
3221 realmask = umask (0);
3222 umask (realmask);
3224 XSETINT (value, (~ realmask) & 0777);
3225 return value;
3228 #ifdef unix
3230 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3231 "Tell Unix to finish all pending disk updates.")
3234 sync ();
3235 return Qnil;
3238 #endif /* unix */
3240 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3241 "Return t if file FILE1 is newer than file FILE2.\n\
3242 If FILE1 does not exist, the answer is nil;\n\
3243 otherwise, if FILE2 does not exist, the answer is t.")
3244 (file1, file2)
3245 Lisp_Object file1, file2;
3247 Lisp_Object absname1, absname2;
3248 struct stat st;
3249 int mtime1;
3250 Lisp_Object handler;
3251 struct gcpro gcpro1, gcpro2;
3253 CHECK_STRING (file1, 0);
3254 CHECK_STRING (file2, 0);
3256 absname1 = Qnil;
3257 GCPRO2 (absname1, file2);
3258 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
3259 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
3260 UNGCPRO;
3262 /* If the file name has special constructs in it,
3263 call the corresponding file handler. */
3264 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3265 if (NILP (handler))
3266 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3267 if (!NILP (handler))
3268 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3270 GCPRO2 (absname1, absname2);
3271 absname1 = ENCODE_FILE (absname1);
3272 absname2 = ENCODE_FILE (absname2);
3273 UNGCPRO;
3275 if (stat (XSTRING (absname1)->data, &st) < 0)
3276 return Qnil;
3278 mtime1 = st.st_mtime;
3280 if (stat (XSTRING (absname2)->data, &st) < 0)
3281 return Qt;
3283 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3286 #ifdef DOS_NT
3287 Lisp_Object Qfind_buffer_file_type;
3288 #endif /* DOS_NT */
3290 #ifndef READ_BUF_SIZE
3291 #define READ_BUF_SIZE (64 << 10)
3292 #endif
3294 /* This function is called when a function bound to
3295 Vset_auto_coding_function causes some error. At that time, a text
3296 of a file has already been inserted in the current buffer, but,
3297 markers has not yet been adjusted. Thus we must adjust markers
3298 here. We are sure that the buffer was empty before the text of the
3299 file was inserted. */
3301 static Lisp_Object
3302 set_auto_coding_unwind (multibyte)
3303 Lisp_Object multibyte;
3305 int inserted = Z_BYTE - BEG_BYTE;
3307 if (!NILP (multibyte))
3308 inserted = multibyte_chars_in_text (GPT_ADDR - inserted, inserted);
3309 adjust_after_insert (PT, PT_BYTE, Z, Z_BYTE, inserted);
3311 return Qnil;
3314 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3315 1, 5, 0,
3316 "Insert contents of file FILENAME after point.\n\
3317 Returns list of absolute file name and number of bytes inserted.\n\
3318 If second argument VISIT is non-nil, the buffer's visited filename\n\
3319 and last save file modtime are set, and it is marked unmodified.\n\
3320 If visiting and the file does not exist, visiting is completed\n\
3321 before the error is signaled.\n\
3322 The optional third and fourth arguments BEG and END\n\
3323 specify what portion of the file to insert.\n\
3324 These arguments count bytes in the file, not characters in the buffer.\n\
3325 If VISIT is non-nil, BEG and END must be nil.\n\
3327 If optional fifth argument REPLACE is non-nil,\n\
3328 it means replace the current buffer contents (in the accessible portion)\n\
3329 with the file contents. This is better than simply deleting and inserting\n\
3330 the whole thing because (1) it preserves some marker positions\n\
3331 and (2) it puts less data in the undo list.\n\
3332 When REPLACE is non-nil, the value is the number of characters actually read,\n\
3333 which is often less than the number of characters to be read.\n\
3335 This does code conversion according to the value of\n\
3336 `coding-system-for-read' or `file-coding-system-alist',\n\
3337 and sets the variable `last-coding-system-used' to the coding system\n\
3338 actually used.")
3339 (filename, visit, beg, end, replace)
3340 Lisp_Object filename, visit, beg, end, replace;
3342 struct stat st;
3343 register int fd;
3344 int inserted = 0;
3345 register int how_much;
3346 register int unprocessed;
3347 int count = specpdl_ptr - specpdl;
3348 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
3349 Lisp_Object handler, val, insval, orig_filename;
3350 Lisp_Object p;
3351 int total;
3352 int not_regular = 0;
3353 unsigned char read_buf[READ_BUF_SIZE];
3354 struct coding_system coding;
3355 unsigned char buffer[1 << 14];
3356 int replace_handled = 0;
3357 int set_coding_system = 0;
3358 int coding_system_decided = 0;
3360 if (current_buffer->base_buffer && ! NILP (visit))
3361 error ("Cannot do file visiting in an indirect buffer");
3363 if (!NILP (current_buffer->read_only))
3364 Fbarf_if_buffer_read_only ();
3366 val = Qnil;
3367 p = Qnil;
3368 orig_filename = Qnil;
3370 GCPRO4 (filename, val, p, orig_filename);
3372 CHECK_STRING (filename, 0);
3373 filename = Fexpand_file_name (filename, Qnil);
3375 /* If the file name has special constructs in it,
3376 call the corresponding file handler. */
3377 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3378 if (!NILP (handler))
3380 val = call6 (handler, Qinsert_file_contents, filename,
3381 visit, beg, end, replace);
3382 if (CONSP (val) && CONSP (XCDR (val)))
3383 inserted = XINT (XCAR (XCDR (val)));
3384 goto handled;
3387 orig_filename = filename;
3388 filename = ENCODE_FILE (filename);
3390 fd = -1;
3392 #ifdef WINDOWSNT
3394 Lisp_Object tem = Vw32_get_true_file_attributes;
3396 /* Tell stat to use expensive method to get accurate info. */
3397 Vw32_get_true_file_attributes = Qt;
3398 total = stat (XSTRING (filename)->data, &st);
3399 Vw32_get_true_file_attributes = tem;
3401 if (total < 0)
3402 #else
3403 #ifndef APOLLO
3404 if (stat (XSTRING (filename)->data, &st) < 0)
3405 #else
3406 if ((fd = open (XSTRING (filename)->data, O_RDONLY)) < 0
3407 || fstat (fd, &st) < 0)
3408 #endif /* not APOLLO */
3409 #endif /* WINDOWSNT */
3411 if (fd >= 0) close (fd);
3412 badopen:
3413 if (NILP (visit))
3414 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3415 st.st_mtime = -1;
3416 how_much = 0;
3417 if (!NILP (Vcoding_system_for_read))
3418 current_buffer->buffer_file_coding_system = Vcoding_system_for_read;
3419 goto notfound;
3422 #ifdef S_IFREG
3423 /* This code will need to be changed in order to work on named
3424 pipes, and it's probably just not worth it. So we should at
3425 least signal an error. */
3426 if (!S_ISREG (st.st_mode))
3428 not_regular = 1;
3430 if (! NILP (visit))
3431 goto notfound;
3433 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3434 Fsignal (Qfile_error,
3435 Fcons (build_string ("not a regular file"),
3436 Fcons (orig_filename, Qnil)));
3438 #endif
3440 if (fd < 0)
3441 if ((fd = open (XSTRING (filename)->data, O_RDONLY)) < 0)
3442 goto badopen;
3444 /* Replacement should preserve point as it preserves markers. */
3445 if (!NILP (replace))
3446 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3448 record_unwind_protect (close_file_unwind, make_number (fd));
3450 /* Supposedly happens on VMS. */
3451 if (! not_regular && st.st_size < 0)
3452 error ("File size is negative");
3454 /* Prevent redisplay optimizations. */
3455 current_buffer->clip_changed = 1;
3457 if (!NILP (beg) || !NILP (end))
3458 if (!NILP (visit))
3459 error ("Attempt to visit less than an entire file");
3461 if (!NILP (beg))
3462 CHECK_NUMBER (beg, 0);
3463 else
3464 XSETFASTINT (beg, 0);
3466 if (!NILP (end))
3467 CHECK_NUMBER (end, 0);
3468 else
3470 if (! not_regular)
3472 XSETINT (end, st.st_size);
3473 if (XINT (end) != st.st_size)
3474 error ("Maximum buffer size exceeded");
3478 if (BEG < Z)
3480 /* Decide the coding system to use for reading the file now
3481 because we can't use an optimized method for handling
3482 `coding:' tag if the current buffer is not empty. */
3483 Lisp_Object val;
3484 val = Qnil;
3486 if (!NILP (Vcoding_system_for_read))
3487 val = Vcoding_system_for_read;
3488 else if (! NILP (replace))
3489 /* In REPLACE mode, we can use the same coding system
3490 that was used to visit the file. */
3491 val = current_buffer->buffer_file_coding_system;
3492 else
3494 /* Don't try looking inside a file for a coding system
3495 specification if it is not seekable. */
3496 if (! not_regular && ! NILP (Vset_auto_coding_function))
3498 /* Find a coding system specified in the heading two
3499 lines or in the tailing several lines of the file.
3500 We assume that the 1K-byte and 3K-byte for heading
3501 and tailing respectively are sufficient for this
3502 purpose. */
3503 int how_many, nread;
3505 if (st.st_size <= (1024 * 4))
3506 nread = read (fd, read_buf, 1024 * 4);
3507 else
3509 nread = read (fd, read_buf, 1024);
3510 if (nread >= 0)
3512 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3513 report_file_error ("Setting file position",
3514 Fcons (orig_filename, Qnil));
3515 nread += read (fd, read_buf + nread, 1024 * 3);
3519 if (nread < 0)
3520 error ("IO error reading %s: %s",
3521 XSTRING (orig_filename)->data, strerror (errno));
3522 else if (nread > 0)
3524 int count = specpdl_ptr - specpdl;
3525 struct buffer *prev = current_buffer;
3527 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3528 temp_output_buffer_setup (" *code-converting-work*");
3529 set_buffer_internal (XBUFFER (Vstandard_output));
3530 current_buffer->enable_multibyte_characters = Qnil;
3531 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3532 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3533 val = call2 (Vset_auto_coding_function,
3534 filename, make_number (nread));
3535 set_buffer_internal (prev);
3536 /* Discard the unwind protect for recovering the
3537 current buffer. */
3538 specpdl_ptr--;
3540 /* Rewind the file for the actual read done later. */
3541 if (lseek (fd, 0, 0) < 0)
3542 report_file_error ("Setting file position",
3543 Fcons (orig_filename, Qnil));
3547 if (NILP (val))
3549 /* If we have not yet decided a coding system, check
3550 file-coding-system-alist. */
3551 Lisp_Object args[6], coding_systems;
3553 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3554 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3555 coding_systems = Ffind_operation_coding_system (6, args);
3556 if (CONSP (coding_systems))
3557 val = XCAR (coding_systems);
3561 setup_coding_system (Fcheck_coding_system (val), &coding);
3563 if (NILP (current_buffer->enable_multibyte_characters)
3564 && ! NILP (val))
3565 /* We must suppress all character code conversion except for
3566 end-of-line conversion. */
3567 setup_raw_text_coding_system (&coding);
3569 coding_system_decided = 1;
3572 /* Ensure we always set Vlast_coding_system_used. */
3573 set_coding_system = 1;
3575 /* If requested, replace the accessible part of the buffer
3576 with the file contents. Avoid replacing text at the
3577 beginning or end of the buffer that matches the file contents;
3578 that preserves markers pointing to the unchanged parts.
3580 Here we implement this feature in an optimized way
3581 for the case where code conversion is NOT needed.
3582 The following if-statement handles the case of conversion
3583 in a less optimal way.
3585 If the code conversion is "automatic" then we try using this
3586 method and hope for the best.
3587 But if we discover the need for conversion, we give up on this method
3588 and let the following if-statement handle the replace job. */
3589 if (!NILP (replace)
3590 && BEGV < ZV
3591 && ! CODING_REQUIRE_DECODING (&coding)
3592 && (coding.eol_type == CODING_EOL_UNDECIDED
3593 || coding.eol_type == CODING_EOL_LF))
3595 /* same_at_start and same_at_end count bytes,
3596 because file access counts bytes
3597 and BEG and END count bytes. */
3598 int same_at_start = BEGV_BYTE;
3599 int same_at_end = ZV_BYTE;
3600 int overlap;
3601 /* There is still a possibility we will find the need to do code
3602 conversion. If that happens, we set this variable to 1 to
3603 give up on handling REPLACE in the optimized way. */
3604 int giveup_match_end = 0;
3606 if (XINT (beg) != 0)
3608 if (lseek (fd, XINT (beg), 0) < 0)
3609 report_file_error ("Setting file position",
3610 Fcons (orig_filename, Qnil));
3613 immediate_quit = 1;
3614 QUIT;
3615 /* Count how many chars at the start of the file
3616 match the text at the beginning of the buffer. */
3617 while (1)
3619 int nread, bufpos;
3621 nread = read (fd, buffer, sizeof buffer);
3622 if (nread < 0)
3623 error ("IO error reading %s: %s",
3624 XSTRING (orig_filename)->data, strerror (errno));
3625 else if (nread == 0)
3626 break;
3628 if (coding.type == coding_type_undecided)
3629 detect_coding (&coding, buffer, nread);
3630 if (CODING_REQUIRE_DECODING (&coding))
3631 /* We found that the file should be decoded somehow.
3632 Let's give up here. */
3634 giveup_match_end = 1;
3635 break;
3638 if (coding.eol_type == CODING_EOL_UNDECIDED)
3639 detect_eol (&coding, buffer, nread);
3640 if (coding.eol_type != CODING_EOL_UNDECIDED
3641 && coding.eol_type != CODING_EOL_LF)
3642 /* We found that the format of eol should be decoded.
3643 Let's give up here. */
3645 giveup_match_end = 1;
3646 break;
3649 bufpos = 0;
3650 while (bufpos < nread && same_at_start < ZV_BYTE
3651 && FETCH_BYTE (same_at_start) == buffer[bufpos])
3652 same_at_start++, bufpos++;
3653 /* If we found a discrepancy, stop the scan.
3654 Otherwise loop around and scan the next bufferful. */
3655 if (bufpos != nread)
3656 break;
3658 immediate_quit = 0;
3659 /* If the file matches the buffer completely,
3660 there's no need to replace anything. */
3661 if (same_at_start - BEGV_BYTE == XINT (end))
3663 close (fd);
3664 specpdl_ptr--;
3665 /* Truncate the buffer to the size of the file. */
3666 del_range_1 (same_at_start, same_at_end, 0);
3667 goto handled;
3669 immediate_quit = 1;
3670 QUIT;
3671 /* Count how many chars at the end of the file
3672 match the text at the end of the buffer. But, if we have
3673 already found that decoding is necessary, don't waste time. */
3674 while (!giveup_match_end)
3676 int total_read, nread, bufpos, curpos, trial;
3678 /* At what file position are we now scanning? */
3679 curpos = XINT (end) - (ZV_BYTE - same_at_end);
3680 /* If the entire file matches the buffer tail, stop the scan. */
3681 if (curpos == 0)
3682 break;
3683 /* How much can we scan in the next step? */
3684 trial = min (curpos, sizeof buffer);
3685 if (lseek (fd, curpos - trial, 0) < 0)
3686 report_file_error ("Setting file position",
3687 Fcons (orig_filename, Qnil));
3689 total_read = 0;
3690 while (total_read < trial)
3692 nread = read (fd, buffer + total_read, trial - total_read);
3693 if (nread <= 0)
3694 error ("IO error reading %s: %s",
3695 XSTRING (orig_filename)->data, strerror (errno));
3696 total_read += nread;
3698 /* Scan this bufferful from the end, comparing with
3699 the Emacs buffer. */
3700 bufpos = total_read;
3701 /* Compare with same_at_start to avoid counting some buffer text
3702 as matching both at the file's beginning and at the end. */
3703 while (bufpos > 0 && same_at_end > same_at_start
3704 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
3705 same_at_end--, bufpos--;
3707 /* If we found a discrepancy, stop the scan.
3708 Otherwise loop around and scan the preceding bufferful. */
3709 if (bufpos != 0)
3711 /* If this discrepancy is because of code conversion,
3712 we cannot use this method; giveup and try the other. */
3713 if (same_at_end > same_at_start
3714 && FETCH_BYTE (same_at_end - 1) >= 0200
3715 && ! NILP (current_buffer->enable_multibyte_characters)
3716 && (CODING_MAY_REQUIRE_DECODING (&coding)))
3717 giveup_match_end = 1;
3718 break;
3721 immediate_quit = 0;
3723 if (! giveup_match_end)
3725 int temp;
3727 /* We win! We can handle REPLACE the optimized way. */
3729 /* Extend the start of non-matching text area to multibyte
3730 character boundary. */
3731 if (! NILP (current_buffer->enable_multibyte_characters))
3732 while (same_at_start > BEGV_BYTE
3733 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3734 same_at_start--;
3736 /* Extend the end of non-matching text area to multibyte
3737 character boundary. */
3738 if (! NILP (current_buffer->enable_multibyte_characters))
3739 while (same_at_end < ZV_BYTE
3740 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3741 same_at_end++;
3743 /* Don't try to reuse the same piece of text twice. */
3744 overlap = (same_at_start - BEGV_BYTE
3745 - (same_at_end + st.st_size - ZV));
3746 if (overlap > 0)
3747 same_at_end += overlap;
3749 /* Arrange to read only the nonmatching middle part of the file. */
3750 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
3751 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
3753 del_range_byte (same_at_start, same_at_end, 0);
3754 /* Insert from the file at the proper position. */
3755 temp = BYTE_TO_CHAR (same_at_start);
3756 SET_PT_BOTH (temp, same_at_start);
3758 /* If display currently starts at beginning of line,
3759 keep it that way. */
3760 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3761 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3763 replace_handled = 1;
3767 /* If requested, replace the accessible part of the buffer
3768 with the file contents. Avoid replacing text at the
3769 beginning or end of the buffer that matches the file contents;
3770 that preserves markers pointing to the unchanged parts.
3772 Here we implement this feature for the case where code conversion
3773 is needed, in a simple way that needs a lot of memory.
3774 The preceding if-statement handles the case of no conversion
3775 in a more optimized way. */
3776 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
3778 int same_at_start = BEGV_BYTE;
3779 int same_at_end = ZV_BYTE;
3780 int overlap;
3781 int bufpos;
3782 /* Make sure that the gap is large enough. */
3783 int bufsize = 2 * st.st_size;
3784 unsigned char *conversion_buffer = (unsigned char *) xmalloc (bufsize);
3785 int temp;
3787 /* First read the whole file, performing code conversion into
3788 CONVERSION_BUFFER. */
3790 if (lseek (fd, XINT (beg), 0) < 0)
3792 xfree (conversion_buffer);
3793 report_file_error ("Setting file position",
3794 Fcons (orig_filename, Qnil));
3797 total = st.st_size; /* Total bytes in the file. */
3798 how_much = 0; /* Bytes read from file so far. */
3799 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
3800 unprocessed = 0; /* Bytes not processed in previous loop. */
3802 while (how_much < total)
3804 /* try is reserved in some compilers (Microsoft C) */
3805 int trytry = min (total - how_much, READ_BUF_SIZE - unprocessed);
3806 unsigned char *destination = read_buf + unprocessed;
3807 int this;
3809 /* Allow quitting out of the actual I/O. */
3810 immediate_quit = 1;
3811 QUIT;
3812 this = read (fd, destination, trytry);
3813 immediate_quit = 0;
3815 if (this < 0 || this + unprocessed == 0)
3817 how_much = this;
3818 break;
3821 how_much += this;
3823 if (CODING_MAY_REQUIRE_DECODING (&coding))
3825 int require, result;
3827 this += unprocessed;
3829 /* If we are using more space than estimated,
3830 make CONVERSION_BUFFER bigger. */
3831 require = decoding_buffer_size (&coding, this);
3832 if (inserted + require + 2 * (total - how_much) > bufsize)
3834 bufsize = inserted + require + 2 * (total - how_much);
3835 conversion_buffer = (unsigned char *) xrealloc (conversion_buffer, bufsize);
3838 /* Convert this batch with results in CONVERSION_BUFFER. */
3839 if (how_much >= total) /* This is the last block. */
3840 coding.mode |= CODING_MODE_LAST_BLOCK;
3841 result = decode_coding (&coding, read_buf,
3842 conversion_buffer + inserted,
3843 this, bufsize - inserted);
3845 /* Save for next iteration whatever we didn't convert. */
3846 unprocessed = this - coding.consumed;
3847 bcopy (read_buf + coding.consumed, read_buf, unprocessed);
3848 this = coding.produced;
3851 inserted += this;
3854 /* At this point, INSERTED is how many characters (i.e. bytes)
3855 are present in CONVERSION_BUFFER.
3856 HOW_MUCH should equal TOTAL,
3857 or should be <= 0 if we couldn't read the file. */
3859 if (how_much < 0)
3861 xfree (conversion_buffer);
3863 if (how_much == -1)
3864 error ("IO error reading %s: %s",
3865 XSTRING (orig_filename)->data, strerror (errno));
3866 else if (how_much == -2)
3867 error ("maximum buffer size exceeded");
3870 /* Compare the beginning of the converted file
3871 with the buffer text. */
3873 bufpos = 0;
3874 while (bufpos < inserted && same_at_start < same_at_end
3875 && FETCH_BYTE (same_at_start) == conversion_buffer[bufpos])
3876 same_at_start++, bufpos++;
3878 /* If the file matches the buffer completely,
3879 there's no need to replace anything. */
3881 if (bufpos == inserted)
3883 xfree (conversion_buffer);
3884 close (fd);
3885 specpdl_ptr--;
3886 /* Truncate the buffer to the size of the file. */
3887 del_range_byte (same_at_start, same_at_end, 0);
3888 inserted = 0;
3889 goto handled;
3892 /* Extend the start of non-matching text area to multibyte
3893 character boundary. */
3894 if (! NILP (current_buffer->enable_multibyte_characters))
3895 while (same_at_start > BEGV_BYTE
3896 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
3897 same_at_start--;
3899 /* Scan this bufferful from the end, comparing with
3900 the Emacs buffer. */
3901 bufpos = inserted;
3903 /* Compare with same_at_start to avoid counting some buffer text
3904 as matching both at the file's beginning and at the end. */
3905 while (bufpos > 0 && same_at_end > same_at_start
3906 && FETCH_BYTE (same_at_end - 1) == conversion_buffer[bufpos - 1])
3907 same_at_end--, bufpos--;
3909 /* Extend the end of non-matching text area to multibyte
3910 character boundary. */
3911 if (! NILP (current_buffer->enable_multibyte_characters))
3912 while (same_at_end < ZV_BYTE
3913 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
3914 same_at_end++;
3916 /* Don't try to reuse the same piece of text twice. */
3917 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
3918 if (overlap > 0)
3919 same_at_end += overlap;
3921 /* If display currently starts at beginning of line,
3922 keep it that way. */
3923 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
3924 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
3926 /* Replace the chars that we need to replace,
3927 and update INSERTED to equal the number of bytes
3928 we are taking from the file. */
3929 inserted -= (Z_BYTE - same_at_end) + (same_at_start - BEG_BYTE);
3931 if (same_at_end != same_at_start)
3933 del_range_byte (same_at_start, same_at_end, 0);
3934 temp = GPT;
3935 same_at_start = GPT_BYTE;
3937 else
3939 temp = BYTE_TO_CHAR (same_at_start);
3941 /* Insert from the file at the proper position. */
3942 SET_PT_BOTH (temp, same_at_start);
3943 insert_1 (conversion_buffer + same_at_start - BEG_BYTE, inserted,
3944 0, 0, 0);
3945 /* Set `inserted' to the number of inserted characters. */
3946 inserted = PT - temp;
3948 free (conversion_buffer);
3949 close (fd);
3950 specpdl_ptr--;
3952 goto handled;
3955 if (! not_regular)
3957 register Lisp_Object temp;
3959 total = XINT (end) - XINT (beg);
3961 /* Make sure point-max won't overflow after this insertion. */
3962 XSETINT (temp, total);
3963 if (total != XINT (temp))
3964 error ("Maximum buffer size exceeded");
3966 else
3967 /* For a special file, all we can do is guess. */
3968 total = READ_BUF_SIZE;
3970 if (NILP (visit) && total > 0)
3971 prepare_to_modify_buffer (PT, PT, NULL);
3973 move_gap (PT);
3974 if (GAP_SIZE < total)
3975 make_gap (total - GAP_SIZE);
3977 if (XINT (beg) != 0 || !NILP (replace))
3979 if (lseek (fd, XINT (beg), 0) < 0)
3980 report_file_error ("Setting file position",
3981 Fcons (orig_filename, Qnil));
3984 /* In the following loop, HOW_MUCH contains the total bytes read so
3985 far for a regular file, and not changed for a special file. But,
3986 before exiting the loop, it is set to a negative value if I/O
3987 error occurs. */
3988 how_much = 0;
3989 /* Total bytes inserted. */
3990 inserted = 0;
3991 /* Here, we don't do code conversion in the loop. It is done by
3992 code_convert_region after all data are read into the buffer. */
3993 while (how_much < total)
3995 /* try is reserved in some compilers (Microsoft C) */
3996 int trytry = min (total - how_much, READ_BUF_SIZE);
3997 int this;
3999 /* For a special file, GAP_SIZE should be checked every time. */
4000 if (not_regular && GAP_SIZE < trytry)
4001 make_gap (total - GAP_SIZE);
4003 /* Allow quitting out of the actual I/O. */
4004 immediate_quit = 1;
4005 QUIT;
4006 this = read (fd, BYTE_POS_ADDR (PT_BYTE + inserted - 1) + 1, trytry);
4007 immediate_quit = 0;
4009 if (this <= 0)
4011 how_much = this;
4012 break;
4015 GAP_SIZE -= this;
4016 GPT_BYTE += this;
4017 ZV_BYTE += this;
4018 Z_BYTE += this;
4019 GPT += this;
4020 ZV += this;
4021 Z += this;
4023 /* For a regular file, where TOTAL is the real size,
4024 count HOW_MUCH to compare with it.
4025 For a special file, where TOTAL is just a buffer size,
4026 so don't bother counting in HOW_MUCH.
4027 (INSERTED is where we count the number of characters inserted.) */
4028 if (! not_regular)
4029 how_much += this;
4030 inserted += this;
4033 if (GAP_SIZE > 0)
4034 /* Put an anchor to ensure multi-byte form ends at gap. */
4035 *GPT_ADDR = 0;
4037 close (fd);
4039 /* Discard the unwind protect for closing the file. */
4040 specpdl_ptr--;
4042 if (how_much < 0)
4043 error ("IO error reading %s: %s",
4044 XSTRING (orig_filename)->data, strerror (errno));
4046 if (! coding_system_decided)
4048 /* The coding system is not yet decided. Decide it by an
4049 optimized method for handling `coding:' tag. */
4050 Lisp_Object val;
4051 val = Qnil;
4053 if (!NILP (Vcoding_system_for_read))
4054 val = Vcoding_system_for_read;
4055 else
4057 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4059 /* Since we are sure that the current buffer was
4060 empty before the insertion, we can toggle
4061 enable-multibyte-characters directly here without
4062 taking care of marker adjustment and byte
4063 combining problem. */
4064 Lisp_Object prev_multibyte;
4065 int count = specpdl_ptr - specpdl;
4067 prev_multibyte = current_buffer->enable_multibyte_characters;
4068 current_buffer->enable_multibyte_characters = Qnil;
4069 record_unwind_protect (set_auto_coding_unwind,
4070 prev_multibyte);
4071 val = call2 (Vset_auto_coding_function,
4072 filename, make_number (inserted));
4073 /* Discard the unwind protect for recovering the
4074 error of Vset_auto_coding_function. */
4075 specpdl_ptr--;
4076 current_buffer->enable_multibyte_characters = prev_multibyte;
4077 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
4080 if (NILP (val))
4082 /* If the coding system is not yet decided, check
4083 file-coding-system-alist. */
4084 Lisp_Object args[6], coding_systems;
4086 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4087 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4088 coding_systems = Ffind_operation_coding_system (6, args);
4089 if (CONSP (coding_systems))
4090 val = XCAR (coding_systems);
4094 /* The following kludgy code is to avoid some compiler bug.
4095 We can't simply do
4096 setup_coding_system (val, &coding);
4097 on some system. */
4099 struct coding_system temp_coding;
4100 setup_coding_system (val, &temp_coding);
4101 bcopy (&temp_coding, &coding, sizeof coding);
4104 if (NILP (current_buffer->enable_multibyte_characters)
4105 && ! NILP (val))
4106 /* We must suppress all character code conversion except for
4107 end-of-line conversion. */
4108 setup_raw_text_coding_system (&coding);
4111 if (inserted > 0 || coding.type == coding_type_ccl)
4113 if (CODING_MAY_REQUIRE_DECODING (&coding))
4115 /* Here, we don't have to consider byte combining (see the
4116 comment below) because code_convert_region takes care of
4117 it. */
4118 code_convert_region (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4119 &coding, 0, 0);
4120 inserted = (NILP (current_buffer->enable_multibyte_characters)
4121 ? coding.produced : coding.produced_char);
4123 else if (!NILP (current_buffer->enable_multibyte_characters))
4125 int inserted_byte = inserted;
4127 /* There's a possibility that we must combine bytes at the
4128 head (resp. the tail) of the just inserted text with the
4129 bytes before (resp. after) the gap to form a single
4130 character. */
4131 inserted = multibyte_chars_in_text (GPT_ADDR - inserted, inserted);
4132 adjust_after_insert (PT, PT_BYTE,
4133 PT + inserted_byte, PT_BYTE + inserted_byte,
4134 inserted);
4136 else
4137 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4138 inserted);
4141 #ifdef DOS_NT
4142 /* Use the conversion type to determine buffer-file-type
4143 (find-buffer-file-type is now used to help determine the
4144 conversion). */
4145 if ((coding.eol_type == CODING_EOL_UNDECIDED
4146 || coding.eol_type == CODING_EOL_LF)
4147 && ! CODING_REQUIRE_DECODING (&coding))
4148 current_buffer->buffer_file_type = Qt;
4149 else
4150 current_buffer->buffer_file_type = Qnil;
4151 #endif
4153 notfound:
4154 handled:
4156 if (!NILP (visit))
4158 if (!EQ (current_buffer->undo_list, Qt))
4159 current_buffer->undo_list = Qnil;
4160 #ifdef APOLLO
4161 stat (XSTRING (filename)->data, &st);
4162 #endif
4164 if (NILP (handler))
4166 current_buffer->modtime = st.st_mtime;
4167 current_buffer->filename = orig_filename;
4170 SAVE_MODIFF = MODIFF;
4171 current_buffer->auto_save_modified = MODIFF;
4172 XSETFASTINT (current_buffer->save_length, Z - BEG);
4173 #ifdef CLASH_DETECTION
4174 if (NILP (handler))
4176 if (!NILP (current_buffer->file_truename))
4177 unlock_file (current_buffer->file_truename);
4178 unlock_file (filename);
4180 #endif /* CLASH_DETECTION */
4181 if (not_regular)
4182 Fsignal (Qfile_error,
4183 Fcons (build_string ("not a regular file"),
4184 Fcons (orig_filename, Qnil)));
4186 /* If visiting nonexistent file, return nil. */
4187 if (current_buffer->modtime == -1)
4188 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4191 /* Decode file format */
4192 if (inserted > 0)
4194 insval = call3 (Qformat_decode,
4195 Qnil, make_number (inserted), visit);
4196 CHECK_NUMBER (insval, 0);
4197 inserted = XFASTINT (insval);
4200 /* Call after-change hooks for the inserted text, aside from the case
4201 of normal visiting (not with REPLACE), which is done in a new buffer
4202 "before" the buffer is changed. */
4203 if (inserted > 0 && total > 0
4204 && (NILP (visit) || !NILP (replace)))
4205 signal_after_change (PT, 0, inserted);
4207 if (set_coding_system)
4208 Vlast_coding_system_used = coding.symbol;
4210 if (inserted > 0)
4212 p = Vafter_insert_file_functions;
4213 while (!NILP (p))
4215 insval = call1 (Fcar (p), make_number (inserted));
4216 if (!NILP (insval))
4218 CHECK_NUMBER (insval, 0);
4219 inserted = XFASTINT (insval);
4221 QUIT;
4222 p = Fcdr (p);
4226 /* ??? Retval needs to be dealt with in all cases consistently. */
4227 if (NILP (val))
4228 val = Fcons (orig_filename,
4229 Fcons (make_number (inserted),
4230 Qnil));
4232 RETURN_UNGCPRO (unbind_to (count, val));
4235 static Lisp_Object build_annotations P_ ((Lisp_Object, Lisp_Object,
4236 Lisp_Object));
4238 /* If build_annotations switched buffers, switch back to BUF.
4239 Kill the temporary buffer that was selected in the meantime.
4241 Since this kill only the last temporary buffer, some buffers remain
4242 not killed if build_annotations switched buffers more than once.
4243 -- K.Handa */
4245 static Lisp_Object
4246 build_annotations_unwind (buf)
4247 Lisp_Object buf;
4249 Lisp_Object tembuf;
4251 if (XBUFFER (buf) == current_buffer)
4252 return Qnil;
4253 tembuf = Fcurrent_buffer ();
4254 Fset_buffer (buf);
4255 Fkill_buffer (tembuf);
4256 return Qnil;
4259 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4260 "r\nFWrite region to file: \ni\ni\ni\np",
4261 "Write current region into specified file.\n\
4262 When called from a program, takes three arguments:\n\
4263 START, END and FILENAME. START and END are buffer positions.\n\
4264 Optional fourth argument APPEND if non-nil means\n\
4265 append to existing file contents (if any).\n\
4266 Optional fifth argument VISIT if t means\n\
4267 set the last-save-file-modtime of buffer to this file's modtime\n\
4268 and mark buffer not modified.\n\
4269 If VISIT is a string, it is a second file name;\n\
4270 the output goes to FILENAME, but the buffer is marked as visiting VISIT.\n\
4271 VISIT is also the file name to lock and unlock for clash detection.\n\
4272 If VISIT is neither t nor nil nor a string,\n\
4273 that means do not print the \"Wrote file\" message.\n\
4274 The optional sixth arg LOCKNAME, if non-nil, specifies the name to\n\
4275 use for locking and unlocking, overriding FILENAME and VISIT.\n\
4276 The optional seventh arg MUSTBENEW, if non-nil, insists on a check\n\
4277 for an existing file with the same name. If MUSTBENEW is `excl',\n\
4278 that means to get an error if the file already exists; never overwrite.\n\
4279 If MUSTBENEW is neither nil nor `excl', that means ask for\n\
4280 confirmation before overwriting, but do go ahead and overwrite the file\n\
4281 if the user confirms.\n\
4282 Kludgy feature: if START is a string, then that string is written\n\
4283 to the file, instead of any buffer contents, and END is ignored.\n\
4285 This does code conversion according to the value of\n\
4286 `coding-system-for-write', `buffer-file-coding-system', or\n\
4287 `file-coding-system-alist', and sets the variable\n\
4288 `last-coding-system-used' to the coding system actually used.")
4290 (start, end, filename, append, visit, lockname, mustbenew)
4291 Lisp_Object start, end, filename, append, visit, lockname, mustbenew;
4293 register int desc;
4294 int failure;
4295 int save_errno;
4296 unsigned char *fn;
4297 struct stat st;
4298 int tem;
4299 int count = specpdl_ptr - specpdl;
4300 int count1;
4301 #ifdef VMS
4302 unsigned char *fname = 0; /* If non-0, original filename (must rename) */
4303 #endif /* VMS */
4304 Lisp_Object handler;
4305 Lisp_Object visit_file;
4306 Lisp_Object annotations;
4307 Lisp_Object encoded_filename;
4308 int visiting, quietly;
4309 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4310 struct buffer *given_buffer;
4311 #ifdef DOS_NT
4312 int buffer_file_type = O_BINARY;
4313 #endif /* DOS_NT */
4314 struct coding_system coding;
4316 if (current_buffer->base_buffer && ! NILP (visit))
4317 error ("Cannot do file visiting in an indirect buffer");
4319 if (!NILP (start) && !STRINGP (start))
4320 validate_region (&start, &end);
4322 GCPRO4 (start, filename, visit, lockname);
4324 /* Decide the coding-system to encode the data with. */
4326 Lisp_Object val;
4328 if (auto_saving)
4329 val = Qnil;
4330 else if (!NILP (Vcoding_system_for_write))
4331 val = Vcoding_system_for_write;
4332 else
4334 /* If the variable `buffer-file-coding-system' is set locally,
4335 it means that the file was read with some kind of code
4336 conversion or the varialbe is explicitely set by users. We
4337 had better write it out with the same coding system even if
4338 `enable-multibyte-characters' is nil.
4340 If it is not set locally, we anyway have to convert EOL
4341 format if the default value of `buffer-file-coding-system'
4342 tells that it is not Unix-like (LF only) format. */
4343 int using_default_coding = 0;
4344 int force_raw_text = 0;
4346 val = current_buffer->buffer_file_coding_system;
4347 if (NILP (val)
4348 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4350 val = Qnil;
4351 if (NILP (current_buffer->enable_multibyte_characters))
4352 force_raw_text = 1;
4355 if (NILP (val))
4357 /* Check file-coding-system-alist. */
4358 Lisp_Object args[7], coding_systems;
4360 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4361 args[3] = filename; args[4] = append; args[5] = visit;
4362 args[6] = lockname;
4363 coding_systems = Ffind_operation_coding_system (7, args);
4364 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4365 val = XCDR (coding_systems);
4368 if (NILP (val)
4369 && !NILP (current_buffer->buffer_file_coding_system))
4371 /* If we still have not decided a coding system, use the
4372 default value of buffer-file-coding-system. */
4373 val = current_buffer->buffer_file_coding_system;
4374 using_default_coding = 1;
4377 if (!force_raw_text
4378 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4379 /* Confirm that VAL can surely encode the current region. */
4380 val = call3 (Vselect_safe_coding_system_function, start, end, val);
4382 setup_coding_system (Fcheck_coding_system (val), &coding);
4383 if (coding.eol_type == CODING_EOL_UNDECIDED
4384 && !using_default_coding)
4386 if (! EQ (default_buffer_file_coding.symbol,
4387 buffer_defaults.buffer_file_coding_system))
4388 setup_coding_system (buffer_defaults.buffer_file_coding_system,
4389 &default_buffer_file_coding);
4390 if (default_buffer_file_coding.eol_type != CODING_EOL_UNDECIDED)
4392 Lisp_Object subsidiaries;
4394 coding.eol_type = default_buffer_file_coding.eol_type;
4395 subsidiaries = Fget (coding.symbol, Qeol_type);
4396 if (VECTORP (subsidiaries)
4397 && XVECTOR (subsidiaries)->size == 3)
4398 coding.symbol
4399 = XVECTOR (subsidiaries)->contents[coding.eol_type];
4403 if (force_raw_text)
4404 setup_raw_text_coding_system (&coding);
4405 goto done_setup_coding;
4408 setup_coding_system (Fcheck_coding_system (val), &coding);
4410 done_setup_coding:
4411 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4412 coding.mode |= CODING_MODE_SELECTIVE_DISPLAY;
4415 Vlast_coding_system_used = coding.symbol;
4417 filename = Fexpand_file_name (filename, Qnil);
4419 if (! NILP (mustbenew) && mustbenew != Qexcl)
4420 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4422 if (STRINGP (visit))
4423 visit_file = Fexpand_file_name (visit, Qnil);
4424 else
4425 visit_file = filename;
4426 UNGCPRO;
4428 visiting = (EQ (visit, Qt) || STRINGP (visit));
4429 quietly = !NILP (visit);
4431 annotations = Qnil;
4433 if (NILP (lockname))
4434 lockname = visit_file;
4436 GCPRO5 (start, filename, annotations, visit_file, lockname);
4438 /* If the file name has special constructs in it,
4439 call the corresponding file handler. */
4440 handler = Ffind_file_name_handler (filename, Qwrite_region);
4441 /* If FILENAME has no handler, see if VISIT has one. */
4442 if (NILP (handler) && STRINGP (visit))
4443 handler = Ffind_file_name_handler (visit, Qwrite_region);
4445 if (!NILP (handler))
4447 Lisp_Object val;
4448 val = call6 (handler, Qwrite_region, start, end,
4449 filename, append, visit);
4451 if (visiting)
4453 SAVE_MODIFF = MODIFF;
4454 XSETFASTINT (current_buffer->save_length, Z - BEG);
4455 current_buffer->filename = visit_file;
4457 UNGCPRO;
4458 return val;
4461 /* Special kludge to simplify auto-saving. */
4462 if (NILP (start))
4464 XSETFASTINT (start, BEG);
4465 XSETFASTINT (end, Z);
4468 record_unwind_protect (build_annotations_unwind, Fcurrent_buffer ());
4469 count1 = specpdl_ptr - specpdl;
4471 given_buffer = current_buffer;
4472 annotations = build_annotations (start, end, coding.pre_write_conversion);
4473 if (current_buffer != given_buffer)
4475 XSETFASTINT (start, BEGV);
4476 XSETFASTINT (end, ZV);
4479 #ifdef CLASH_DETECTION
4480 if (!auto_saving)
4482 #if 0 /* This causes trouble for GNUS. */
4483 /* If we've locked this file for some other buffer,
4484 query before proceeding. */
4485 if (!visiting && EQ (Ffile_locked_p (lockname), Qt))
4486 call2 (intern ("ask-user-about-lock"), filename, Vuser_login_name);
4487 #endif
4489 lock_file (lockname);
4491 #endif /* CLASH_DETECTION */
4493 encoded_filename = ENCODE_FILE (filename);
4495 fn = XSTRING (encoded_filename)->data;
4496 desc = -1;
4497 if (!NILP (append))
4498 #ifdef DOS_NT
4499 desc = open (fn, O_WRONLY | buffer_file_type);
4500 #else /* not DOS_NT */
4501 desc = open (fn, O_WRONLY);
4502 #endif /* not DOS_NT */
4504 if (desc < 0 && (NILP (append) || errno == ENOENT))
4505 #ifdef VMS
4506 if (auto_saving) /* Overwrite any previous version of autosave file */
4508 vms_truncate (fn); /* if fn exists, truncate to zero length */
4509 desc = open (fn, O_RDWR);
4510 if (desc < 0)
4511 desc = creat_copy_attrs (STRINGP (current_buffer->filename)
4512 ? XSTRING (current_buffer->filename)->data : 0,
4513 fn);
4515 else /* Write to temporary name and rename if no errors */
4517 Lisp_Object temp_name;
4518 temp_name = Ffile_name_directory (filename);
4520 if (!NILP (temp_name))
4522 temp_name = Fmake_temp_name (concat2 (temp_name,
4523 build_string ("$$SAVE$$")));
4524 fname = XSTRING (filename)->data;
4525 fn = XSTRING (temp_name)->data;
4526 desc = creat_copy_attrs (fname, fn);
4527 if (desc < 0)
4529 /* If we can't open the temporary file, try creating a new
4530 version of the original file. VMS "creat" creates a
4531 new version rather than truncating an existing file. */
4532 fn = fname;
4533 fname = 0;
4534 desc = creat (fn, 0666);
4535 #if 0 /* This can clobber an existing file and fail to replace it,
4536 if the user runs out of space. */
4537 if (desc < 0)
4539 /* We can't make a new version;
4540 try to truncate and rewrite existing version if any. */
4541 vms_truncate (fn);
4542 desc = open (fn, O_RDWR);
4544 #endif
4547 else
4548 desc = creat (fn, 0666);
4550 #else /* not VMS */
4551 #ifdef DOS_NT
4552 desc = open (fn,
4553 O_WRONLY | O_TRUNC | O_CREAT | buffer_file_type
4554 | (mustbenew == Qexcl ? O_EXCL : 0),
4555 S_IREAD | S_IWRITE);
4556 #else /* not DOS_NT */
4557 desc = open (fn, O_WRONLY | O_TRUNC | O_CREAT
4558 | (mustbenew == Qexcl ? O_EXCL : 0),
4559 auto_saving ? auto_save_mode_bits : 0666);
4560 #endif /* not DOS_NT */
4561 #endif /* not VMS */
4563 UNGCPRO;
4565 if (desc < 0)
4567 #ifdef CLASH_DETECTION
4568 save_errno = errno;
4569 if (!auto_saving) unlock_file (lockname);
4570 errno = save_errno;
4571 #endif /* CLASH_DETECTION */
4572 report_file_error ("Opening output file", Fcons (filename, Qnil));
4575 record_unwind_protect (close_file_unwind, make_number (desc));
4577 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
4578 if (lseek (desc, 0, 2) < 0)
4580 #ifdef CLASH_DETECTION
4581 if (!auto_saving) unlock_file (lockname);
4582 #endif /* CLASH_DETECTION */
4583 report_file_error ("Lseek error", Fcons (filename, Qnil));
4586 #ifdef VMS
4588 * Kludge Warning: The VMS C RTL likes to insert carriage returns
4589 * if we do writes that don't end with a carriage return. Furthermore
4590 * it cannot handle writes of more then 16K. The modified
4591 * version of "sys_write" in SYSDEP.C (see comment there) copes with
4592 * this EXCEPT for the last record (iff it doesn't end with a carriage
4593 * return). This implies that if your buffer doesn't end with a carriage
4594 * return, you get one free... tough. However it also means that if
4595 * we make two calls to sys_write (a la the following code) you can
4596 * get one at the gap as well. The easiest way to fix this (honest)
4597 * is to move the gap to the next newline (or the end of the buffer).
4598 * Thus this change.
4600 * Yech!
4602 if (GPT > BEG && GPT_ADDR[-1] != '\n')
4603 move_gap (find_next_newline (GPT, 1));
4604 #else
4605 /* Whether VMS or not, we must move the gap to the next of newline
4606 when we must put designation sequences at beginning of line. */
4607 if (INTEGERP (start)
4608 && coding.type == coding_type_iso2022
4609 && coding.flags & CODING_FLAG_ISO_DESIGNATE_AT_BOL
4610 && GPT > BEG && GPT_ADDR[-1] != '\n')
4612 int opoint = PT, opoint_byte = PT_BYTE;
4613 scan_newline (PT, PT_BYTE, ZV, ZV_BYTE, 1, 0);
4614 move_gap_both (PT, PT_BYTE);
4615 SET_PT_BOTH (opoint, opoint_byte);
4617 #endif
4619 failure = 0;
4620 immediate_quit = 1;
4622 if (STRINGP (start))
4624 failure = 0 > a_write (desc, XSTRING (start)->data,
4625 STRING_BYTES (XSTRING (start)), 0, &annotations,
4626 &coding);
4627 save_errno = errno;
4629 else if (XINT (start) != XINT (end))
4631 register int end1 = CHAR_TO_BYTE (XINT (end));
4633 tem = CHAR_TO_BYTE (XINT (start));
4635 if (XINT (start) < GPT)
4637 failure = 0 > a_write (desc, BYTE_POS_ADDR (tem),
4638 min (GPT_BYTE, end1) - tem, tem, &annotations,
4639 &coding);
4640 save_errno = errno;
4643 if (XINT (end) > GPT && !failure)
4645 tem = max (tem, GPT_BYTE);
4646 failure = 0 > a_write (desc, BYTE_POS_ADDR (tem), end1 - tem,
4647 tem, &annotations, &coding);
4648 save_errno = errno;
4651 else
4653 /* If file was empty, still need to write the annotations */
4654 coding.mode |= CODING_MODE_LAST_BLOCK;
4655 failure = 0 > a_write (desc, "", 0, XINT (start), &annotations, &coding);
4656 save_errno = errno;
4659 if (CODING_REQUIRE_FLUSHING (&coding)
4660 && !(coding.mode & CODING_MODE_LAST_BLOCK)
4661 && ! failure)
4663 /* We have to flush out a data. */
4664 coding.mode |= CODING_MODE_LAST_BLOCK;
4665 failure = 0 > e_write (desc, "", 0, &coding);
4666 save_errno = errno;
4669 immediate_quit = 0;
4671 #ifdef HAVE_FSYNC
4672 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
4673 Disk full in NFS may be reported here. */
4674 /* mib says that closing the file will try to write as fast as NFS can do
4675 it, and that means the fsync here is not crucial for autosave files. */
4676 if (!auto_saving && fsync (desc) < 0)
4678 /* If fsync fails with EINTR, don't treat that as serious. */
4679 if (errno != EINTR)
4680 failure = 1, save_errno = errno;
4682 #endif
4684 /* Spurious "file has changed on disk" warnings have been
4685 observed on Suns as well.
4686 It seems that `close' can change the modtime, under nfs.
4688 (This has supposedly been fixed in Sunos 4,
4689 but who knows about all the other machines with NFS?) */
4690 #if 0
4692 /* On VMS and APOLLO, must do the stat after the close
4693 since closing changes the modtime. */
4694 #ifndef VMS
4695 #ifndef APOLLO
4696 /* Recall that #if defined does not work on VMS. */
4697 #define FOO
4698 fstat (desc, &st);
4699 #endif
4700 #endif
4701 #endif
4703 /* NFS can report a write failure now. */
4704 if (close (desc) < 0)
4705 failure = 1, save_errno = errno;
4707 #ifdef VMS
4708 /* If we wrote to a temporary name and had no errors, rename to real name. */
4709 if (fname)
4711 if (!failure)
4712 failure = (rename (fn, fname) != 0), save_errno = errno;
4713 fn = fname;
4715 #endif /* VMS */
4717 #ifndef FOO
4718 stat (fn, &st);
4719 #endif
4720 /* Discard the unwind protect for close_file_unwind. */
4721 specpdl_ptr = specpdl + count1;
4722 /* Restore the original current buffer. */
4723 visit_file = unbind_to (count, visit_file);
4725 #ifdef CLASH_DETECTION
4726 if (!auto_saving)
4727 unlock_file (lockname);
4728 #endif /* CLASH_DETECTION */
4730 /* Do this before reporting IO error
4731 to avoid a "file has changed on disk" warning on
4732 next attempt to save. */
4733 if (visiting)
4734 current_buffer->modtime = st.st_mtime;
4736 if (failure)
4737 error ("IO error writing %s: %s", XSTRING (filename)->data,
4738 strerror (save_errno));
4740 if (visiting)
4742 SAVE_MODIFF = MODIFF;
4743 XSETFASTINT (current_buffer->save_length, Z - BEG);
4744 current_buffer->filename = visit_file;
4745 update_mode_lines++;
4747 else if (quietly)
4748 return Qnil;
4750 if (!auto_saving)
4751 message_with_string ("Wrote %s", visit_file, 1);
4753 return Qnil;
4756 Lisp_Object merge ();
4758 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
4759 "Return t if (car A) is numerically less than (car B).")
4760 (a, b)
4761 Lisp_Object a, b;
4763 return Flss (Fcar (a), Fcar (b));
4766 /* Build the complete list of annotations appropriate for writing out
4767 the text between START and END, by calling all the functions in
4768 write-region-annotate-functions and merging the lists they return.
4769 If one of these functions switches to a different buffer, we assume
4770 that buffer contains altered text. Therefore, the caller must
4771 make sure to restore the current buffer in all cases,
4772 as save-excursion would do. */
4774 static Lisp_Object
4775 build_annotations (start, end, pre_write_conversion)
4776 Lisp_Object start, end, pre_write_conversion;
4778 Lisp_Object annotations;
4779 Lisp_Object p, res;
4780 struct gcpro gcpro1, gcpro2;
4781 Lisp_Object original_buffer;
4783 XSETBUFFER (original_buffer, current_buffer);
4785 annotations = Qnil;
4786 p = Vwrite_region_annotate_functions;
4787 GCPRO2 (annotations, p);
4788 while (!NILP (p))
4790 struct buffer *given_buffer = current_buffer;
4791 Vwrite_region_annotations_so_far = annotations;
4792 res = call2 (Fcar (p), start, end);
4793 /* If the function makes a different buffer current,
4794 assume that means this buffer contains altered text to be output.
4795 Reset START and END from the buffer bounds
4796 and discard all previous annotations because they should have
4797 been dealt with by this function. */
4798 if (current_buffer != given_buffer)
4800 XSETFASTINT (start, BEGV);
4801 XSETFASTINT (end, ZV);
4802 annotations = Qnil;
4804 Flength (res); /* Check basic validity of return value */
4805 annotations = merge (annotations, res, Qcar_less_than_car);
4806 p = Fcdr (p);
4809 /* Now do the same for annotation functions implied by the file-format */
4810 if (auto_saving && (!EQ (Vauto_save_file_format, Qt)))
4811 p = Vauto_save_file_format;
4812 else
4813 p = current_buffer->file_format;
4814 while (!NILP (p))
4816 struct buffer *given_buffer = current_buffer;
4817 Vwrite_region_annotations_so_far = annotations;
4818 res = call4 (Qformat_annotate_function, Fcar (p), start, end,
4819 original_buffer);
4820 if (current_buffer != given_buffer)
4822 XSETFASTINT (start, BEGV);
4823 XSETFASTINT (end, ZV);
4824 annotations = Qnil;
4826 Flength (res);
4827 annotations = merge (annotations, res, Qcar_less_than_car);
4828 p = Fcdr (p);
4831 /* At last, do the same for the function PRE_WRITE_CONVERSION
4832 implied by the current coding-system. */
4833 if (!NILP (pre_write_conversion))
4835 struct buffer *given_buffer = current_buffer;
4836 Vwrite_region_annotations_so_far = annotations;
4837 res = call2 (pre_write_conversion, start, end);
4838 Flength (res);
4839 annotations = (current_buffer != given_buffer
4840 ? res
4841 : merge (annotations, res, Qcar_less_than_car));
4844 UNGCPRO;
4845 return annotations;
4848 /* Write to descriptor DESC the NBYTES bytes starting at ADDR,
4849 assuming they start at byte position BYTEPOS in the buffer.
4850 Intersperse with them the annotations from *ANNOT
4851 which fall within the range of byte positions BYTEPOS to BYTEPOS + NBYTES,
4852 each at its appropriate position.
4854 We modify *ANNOT by discarding elements as we use them up.
4856 The return value is negative in case of system call failure. */
4858 static int
4859 a_write (desc, addr, nbytes, bytepos, annot, coding)
4860 int desc;
4861 register char *addr;
4862 register int nbytes;
4863 int bytepos;
4864 Lisp_Object *annot;
4865 struct coding_system *coding;
4867 Lisp_Object tem;
4868 int nextpos;
4869 int lastpos = bytepos + nbytes;
4871 while (NILP (*annot) || CONSP (*annot))
4873 tem = Fcar_safe (Fcar (*annot));
4874 nextpos = bytepos - 1;
4875 if (INTEGERP (tem))
4876 nextpos = CHAR_TO_BYTE (XFASTINT (tem));
4878 /* If there are no more annotations in this range,
4879 output the rest of the range all at once. */
4880 if (! (nextpos >= bytepos && nextpos <= lastpos))
4881 return e_write (desc, addr, lastpos - bytepos, coding);
4883 /* Output buffer text up to the next annotation's position. */
4884 if (nextpos > bytepos)
4886 if (0 > e_write (desc, addr, nextpos - bytepos, coding))
4887 return -1;
4888 addr += nextpos - bytepos;
4889 bytepos = nextpos;
4891 /* Output the annotation. */
4892 tem = Fcdr (Fcar (*annot));
4893 if (STRINGP (tem))
4895 if (0 > e_write (desc, XSTRING (tem)->data, STRING_BYTES (XSTRING (tem)),
4896 coding))
4897 return -1;
4899 *annot = Fcdr (*annot);
4901 return 0;
4904 #ifndef WRITE_BUF_SIZE
4905 #define WRITE_BUF_SIZE (16 * 1024)
4906 #endif
4908 /* Write NBYTES bytes starting at ADDR into descriptor DESC,
4909 encoding them with coding system CODING. */
4911 static int
4912 e_write (desc, addr, nbytes, coding)
4913 int desc;
4914 register char *addr;
4915 register int nbytes;
4916 struct coding_system *coding;
4918 char buf[WRITE_BUF_SIZE];
4920 /* We used to have a code for handling selective display here. But,
4921 now it is handled within encode_coding. */
4922 while (1)
4924 int result;
4926 result = encode_coding (coding, addr, buf, nbytes, WRITE_BUF_SIZE);
4927 nbytes -= coding->consumed, addr += coding->consumed;
4928 if (coding->produced > 0)
4930 coding->produced -= write (desc, buf, coding->produced);
4931 if (coding->produced) return -1;
4933 if (result == CODING_FINISH_INSUFFICIENT_SRC)
4935 /* The source text ends by an incomplete multibyte form.
4936 There's no way other than write it out as is. */
4937 nbytes -= write (desc, addr, nbytes);
4938 if (nbytes) return -1;
4940 if (nbytes <= 0)
4941 break;
4943 return 0;
4946 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
4947 Sverify_visited_file_modtime, 1, 1, 0,
4948 "Return t if last mod time of BUF's visited file matches what BUF records.\n\
4949 This means that the file has not been changed since it was visited or saved.")
4950 (buf)
4951 Lisp_Object buf;
4953 struct buffer *b;
4954 struct stat st;
4955 Lisp_Object handler;
4956 Lisp_Object filename;
4958 CHECK_BUFFER (buf, 0);
4959 b = XBUFFER (buf);
4961 if (!STRINGP (b->filename)) return Qt;
4962 if (b->modtime == 0) return Qt;
4964 /* If the file name has special constructs in it,
4965 call the corresponding file handler. */
4966 handler = Ffind_file_name_handler (b->filename,
4967 Qverify_visited_file_modtime);
4968 if (!NILP (handler))
4969 return call2 (handler, Qverify_visited_file_modtime, buf);
4971 filename = ENCODE_FILE (b->filename);
4973 if (stat (XSTRING (filename)->data, &st) < 0)
4975 /* If the file doesn't exist now and didn't exist before,
4976 we say that it isn't modified, provided the error is a tame one. */
4977 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
4978 st.st_mtime = -1;
4979 else
4980 st.st_mtime = 0;
4982 if (st.st_mtime == b->modtime
4983 /* If both are positive, accept them if they are off by one second. */
4984 || (st.st_mtime > 0 && b->modtime > 0
4985 && (st.st_mtime == b->modtime + 1
4986 || st.st_mtime == b->modtime - 1)))
4987 return Qt;
4988 return Qnil;
4991 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
4992 Sclear_visited_file_modtime, 0, 0, 0,
4993 "Clear out records of last mod time of visited file.\n\
4994 Next attempt to save will certainly not complain of a discrepancy.")
4997 current_buffer->modtime = 0;
4998 return Qnil;
5001 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5002 Svisited_file_modtime, 0, 0, 0,
5003 "Return the current buffer's recorded visited file modification time.\n\
5004 The value is a list of the form (HIGH . LOW), like the time values\n\
5005 that `file-attributes' returns.")
5008 return long_to_cons ((unsigned long) current_buffer->modtime);
5011 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5012 Sset_visited_file_modtime, 0, 1, 0,
5013 "Update buffer's recorded modification time from the visited file's time.\n\
5014 Useful if the buffer was not read from the file normally\n\
5015 or if the file itself has been changed for some known benign reason.\n\
5016 An argument specifies the modification time value to use\n\
5017 \(instead of that of the visited file), in the form of a list\n\
5018 \(HIGH . LOW) or (HIGH LOW).")
5019 (time_list)
5020 Lisp_Object time_list;
5022 if (!NILP (time_list))
5023 current_buffer->modtime = cons_to_long (time_list);
5024 else
5026 register Lisp_Object filename;
5027 struct stat st;
5028 Lisp_Object handler;
5030 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5032 /* If the file name has special constructs in it,
5033 call the corresponding file handler. */
5034 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5035 if (!NILP (handler))
5036 /* The handler can find the file name the same way we did. */
5037 return call2 (handler, Qset_visited_file_modtime, Qnil);
5039 filename = ENCODE_FILE (filename);
5041 if (stat (XSTRING (filename)->data, &st) >= 0)
5042 current_buffer->modtime = st.st_mtime;
5045 return Qnil;
5048 Lisp_Object
5049 auto_save_error ()
5051 ring_bell ();
5052 message_with_string ("Autosaving...error for %s", current_buffer->name, 1);
5053 Fsleep_for (make_number (1), Qnil);
5054 message_with_string ("Autosaving...error for %s", current_buffer->name, 0);
5055 Fsleep_for (make_number (1), Qnil);
5056 message_with_string ("Autosaving...error for %s", current_buffer->name, 0);
5057 Fsleep_for (make_number (1), Qnil);
5058 return Qnil;
5061 Lisp_Object
5062 auto_save_1 ()
5064 unsigned char *fn;
5065 struct stat st;
5067 /* Get visited file's mode to become the auto save file's mode. */
5068 if (stat (XSTRING (current_buffer->filename)->data, &st) >= 0)
5069 /* But make sure we can overwrite it later! */
5070 auto_save_mode_bits = st.st_mode | 0600;
5071 else
5072 auto_save_mode_bits = 0666;
5074 return
5075 Fwrite_region (Qnil, Qnil,
5076 current_buffer->auto_save_file_name,
5077 Qnil, Qlambda, Qnil, Qnil);
5080 static Lisp_Object
5081 do_auto_save_unwind (stream) /* used as unwind-protect function */
5082 Lisp_Object stream;
5084 auto_saving = 0;
5085 if (!NILP (stream))
5086 fclose ((FILE *) (XFASTINT (XCAR (stream)) << 16
5087 | XFASTINT (XCDR (stream))));
5088 return Qnil;
5091 static Lisp_Object
5092 do_auto_save_unwind_1 (value) /* used as unwind-protect function */
5093 Lisp_Object value;
5095 minibuffer_auto_raise = XINT (value);
5096 return Qnil;
5099 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5100 "Auto-save all buffers that need it.\n\
5101 This is all buffers that have auto-saving enabled\n\
5102 and are changed since last auto-saved.\n\
5103 Auto-saving writes the buffer into a file\n\
5104 so that your editing is not lost if the system crashes.\n\
5105 This file is not the file you visited; that changes only when you save.\n\
5106 Normally we run the normal hook `auto-save-hook' before saving.\n\n\
5107 A non-nil NO-MESSAGE argument means do not print any message if successful.\n\
5108 A non-nil CURRENT-ONLY argument means save only current buffer.")
5109 (no_message, current_only)
5110 Lisp_Object no_message, current_only;
5112 struct buffer *old = current_buffer, *b;
5113 Lisp_Object tail, buf;
5114 int auto_saved = 0;
5115 int do_handled_files;
5116 Lisp_Object oquit;
5117 FILE *stream;
5118 Lisp_Object lispstream;
5119 int count = specpdl_ptr - specpdl;
5120 int *ptr;
5121 int orig_minibuffer_auto_raise = minibuffer_auto_raise;
5122 int message_p = push_message ();
5124 /* Ordinarily don't quit within this function,
5125 but don't make it impossible to quit (in case we get hung in I/O). */
5126 oquit = Vquit_flag;
5127 Vquit_flag = Qnil;
5129 /* No GCPRO needed, because (when it matters) all Lisp_Object variables
5130 point to non-strings reached from Vbuffer_alist. */
5132 if (minibuf_level)
5133 no_message = Qt;
5135 if (!NILP (Vrun_hooks))
5136 call1 (Vrun_hooks, intern ("auto-save-hook"));
5138 if (STRINGP (Vauto_save_list_file_name))
5140 Lisp_Object listfile;
5141 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
5142 stream = fopen (XSTRING (listfile)->data, "w");
5143 if (stream != NULL)
5145 /* Arrange to close that file whether or not we get an error.
5146 Also reset auto_saving to 0. */
5147 lispstream = Fcons (Qnil, Qnil);
5148 XSETFASTINT (XCAR (lispstream), (EMACS_UINT)stream >> 16);
5149 XSETFASTINT (XCDR (lispstream), (EMACS_UINT)stream & 0xffff);
5151 else
5152 lispstream = Qnil;
5154 else
5156 stream = NULL;
5157 lispstream = Qnil;
5160 record_unwind_protect (do_auto_save_unwind, lispstream);
5161 record_unwind_protect (do_auto_save_unwind_1,
5162 make_number (minibuffer_auto_raise));
5163 minibuffer_auto_raise = 0;
5164 auto_saving = 1;
5166 /* First, save all files which don't have handlers. If Emacs is
5167 crashing, the handlers may tweak what is causing Emacs to crash
5168 in the first place, and it would be a shame if Emacs failed to
5169 autosave perfectly ordinary files because it couldn't handle some
5170 ange-ftp'd file. */
5171 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5172 for (tail = Vbuffer_alist; GC_CONSP (tail); tail = XCDR (tail))
5174 buf = XCDR (XCAR (tail));
5175 b = XBUFFER (buf);
5177 /* Record all the buffers that have auto save mode
5178 in the special file that lists them. For each of these buffers,
5179 Record visited name (if any) and auto save name. */
5180 if (STRINGP (b->auto_save_file_name)
5181 && stream != NULL && do_handled_files == 0)
5183 if (!NILP (b->filename))
5185 fwrite (XSTRING (b->filename)->data, 1,
5186 STRING_BYTES (XSTRING (b->filename)), stream);
5188 putc ('\n', stream);
5189 fwrite (XSTRING (b->auto_save_file_name)->data, 1,
5190 STRING_BYTES (XSTRING (b->auto_save_file_name)), stream);
5191 putc ('\n', stream);
5194 if (!NILP (current_only)
5195 && b != current_buffer)
5196 continue;
5198 /* Don't auto-save indirect buffers.
5199 The base buffer takes care of it. */
5200 if (b->base_buffer)
5201 continue;
5203 /* Check for auto save enabled
5204 and file changed since last auto save
5205 and file changed since last real save. */
5206 if (STRINGP (b->auto_save_file_name)
5207 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5208 && b->auto_save_modified < BUF_MODIFF (b)
5209 /* -1 means we've turned off autosaving for a while--see below. */
5210 && XINT (b->save_length) >= 0
5211 && (do_handled_files
5212 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
5213 Qwrite_region))))
5215 EMACS_TIME before_time, after_time;
5217 EMACS_GET_TIME (before_time);
5219 /* If we had a failure, don't try again for 20 minutes. */
5220 if (b->auto_save_failure_time >= 0
5221 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5222 continue;
5224 if ((XFASTINT (b->save_length) * 10
5225 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5226 /* A short file is likely to change a large fraction;
5227 spare the user annoying messages. */
5228 && XFASTINT (b->save_length) > 5000
5229 /* These messages are frequent and annoying for `*mail*'. */
5230 && !EQ (b->filename, Qnil)
5231 && NILP (no_message))
5233 /* It has shrunk too much; turn off auto-saving here. */
5234 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5235 message_with_string ("Buffer %s has shrunk a lot; auto save turned off there",
5236 b->name, 1);
5237 minibuffer_auto_raise = 0;
5238 /* Turn off auto-saving until there's a real save,
5239 and prevent any more warnings. */
5240 XSETINT (b->save_length, -1);
5241 Fsleep_for (make_number (1), Qnil);
5242 continue;
5244 set_buffer_internal (b);
5245 if (!auto_saved && NILP (no_message))
5246 message1 ("Auto-saving...");
5247 internal_condition_case (auto_save_1, Qt, auto_save_error);
5248 auto_saved++;
5249 b->auto_save_modified = BUF_MODIFF (b);
5250 XSETFASTINT (current_buffer->save_length, Z - BEG);
5251 set_buffer_internal (old);
5253 EMACS_GET_TIME (after_time);
5255 /* If auto-save took more than 60 seconds,
5256 assume it was an NFS failure that got a timeout. */
5257 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5258 b->auto_save_failure_time = EMACS_SECS (after_time);
5262 /* Prevent another auto save till enough input events come in. */
5263 record_auto_save ();
5265 if (auto_saved && NILP (no_message))
5267 if (message_p)
5269 sit_for (1, 0, 0, 0, 0);
5270 restore_message ();
5272 else
5273 message1 ("Auto-saving...done");
5276 Vquit_flag = oquit;
5278 pop_message ();
5279 unbind_to (count, Qnil);
5280 return Qnil;
5283 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5284 Sset_buffer_auto_saved, 0, 0, 0,
5285 "Mark current buffer as auto-saved with its current text.\n\
5286 No auto-save file will be written until the buffer changes again.")
5289 current_buffer->auto_save_modified = MODIFF;
5290 XSETFASTINT (current_buffer->save_length, Z - BEG);
5291 current_buffer->auto_save_failure_time = -1;
5292 return Qnil;
5295 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5296 Sclear_buffer_auto_save_failure, 0, 0, 0,
5297 "Clear any record of a recent auto-save failure in the current buffer.")
5300 current_buffer->auto_save_failure_time = -1;
5301 return Qnil;
5304 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5305 0, 0, 0,
5306 "Return t if buffer has been auto-saved since last read in or saved.")
5309 return (SAVE_MODIFF < current_buffer->auto_save_modified) ? Qt : Qnil;
5312 /* Reading and completing file names */
5313 extern Lisp_Object Ffile_name_completion (), Ffile_name_all_completions ();
5315 /* In the string VAL, change each $ to $$ and return the result. */
5317 static Lisp_Object
5318 double_dollars (val)
5319 Lisp_Object val;
5321 register unsigned char *old, *new;
5322 register int n;
5323 int osize, count;
5325 osize = STRING_BYTES (XSTRING (val));
5327 /* Count the number of $ characters. */
5328 for (n = osize, count = 0, old = XSTRING (val)->data; n > 0; n--)
5329 if (*old++ == '$') count++;
5330 if (count > 0)
5332 old = XSTRING (val)->data;
5333 val = make_uninit_multibyte_string (XSTRING (val)->size + count,
5334 osize + count);
5335 new = XSTRING (val)->data;
5336 for (n = osize; n > 0; n--)
5337 if (*old != '$')
5338 *new++ = *old++;
5339 else
5341 *new++ = '$';
5342 *new++ = '$';
5343 old++;
5346 return val;
5349 DEFUN ("read-file-name-internal", Fread_file_name_internal, Sread_file_name_internal,
5350 3, 3, 0,
5351 "Internal subroutine for read-file-name. Do not call this.")
5352 (string, dir, action)
5353 Lisp_Object string, dir, action;
5354 /* action is nil for complete, t for return list of completions,
5355 lambda for verify final value */
5357 Lisp_Object name, specdir, realdir, val, orig_string;
5358 int changed;
5359 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
5361 CHECK_STRING (string, 0);
5363 realdir = dir;
5364 name = string;
5365 orig_string = Qnil;
5366 specdir = Qnil;
5367 changed = 0;
5368 /* No need to protect ACTION--we only compare it with t and nil. */
5369 GCPRO5 (string, realdir, name, specdir, orig_string);
5371 if (XSTRING (string)->size == 0)
5373 if (EQ (action, Qlambda))
5375 UNGCPRO;
5376 return Qnil;
5379 else
5381 orig_string = string;
5382 string = Fsubstitute_in_file_name (string);
5383 changed = NILP (Fstring_equal (string, orig_string));
5384 name = Ffile_name_nondirectory (string);
5385 val = Ffile_name_directory (string);
5386 if (! NILP (val))
5387 realdir = Fexpand_file_name (val, realdir);
5390 if (NILP (action))
5392 specdir = Ffile_name_directory (string);
5393 val = Ffile_name_completion (name, realdir);
5394 UNGCPRO;
5395 if (!STRINGP (val))
5397 if (changed)
5398 return double_dollars (string);
5399 return val;
5402 if (!NILP (specdir))
5403 val = concat2 (specdir, val);
5404 #ifndef VMS
5405 return double_dollars (val);
5406 #else /* not VMS */
5407 return val;
5408 #endif /* not VMS */
5410 UNGCPRO;
5412 if (EQ (action, Qt))
5413 return Ffile_name_all_completions (name, realdir);
5414 /* Only other case actually used is ACTION = lambda */
5415 #ifdef VMS
5416 /* Supposedly this helps commands such as `cd' that read directory names,
5417 but can someone explain how it helps them? -- RMS */
5418 if (XSTRING (name)->size == 0)
5419 return Qt;
5420 #endif /* VMS */
5421 return Ffile_exists_p (string);
5424 DEFUN ("read-file-name", Fread_file_name, Sread_file_name, 1, 5, 0,
5425 "Read file name, prompting with PROMPT and completing in directory DIR.\n\
5426 Value is not expanded---you must call `expand-file-name' yourself.\n\
5427 Default name to DEFAULT-FILENAME if user enters a null string.\n\
5428 (If DEFAULT-FILENAME is omitted, the visited file name is used,\n\
5429 except that if INITIAL is specified, that combined with DIR is used.)\n\
5430 Fourth arg MUSTMATCH non-nil means require existing file's name.\n\
5431 Non-nil and non-t means also require confirmation after completion.\n\
5432 Fifth arg INITIAL specifies text to start with.\n\
5433 DIR defaults to current buffer's directory default.")
5434 (prompt, dir, default_filename, mustmatch, initial)
5435 Lisp_Object prompt, dir, default_filename, mustmatch, initial;
5437 Lisp_Object val, insdef, tem;
5438 struct gcpro gcpro1, gcpro2;
5439 register char *homedir;
5440 int replace_in_history = 0;
5441 int add_to_history = 0;
5442 int count;
5444 if (NILP (dir))
5445 dir = current_buffer->directory;
5446 if (NILP (default_filename))
5448 if (! NILP (initial))
5449 default_filename = Fexpand_file_name (initial, dir);
5450 else
5451 default_filename = current_buffer->filename;
5454 /* If dir starts with user's homedir, change that to ~. */
5455 homedir = (char *) egetenv ("HOME");
5456 #ifdef DOS_NT
5457 homedir = strcpy (alloca (strlen (homedir) + 1), homedir);
5458 CORRECT_DIR_SEPS (homedir);
5459 #endif
5460 if (homedir != 0
5461 && STRINGP (dir)
5462 && !strncmp (homedir, XSTRING (dir)->data, strlen (homedir))
5463 && IS_DIRECTORY_SEP (XSTRING (dir)->data[strlen (homedir)]))
5465 dir = make_string (XSTRING (dir)->data + strlen (homedir) - 1,
5466 STRING_BYTES (XSTRING (dir)) - strlen (homedir) + 1);
5467 XSTRING (dir)->data[0] = '~';
5469 /* Likewise for default_filename. */
5470 if (homedir != 0
5471 && STRINGP (default_filename)
5472 && !strncmp (homedir, XSTRING (default_filename)->data, strlen (homedir))
5473 && IS_DIRECTORY_SEP (XSTRING (default_filename)->data[strlen (homedir)]))
5475 default_filename
5476 = make_string (XSTRING (default_filename)->data + strlen (homedir) - 1,
5477 STRING_BYTES (XSTRING (default_filename)) - strlen (homedir) + 1);
5478 XSTRING (default_filename)->data[0] = '~';
5480 if (!NILP (default_filename))
5482 CHECK_STRING (default_filename, 3);
5483 default_filename = double_dollars (default_filename);
5486 if (insert_default_directory && STRINGP (dir))
5488 insdef = dir;
5489 if (!NILP (initial))
5491 Lisp_Object args[2], pos;
5493 args[0] = insdef;
5494 args[1] = initial;
5495 insdef = Fconcat (2, args);
5496 pos = make_number (XSTRING (double_dollars (dir))->size);
5497 insdef = Fcons (double_dollars (insdef), pos);
5499 else
5500 insdef = double_dollars (insdef);
5502 else if (STRINGP (initial))
5503 insdef = Fcons (double_dollars (initial), make_number (0));
5504 else
5505 insdef = Qnil;
5507 count = specpdl_ptr - specpdl;
5508 #ifdef VMS
5509 specbind (intern ("completion-ignore-case"), Qt);
5510 #endif
5512 specbind (intern ("minibuffer-completing-file-name"), Qt);
5514 GCPRO2 (insdef, default_filename);
5516 #ifdef USE_MOTIF
5517 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
5518 && use_dialog_box
5519 && have_menus_p ())
5521 val = Fx_file_dialog (prompt, dir, default_filename, mustmatch);
5522 add_to_history = 1;
5524 else
5525 #endif
5526 val = Fcompleting_read (prompt, intern ("read-file-name-internal"),
5527 dir, mustmatch, insdef,
5528 Qfile_name_history, default_filename, Qnil);
5530 tem = Fsymbol_value (Qfile_name_history);
5531 if (CONSP (tem) && EQ (XCAR (tem), val))
5532 replace_in_history = 1;
5534 /* If Fcompleting_read returned the inserted default string itself
5535 (rather than a new string with the same contents),
5536 it has to mean that the user typed RET with the minibuffer empty.
5537 In that case, we really want to return ""
5538 so that commands such as set-visited-file-name can distinguish. */
5539 if (EQ (val, default_filename))
5541 /* In this case, Fcompleting_read has not added an element
5542 to the history. Maybe we should. */
5543 if (! replace_in_history)
5544 add_to_history = 1;
5546 val = build_string ("");
5549 unbind_to (count, Qnil);
5550 UNGCPRO;
5551 if (NILP (val))
5552 error ("No file name specified");
5554 tem = Fstring_equal (val, CONSP (insdef) ? XCAR (insdef) : insdef);
5556 if (!NILP (tem) && !NILP (default_filename))
5557 val = default_filename;
5558 else if (XSTRING (val)->size == 0 && NILP (insdef))
5560 if (!NILP (default_filename))
5561 val = default_filename;
5562 else
5563 error ("No default file name");
5565 val = Fsubstitute_in_file_name (val);
5567 if (replace_in_history)
5568 /* Replace what Fcompleting_read added to the history
5569 with what we will actually return. */
5570 XCAR (Fsymbol_value (Qfile_name_history)) = double_dollars (val);
5571 else if (add_to_history)
5573 /* Add the value to the history--but not if it matches
5574 the last value already there. */
5575 Lisp_Object val1 = double_dollars (val);
5576 tem = Fsymbol_value (Qfile_name_history);
5577 if (! CONSP (tem) || NILP (Fequal (XCAR (tem), val1)))
5578 Fset (Qfile_name_history,
5579 Fcons (val1, tem));
5582 return val;
5586 void
5587 init_fileio_once ()
5589 /* Must be set before any path manipulation is performed. */
5590 XSETFASTINT (Vdirectory_sep_char, '/');
5594 void
5595 syms_of_fileio ()
5597 Qexpand_file_name = intern ("expand-file-name");
5598 Qsubstitute_in_file_name = intern ("substitute-in-file-name");
5599 Qdirectory_file_name = intern ("directory-file-name");
5600 Qfile_name_directory = intern ("file-name-directory");
5601 Qfile_name_nondirectory = intern ("file-name-nondirectory");
5602 Qunhandled_file_name_directory = intern ("unhandled-file-name-directory");
5603 Qfile_name_as_directory = intern ("file-name-as-directory");
5604 Qcopy_file = intern ("copy-file");
5605 Qmake_directory_internal = intern ("make-directory-internal");
5606 Qdelete_directory = intern ("delete-directory");
5607 Qdelete_file = intern ("delete-file");
5608 Qrename_file = intern ("rename-file");
5609 Qadd_name_to_file = intern ("add-name-to-file");
5610 Qmake_symbolic_link = intern ("make-symbolic-link");
5611 Qfile_exists_p = intern ("file-exists-p");
5612 Qfile_executable_p = intern ("file-executable-p");
5613 Qfile_readable_p = intern ("file-readable-p");
5614 Qfile_writable_p = intern ("file-writable-p");
5615 Qfile_symlink_p = intern ("file-symlink-p");
5616 Qaccess_file = intern ("access-file");
5617 Qfile_directory_p = intern ("file-directory-p");
5618 Qfile_regular_p = intern ("file-regular-p");
5619 Qfile_accessible_directory_p = intern ("file-accessible-directory-p");
5620 Qfile_modes = intern ("file-modes");
5621 Qset_file_modes = intern ("set-file-modes");
5622 Qfile_newer_than_file_p = intern ("file-newer-than-file-p");
5623 Qinsert_file_contents = intern ("insert-file-contents");
5624 Qwrite_region = intern ("write-region");
5625 Qverify_visited_file_modtime = intern ("verify-visited-file-modtime");
5626 Qset_visited_file_modtime = intern ("set-visited-file-modtime");
5628 staticpro (&Qexpand_file_name);
5629 staticpro (&Qsubstitute_in_file_name);
5630 staticpro (&Qdirectory_file_name);
5631 staticpro (&Qfile_name_directory);
5632 staticpro (&Qfile_name_nondirectory);
5633 staticpro (&Qunhandled_file_name_directory);
5634 staticpro (&Qfile_name_as_directory);
5635 staticpro (&Qcopy_file);
5636 staticpro (&Qmake_directory_internal);
5637 staticpro (&Qdelete_directory);
5638 staticpro (&Qdelete_file);
5639 staticpro (&Qrename_file);
5640 staticpro (&Qadd_name_to_file);
5641 staticpro (&Qmake_symbolic_link);
5642 staticpro (&Qfile_exists_p);
5643 staticpro (&Qfile_executable_p);
5644 staticpro (&Qfile_readable_p);
5645 staticpro (&Qfile_writable_p);
5646 staticpro (&Qaccess_file);
5647 staticpro (&Qfile_symlink_p);
5648 staticpro (&Qfile_directory_p);
5649 staticpro (&Qfile_regular_p);
5650 staticpro (&Qfile_accessible_directory_p);
5651 staticpro (&Qfile_modes);
5652 staticpro (&Qset_file_modes);
5653 staticpro (&Qfile_newer_than_file_p);
5654 staticpro (&Qinsert_file_contents);
5655 staticpro (&Qwrite_region);
5656 staticpro (&Qverify_visited_file_modtime);
5657 staticpro (&Qset_visited_file_modtime);
5659 Qfile_name_history = intern ("file-name-history");
5660 Fset (Qfile_name_history, Qnil);
5661 staticpro (&Qfile_name_history);
5663 Qfile_error = intern ("file-error");
5664 staticpro (&Qfile_error);
5665 Qfile_already_exists = intern ("file-already-exists");
5666 staticpro (&Qfile_already_exists);
5667 Qfile_date_error = intern ("file-date-error");
5668 staticpro (&Qfile_date_error);
5669 Qexcl = intern ("excl");
5670 staticpro (&Qexcl);
5672 #ifdef DOS_NT
5673 Qfind_buffer_file_type = intern ("find-buffer-file-type");
5674 staticpro (&Qfind_buffer_file_type);
5675 #endif /* DOS_NT */
5677 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
5678 "*Coding system for encoding file names.\n\
5679 If it is nil, default-file-name-coding-system (which see) is used.");
5680 Vfile_name_coding_system = Qnil;
5682 DEFVAR_LISP ("default-file-name-coding-system",
5683 &Vdefault_file_name_coding_system,
5684 "Default coding system for encoding file names.\n\
5685 This variable is used only when file-name-coding-system is nil.\n\
5687 This variable is set/changed by the command set-language-environment.\n\
5688 User should not set this variable manually,\n\
5689 instead use file-name-coding-system to get a constant encoding\n\
5690 of file names regardless of the current language environment.");
5691 Vdefault_file_name_coding_system = Qnil;
5693 DEFVAR_LISP ("auto-save-file-format", &Vauto_save_file_format,
5694 "*Format in which to write auto-save files.\n\
5695 Should be a list of symbols naming formats that are defined in `format-alist'.\n\
5696 If it is t, which is the default, auto-save files are written in the\n\
5697 same format as a regular save would use.");
5698 Vauto_save_file_format = Qt;
5700 Qformat_decode = intern ("format-decode");
5701 staticpro (&Qformat_decode);
5702 Qformat_annotate_function = intern ("format-annotate-function");
5703 staticpro (&Qformat_annotate_function);
5705 Qcar_less_than_car = intern ("car-less-than-car");
5706 staticpro (&Qcar_less_than_car);
5708 Fput (Qfile_error, Qerror_conditions,
5709 Fcons (Qfile_error, Fcons (Qerror, Qnil)));
5710 Fput (Qfile_error, Qerror_message,
5711 build_string ("File error"));
5713 Fput (Qfile_already_exists, Qerror_conditions,
5714 Fcons (Qfile_already_exists,
5715 Fcons (Qfile_error, Fcons (Qerror, Qnil))));
5716 Fput (Qfile_already_exists, Qerror_message,
5717 build_string ("File already exists"));
5719 Fput (Qfile_date_error, Qerror_conditions,
5720 Fcons (Qfile_date_error,
5721 Fcons (Qfile_error, Fcons (Qerror, Qnil))));
5722 Fput (Qfile_date_error, Qerror_message,
5723 build_string ("Cannot set file date"));
5725 DEFVAR_BOOL ("insert-default-directory", &insert_default_directory,
5726 "*Non-nil means when reading a filename start with default dir in minibuffer.");
5727 insert_default_directory = 1;
5729 DEFVAR_BOOL ("vms-stmlf-recfm", &vms_stmlf_recfm,
5730 "*Non-nil means write new files with record format `stmlf'.\n\
5731 nil means use format `var'. This variable is meaningful only on VMS.");
5732 vms_stmlf_recfm = 0;
5734 DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char,
5735 "Directory separator character for built-in functions that return file names.\n\
5736 The value should be either ?/ or ?\\ (any other value is treated as ?\\).\n\
5737 This variable affects the built-in functions only on Windows,\n\
5738 on other platforms, it is initialized so that Lisp code can find out\n\
5739 what the normal separator is.");
5741 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
5742 "*Alist of elements (REGEXP . HANDLER) for file names handled specially.\n\
5743 If a file name matches REGEXP, then all I/O on that file is done by calling\n\
5744 HANDLER.\n\
5746 The first argument given to HANDLER is the name of the I/O primitive\n\
5747 to be handled; the remaining arguments are the arguments that were\n\
5748 passed to that primitive. For example, if you do\n\
5749 (file-exists-p FILENAME)\n\
5750 and FILENAME is handled by HANDLER, then HANDLER is called like this:\n\
5751 (funcall HANDLER 'file-exists-p FILENAME)\n\
5752 The function `find-file-name-handler' checks this list for a handler\n\
5753 for its argument.");
5754 Vfile_name_handler_alist = Qnil;
5756 DEFVAR_LISP ("set-auto-coding-function",
5757 &Vset_auto_coding_function,
5758 "If non-nil, a function to call to decide a coding system of file.\n\
5759 Two arguments are passed to this function: the file name\n\
5760 and the length of a file contents following the point.\n\
5761 This function should return a coding system to decode the file contents.\n\
5762 It should check the file name against `auto-coding-alist'.\n\
5763 If no coding system is decided, it should check a coding system\n\
5764 specified in the heading lines with the format:\n\
5765 -*- ... coding: CODING-SYSTEM; ... -*-\n\
5766 or local variable spec of the tailing lines with `coding:' tag.");
5767 Vset_auto_coding_function = Qnil;
5769 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
5770 "A list of functions to be called at the end of `insert-file-contents'.\n\
5771 Each is passed one argument, the number of bytes inserted. It should return\n\
5772 the new byte count, and leave point the same. If `insert-file-contents' is\n\
5773 intercepted by a handler from `file-name-handler-alist', that handler is\n\
5774 responsible for calling the after-insert-file-functions if appropriate.");
5775 Vafter_insert_file_functions = Qnil;
5777 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
5778 "A list of functions to be called at the start of `write-region'.\n\
5779 Each is passed two arguments, START and END as for `write-region'.\n\
5780 These are usually two numbers but not always; see the documentation\n\
5781 for `write-region'. The function should return a list of pairs\n\
5782 of the form (POSITION . STRING), consisting of strings to be effectively\n\
5783 inserted at the specified positions of the file being written (1 means to\n\
5784 insert before the first byte written). The POSITIONs must be sorted into\n\
5785 increasing order. If there are several functions in the list, the several\n\
5786 lists are merged destructively.");
5787 Vwrite_region_annotate_functions = Qnil;
5789 DEFVAR_LISP ("write-region-annotations-so-far",
5790 &Vwrite_region_annotations_so_far,
5791 "When an annotation function is called, this holds the previous annotations.\n\
5792 These are the annotations made by other annotation functions\n\
5793 that were already called. See also `write-region-annotate-functions'.");
5794 Vwrite_region_annotations_so_far = Qnil;
5796 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
5797 "A list of file name handlers that temporarily should not be used.\n\
5798 This applies only to the operation `inhibit-file-name-operation'.");
5799 Vinhibit_file_name_handlers = Qnil;
5801 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
5802 "The operation for which `inhibit-file-name-handlers' is applicable.");
5803 Vinhibit_file_name_operation = Qnil;
5805 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
5806 "File name in which we write a list of all auto save file names.\n\
5807 This variable is initialized automatically from `auto-save-list-file-prefix'\n\
5808 shortly after Emacs reads your `.emacs' file, if you have not yet given it\n\
5809 a non-nil value.");
5810 Vauto_save_list_file_name = Qnil;
5812 defsubr (&Sfind_file_name_handler);
5813 defsubr (&Sfile_name_directory);
5814 defsubr (&Sfile_name_nondirectory);
5815 defsubr (&Sunhandled_file_name_directory);
5816 defsubr (&Sfile_name_as_directory);
5817 defsubr (&Sdirectory_file_name);
5818 defsubr (&Smake_temp_name);
5819 defsubr (&Sexpand_file_name);
5820 defsubr (&Ssubstitute_in_file_name);
5821 defsubr (&Scopy_file);
5822 defsubr (&Smake_directory_internal);
5823 defsubr (&Sdelete_directory);
5824 defsubr (&Sdelete_file);
5825 defsubr (&Srename_file);
5826 defsubr (&Sadd_name_to_file);
5827 #ifdef S_IFLNK
5828 defsubr (&Smake_symbolic_link);
5829 #endif /* S_IFLNK */
5830 #ifdef VMS
5831 defsubr (&Sdefine_logical_name);
5832 #endif /* VMS */
5833 #ifdef HPUX_NET
5834 defsubr (&Ssysnetunam);
5835 #endif /* HPUX_NET */
5836 defsubr (&Sfile_name_absolute_p);
5837 defsubr (&Sfile_exists_p);
5838 defsubr (&Sfile_executable_p);
5839 defsubr (&Sfile_readable_p);
5840 defsubr (&Sfile_writable_p);
5841 defsubr (&Saccess_file);
5842 defsubr (&Sfile_symlink_p);
5843 defsubr (&Sfile_directory_p);
5844 defsubr (&Sfile_accessible_directory_p);
5845 defsubr (&Sfile_regular_p);
5846 defsubr (&Sfile_modes);
5847 defsubr (&Sset_file_modes);
5848 defsubr (&Sset_default_file_modes);
5849 defsubr (&Sdefault_file_modes);
5850 defsubr (&Sfile_newer_than_file_p);
5851 defsubr (&Sinsert_file_contents);
5852 defsubr (&Swrite_region);
5853 defsubr (&Scar_less_than_car);
5854 defsubr (&Sverify_visited_file_modtime);
5855 defsubr (&Sclear_visited_file_modtime);
5856 defsubr (&Svisited_file_modtime);
5857 defsubr (&Sset_visited_file_modtime);
5858 defsubr (&Sdo_auto_save);
5859 defsubr (&Sset_buffer_auto_saved);
5860 defsubr (&Sclear_buffer_auto_save_failure);
5861 defsubr (&Srecent_auto_save_p);
5863 defsubr (&Sread_file_name_internal);
5864 defsubr (&Sread_file_name);
5866 #ifdef unix
5867 defsubr (&Sunix_sync);
5868 #endif