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