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