Merge from emacs--devo--0
[emacs/old-mirror.git] / src / fileio.c
blob2cdc5323d8e70c269e9939e92d5f5d952c395295
1 /* File IO for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995, 1996,
3 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
23 #include <config.h>
25 #ifdef HAVE_FCNTL_H
26 #include <fcntl.h>
27 #endif
29 #include <stdio.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
37 #if !defined (S_ISLNK) && defined (S_IFLNK)
38 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
39 #endif
41 #if !defined (S_ISFIFO) && defined (S_IFIFO)
42 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
43 #endif
45 #if !defined (S_ISREG) && defined (S_IFREG)
46 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
47 #endif
49 #ifdef HAVE_PWD_H
50 #include <pwd.h>
51 #endif
53 #include <ctype.h>
55 #ifdef VMS
56 #include "vmsdir.h"
57 #include <perror.h>
58 #include <stddef.h>
59 #include <string.h>
60 #endif
62 #include <errno.h>
64 #ifndef vax11c
65 #ifndef USE_CRT_DLL
66 extern int errno;
67 #endif
68 #endif
70 #ifdef APOLLO
71 #include <sys/time.h>
72 #endif
74 #include "lisp.h"
75 #include "intervals.h"
76 #include "buffer.h"
77 #include "character.h"
78 #include "coding.h"
79 #include "window.h"
80 #include "blockinput.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 #ifndef FILE_SYSTEM_CASE
152 #define FILE_SYSTEM_CASE(filename) (filename)
153 #endif
155 /* Nonzero during writing of auto-save files */
156 int auto_saving;
158 /* Set by auto_save_1 to mode of original file so Fwrite_region will create
159 a new file with the same mode as the original */
160 int auto_save_mode_bits;
162 /* The symbol bound to coding-system-for-read when
163 insert-file-contents is called for recovering a file. This is not
164 an actual coding system name, but just an indicator to tell
165 insert-file-contents to use `emacs-mule' with a special flag for
166 auto saving and recovering a file. */
167 Lisp_Object Qauto_save_coding;
169 /* Coding system for file names, or nil if none. */
170 Lisp_Object Vfile_name_coding_system;
172 /* Coding system for file names used only when
173 Vfile_name_coding_system is nil. */
174 Lisp_Object Vdefault_file_name_coding_system;
176 /* Alist of elements (REGEXP . HANDLER) for file names
177 whose I/O is done with a special handler. */
178 Lisp_Object Vfile_name_handler_alist;
180 /* Property name of a file name handler,
181 which gives a list of operations it handles.. */
182 Lisp_Object Qoperations;
184 /* Lisp functions for translating file formats */
185 Lisp_Object Qformat_decode, Qformat_annotate_function;
187 /* Function to be called to decide a coding system of a reading file. */
188 Lisp_Object Vset_auto_coding_function;
190 /* Functions to be called to process text properties in inserted file. */
191 Lisp_Object Vafter_insert_file_functions;
193 /* Lisp function for setting buffer-file-coding-system and the
194 multibyteness of the current buffer after inserting a file. */
195 Lisp_Object Qafter_insert_file_set_coding;
197 /* Functions to be called to create text property annotations for file. */
198 Lisp_Object Vwrite_region_annotate_functions;
199 Lisp_Object Qwrite_region_annotate_functions;
201 /* During build_annotations, each time an annotation function is called,
202 this holds the annotations made by the previous functions. */
203 Lisp_Object Vwrite_region_annotations_so_far;
205 /* File name in which we write a list of all our auto save files. */
206 Lisp_Object Vauto_save_list_file_name;
208 /* Function to call to read a file name. */
209 Lisp_Object Vread_file_name_function;
211 /* Current predicate used by read_file_name_internal. */
212 Lisp_Object Vread_file_name_predicate;
214 /* Nonzero means completion ignores case when reading file name. */
215 int read_file_name_completion_ignore_case;
217 /* Nonzero means, when reading a filename in the minibuffer,
218 start out by inserting the default directory into the minibuffer. */
219 int insert_default_directory;
221 /* On VMS, nonzero means write new files with record format stmlf.
222 Zero means use var format. */
223 int vms_stmlf_recfm;
225 /* On NT, specifies the directory separator character, used (eg.) when
226 expanding file names. This can be bound to / or \. */
227 Lisp_Object Vdirectory_sep_char;
229 #ifdef HAVE_FSYNC
230 /* Nonzero means skip the call to fsync in Fwrite-region. */
231 int write_region_inhibit_fsync;
232 #endif
234 extern Lisp_Object Vuser_login_name;
236 #ifdef WINDOWSNT
237 extern Lisp_Object Vw32_get_true_file_attributes;
238 #endif
240 extern int minibuf_level;
242 extern int minibuffer_auto_raise;
244 extern int history_delete_duplicates;
246 /* These variables describe handlers that have "already" had a chance
247 to handle the current operation.
249 Vinhibit_file_name_handlers is a list of file name handlers.
250 Vinhibit_file_name_operation is the operation being handled.
251 If we try to handle that operation, we ignore those handlers. */
253 static Lisp_Object Vinhibit_file_name_handlers;
254 static Lisp_Object Vinhibit_file_name_operation;
256 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
257 Lisp_Object Qexcl;
258 Lisp_Object Qfile_name_history;
260 Lisp_Object Qcar_less_than_car;
262 static int a_write P_ ((int, Lisp_Object, int, int,
263 Lisp_Object *, struct coding_system *));
264 static int e_write P_ ((int, Lisp_Object, int, int, struct coding_system *));
267 void
268 report_file_error (string, data)
269 const char *string;
270 Lisp_Object data;
272 Lisp_Object errstring;
273 int errorno = errno;
274 char *str;
276 synchronize_system_messages_locale ();
277 str = strerror (errorno);
278 errstring = code_convert_string_norecord (make_unibyte_string (str,
279 strlen (str)),
280 Vlocale_coding_system, 0);
282 while (1)
283 switch (errorno)
285 case EEXIST:
286 xsignal (Qfile_already_exists, Fcons (errstring, data));
287 break;
288 default:
289 /* System error messages are capitalized. Downcase the initial
290 unless it is followed by a slash. */
291 if (SREF (errstring, 1) != '/')
292 SSET (errstring, 0, DOWNCASE (SREF (errstring, 0)));
294 xsignal (Qfile_error,
295 Fcons (build_string (string), Fcons (errstring, data)));
299 Lisp_Object
300 close_file_unwind (fd)
301 Lisp_Object fd;
303 emacs_close (XFASTINT (fd));
304 return Qnil;
307 /* Restore point, having saved it as a marker. */
309 static Lisp_Object
310 restore_point_unwind (location)
311 Lisp_Object location;
313 Fgoto_char (location);
314 Fset_marker (location, Qnil, Qnil);
315 return Qnil;
319 Lisp_Object Qexpand_file_name;
320 Lisp_Object Qsubstitute_in_file_name;
321 Lisp_Object Qdirectory_file_name;
322 Lisp_Object Qfile_name_directory;
323 Lisp_Object Qfile_name_nondirectory;
324 Lisp_Object Qunhandled_file_name_directory;
325 Lisp_Object Qfile_name_as_directory;
326 Lisp_Object Qcopy_file;
327 Lisp_Object Qmake_directory_internal;
328 Lisp_Object Qmake_directory;
329 Lisp_Object Qdelete_directory;
330 Lisp_Object Qdelete_file;
331 Lisp_Object Qrename_file;
332 Lisp_Object Qadd_name_to_file;
333 Lisp_Object Qmake_symbolic_link;
334 Lisp_Object Qfile_exists_p;
335 Lisp_Object Qfile_executable_p;
336 Lisp_Object Qfile_readable_p;
337 Lisp_Object Qfile_writable_p;
338 Lisp_Object Qfile_symlink_p;
339 Lisp_Object Qaccess_file;
340 Lisp_Object Qfile_directory_p;
341 Lisp_Object Qfile_regular_p;
342 Lisp_Object Qfile_accessible_directory_p;
343 Lisp_Object Qfile_modes;
344 Lisp_Object Qset_file_modes;
345 Lisp_Object Qset_file_times;
346 Lisp_Object Qfile_newer_than_file_p;
347 Lisp_Object Qinsert_file_contents;
348 Lisp_Object Qwrite_region;
349 Lisp_Object Qverify_visited_file_modtime;
350 Lisp_Object Qset_visited_file_modtime;
352 DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
353 doc: /* Return FILENAME's handler function for OPERATION, if it has one.
354 Otherwise, return nil.
355 A file name is handled if one of the regular expressions in
356 `file-name-handler-alist' matches it.
358 If OPERATION equals `inhibit-file-name-operation', then we ignore
359 any handlers that are members of `inhibit-file-name-handlers',
360 but we still do run any other handlers. This lets handlers
361 use the standard functions without calling themselves recursively. */)
362 (filename, operation)
363 Lisp_Object filename, operation;
365 /* This function must not munge the match data. */
366 Lisp_Object chain, inhibited_handlers, result;
367 int pos = -1;
369 result = Qnil;
370 CHECK_STRING (filename);
372 if (EQ (operation, Vinhibit_file_name_operation))
373 inhibited_handlers = Vinhibit_file_name_handlers;
374 else
375 inhibited_handlers = Qnil;
377 for (chain = Vfile_name_handler_alist; CONSP (chain);
378 chain = XCDR (chain))
380 Lisp_Object elt;
381 elt = XCAR (chain);
382 if (CONSP (elt))
384 Lisp_Object string = XCAR (elt);
385 int match_pos;
386 Lisp_Object handler = XCDR (elt);
387 Lisp_Object operations = Qnil;
389 if (SYMBOLP (handler))
390 operations = Fget (handler, Qoperations);
392 if (STRINGP (string)
393 && (match_pos = fast_string_match (string, filename)) > pos
394 && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
396 Lisp_Object tem;
398 handler = XCDR (elt);
399 tem = Fmemq (handler, inhibited_handlers);
400 if (NILP (tem))
402 result = handler;
403 pos = match_pos;
408 QUIT;
410 return result;
413 DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
414 1, 1, 0,
415 doc: /* Return the directory component in file name FILENAME.
416 Return nil if FILENAME does not include a directory.
417 Otherwise return a directory spec.
418 Given a Unix syntax file name, returns a string ending in slash;
419 on VMS, perhaps instead a string ending in `:', `]' or `>'. */)
420 (filename)
421 Lisp_Object filename;
423 #ifndef DOS_NT
424 register const unsigned char *beg;
425 #else
426 register unsigned char *beg;
427 #endif
428 register const unsigned char *p;
429 Lisp_Object handler;
431 CHECK_STRING (filename);
433 /* If the file name has special constructs in it,
434 call the corresponding file handler. */
435 handler = Ffind_file_name_handler (filename, Qfile_name_directory);
436 if (!NILP (handler))
437 return call2 (handler, Qfile_name_directory, filename);
439 filename = FILE_SYSTEM_CASE (filename);
440 beg = SDATA (filename);
441 #ifdef DOS_NT
442 beg = strcpy (alloca (strlen (beg) + 1), beg);
443 #endif
444 p = beg + SBYTES (filename);
446 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
447 #ifdef VMS
448 && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
449 #endif /* VMS */
450 #ifdef DOS_NT
451 /* only recognise drive specifier at the beginning */
452 && !(p[-1] == ':'
453 /* handle the "/:d:foo" and "/:foo" cases correctly */
454 && ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
455 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
456 #endif
457 ) p--;
459 if (p == beg)
460 return Qnil;
461 #ifdef DOS_NT
462 /* Expansion of "c:" to drive and default directory. */
463 if (p[-1] == ':')
465 /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
466 unsigned char *res = alloca (MAXPATHLEN + 1);
467 unsigned char *r = res;
469 if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
471 strncpy (res, beg, 2);
472 beg += 2;
473 r += 2;
476 if (getdefdir (toupper (*beg) - 'A' + 1, r))
478 if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
479 strcat (res, "/");
480 beg = res;
481 p = beg + strlen (beg);
484 CORRECT_DIR_SEPS (beg);
485 #endif /* DOS_NT */
487 return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
490 DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
491 Sfile_name_nondirectory, 1, 1, 0,
492 doc: /* Return file name FILENAME sans its directory.
493 For example, in a Unix-syntax file name,
494 this is everything after the last slash,
495 or the entire name if it contains no slash. */)
496 (filename)
497 Lisp_Object filename;
499 register const unsigned char *beg, *p, *end;
500 Lisp_Object handler;
502 CHECK_STRING (filename);
504 /* If the file name has special constructs in it,
505 call the corresponding file handler. */
506 handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
507 if (!NILP (handler))
508 return call2 (handler, Qfile_name_nondirectory, filename);
510 beg = SDATA (filename);
511 end = p = beg + SBYTES (filename);
513 while (p != beg && !IS_DIRECTORY_SEP (p[-1])
514 #ifdef VMS
515 && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
516 #endif /* VMS */
517 #ifdef DOS_NT
518 /* only recognise drive specifier at beginning */
519 && !(p[-1] == ':'
520 /* handle the "/:d:foo" case correctly */
521 && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
522 #endif
524 p--;
526 return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
529 DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
530 Sunhandled_file_name_directory, 1, 1, 0,
531 doc: /* Return a directly usable directory name somehow associated with FILENAME.
532 A `directly usable' directory name is one that may be used without the
533 intervention of any file handler.
534 If FILENAME is a directly usable file itself, return
535 \(file-name-directory FILENAME).
536 The `call-process' and `start-process' functions use this function to
537 get a current directory to run processes in. */)
538 (filename)
539 Lisp_Object filename;
541 Lisp_Object handler;
543 /* If the file name has special constructs in it,
544 call the corresponding file handler. */
545 handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
546 if (!NILP (handler))
547 return call2 (handler, Qunhandled_file_name_directory, filename);
549 return Ffile_name_directory (filename);
553 char *
554 file_name_as_directory (out, in)
555 char *out, *in;
557 int size = strlen (in) - 1;
559 strcpy (out, in);
561 if (size < 0)
563 out[0] = '.';
564 out[1] = '/';
565 out[2] = 0;
566 return out;
569 #ifdef VMS
570 /* Is it already a directory string? */
571 if (in[size] == ':' || in[size] == ']' || in[size] == '>')
572 return out;
573 /* Is it a VMS directory file name? If so, hack VMS syntax. */
574 else if (! index (in, '/')
575 && ((size > 3 && ! strcmp (&in[size - 3], ".DIR"))
576 || (size > 3 && ! strcmp (&in[size - 3], ".dir"))
577 || (size > 5 && (! strncmp (&in[size - 5], ".DIR", 4)
578 || ! strncmp (&in[size - 5], ".dir", 4))
579 && (in[size - 1] == '.' || in[size - 1] == ';')
580 && in[size] == '1')))
582 register char *p, *dot;
583 char brack;
585 /* x.dir -> [.x]
586 dir:x.dir --> dir:[x]
587 dir:[x]y.dir --> dir:[x.y] */
588 p = in + size;
589 while (p != in && *p != ':' && *p != '>' && *p != ']') p--;
590 if (p != in)
592 strncpy (out, in, p - in);
593 out[p - in] = '\0';
594 if (*p == ':')
596 brack = ']';
597 strcat (out, ":[");
599 else
601 brack = *p;
602 strcat (out, ".");
604 p++;
606 else
608 brack = ']';
609 strcpy (out, "[.");
611 dot = index (p, '.');
612 if (dot)
614 /* blindly remove any extension */
615 size = strlen (out) + (dot - p);
616 strncat (out, p, dot - p);
618 else
620 strcat (out, p);
621 size = strlen (out);
623 out[size++] = brack;
624 out[size] = '\0';
626 #else /* not VMS */
627 /* For Unix syntax, Append a slash if necessary */
628 if (!IS_DIRECTORY_SEP (out[size]))
630 /* Cannot use DIRECTORY_SEP, which could have any value */
631 out[size + 1] = '/';
632 out[size + 2] = '\0';
634 #ifdef DOS_NT
635 CORRECT_DIR_SEPS (out);
636 #endif
637 #endif /* not VMS */
638 return out;
641 DEFUN ("file-name-as-directory", Ffile_name_as_directory,
642 Sfile_name_as_directory, 1, 1, 0,
643 doc: /* Return a string representing the file name FILE interpreted as a directory.
644 This operation exists because a directory is also a file, but its name as
645 a directory is different from its name as a file.
646 The result can be used as the value of `default-directory'
647 or passed as second argument to `expand-file-name'.
648 For a Unix-syntax file name, just appends a slash.
649 On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc. */)
650 (file)
651 Lisp_Object file;
653 char *buf;
654 Lisp_Object handler;
656 CHECK_STRING (file);
657 if (NILP (file))
658 return Qnil;
660 /* If the file name has special constructs in it,
661 call the corresponding file handler. */
662 handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
663 if (!NILP (handler))
664 return call2 (handler, Qfile_name_as_directory, file);
666 buf = (char *) alloca (SBYTES (file) + 10);
667 file_name_as_directory (buf, SDATA (file));
668 return make_specified_string (buf, -1, strlen (buf),
669 STRING_MULTIBYTE (file));
673 * Convert from directory name to filename.
674 * On VMS:
675 * xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
676 * xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
677 * On UNIX, it's simple: just make sure there isn't a terminating /
679 * Value is nonzero if the string output is different from the input.
683 directory_file_name (src, dst)
684 char *src, *dst;
686 long slen;
687 #ifdef VMS
688 long rlen;
689 char * ptr, * rptr;
690 char bracket;
691 struct FAB fab = cc$rms_fab;
692 struct NAM nam = cc$rms_nam;
693 char esa[NAM$C_MAXRSS];
694 #endif /* VMS */
696 slen = strlen (src);
697 #ifdef VMS
698 if (! index (src, '/')
699 && (src[slen - 1] == ']'
700 || src[slen - 1] == ':'
701 || src[slen - 1] == '>'))
703 /* VMS style - convert [x.y.z] to [x.y]z, [x] to [000000]x */
704 fab.fab$l_fna = src;
705 fab.fab$b_fns = slen;
706 fab.fab$l_nam = &nam;
707 fab.fab$l_fop = FAB$M_NAM;
709 nam.nam$l_esa = esa;
710 nam.nam$b_ess = sizeof esa;
711 nam.nam$b_nop |= NAM$M_SYNCHK;
713 /* We call SYS$PARSE to handle such things as [--] for us. */
714 if (SYS$PARSE (&fab, 0, 0) == RMS$_NORMAL)
716 slen = nam.nam$b_esl;
717 if (esa[slen - 1] == ';' && esa[slen - 2] == '.')
718 slen -= 2;
719 esa[slen] = '\0';
720 src = esa;
722 if (src[slen - 1] != ']' && src[slen - 1] != '>')
724 /* what about when we have logical_name:???? */
725 if (src[slen - 1] == ':')
726 { /* Xlate logical name and see what we get */
727 ptr = strcpy (dst, src); /* upper case for getenv */
728 while (*ptr)
730 if ('a' <= *ptr && *ptr <= 'z')
731 *ptr -= 040;
732 ptr++;
734 dst[slen - 1] = 0; /* remove colon */
735 if (!(src = egetenv (dst)))
736 return 0;
737 /* should we jump to the beginning of this procedure?
738 Good points: allows us to use logical names that xlate
739 to Unix names,
740 Bad points: can be a problem if we just translated to a device
741 name...
742 For now, I'll punt and always expect VMS names, and hope for
743 the best! */
744 slen = strlen (src);
745 if (src[slen - 1] != ']' && src[slen - 1] != '>')
746 { /* no recursion here! */
747 strcpy (dst, src);
748 return 0;
751 else
752 { /* not a directory spec */
753 strcpy (dst, src);
754 return 0;
757 bracket = src[slen - 1];
759 /* If bracket is ']' or '>', bracket - 2 is the corresponding
760 opening bracket. */
761 ptr = index (src, bracket - 2);
762 if (ptr == 0)
763 { /* no opening bracket */
764 strcpy (dst, src);
765 return 0;
767 if (!(rptr = rindex (src, '.')))
768 rptr = ptr;
769 slen = rptr - src;
770 strncpy (dst, src, slen);
771 dst[slen] = '\0';
772 if (*rptr == '.')
774 dst[slen++] = bracket;
775 dst[slen] = '\0';
777 else
779 /* If we have the top-level of a rooted directory (i.e. xx:[000000]),
780 then translate the device and recurse. */
781 if (dst[slen - 1] == ':'
782 && dst[slen - 2] != ':' /* skip decnet nodes */
783 && strcmp (src + slen, "[000000]") == 0)
785 dst[slen - 1] = '\0';
786 if ((ptr = egetenv (dst))
787 && (rlen = strlen (ptr) - 1) > 0
788 && (ptr[rlen] == ']' || ptr[rlen] == '>')
789 && ptr[rlen - 1] == '.')
791 char * buf = (char *) alloca (strlen (ptr) + 1);
792 strcpy (buf, ptr);
793 buf[rlen - 1] = ']';
794 buf[rlen] = '\0';
795 return directory_file_name (buf, dst);
797 else
798 dst[slen - 1] = ':';
800 strcat (dst, "[000000]");
801 slen += 8;
803 rptr++;
804 rlen = strlen (rptr) - 1;
805 strncat (dst, rptr, rlen);
806 dst[slen + rlen] = '\0';
807 strcat (dst, ".DIR.1");
808 return 1;
810 #endif /* VMS */
811 /* Process as Unix format: just remove any final slash.
812 But leave "/" unchanged; do not change it to "". */
813 strcpy (dst, src);
814 #ifdef APOLLO
815 /* Handle // as root for apollo's. */
816 if ((slen > 2 && dst[slen - 1] == '/')
817 || (slen > 1 && dst[0] != '/' && dst[slen - 1] == '/'))
818 dst[slen - 1] = 0;
819 #else
820 if (slen > 1
821 && IS_DIRECTORY_SEP (dst[slen - 1])
822 #ifdef DOS_NT
823 && !IS_ANY_SEP (dst[slen - 2])
824 #endif
826 dst[slen - 1] = 0;
827 #endif
828 #ifdef DOS_NT
829 CORRECT_DIR_SEPS (dst);
830 #endif
831 return 1;
834 DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
835 1, 1, 0,
836 doc: /* Returns the file name of the directory named DIRECTORY.
837 This is the name of the file that holds the data for the directory DIRECTORY.
838 This operation exists because a directory is also a file, but its name as
839 a directory is different from its name as a file.
840 In Unix-syntax, this function just removes the final slash.
841 On VMS, given a VMS-syntax directory name such as \"[X.Y]\",
842 it returns a file name such as \"[X]Y.DIR.1\". */)
843 (directory)
844 Lisp_Object directory;
846 char *buf;
847 Lisp_Object handler;
849 CHECK_STRING (directory);
851 if (NILP (directory))
852 return Qnil;
854 /* If the file name has special constructs in it,
855 call the corresponding file handler. */
856 handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
857 if (!NILP (handler))
858 return call2 (handler, Qdirectory_file_name, directory);
860 #ifdef VMS
861 /* 20 extra chars is insufficient for VMS, since we might perform a
862 logical name translation. an equivalence string can be up to 255
863 chars long, so grab that much extra space... - sss */
864 buf = (char *) alloca (SBYTES (directory) + 20 + 255);
865 #else
866 buf = (char *) alloca (SBYTES (directory) + 20);
867 #endif
868 directory_file_name (SDATA (directory), buf);
869 return make_specified_string (buf, -1, strlen (buf),
870 STRING_MULTIBYTE (directory));
873 static char make_temp_name_tbl[64] =
875 'A','B','C','D','E','F','G','H',
876 'I','J','K','L','M','N','O','P',
877 'Q','R','S','T','U','V','W','X',
878 'Y','Z','a','b','c','d','e','f',
879 'g','h','i','j','k','l','m','n',
880 'o','p','q','r','s','t','u','v',
881 'w','x','y','z','0','1','2','3',
882 '4','5','6','7','8','9','-','_'
885 static unsigned make_temp_name_count, make_temp_name_count_initialized_p;
887 /* Value is a temporary file name starting with PREFIX, a string.
889 The Emacs process number forms part of the result, so there is
890 no danger of generating a name being used by another process.
891 In addition, this function makes an attempt to choose a name
892 which has no existing file. To make this work, PREFIX should be
893 an absolute file name.
895 BASE64_P non-zero means add the pid as 3 characters in base64
896 encoding. In this case, 6 characters will be added to PREFIX to
897 form the file name. Otherwise, if Emacs is running on a system
898 with long file names, add the pid as a decimal number.
900 This function signals an error if no unique file name could be
901 generated. */
903 Lisp_Object
904 make_temp_name (prefix, base64_p)
905 Lisp_Object prefix;
906 int base64_p;
908 Lisp_Object val;
909 int len, clen;
910 int pid;
911 unsigned char *p, *data;
912 char pidbuf[20];
913 int pidlen;
915 CHECK_STRING (prefix);
917 /* VAL is created by adding 6 characters to PREFIX. The first
918 three are the PID of this process, in base 64, and the second
919 three are incremented if the file already exists. This ensures
920 262144 unique file names per PID per PREFIX. */
922 pid = (int) getpid ();
924 if (base64_p)
926 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
927 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
928 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
929 pidlen = 3;
931 else
933 #ifdef HAVE_LONG_FILE_NAMES
934 sprintf (pidbuf, "%d", pid);
935 pidlen = strlen (pidbuf);
936 #else
937 pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
938 pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
939 pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
940 pidlen = 3;
941 #endif
944 len = SBYTES (prefix); clen = SCHARS (prefix);
945 val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
946 if (!STRING_MULTIBYTE (prefix))
947 STRING_SET_UNIBYTE (val);
948 data = SDATA (val);
949 bcopy(SDATA (prefix), data, len);
950 p = data + len;
952 bcopy (pidbuf, p, pidlen);
953 p += pidlen;
955 /* Here we try to minimize useless stat'ing when this function is
956 invoked many times successively with the same PREFIX. We achieve
957 this by initializing count to a random value, and incrementing it
958 afterwards.
960 We don't want make-temp-name to be called while dumping,
961 because then make_temp_name_count_initialized_p would get set
962 and then make_temp_name_count would not be set when Emacs starts. */
964 if (!make_temp_name_count_initialized_p)
966 make_temp_name_count = (unsigned) time (NULL);
967 make_temp_name_count_initialized_p = 1;
970 while (1)
972 struct stat ignored;
973 unsigned num = make_temp_name_count;
975 p[0] = make_temp_name_tbl[num & 63], num >>= 6;
976 p[1] = make_temp_name_tbl[num & 63], num >>= 6;
977 p[2] = make_temp_name_tbl[num & 63], num >>= 6;
979 /* Poor man's congruential RN generator. Replace with
980 ++make_temp_name_count for debugging. */
981 make_temp_name_count += 25229;
982 make_temp_name_count %= 225307;
984 if (stat (data, &ignored) < 0)
986 /* We want to return only if errno is ENOENT. */
987 if (errno == ENOENT)
988 return val;
989 else
990 /* The error here is dubious, but there is little else we
991 can do. The alternatives are to return nil, which is
992 as bad as (and in many cases worse than) throwing the
993 error, or to ignore the error, which will likely result
994 in looping through 225307 stat's, which is not only
995 dog-slow, but also useless since it will fallback to
996 the errow below, anyway. */
997 report_file_error ("Cannot create temporary name for prefix",
998 Fcons (prefix, Qnil));
999 /* not reached */
1003 error ("Cannot create temporary name for prefix `%s'",
1004 SDATA (prefix));
1005 return Qnil;
1009 DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
1010 doc: /* Generate temporary file name (string) starting with PREFIX (a string).
1011 The Emacs process number forms part of the result,
1012 so there is no danger of generating a name being used by another process.
1014 In addition, this function makes an attempt to choose a name
1015 which has no existing file. To make this work,
1016 PREFIX should be an absolute file name.
1018 There is a race condition between calling `make-temp-name' and creating the
1019 file which opens all kinds of security holes. For that reason, you should
1020 probably use `make-temp-file' instead, except in three circumstances:
1022 * If you are creating the file in the user's home directory.
1023 * If you are creating a directory rather than an ordinary file.
1024 * If you are taking special precautions as `make-temp-file' does. */)
1025 (prefix)
1026 Lisp_Object prefix;
1028 return make_temp_name (prefix, 0);
1033 DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1034 doc: /* Convert filename NAME to absolute, and canonicalize it.
1035 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
1036 \(does not start with slash); if DEFAULT-DIRECTORY is nil or missing,
1037 the current buffer's value of `default-directory' is used.
1038 File name components that are `.' are removed, and
1039 so are file name components followed by `..', along with the `..' itself;
1040 note that these simplifications are done without checking the resulting
1041 file names in the file system.
1042 An initial `~/' expands to your home directory.
1043 An initial `~USER/' expands to USER's home directory.
1044 See also the function `substitute-in-file-name'. */)
1045 (name, default_directory)
1046 Lisp_Object name, default_directory;
1048 unsigned char *nm;
1050 register unsigned char *newdir, *p, *o;
1051 int tlen;
1052 unsigned char *target;
1053 struct passwd *pw;
1054 #ifdef VMS
1055 unsigned char * colon = 0;
1056 unsigned char * close = 0;
1057 unsigned char * slash = 0;
1058 unsigned char * brack = 0;
1059 int lbrack = 0, rbrack = 0;
1060 int dots = 0;
1061 #endif /* VMS */
1062 #ifdef DOS_NT
1063 int drive = 0;
1064 int collapse_newdir = 1;
1065 int is_escaped = 0;
1066 #endif /* DOS_NT */
1067 int length;
1068 Lisp_Object handler, result;
1069 int multibyte;
1071 CHECK_STRING (name);
1073 /* If the file name has special constructs in it,
1074 call the corresponding file handler. */
1075 handler = Ffind_file_name_handler (name, Qexpand_file_name);
1076 if (!NILP (handler))
1077 return call3 (handler, Qexpand_file_name, name, default_directory);
1079 /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
1080 if (NILP (default_directory))
1081 default_directory = current_buffer->directory;
1082 if (! STRINGP (default_directory))
1084 #ifdef DOS_NT
1085 /* "/" is not considered a root directory on DOS_NT, so using "/"
1086 here causes an infinite recursion in, e.g., the following:
1088 (let (default-directory)
1089 (expand-file-name "a"))
1091 To avoid this, we set default_directory to the root of the
1092 current drive. */
1093 extern char *emacs_root_dir (void);
1095 default_directory = build_string (emacs_root_dir ());
1096 #else
1097 default_directory = build_string ("/");
1098 #endif
1101 if (!NILP (default_directory))
1103 handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
1104 if (!NILP (handler))
1105 return call3 (handler, Qexpand_file_name, name, default_directory);
1108 o = SDATA (default_directory);
1110 /* Make sure DEFAULT_DIRECTORY is properly expanded.
1111 It would be better to do this down below where we actually use
1112 default_directory. Unfortunately, calling Fexpand_file_name recursively
1113 could invoke GC, and the strings might be relocated. This would
1114 be annoying because we have pointers into strings lying around
1115 that would need adjusting, and people would add new pointers to
1116 the code and forget to adjust them, resulting in intermittent bugs.
1117 Putting this call here avoids all that crud.
1119 The EQ test avoids infinite recursion. */
1120 if (! NILP (default_directory) && !EQ (default_directory, name)
1121 /* Save time in some common cases - as long as default_directory
1122 is not relative, it can be canonicalized with name below (if it
1123 is needed at all) without requiring it to be expanded now. */
1124 #ifdef DOS_NT
1125 /* Detect MSDOS file names with drive specifiers. */
1126 && ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1]) && IS_DIRECTORY_SEP (o[2]))
1127 #ifdef WINDOWSNT
1128 /* Detect Windows file names in UNC format. */
1129 && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
1130 #endif
1131 #else /* not DOS_NT */
1132 /* Detect Unix absolute file names (/... alone is not absolute on
1133 DOS or Windows). */
1134 && ! (IS_DIRECTORY_SEP (o[0]))
1135 #endif /* not DOS_NT */
1138 struct gcpro gcpro1;
1140 GCPRO1 (name);
1141 default_directory = Fexpand_file_name (default_directory, Qnil);
1142 UNGCPRO;
1145 name = FILE_SYSTEM_CASE (name);
1146 nm = SDATA (name);
1147 multibyte = STRING_MULTIBYTE (name);
1149 #ifdef DOS_NT
1150 /* We will force directory separators to be either all \ or /, so make
1151 a local copy to modify, even if there ends up being no change. */
1152 nm = strcpy (alloca (strlen (nm) + 1), nm);
1154 /* Note if special escape prefix is present, but remove for now. */
1155 if (nm[0] == '/' && nm[1] == ':')
1157 is_escaped = 1;
1158 nm += 2;
1161 /* Find and remove drive specifier if present; this makes nm absolute
1162 even if the rest of the name appears to be relative. Only look for
1163 drive specifier at the beginning. */
1164 if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
1166 drive = nm[0];
1167 nm += 2;
1170 #ifdef WINDOWSNT
1171 /* If we see "c://somedir", we want to strip the first slash after the
1172 colon when stripping the drive letter. Otherwise, this expands to
1173 "//somedir". */
1174 if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1175 nm++;
1176 #endif /* WINDOWSNT */
1177 #endif /* DOS_NT */
1179 #ifdef WINDOWSNT
1180 /* Discard any previous drive specifier if nm is now in UNC format. */
1181 if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1183 drive = 0;
1185 #endif
1187 /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
1188 none are found, we can probably return right away. We will avoid
1189 allocating a new string if name is already fully expanded. */
1190 if (
1191 IS_DIRECTORY_SEP (nm[0])
1192 #ifdef MSDOS
1193 && drive && !is_escaped
1194 #endif
1195 #ifdef WINDOWSNT
1196 && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
1197 #endif
1198 #ifdef VMS
1199 || index (nm, ':')
1200 #endif /* VMS */
1203 /* If it turns out that the filename we want to return is just a
1204 suffix of FILENAME, we don't need to go through and edit
1205 things; we just need to construct a new string using data
1206 starting at the middle of FILENAME. If we set lose to a
1207 non-zero value, that means we've discovered that we can't do
1208 that cool trick. */
1209 int lose = 0;
1211 p = nm;
1212 while (*p)
1214 /* Since we know the name is absolute, we can assume that each
1215 element starts with a "/". */
1217 /* "." and ".." are hairy. */
1218 if (IS_DIRECTORY_SEP (p[0])
1219 && p[1] == '.'
1220 && (IS_DIRECTORY_SEP (p[2])
1221 || p[2] == 0
1222 || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
1223 || p[3] == 0))))
1224 lose = 1;
1225 /* We want to replace multiple `/' in a row with a single
1226 slash. */
1227 else if (p > nm
1228 && IS_DIRECTORY_SEP (p[0])
1229 && IS_DIRECTORY_SEP (p[1]))
1230 lose = 1;
1232 #ifdef VMS
1233 if (p[0] == '\\')
1234 lose = 1;
1235 if (p[0] == '/') {
1236 /* if dev:[dir]/, move nm to / */
1237 if (!slash && p > nm && (brack || colon)) {
1238 nm = (brack ? brack + 1 : colon + 1);
1239 lbrack = rbrack = 0;
1240 brack = 0;
1241 colon = 0;
1243 slash = p;
1245 if (p[0] == '-')
1246 #ifdef NO_HYPHENS_IN_FILENAMES
1247 if (lbrack == rbrack)
1249 /* Avoid clobbering negative version numbers. */
1250 if (dots < 2)
1251 p[0] = '_';
1253 else
1254 #endif /* NO_HYPHENS_IN_FILENAMES */
1255 if (lbrack > rbrack
1256 && ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<')
1257 && (p[1] == '.' || p[1] == ']' || p[1] == '>')))
1258 lose = 1;
1259 #ifdef NO_HYPHENS_IN_FILENAMES
1260 else
1261 p[0] = '_';
1262 #endif /* NO_HYPHENS_IN_FILENAMES */
1263 /* count open brackets, reset close bracket pointer */
1264 if (p[0] == '[' || p[0] == '<')
1265 lbrack++, brack = 0;
1266 /* count close brackets, set close bracket pointer */
1267 if (p[0] == ']' || p[0] == '>')
1268 rbrack++, brack = p;
1269 /* detect ][ or >< */
1270 if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
1271 lose = 1;
1272 if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
1273 nm = p + 1, lose = 1;
1274 if (p[0] == ':' && (colon || slash))
1275 /* if dev1:[dir]dev2:, move nm to dev2: */
1276 if (brack)
1278 nm = brack + 1;
1279 brack = 0;
1281 /* if /name/dev:, move nm to dev: */
1282 else if (slash)
1283 nm = slash + 1;
1284 /* if node::dev:, move colon following dev */
1285 else if (colon && colon[-1] == ':')
1286 colon = p;
1287 /* if dev1:dev2:, move nm to dev2: */
1288 else if (colon && colon[-1] != ':')
1290 nm = colon + 1;
1291 colon = 0;
1293 if (p[0] == ':' && !colon)
1295 if (p[1] == ':')
1296 p++;
1297 colon = p;
1299 if (lbrack == rbrack)
1300 if (p[0] == ';')
1301 dots = 2;
1302 else if (p[0] == '.')
1303 dots++;
1304 #endif /* VMS */
1305 p++;
1307 if (!lose)
1309 #ifdef VMS
1310 if (index (nm, '/'))
1312 nm = sys_translate_unix (nm);
1313 return make_specified_string (nm, -1, strlen (nm), multibyte);
1315 #endif /* VMS */
1316 #ifdef DOS_NT
1317 /* Make sure directories are all separated with / or \ as
1318 desired, but avoid allocation of a new string when not
1319 required. */
1320 CORRECT_DIR_SEPS (nm);
1321 #ifdef WINDOWSNT
1322 if (IS_DIRECTORY_SEP (nm[1]))
1324 if (strcmp (nm, SDATA (name)) != 0)
1325 name = make_specified_string (nm, -1, strlen (nm), multibyte);
1327 else
1328 #endif
1329 /* drive must be set, so this is okay */
1330 if (strcmp (nm - 2, SDATA (name)) != 0)
1332 char temp[] = " :";
1334 name = make_specified_string (nm, -1, p - nm, multibyte);
1335 temp[0] = DRIVE_LETTER (drive);
1336 name = concat2 (build_string (temp), name);
1338 return name;
1339 #else /* not DOS_NT */
1340 if (nm == SDATA (name))
1341 return name;
1342 return make_specified_string (nm, -1, strlen (nm), multibyte);
1343 #endif /* not DOS_NT */
1347 /* At this point, nm might or might not be an absolute file name. We
1348 need to expand ~ or ~user if present, otherwise prefix nm with
1349 default_directory if nm is not absolute, and finally collapse /./
1350 and /foo/../ sequences.
1352 We set newdir to be the appropriate prefix if one is needed:
1353 - the relevant user directory if nm starts with ~ or ~user
1354 - the specified drive's working dir (DOS/NT only) if nm does not
1355 start with /
1356 - the value of default_directory.
1358 Note that these prefixes are not guaranteed to be absolute (except
1359 for the working dir of a drive). Therefore, to ensure we always
1360 return an absolute name, if the final prefix is not absolute we
1361 append it to the current working directory. */
1363 newdir = 0;
1365 if (nm[0] == '~') /* prefix ~ */
1367 if (IS_DIRECTORY_SEP (nm[1])
1368 #ifdef VMS
1369 || nm[1] == ':'
1370 #endif /* VMS */
1371 || nm[1] == 0) /* ~ by itself */
1373 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1374 newdir = (unsigned char *) "";
1375 nm++;
1376 #ifdef DOS_NT
1377 collapse_newdir = 0;
1378 #endif
1379 #ifdef VMS
1380 nm++; /* Don't leave the slash in nm. */
1381 #endif /* VMS */
1383 else /* ~user/filename */
1385 for (p = nm; *p && (!IS_DIRECTORY_SEP (*p)
1386 #ifdef VMS
1387 && *p != ':'
1388 #endif /* VMS */
1389 ); p++);
1390 o = (unsigned char *) alloca (p - nm + 1);
1391 bcopy ((char *) nm, o, p - nm);
1392 o [p - nm] = 0;
1394 BLOCK_INPUT;
1395 pw = (struct passwd *) getpwnam (o + 1);
1396 UNBLOCK_INPUT;
1397 if (pw)
1399 newdir = (unsigned char *) pw -> pw_dir;
1400 #ifdef VMS
1401 nm = p + 1; /* skip the terminator */
1402 #else
1403 nm = p;
1404 #ifdef DOS_NT
1405 collapse_newdir = 0;
1406 #endif
1407 #endif /* VMS */
1410 /* If we don't find a user of that name, leave the name
1411 unchanged; don't move nm forward to p. */
1415 #ifdef DOS_NT
1416 /* On DOS and Windows, nm is absolute if a drive name was specified;
1417 use the drive's current directory as the prefix if needed. */
1418 if (!newdir && drive)
1420 /* Get default directory if needed to make nm absolute. */
1421 if (!IS_DIRECTORY_SEP (nm[0]))
1423 newdir = alloca (MAXPATHLEN + 1);
1424 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1425 newdir = NULL;
1427 if (!newdir)
1429 /* Either nm starts with /, or drive isn't mounted. */
1430 newdir = alloca (4);
1431 newdir[0] = DRIVE_LETTER (drive);
1432 newdir[1] = ':';
1433 newdir[2] = '/';
1434 newdir[3] = 0;
1437 #endif /* DOS_NT */
1439 /* Finally, if no prefix has been specified and nm is not absolute,
1440 then it must be expanded relative to default_directory. */
1442 if (1
1443 #ifndef DOS_NT
1444 /* /... alone is not absolute on DOS and Windows. */
1445 && !IS_DIRECTORY_SEP (nm[0])
1446 #endif
1447 #ifdef WINDOWSNT
1448 && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
1449 #endif
1450 #ifdef VMS
1451 && !index (nm, ':')
1452 #endif
1453 && !newdir)
1455 newdir = SDATA (default_directory);
1456 multibyte |= STRING_MULTIBYTE (default_directory);
1457 #ifdef DOS_NT
1458 /* Note if special escape prefix is present, but remove for now. */
1459 if (newdir[0] == '/' && newdir[1] == ':')
1461 is_escaped = 1;
1462 newdir += 2;
1464 #endif
1467 #ifdef DOS_NT
1468 if (newdir)
1470 /* First ensure newdir is an absolute name. */
1471 if (
1472 /* Detect MSDOS file names with drive specifiers. */
1473 ! (IS_DRIVE (newdir[0])
1474 && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
1475 #ifdef WINDOWSNT
1476 /* Detect Windows file names in UNC format. */
1477 && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1478 #endif
1481 /* Effectively, let newdir be (expand-file-name newdir cwd).
1482 Because of the admonition against calling expand-file-name
1483 when we have pointers into lisp strings, we accomplish this
1484 indirectly by prepending newdir to nm if necessary, and using
1485 cwd (or the wd of newdir's drive) as the new newdir. */
1487 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1489 drive = newdir[0];
1490 newdir += 2;
1492 if (!IS_DIRECTORY_SEP (nm[0]))
1494 char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
1495 file_name_as_directory (tmp, newdir);
1496 strcat (tmp, nm);
1497 nm = tmp;
1499 newdir = alloca (MAXPATHLEN + 1);
1500 if (drive)
1502 if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
1503 newdir = "/";
1505 else
1506 getwd (newdir);
1509 /* Strip off drive name from prefix, if present. */
1510 if (IS_DRIVE (newdir[0]) && IS_DEVICE_SEP (newdir[1]))
1512 drive = newdir[0];
1513 newdir += 2;
1516 /* Keep only a prefix from newdir if nm starts with slash
1517 (//server/share for UNC, nothing otherwise). */
1518 if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
1520 #ifdef WINDOWSNT
1521 if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
1523 newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
1524 p = newdir + 2;
1525 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1526 p++;
1527 while (*p && !IS_DIRECTORY_SEP (*p)) p++;
1528 *p = 0;
1530 else
1531 #endif
1532 newdir = "";
1535 #endif /* DOS_NT */
1537 if (newdir)
1539 /* Get rid of any slash at the end of newdir, unless newdir is
1540 just / or // (an incomplete UNC name). */
1541 length = strlen (newdir);
1542 if (length > 1 && IS_DIRECTORY_SEP (newdir[length - 1])
1543 #ifdef WINDOWSNT
1544 && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
1545 #endif
1548 unsigned char *temp = (unsigned char *) alloca (length);
1549 bcopy (newdir, temp, length - 1);
1550 temp[length - 1] = 0;
1551 newdir = temp;
1553 tlen = length + 1;
1555 else
1556 tlen = 0;
1558 /* Now concatenate the directory and name to new space in the stack frame */
1559 tlen += strlen (nm) + 1;
1560 #ifdef DOS_NT
1561 /* Reserve space for drive specifier and escape prefix, since either
1562 or both may need to be inserted. (The Microsoft x86 compiler
1563 produces incorrect code if the following two lines are combined.) */
1564 target = (unsigned char *) alloca (tlen + 4);
1565 target += 4;
1566 #else /* not DOS_NT */
1567 target = (unsigned char *) alloca (tlen);
1568 #endif /* not DOS_NT */
1569 *target = 0;
1571 if (newdir)
1573 #ifndef VMS
1574 if (nm[0] == 0 || IS_DIRECTORY_SEP (nm[0]))
1576 #ifdef DOS_NT
1577 /* If newdir is effectively "C:/", then the drive letter will have
1578 been stripped and newdir will be "/". Concatenating with an
1579 absolute directory in nm produces "//", which will then be
1580 incorrectly treated as a network share. Ignore newdir in
1581 this case (keeping the drive letter). */
1582 if (!(drive && nm[0] && IS_DIRECTORY_SEP (newdir[0])
1583 && newdir[1] == '\0'))
1584 #endif
1585 strcpy (target, newdir);
1587 else
1588 #endif
1589 file_name_as_directory (target, newdir);
1592 strcat (target, nm);
1593 #ifdef VMS
1594 if (index (target, '/'))
1595 strcpy (target, sys_translate_unix (target));
1596 #endif /* VMS */
1598 /* ASSERT (IS_DIRECTORY_SEP (target[0])) if not VMS */
1600 /* Now canonicalize by removing `//', `/.' and `/foo/..' if they
1601 appear. */
1603 p = target;
1604 o = target;
1606 while (*p)
1608 #ifdef VMS
1609 if (*p != ']' && *p != '>' && *p != '-')
1611 if (*p == '\\')
1612 p++;
1613 *o++ = *p++;
1615 else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
1616 /* brackets are offset from each other by 2 */
1618 p += 2;
1619 if (*p != '.' && *p != '-' && o[-1] != '.')
1620 /* convert [foo][bar] to [bar] */
1621 while (o[-1] != '[' && o[-1] != '<')
1622 o--;
1623 else if (*p == '-' && *o != '.')
1624 *--p = '.';
1626 else if (p[0] == '-' && o[-1] == '.'
1627 && (p[1] == '.' || p[1] == ']' || p[1] == '>'))
1628 /* flush .foo.- ; leave - if stopped by '[' or '<' */
1631 o--;
1632 while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
1633 if (p[1] == '.') /* foo.-.bar ==> bar. */
1634 p += 2;
1635 else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
1636 p++, o--;
1637 /* else [foo.-] ==> [-] */
1639 else
1641 #ifdef NO_HYPHENS_IN_FILENAMES
1642 if (*p == '-'
1643 && o[-1] != '[' && o[-1] != '<' && o[-1] != '.'
1644 && p[1] != ']' && p[1] != '>' && p[1] != '.')
1645 *p = '_';
1646 #endif /* NO_HYPHENS_IN_FILENAMES */
1647 *o++ = *p++;
1649 #else /* not VMS */
1650 if (!IS_DIRECTORY_SEP (*p))
1652 *o++ = *p++;
1654 else if (p[1] == '.'
1655 && (IS_DIRECTORY_SEP (p[2])
1656 || p[2] == 0))
1658 /* If "/." is the entire filename, keep the "/". Otherwise,
1659 just delete the whole "/.". */
1660 if (o == target && p[2] == '\0')
1661 *o++ = *p;
1662 p += 2;
1664 else if (p[1] == '.' && p[2] == '.'
1665 /* `/../' is the "superroot" on certain file systems.
1666 Turned off on DOS_NT systems because they have no
1667 "superroot" and because this causes us to produce
1668 file names like "d:/../foo" which fail file-related
1669 functions of the underlying OS. (To reproduce, try a
1670 long series of "../../" in default_directory, longer
1671 than the number of levels from the root.) */
1672 #ifndef DOS_NT
1673 && o != target
1674 #endif
1675 && (IS_DIRECTORY_SEP (p[3]) || p[3] == 0))
1677 while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
1679 /* Keep initial / only if this is the whole name. */
1680 if (o == target && IS_ANY_SEP (*o) && p[3] == 0)
1681 ++o;
1682 p += 3;
1684 else if (p > target && IS_DIRECTORY_SEP (p[1]))
1685 /* Collapse multiple `/' in a row. */
1686 p++;
1687 else
1689 *o++ = *p++;
1691 #endif /* not VMS */
1694 #ifdef DOS_NT
1695 /* At last, set drive name. */
1696 #ifdef WINDOWSNT
1697 /* Except for network file name. */
1698 if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
1699 #endif /* WINDOWSNT */
1701 if (!drive) abort ();
1702 target -= 2;
1703 target[0] = DRIVE_LETTER (drive);
1704 target[1] = ':';
1706 /* Reinsert the escape prefix if required. */
1707 if (is_escaped)
1709 target -= 2;
1710 target[0] = '/';
1711 target[1] = ':';
1713 CORRECT_DIR_SEPS (target);
1714 #endif /* DOS_NT */
1716 result = make_specified_string (target, -1, o - target, multibyte);
1718 /* Again look to see if the file name has special constructs in it
1719 and perhaps call the corresponding file handler. This is needed
1720 for filenames such as "/foo/../user@host:/bar/../baz". Expanding
1721 the ".." component gives us "/user@host:/bar/../baz" which needs
1722 to be expanded again. */
1723 handler = Ffind_file_name_handler (result, Qexpand_file_name);
1724 if (!NILP (handler))
1725 return call3 (handler, Qexpand_file_name, result, default_directory);
1727 return result;
1730 #if 0
1731 /* PLEASE DO NOT DELETE THIS COMMENTED-OUT VERSION!
1732 This is the old version of expand-file-name, before it was thoroughly
1733 rewritten for Emacs 10.31. We leave this version here commented-out,
1734 because the code is very complex and likely to have subtle bugs. If
1735 bugs _are_ found, it might be of interest to look at the old code and
1736 see what did it do in the relevant situation.
1738 Don't remove this code: it's true that it will be accessible via CVS,
1739 but a few years from deletion, people will forget it is there. */
1741 /* Changed this DEFUN to a DEAFUN, so as not to confuse `make-docfile'. */
1742 DEAFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
1743 "Convert FILENAME to absolute, and canonicalize it.\n\
1744 Second arg DEFAULT is directory to start with if FILENAME is relative\n\
1745 \(does not start with slash); if DEFAULT is nil or missing,\n\
1746 the current buffer's value of default-directory is used.\n\
1747 Filenames containing `.' or `..' as components are simplified;\n\
1748 initial `~/' expands to your home directory.\n\
1749 See also the function `substitute-in-file-name'.")
1750 (name, defalt)
1751 Lisp_Object name, defalt;
1753 unsigned char *nm;
1755 register unsigned char *newdir, *p, *o;
1756 int tlen;
1757 unsigned char *target;
1758 struct passwd *pw;
1759 int lose;
1760 #ifdef VMS
1761 unsigned char * colon = 0;
1762 unsigned char * close = 0;
1763 unsigned char * slash = 0;
1764 unsigned char * brack = 0;
1765 int lbrack = 0, rbrack = 0;
1766 int dots = 0;
1767 #endif /* VMS */
1769 CHECK_STRING (name);
1771 #ifdef VMS
1772 /* Filenames on VMS are always upper case. */
1773 name = Fupcase (name);
1774 #endif
1776 nm = SDATA (name);
1778 /* If nm is absolute, flush ...// and detect /./ and /../.
1779 If no /./ or /../ we can return right away. */
1780 if (
1781 nm[0] == '/'
1782 #ifdef VMS
1783 || index (nm, ':')
1784 #endif /* VMS */
1787 p = nm;
1788 lose = 0;
1789 while (*p)
1791 if (p[0] == '/' && p[1] == '/'
1792 #ifdef APOLLO
1793 /* // at start of filename is meaningful on Apollo system. */
1794 && nm != p
1795 #endif /* APOLLO */
1797 nm = p + 1;
1798 if (p[0] == '/' && p[1] == '~')
1799 nm = p + 1, lose = 1;
1800 if (p[0] == '/' && p[1] == '.'
1801 && (p[2] == '/' || p[2] == 0
1802 || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
1803 lose = 1;
1804 #ifdef VMS
1805 if (p[0] == '\\')
1806 lose = 1;
1807 if (p[0] == '/') {
1808 /* if dev:[dir]/, move nm to / */
1809 if (!slash && p > nm && (brack || colon)) {
1810 nm = (brack ? brack + 1 : colon + 1);
1811 lbrack = rbrack = 0;
1812 brack = 0;
1813 colon = 0;
1815 slash = p;
1817 if (p[0] == '-')
1818 #ifndef VMS4_4
1819 /* VMS pre V4.4,convert '-'s in filenames. */
1820 if (lbrack == rbrack)
1822 if (dots < 2) /* this is to allow negative version numbers */
1823 p[0] = '_';
1825 else
1826 #endif /* VMS4_4 */
1827 if (lbrack > rbrack
1828 && ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<')
1829 && (p[1] == '.' || p[1] == ']' || p[1] == '>')))
1830 lose = 1;
1831 #ifndef VMS4_4
1832 else
1833 p[0] = '_';
1834 #endif /* VMS4_4 */
1835 /* count open brackets, reset close bracket pointer */
1836 if (p[0] == '[' || p[0] == '<')
1837 lbrack++, brack = 0;
1838 /* count close brackets, set close bracket pointer */
1839 if (p[0] == ']' || p[0] == '>')
1840 rbrack++, brack = p;
1841 /* detect ][ or >< */
1842 if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
1843 lose = 1;
1844 if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
1845 nm = p + 1, lose = 1;
1846 if (p[0] == ':' && (colon || slash))
1847 /* if dev1:[dir]dev2:, move nm to dev2: */
1848 if (brack)
1850 nm = brack + 1;
1851 brack = 0;
1853 /* If /name/dev:, move nm to dev: */
1854 else if (slash)
1855 nm = slash + 1;
1856 /* If node::dev:, move colon following dev */
1857 else if (colon && colon[-1] == ':')
1858 colon = p;
1859 /* If dev1:dev2:, move nm to dev2: */
1860 else if (colon && colon[-1] != ':')
1862 nm = colon + 1;
1863 colon = 0;
1865 if (p[0] == ':' && !colon)
1867 if (p[1] == ':')
1868 p++;
1869 colon = p;
1871 if (lbrack == rbrack)
1872 if (p[0] == ';')
1873 dots = 2;
1874 else if (p[0] == '.')
1875 dots++;
1876 #endif /* VMS */
1877 p++;
1879 if (!lose)
1881 #ifdef VMS
1882 if (index (nm, '/'))
1883 return build_string (sys_translate_unix (nm));
1884 #endif /* VMS */
1885 if (nm == SDATA (name))
1886 return name;
1887 return build_string (nm);
1891 /* Now determine directory to start with and put it in NEWDIR */
1893 newdir = 0;
1895 if (nm[0] == '~') /* prefix ~ */
1896 if (nm[1] == '/'
1897 #ifdef VMS
1898 || nm[1] == ':'
1899 #endif /* VMS */
1900 || nm[1] == 0)/* ~/filename */
1902 if (!(newdir = (unsigned char *) egetenv ("HOME")))
1903 newdir = (unsigned char *) "";
1904 nm++;
1905 #ifdef VMS
1906 nm++; /* Don't leave the slash in nm. */
1907 #endif /* VMS */
1909 else /* ~user/filename */
1911 /* Get past ~ to user */
1912 unsigned char *user = nm + 1;
1913 /* Find end of name. */
1914 unsigned char *ptr = (unsigned char *) index (user, '/');
1915 int len = ptr ? ptr - user : strlen (user);
1916 #ifdef VMS
1917 unsigned char *ptr1 = index (user, ':');
1918 if (ptr1 != 0 && ptr1 - user < len)
1919 len = ptr1 - user;
1920 #endif /* VMS */
1921 /* Copy the user name into temp storage. */
1922 o = (unsigned char *) alloca (len + 1);
1923 bcopy ((char *) user, o, len);
1924 o[len] = 0;
1926 /* Look up the user name. */
1927 BLOCK_INPUT;
1928 pw = (struct passwd *) getpwnam (o + 1);
1929 UNBLOCK_INPUT;
1930 if (!pw)
1931 error ("\"%s\" isn't a registered user", o + 1);
1933 newdir = (unsigned char *) pw->pw_dir;
1935 /* Discard the user name from NM. */
1936 nm += len;
1939 if (nm[0] != '/'
1940 #ifdef VMS
1941 && !index (nm, ':')
1942 #endif /* not VMS */
1943 && !newdir)
1945 if (NILP (defalt))
1946 defalt = current_buffer->directory;
1947 CHECK_STRING (defalt);
1948 newdir = SDATA (defalt);
1951 /* Now concatenate the directory and name to new space in the stack frame */
1953 tlen = (newdir ? strlen (newdir) + 1 : 0) + strlen (nm) + 1;
1954 target = (unsigned char *) alloca (tlen);
1955 *target = 0;
1957 if (newdir)
1959 #ifndef VMS
1960 if (nm[0] == 0 || nm[0] == '/')
1961 strcpy (target, newdir);
1962 else
1963 #endif
1964 file_name_as_directory (target, newdir);
1967 strcat (target, nm);
1968 #ifdef VMS
1969 if (index (target, '/'))
1970 strcpy (target, sys_translate_unix (target));
1971 #endif /* VMS */
1973 /* Now canonicalize by removing /. and /foo/.. if they appear */
1975 p = target;
1976 o = target;
1978 while (*p)
1980 #ifdef VMS
1981 if (*p != ']' && *p != '>' && *p != '-')
1983 if (*p == '\\')
1984 p++;
1985 *o++ = *p++;
1987 else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
1988 /* brackets are offset from each other by 2 */
1990 p += 2;
1991 if (*p != '.' && *p != '-' && o[-1] != '.')
1992 /* convert [foo][bar] to [bar] */
1993 while (o[-1] != '[' && o[-1] != '<')
1994 o--;
1995 else if (*p == '-' && *o != '.')
1996 *--p = '.';
1998 else if (p[0] == '-' && o[-1] == '.'
1999 && (p[1] == '.' || p[1] == ']' || p[1] == '>'))
2000 /* flush .foo.- ; leave - if stopped by '[' or '<' */
2003 o--;
2004 while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
2005 if (p[1] == '.') /* foo.-.bar ==> bar. */
2006 p += 2;
2007 else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
2008 p++, o--;
2009 /* else [foo.-] ==> [-] */
2011 else
2013 #ifndef VMS4_4
2014 if (*p == '-'
2015 && o[-1] != '[' && o[-1] != '<' && o[-1] != '.'
2016 && p[1] != ']' && p[1] != '>' && p[1] != '.')
2017 *p = '_';
2018 #endif /* VMS4_4 */
2019 *o++ = *p++;
2021 #else /* not VMS */
2022 if (*p != '/')
2024 *o++ = *p++;
2026 else if (!strncmp (p, "//", 2)
2027 #ifdef APOLLO
2028 /* // at start of filename is meaningful in Apollo system. */
2029 && o != target
2030 #endif /* APOLLO */
2033 o = target;
2034 p++;
2036 else if (p[0] == '/' && p[1] == '.'
2037 && (p[2] == '/' || p[2] == 0))
2038 p += 2;
2039 else if (!strncmp (p, "/..", 3)
2040 /* `/../' is the "superroot" on certain file systems. */
2041 && o != target
2042 && (p[3] == '/' || p[3] == 0))
2044 while (o != target && *--o != '/')
2046 #ifdef APOLLO
2047 if (o == target + 1 && o[-1] == '/' && o[0] == '/')
2048 ++o;
2049 else
2050 #endif /* APOLLO */
2051 if (o == target && *o == '/')
2052 ++o;
2053 p += 3;
2055 else
2057 *o++ = *p++;
2059 #endif /* not VMS */
2062 return make_string (target, o - target);
2064 #endif
2066 /* If /~ or // appears, discard everything through first slash. */
2067 static int
2068 file_name_absolute_p (filename)
2069 const unsigned char *filename;
2071 return
2072 (IS_DIRECTORY_SEP (*filename) || *filename == '~'
2073 #ifdef VMS
2074 /* ??? This criterion is probably wrong for '<'. */
2075 || index (filename, ':') || index (filename, '<')
2076 || (*filename == '[' && (filename[1] != '-'
2077 || (filename[2] != '.' && filename[2] != ']'))
2078 && filename[1] != '.')
2079 #endif /* VMS */
2080 #ifdef DOS_NT
2081 || (IS_DRIVE (*filename) && IS_DEVICE_SEP (filename[1])
2082 && IS_DIRECTORY_SEP (filename[2]))
2083 #endif
2087 static unsigned char *
2088 search_embedded_absfilename (nm, endp)
2089 unsigned char *nm, *endp;
2091 unsigned char *p, *s;
2093 for (p = nm + 1; p < endp; p++)
2095 if ((0
2096 #ifdef VMS
2097 || p[-1] == ':' || p[-1] == ']' || p[-1] == '>'
2098 #endif /* VMS */
2099 || IS_DIRECTORY_SEP (p[-1]))
2100 && file_name_absolute_p (p)
2101 #if defined (APOLLO) || defined (WINDOWSNT) || defined(CYGWIN)
2102 /* // at start of file name is meaningful in Apollo,
2103 WindowsNT and Cygwin systems. */
2104 && !(IS_DIRECTORY_SEP (p[0]) && p - 1 == nm)
2105 #endif /* not (APOLLO || WINDOWSNT || CYGWIN) */
2108 for (s = p; *s && (!IS_DIRECTORY_SEP (*s)
2109 #ifdef VMS
2110 && *s != ':'
2111 #endif /* VMS */
2112 ); s++);
2113 if (p[0] == '~' && s > p + 1) /* we've got "/~something/" */
2115 unsigned char *o = alloca (s - p + 1);
2116 struct passwd *pw;
2117 bcopy (p, o, s - p);
2118 o [s - p] = 0;
2120 /* If we have ~user and `user' exists, discard
2121 everything up to ~. But if `user' does not exist, leave
2122 ~user alone, it might be a literal file name. */
2123 BLOCK_INPUT;
2124 pw = getpwnam (o + 1);
2125 UNBLOCK_INPUT;
2126 if (pw)
2127 return p;
2129 else
2130 return p;
2133 return NULL;
2136 DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
2137 Ssubstitute_in_file_name, 1, 1, 0,
2138 doc: /* Substitute environment variables referred to in FILENAME.
2139 `$FOO' where FOO is an environment variable name means to substitute
2140 the value of that variable. The variable name should be terminated
2141 with a character not a letter, digit or underscore; otherwise, enclose
2142 the entire variable name in braces.
2143 If `/~' appears, all of FILENAME through that `/' is discarded.
2145 On VMS, `$' substitution is not done; this function does little and only
2146 duplicates what `expand-file-name' does. */)
2147 (filename)
2148 Lisp_Object filename;
2150 unsigned char *nm;
2152 register unsigned char *s, *p, *o, *x, *endp;
2153 unsigned char *target = NULL;
2154 int total = 0;
2155 int substituted = 0;
2156 unsigned char *xnm;
2157 Lisp_Object handler;
2159 CHECK_STRING (filename);
2161 /* If the file name has special constructs in it,
2162 call the corresponding file handler. */
2163 handler = Ffind_file_name_handler (filename, Qsubstitute_in_file_name);
2164 if (!NILP (handler))
2165 return call2 (handler, Qsubstitute_in_file_name, filename);
2167 nm = SDATA (filename);
2168 #ifdef DOS_NT
2169 nm = strcpy (alloca (strlen (nm) + 1), nm);
2170 CORRECT_DIR_SEPS (nm);
2171 substituted = (strcmp (nm, SDATA (filename)) != 0);
2172 #endif
2173 endp = nm + SBYTES (filename);
2175 /* If /~ or // appears, discard everything through first slash. */
2176 p = search_embedded_absfilename (nm, endp);
2177 if (p)
2178 /* Start over with the new string, so we check the file-name-handler
2179 again. Important with filenames like "/home/foo//:/hello///there"
2180 which whould substitute to "/:/hello///there" rather than "/there". */
2181 return Fsubstitute_in_file_name
2182 (make_specified_string (p, -1, endp - p,
2183 STRING_MULTIBYTE (filename)));
2185 #ifdef VMS
2186 return filename;
2187 #else
2189 /* See if any variables are substituted into the string
2190 and find the total length of their values in `total' */
2192 for (p = nm; p != endp;)
2193 if (*p != '$')
2194 p++;
2195 else
2197 p++;
2198 if (p == endp)
2199 goto badsubst;
2200 else if (*p == '$')
2202 /* "$$" means a single "$" */
2203 p++;
2204 total -= 1;
2205 substituted = 1;
2206 continue;
2208 else if (*p == '{')
2210 o = ++p;
2211 while (p != endp && *p != '}') p++;
2212 if (*p != '}') goto missingclose;
2213 s = p;
2215 else
2217 o = p;
2218 while (p != endp && (isalnum (*p) || *p == '_')) p++;
2219 s = p;
2222 /* Copy out the variable name */
2223 target = (unsigned char *) alloca (s - o + 1);
2224 strncpy (target, o, s - o);
2225 target[s - o] = 0;
2226 #ifdef DOS_NT
2227 strupr (target); /* $home == $HOME etc. */
2228 #endif /* DOS_NT */
2230 /* Get variable value */
2231 o = (unsigned char *) egetenv (target);
2232 if (o)
2234 total += strlen (o);
2235 substituted = 1;
2237 else if (*p == '}')
2238 goto badvar;
2241 if (!substituted)
2242 return filename;
2244 /* If substitution required, recopy the string and do it */
2245 /* Make space in stack frame for the new copy */
2246 xnm = (unsigned char *) alloca (SBYTES (filename) + total + 1);
2247 x = xnm;
2249 /* Copy the rest of the name through, replacing $ constructs with values */
2250 for (p = nm; *p;)
2251 if (*p != '$')
2252 *x++ = *p++;
2253 else
2255 p++;
2256 if (p == endp)
2257 goto badsubst;
2258 else if (*p == '$')
2260 *x++ = *p++;
2261 continue;
2263 else if (*p == '{')
2265 o = ++p;
2266 while (p != endp && *p != '}') p++;
2267 if (*p != '}') goto missingclose;
2268 s = p++;
2270 else
2272 o = p;
2273 while (p != endp && (isalnum (*p) || *p == '_')) p++;
2274 s = p;
2277 /* Copy out the variable name */
2278 target = (unsigned char *) alloca (s - o + 1);
2279 strncpy (target, o, s - o);
2280 target[s - o] = 0;
2281 #ifdef DOS_NT
2282 strupr (target); /* $home == $HOME etc. */
2283 #endif /* DOS_NT */
2285 /* Get variable value */
2286 o = (unsigned char *) egetenv (target);
2287 if (!o)
2289 *x++ = '$';
2290 strcpy (x, target); x+= strlen (target);
2292 else if (STRING_MULTIBYTE (filename))
2294 /* If the original string is multibyte,
2295 convert what we substitute into multibyte. */
2296 while (*o)
2298 int c = *o++;
2299 c = unibyte_char_to_multibyte (c);
2300 x += CHAR_STRING (c, x);
2303 else
2305 strcpy (x, o);
2306 x += strlen (o);
2310 *x = 0;
2312 /* If /~ or // appears, discard everything through first slash. */
2313 while ((p = search_embedded_absfilename (xnm, x)))
2314 /* This time we do not start over because we've already expanded envvars
2315 and replaced $$ with $. Maybe we should start over as well, but we'd
2316 need to quote some $ to $$ first. */
2317 xnm = p;
2319 return make_specified_string (xnm, -1, x - xnm, STRING_MULTIBYTE (filename));
2321 badsubst:
2322 error ("Bad format environment-variable substitution");
2323 missingclose:
2324 error ("Missing \"}\" in environment-variable substitution");
2325 badvar:
2326 error ("Substituting nonexistent environment variable \"%s\"", target);
2328 /* NOTREACHED */
2329 #endif /* not VMS */
2330 return Qnil;
2333 /* A slightly faster and more convenient way to get
2334 (directory-file-name (expand-file-name FOO)). */
2336 Lisp_Object
2337 expand_and_dir_to_file (filename, defdir)
2338 Lisp_Object filename, defdir;
2340 register Lisp_Object absname;
2342 absname = Fexpand_file_name (filename, defdir);
2343 #ifdef VMS
2345 register int c = SREF (absname, SBYTES (absname) - 1);
2346 if (c == ':' || c == ']' || c == '>')
2347 absname = Fdirectory_file_name (absname);
2349 #else
2350 /* Remove final slash, if any (unless this is the root dir).
2351 stat behaves differently depending! */
2352 if (SCHARS (absname) > 1
2353 && IS_DIRECTORY_SEP (SREF (absname, SBYTES (absname) - 1))
2354 && !IS_DEVICE_SEP (SREF (absname, SBYTES (absname)-2)))
2355 /* We cannot take shortcuts; they might be wrong for magic file names. */
2356 absname = Fdirectory_file_name (absname);
2357 #endif
2358 return absname;
2361 /* Signal an error if the file ABSNAME already exists.
2362 If INTERACTIVE is nonzero, ask the user whether to proceed,
2363 and bypass the error if the user says to go ahead.
2364 QUERYSTRING is a name for the action that is being considered
2365 to alter the file.
2367 *STATPTR is used to store the stat information if the file exists.
2368 If the file does not exist, STATPTR->st_mode is set to 0.
2369 If STATPTR is null, we don't store into it.
2371 If QUICK is nonzero, we ask for y or n, not yes or no. */
2373 void
2374 barf_or_query_if_file_exists (absname, querystring, interactive, statptr, quick)
2375 Lisp_Object absname;
2376 unsigned char *querystring;
2377 int interactive;
2378 struct stat *statptr;
2379 int quick;
2381 register Lisp_Object tem, encoded_filename;
2382 struct stat statbuf;
2383 struct gcpro gcpro1;
2385 encoded_filename = ENCODE_FILE (absname);
2387 /* stat is a good way to tell whether the file exists,
2388 regardless of what access permissions it has. */
2389 if (lstat (SDATA (encoded_filename), &statbuf) >= 0)
2391 if (! interactive)
2392 xsignal2 (Qfile_already_exists,
2393 build_string ("File already exists"), absname);
2394 GCPRO1 (absname);
2395 tem = format2 ("File %s already exists; %s anyway? ",
2396 absname, build_string (querystring));
2397 if (quick)
2398 tem = Fy_or_n_p (tem);
2399 else
2400 tem = do_yes_or_no_p (tem);
2401 UNGCPRO;
2402 if (NILP (tem))
2403 xsignal2 (Qfile_already_exists,
2404 build_string ("File already exists"), absname);
2405 if (statptr)
2406 *statptr = statbuf;
2408 else
2410 if (statptr)
2411 statptr->st_mode = 0;
2413 return;
2416 DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 5,
2417 "fCopy file: \nGCopy %s to file: \np\nP",
2418 doc: /* Copy FILE to NEWNAME. Both args must be strings.
2419 If NEWNAME names a directory, copy FILE there.
2421 This function always sets the file modes of the output file to match
2422 the input file.
2424 The optional third argument OK-IF-ALREADY-EXISTS specifies what to do
2425 if file NEWNAME already exists. If OK-IF-ALREADY-EXISTS is nil, we
2426 signal a `file-already-exists' error without overwriting. If
2427 OK-IF-ALREADY-EXISTS is a number, we request confirmation from the user
2428 about overwriting; this is what happens in interactive use with M-x.
2429 Any other value for OK-IF-ALREADY-EXISTS means to overwrite the
2430 existing file.
2432 Fourth arg KEEP-TIME non-nil means give the output file the same
2433 last-modified time as the old one. (This works on only some systems.)
2435 A prefix arg makes KEEP-TIME non-nil.
2437 If PRESERVE-UID-GID is non-nil, we try to transfer the
2438 uid and gid of FILE to NEWNAME. */)
2439 (file, newname, ok_if_already_exists, keep_time, preserve_uid_gid)
2440 Lisp_Object file, newname, ok_if_already_exists, keep_time;
2441 Lisp_Object preserve_uid_gid;
2443 int ifd, ofd, n;
2444 char buf[16 * 1024];
2445 struct stat st, out_st;
2446 Lisp_Object handler;
2447 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2448 int count = SPECPDL_INDEX ();
2449 int input_file_statable_p;
2450 Lisp_Object encoded_file, encoded_newname;
2452 encoded_file = encoded_newname = Qnil;
2453 GCPRO4 (file, newname, encoded_file, encoded_newname);
2454 CHECK_STRING (file);
2455 CHECK_STRING (newname);
2457 if (!NILP (Ffile_directory_p (newname)))
2458 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2459 else
2460 newname = Fexpand_file_name (newname, Qnil);
2462 file = Fexpand_file_name (file, Qnil);
2464 /* If the input file name has special constructs in it,
2465 call the corresponding file handler. */
2466 handler = Ffind_file_name_handler (file, Qcopy_file);
2467 /* Likewise for output file name. */
2468 if (NILP (handler))
2469 handler = Ffind_file_name_handler (newname, Qcopy_file);
2470 if (!NILP (handler))
2471 RETURN_UNGCPRO (call5 (handler, Qcopy_file, file, newname,
2472 ok_if_already_exists, keep_time));
2474 encoded_file = ENCODE_FILE (file);
2475 encoded_newname = ENCODE_FILE (newname);
2477 if (NILP (ok_if_already_exists)
2478 || INTEGERP (ok_if_already_exists))
2479 barf_or_query_if_file_exists (newname, "copy to it",
2480 INTEGERP (ok_if_already_exists), &out_st, 0);
2481 else if (stat (SDATA (encoded_newname), &out_st) < 0)
2482 out_st.st_mode = 0;
2484 #ifdef WINDOWSNT
2485 if (!CopyFile (SDATA (encoded_file),
2486 SDATA (encoded_newname),
2487 FALSE))
2488 report_file_error ("Copying file", Fcons (file, Fcons (newname, Qnil)));
2489 /* CopyFile retains the timestamp by default. */
2490 else if (NILP (keep_time))
2492 EMACS_TIME now;
2493 DWORD attributes;
2494 char * filename;
2496 EMACS_GET_TIME (now);
2497 filename = SDATA (encoded_newname);
2499 /* Ensure file is writable while its modified time is set. */
2500 attributes = GetFileAttributes (filename);
2501 SetFileAttributes (filename, attributes & ~FILE_ATTRIBUTE_READONLY);
2502 if (set_file_times (filename, now, now))
2504 /* Restore original attributes. */
2505 SetFileAttributes (filename, attributes);
2506 xsignal2 (Qfile_date_error,
2507 build_string ("Cannot set file date"), newname);
2509 /* Restore original attributes. */
2510 SetFileAttributes (filename, attributes);
2512 #else /* not WINDOWSNT */
2513 immediate_quit = 1;
2514 ifd = emacs_open (SDATA (encoded_file), O_RDONLY, 0);
2515 immediate_quit = 0;
2517 if (ifd < 0)
2518 report_file_error ("Opening input file", Fcons (file, Qnil));
2520 record_unwind_protect (close_file_unwind, make_number (ifd));
2522 /* We can only copy regular files and symbolic links. Other files are not
2523 copyable by us. */
2524 input_file_statable_p = (fstat (ifd, &st) >= 0);
2526 #if !defined (MSDOS) || __DJGPP__ > 1
2527 if (out_st.st_mode != 0
2528 && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
2530 errno = 0;
2531 report_file_error ("Input and output files are the same",
2532 Fcons (file, Fcons (newname, Qnil)));
2534 #endif
2536 #if defined (S_ISREG) && defined (S_ISLNK)
2537 if (input_file_statable_p)
2539 if (!(S_ISREG (st.st_mode)) && !(S_ISLNK (st.st_mode)))
2541 #if defined (EISDIR)
2542 /* Get a better looking error message. */
2543 errno = EISDIR;
2544 #endif /* EISDIR */
2545 report_file_error ("Non-regular file", Fcons (file, Qnil));
2548 #endif /* S_ISREG && S_ISLNK */
2550 #ifdef VMS
2551 /* Create the copy file with the same record format as the input file */
2552 ofd = sys_creat (SDATA (encoded_newname), 0666, ifd);
2553 #else
2554 #ifdef MSDOS
2555 /* System's default file type was set to binary by _fmode in emacs.c. */
2556 ofd = emacs_open (SDATA (encoded_newname),
2557 O_WRONLY | O_TRUNC | O_CREAT
2558 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2559 S_IREAD | S_IWRITE);
2560 #else /* not MSDOS */
2561 ofd = emacs_open (SDATA (encoded_newname),
2562 O_WRONLY | O_TRUNC | O_CREAT
2563 | (NILP (ok_if_already_exists) ? O_EXCL : 0),
2564 0666);
2565 #endif /* not MSDOS */
2566 #endif /* VMS */
2567 if (ofd < 0)
2568 report_file_error ("Opening output file", Fcons (newname, Qnil));
2570 record_unwind_protect (close_file_unwind, make_number (ofd));
2572 immediate_quit = 1;
2573 QUIT;
2574 while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
2575 if (emacs_write (ofd, buf, n) != n)
2576 report_file_error ("I/O error", Fcons (newname, Qnil));
2577 immediate_quit = 0;
2579 #ifndef MSDOS
2580 /* Preserve the original file modes, and if requested, also its
2581 owner and group. */
2582 if (input_file_statable_p)
2584 if (! NILP (preserve_uid_gid))
2585 fchown (ofd, st.st_uid, st.st_gid);
2586 fchmod (ofd, st.st_mode & 07777);
2588 #endif /* not MSDOS */
2590 /* Closing the output clobbers the file times on some systems. */
2591 if (emacs_close (ofd) < 0)
2592 report_file_error ("I/O error", Fcons (newname, Qnil));
2594 if (input_file_statable_p)
2596 if (!NILP (keep_time))
2598 EMACS_TIME atime, mtime;
2599 EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
2600 EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
2601 if (set_file_times (SDATA (encoded_newname),
2602 atime, mtime))
2603 xsignal2 (Qfile_date_error,
2604 build_string ("Cannot set file date"), newname);
2608 emacs_close (ifd);
2610 #if defined (__DJGPP__) && __DJGPP__ > 1
2611 if (input_file_statable_p)
2613 /* In DJGPP v2.0 and later, fstat usually returns true file mode bits,
2614 and if it can't, it tells so. Otherwise, under MSDOS we usually
2615 get only the READ bit, which will make the copied file read-only,
2616 so it's better not to chmod at all. */
2617 if ((_djstat_flags & _STFAIL_WRITEBIT) == 0)
2618 chmod (SDATA (encoded_newname), st.st_mode & 07777);
2620 #endif /* DJGPP version 2 or newer */
2621 #endif /* not WINDOWSNT */
2623 /* Discard the unwind protects. */
2624 specpdl_ptr = specpdl + count;
2626 UNGCPRO;
2627 return Qnil;
2630 DEFUN ("make-directory-internal", Fmake_directory_internal,
2631 Smake_directory_internal, 1, 1, 0,
2632 doc: /* Create a new directory named DIRECTORY. */)
2633 (directory)
2634 Lisp_Object directory;
2636 const unsigned char *dir;
2637 Lisp_Object handler;
2638 Lisp_Object encoded_dir;
2640 CHECK_STRING (directory);
2641 directory = Fexpand_file_name (directory, Qnil);
2643 handler = Ffind_file_name_handler (directory, Qmake_directory_internal);
2644 if (!NILP (handler))
2645 return call2 (handler, Qmake_directory_internal, directory);
2647 encoded_dir = ENCODE_FILE (directory);
2649 dir = SDATA (encoded_dir);
2651 #ifdef WINDOWSNT
2652 if (mkdir (dir) != 0)
2653 #else
2654 if (mkdir (dir, 0777) != 0)
2655 #endif
2656 report_file_error ("Creating directory", list1 (directory));
2658 return Qnil;
2661 DEFUN ("delete-directory", Fdelete_directory, Sdelete_directory, 1, 1, "FDelete directory: ",
2662 doc: /* Delete the directory named DIRECTORY. Does not follow symlinks. */)
2663 (directory)
2664 Lisp_Object directory;
2666 const unsigned char *dir;
2667 Lisp_Object handler;
2668 Lisp_Object encoded_dir;
2670 CHECK_STRING (directory);
2671 directory = Fdirectory_file_name (Fexpand_file_name (directory, Qnil));
2673 handler = Ffind_file_name_handler (directory, Qdelete_directory);
2674 if (!NILP (handler))
2675 return call2 (handler, Qdelete_directory, directory);
2677 encoded_dir = ENCODE_FILE (directory);
2679 dir = SDATA (encoded_dir);
2681 if (rmdir (dir) != 0)
2682 report_file_error ("Removing directory", list1 (directory));
2684 return Qnil;
2687 DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 1, "fDelete file: ",
2688 doc: /* Delete file named FILENAME. If it is a symlink, remove the symlink.
2689 If file has multiple names, it continues to exist with the other names. */)
2690 (filename)
2691 Lisp_Object filename;
2693 Lisp_Object handler;
2694 Lisp_Object encoded_file;
2695 struct gcpro gcpro1;
2697 GCPRO1 (filename);
2698 if (!NILP (Ffile_directory_p (filename))
2699 && NILP (Ffile_symlink_p (filename)))
2700 xsignal2 (Qfile_error,
2701 build_string ("Removing old name: is a directory"),
2702 filename);
2703 UNGCPRO;
2704 filename = Fexpand_file_name (filename, Qnil);
2706 handler = Ffind_file_name_handler (filename, Qdelete_file);
2707 if (!NILP (handler))
2708 return call2 (handler, Qdelete_file, filename);
2710 encoded_file = ENCODE_FILE (filename);
2712 if (0 > unlink (SDATA (encoded_file)))
2713 report_file_error ("Removing old name", list1 (filename));
2714 return Qnil;
2717 static Lisp_Object
2718 internal_delete_file_1 (ignore)
2719 Lisp_Object ignore;
2721 return Qt;
2724 /* Delete file FILENAME, returning 1 if successful and 0 if failed. */
2727 internal_delete_file (filename)
2728 Lisp_Object filename;
2730 Lisp_Object tem;
2731 tem = internal_condition_case_1 (Fdelete_file, filename,
2732 Qt, internal_delete_file_1);
2733 return NILP (tem);
2736 DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
2737 "fRename file: \nGRename %s to file: \np",
2738 doc: /* Rename FILE as NEWNAME. Both args must be strings.
2739 If file has names other than FILE, it continues to have those names.
2740 Signals a `file-already-exists' error if a file NEWNAME already exists
2741 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2742 A number as third arg means request confirmation if NEWNAME already exists.
2743 This is what happens in interactive use with M-x. */)
2744 (file, newname, ok_if_already_exists)
2745 Lisp_Object file, newname, ok_if_already_exists;
2747 Lisp_Object handler;
2748 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
2749 Lisp_Object encoded_file, encoded_newname, symlink_target;
2751 symlink_target = encoded_file = encoded_newname = Qnil;
2752 GCPRO5 (file, newname, encoded_file, encoded_newname, symlink_target);
2753 CHECK_STRING (file);
2754 CHECK_STRING (newname);
2755 file = Fexpand_file_name (file, Qnil);
2757 if ((!NILP (Ffile_directory_p (newname)))
2758 #ifdef DOS_NT
2759 /* If the file names are identical but for the case,
2760 don't attempt to move directory to itself. */
2761 && (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2762 #endif
2764 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2765 else
2766 newname = Fexpand_file_name (newname, Qnil);
2768 /* If the file name has special constructs in it,
2769 call the corresponding file handler. */
2770 handler = Ffind_file_name_handler (file, Qrename_file);
2771 if (NILP (handler))
2772 handler = Ffind_file_name_handler (newname, Qrename_file);
2773 if (!NILP (handler))
2774 RETURN_UNGCPRO (call4 (handler, Qrename_file,
2775 file, newname, ok_if_already_exists));
2777 encoded_file = ENCODE_FILE (file);
2778 encoded_newname = ENCODE_FILE (newname);
2780 #ifdef DOS_NT
2781 /* If the file names are identical but for the case, don't ask for
2782 confirmation: they simply want to change the letter-case of the
2783 file name. */
2784 if (NILP (Fstring_equal (Fdowncase (file), Fdowncase (newname))))
2785 #endif
2786 if (NILP (ok_if_already_exists)
2787 || INTEGERP (ok_if_already_exists))
2788 barf_or_query_if_file_exists (newname, "rename to it",
2789 INTEGERP (ok_if_already_exists), 0, 0);
2790 #ifndef BSD4_1
2791 if (0 > rename (SDATA (encoded_file), SDATA (encoded_newname)))
2792 #else
2793 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname))
2794 || 0 > unlink (SDATA (encoded_file)))
2795 #endif
2797 if (errno == EXDEV)
2799 #ifdef S_IFLNK
2800 symlink_target = Ffile_symlink_p (file);
2801 if (! NILP (symlink_target))
2802 Fmake_symbolic_link (symlink_target, newname,
2803 NILP (ok_if_already_exists) ? Qnil : Qt);
2804 else
2805 #endif
2806 Fcopy_file (file, newname,
2807 /* We have already prompted if it was an integer,
2808 so don't have copy-file prompt again. */
2809 NILP (ok_if_already_exists) ? Qnil : Qt,
2810 Qt, Qt);
2812 Fdelete_file (file);
2814 else
2815 report_file_error ("Renaming", list2 (file, newname));
2817 UNGCPRO;
2818 return Qnil;
2821 DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
2822 "fAdd name to file: \nGName to add to %s: \np",
2823 doc: /* Give FILE additional name NEWNAME. Both args must be strings.
2824 Signals a `file-already-exists' error if a file NEWNAME already exists
2825 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2826 A number as third arg means request confirmation if NEWNAME already exists.
2827 This is what happens in interactive use with M-x. */)
2828 (file, newname, ok_if_already_exists)
2829 Lisp_Object file, newname, ok_if_already_exists;
2831 Lisp_Object handler;
2832 Lisp_Object encoded_file, encoded_newname;
2833 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2835 GCPRO4 (file, newname, encoded_file, encoded_newname);
2836 encoded_file = encoded_newname = Qnil;
2837 CHECK_STRING (file);
2838 CHECK_STRING (newname);
2839 file = Fexpand_file_name (file, Qnil);
2841 if (!NILP (Ffile_directory_p (newname)))
2842 newname = Fexpand_file_name (Ffile_name_nondirectory (file), newname);
2843 else
2844 newname = Fexpand_file_name (newname, Qnil);
2846 /* If the file name has special constructs in it,
2847 call the corresponding file handler. */
2848 handler = Ffind_file_name_handler (file, Qadd_name_to_file);
2849 if (!NILP (handler))
2850 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2851 newname, ok_if_already_exists));
2853 /* If the new name has special constructs in it,
2854 call the corresponding file handler. */
2855 handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
2856 if (!NILP (handler))
2857 RETURN_UNGCPRO (call4 (handler, Qadd_name_to_file, file,
2858 newname, ok_if_already_exists));
2860 encoded_file = ENCODE_FILE (file);
2861 encoded_newname = ENCODE_FILE (newname);
2863 if (NILP (ok_if_already_exists)
2864 || INTEGERP (ok_if_already_exists))
2865 barf_or_query_if_file_exists (newname, "make it a new name",
2866 INTEGERP (ok_if_already_exists), 0, 0);
2868 unlink (SDATA (newname));
2869 if (0 > link (SDATA (encoded_file), SDATA (encoded_newname)))
2870 report_file_error ("Adding new name", list2 (file, newname));
2872 UNGCPRO;
2873 return Qnil;
2876 #ifdef S_IFLNK
2877 DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
2878 "FMake symbolic link to file: \nGMake symbolic link to file %s: \np",
2879 doc: /* Make a symbolic link to FILENAME, named LINKNAME.
2880 Both args must be strings.
2881 Signals a `file-already-exists' error if a file LINKNAME already exists
2882 unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.
2883 A number as third arg means request confirmation if LINKNAME already exists.
2884 This happens for interactive use with M-x. */)
2885 (filename, linkname, ok_if_already_exists)
2886 Lisp_Object filename, linkname, ok_if_already_exists;
2888 Lisp_Object handler;
2889 Lisp_Object encoded_filename, encoded_linkname;
2890 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2892 GCPRO4 (filename, linkname, encoded_filename, encoded_linkname);
2893 encoded_filename = encoded_linkname = Qnil;
2894 CHECK_STRING (filename);
2895 CHECK_STRING (linkname);
2896 /* If the link target has a ~, we must expand it to get
2897 a truly valid file name. Otherwise, do not expand;
2898 we want to permit links to relative file names. */
2899 if (SREF (filename, 0) == '~')
2900 filename = Fexpand_file_name (filename, Qnil);
2902 if (!NILP (Ffile_directory_p (linkname)))
2903 linkname = Fexpand_file_name (Ffile_name_nondirectory (filename), linkname);
2904 else
2905 linkname = Fexpand_file_name (linkname, Qnil);
2907 /* If the file name has special constructs in it,
2908 call the corresponding file handler. */
2909 handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
2910 if (!NILP (handler))
2911 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2912 linkname, ok_if_already_exists));
2914 /* If the new link name has special constructs in it,
2915 call the corresponding file handler. */
2916 handler = Ffind_file_name_handler (linkname, Qmake_symbolic_link);
2917 if (!NILP (handler))
2918 RETURN_UNGCPRO (call4 (handler, Qmake_symbolic_link, filename,
2919 linkname, ok_if_already_exists));
2921 encoded_filename = ENCODE_FILE (filename);
2922 encoded_linkname = ENCODE_FILE (linkname);
2924 if (NILP (ok_if_already_exists)
2925 || INTEGERP (ok_if_already_exists))
2926 barf_or_query_if_file_exists (linkname, "make it a link",
2927 INTEGERP (ok_if_already_exists), 0, 0);
2928 if (0 > symlink (SDATA (encoded_filename),
2929 SDATA (encoded_linkname)))
2931 /* If we didn't complain already, silently delete existing file. */
2932 if (errno == EEXIST)
2934 unlink (SDATA (encoded_linkname));
2935 if (0 <= symlink (SDATA (encoded_filename),
2936 SDATA (encoded_linkname)))
2938 UNGCPRO;
2939 return Qnil;
2943 report_file_error ("Making symbolic link", list2 (filename, linkname));
2945 UNGCPRO;
2946 return Qnil;
2948 #endif /* S_IFLNK */
2950 #ifdef VMS
2952 DEFUN ("define-logical-name", Fdefine_logical_name, Sdefine_logical_name,
2953 2, 2, "sDefine logical name: \nsDefine logical name %s as: ",
2954 doc: /* Define the job-wide logical name NAME to have the value STRING.
2955 If STRING is nil or a null string, the logical name NAME is deleted. */)
2956 (name, string)
2957 Lisp_Object name;
2958 Lisp_Object string;
2960 CHECK_STRING (name);
2961 if (NILP (string))
2962 delete_logical_name (SDATA (name));
2963 else
2965 CHECK_STRING (string);
2967 if (SCHARS (string) == 0)
2968 delete_logical_name (SDATA (name));
2969 else
2970 define_logical_name (SDATA (name), SDATA (string));
2973 return string;
2975 #endif /* VMS */
2977 #ifdef HPUX_NET
2979 DEFUN ("sysnetunam", Fsysnetunam, Ssysnetunam, 2, 2, 0,
2980 doc: /* Open a network connection to PATH using LOGIN as the login string. */)
2981 (path, login)
2982 Lisp_Object path, login;
2984 int netresult;
2986 CHECK_STRING (path);
2987 CHECK_STRING (login);
2989 netresult = netunam (SDATA (path), SDATA (login));
2991 if (netresult == -1)
2992 return Qnil;
2993 else
2994 return Qt;
2996 #endif /* HPUX_NET */
2998 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
2999 1, 1, 0,
3000 doc: /* Return t if file FILENAME specifies an absolute file name.
3001 On Unix, this is a name starting with a `/' or a `~'. */)
3002 (filename)
3003 Lisp_Object filename;
3005 CHECK_STRING (filename);
3006 return file_name_absolute_p (SDATA (filename)) ? Qt : Qnil;
3009 /* Return nonzero if file FILENAME exists and can be executed. */
3011 static int
3012 check_executable (filename)
3013 char *filename;
3015 #ifdef DOS_NT
3016 int len = strlen (filename);
3017 char *suffix;
3018 struct stat st;
3019 if (stat (filename, &st) < 0)
3020 return 0;
3021 #if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
3022 return ((st.st_mode & S_IEXEC) != 0);
3023 #else
3024 return (S_ISREG (st.st_mode)
3025 && len >= 5
3026 && (stricmp ((suffix = filename + len-4), ".com") == 0
3027 || stricmp (suffix, ".exe") == 0
3028 || stricmp (suffix, ".bat") == 0)
3029 || (st.st_mode & S_IFMT) == S_IFDIR);
3030 #endif /* not WINDOWSNT */
3031 #else /* not DOS_NT */
3032 #ifdef HAVE_EUIDACCESS
3033 return (euidaccess (filename, 1) >= 0);
3034 #else
3035 /* Access isn't quite right because it uses the real uid
3036 and we really want to test with the effective uid.
3037 But Unix doesn't give us a right way to do it. */
3038 return (access (filename, 1) >= 0);
3039 #endif
3040 #endif /* not DOS_NT */
3043 /* Return nonzero if file FILENAME exists and can be written. */
3045 static int
3046 check_writable (filename)
3047 char *filename;
3049 #ifdef MSDOS
3050 struct stat st;
3051 if (stat (filename, &st) < 0)
3052 return 0;
3053 return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
3054 #else /* not MSDOS */
3055 #ifdef HAVE_EUIDACCESS
3056 return (euidaccess (filename, 2) >= 0);
3057 #else
3058 /* Access isn't quite right because it uses the real uid
3059 and we really want to test with the effective uid.
3060 But Unix doesn't give us a right way to do it.
3061 Opening with O_WRONLY could work for an ordinary file,
3062 but would lose for directories. */
3063 return (access (filename, 2) >= 0);
3064 #endif
3065 #endif /* not MSDOS */
3068 DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
3069 doc: /* Return t if file FILENAME exists (whether or not you can read it.)
3070 See also `file-readable-p' and `file-attributes'.
3071 This returns nil for a symlink to a nonexistent file.
3072 Use `file-symlink-p' to test for such links. */)
3073 (filename)
3074 Lisp_Object filename;
3076 Lisp_Object absname;
3077 Lisp_Object handler;
3078 struct stat statbuf;
3080 CHECK_STRING (filename);
3081 absname = Fexpand_file_name (filename, Qnil);
3083 /* If the file name has special constructs in it,
3084 call the corresponding file handler. */
3085 handler = Ffind_file_name_handler (absname, Qfile_exists_p);
3086 if (!NILP (handler))
3087 return call2 (handler, Qfile_exists_p, absname);
3089 absname = ENCODE_FILE (absname);
3091 return (stat (SDATA (absname), &statbuf) >= 0) ? Qt : Qnil;
3094 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
3095 doc: /* Return t if FILENAME can be executed by you.
3096 For a directory, this means you can access files in that directory. */)
3097 (filename)
3098 Lisp_Object filename;
3100 Lisp_Object absname;
3101 Lisp_Object handler;
3103 CHECK_STRING (filename);
3104 absname = Fexpand_file_name (filename, Qnil);
3106 /* If the file name has special constructs in it,
3107 call the corresponding file handler. */
3108 handler = Ffind_file_name_handler (absname, Qfile_executable_p);
3109 if (!NILP (handler))
3110 return call2 (handler, Qfile_executable_p, absname);
3112 absname = ENCODE_FILE (absname);
3114 return (check_executable (SDATA (absname)) ? Qt : Qnil);
3117 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
3118 doc: /* Return t if file FILENAME exists and you can read it.
3119 See also `file-exists-p' and `file-attributes'. */)
3120 (filename)
3121 Lisp_Object filename;
3123 Lisp_Object absname;
3124 Lisp_Object handler;
3125 int desc;
3126 int flags;
3127 struct stat statbuf;
3129 CHECK_STRING (filename);
3130 absname = Fexpand_file_name (filename, Qnil);
3132 /* If the file name has special constructs in it,
3133 call the corresponding file handler. */
3134 handler = Ffind_file_name_handler (absname, Qfile_readable_p);
3135 if (!NILP (handler))
3136 return call2 (handler, Qfile_readable_p, absname);
3138 absname = ENCODE_FILE (absname);
3140 #if defined(DOS_NT) || defined(macintosh)
3141 /* Under MS-DOS, Windows, and Macintosh, open does not work for
3142 directories. */
3143 if (access (SDATA (absname), 0) == 0)
3144 return Qt;
3145 return Qnil;
3146 #else /* not DOS_NT and not macintosh */
3147 flags = O_RDONLY;
3148 #if defined (S_ISFIFO) && defined (O_NONBLOCK)
3149 /* Opening a fifo without O_NONBLOCK can wait.
3150 We don't want to wait. But we don't want to mess wth O_NONBLOCK
3151 except in the case of a fifo, on a system which handles it. */
3152 desc = stat (SDATA (absname), &statbuf);
3153 if (desc < 0)
3154 return Qnil;
3155 if (S_ISFIFO (statbuf.st_mode))
3156 flags |= O_NONBLOCK;
3157 #endif
3158 desc = emacs_open (SDATA (absname), flags, 0);
3159 if (desc < 0)
3160 return Qnil;
3161 emacs_close (desc);
3162 return Qt;
3163 #endif /* not DOS_NT and not macintosh */
3166 /* Having this before file-symlink-p mysteriously caused it to be forgotten
3167 on the RT/PC. */
3168 DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
3169 doc: /* Return t if file FILENAME can be written or created by you. */)
3170 (filename)
3171 Lisp_Object filename;
3173 Lisp_Object absname, dir, encoded;
3174 Lisp_Object handler;
3175 struct stat statbuf;
3177 CHECK_STRING (filename);
3178 absname = Fexpand_file_name (filename, Qnil);
3180 /* If the file name has special constructs in it,
3181 call the corresponding file handler. */
3182 handler = Ffind_file_name_handler (absname, Qfile_writable_p);
3183 if (!NILP (handler))
3184 return call2 (handler, Qfile_writable_p, absname);
3186 encoded = ENCODE_FILE (absname);
3187 if (stat (SDATA (encoded), &statbuf) >= 0)
3188 return (check_writable (SDATA (encoded))
3189 ? Qt : Qnil);
3191 dir = Ffile_name_directory (absname);
3192 #ifdef VMS
3193 if (!NILP (dir))
3194 dir = Fdirectory_file_name (dir);
3195 #endif /* VMS */
3196 #ifdef MSDOS
3197 if (!NILP (dir))
3198 dir = Fdirectory_file_name (dir);
3199 #endif /* MSDOS */
3201 dir = ENCODE_FILE (dir);
3202 #ifdef WINDOWSNT
3203 /* The read-only attribute of the parent directory doesn't affect
3204 whether a file or directory can be created within it. Some day we
3205 should check ACLs though, which do affect this. */
3206 if (stat (SDATA (dir), &statbuf) < 0)
3207 return Qnil;
3208 return (statbuf.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
3209 #else
3210 return (check_writable (!NILP (dir) ? (char *) SDATA (dir) : "")
3211 ? Qt : Qnil);
3212 #endif
3215 DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
3216 doc: /* Access file FILENAME, and get an error if that does not work.
3217 The second argument STRING is used in the error message.
3218 If there is no error, returns nil. */)
3219 (filename, string)
3220 Lisp_Object filename, string;
3222 Lisp_Object handler, encoded_filename, absname;
3223 int fd;
3225 CHECK_STRING (filename);
3226 absname = Fexpand_file_name (filename, Qnil);
3228 CHECK_STRING (string);
3230 /* If the file name has special constructs in it,
3231 call the corresponding file handler. */
3232 handler = Ffind_file_name_handler (absname, Qaccess_file);
3233 if (!NILP (handler))
3234 return call3 (handler, Qaccess_file, absname, string);
3236 encoded_filename = ENCODE_FILE (absname);
3238 fd = emacs_open (SDATA (encoded_filename), O_RDONLY, 0);
3239 if (fd < 0)
3240 report_file_error (SDATA (string), Fcons (filename, Qnil));
3241 emacs_close (fd);
3243 return Qnil;
3246 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
3247 doc: /* Return non-nil if file FILENAME is the name of a symbolic link.
3248 The value is the link target, as a string.
3249 Otherwise it returns nil.
3251 This function returns t when given the name of a symlink that
3252 points to a nonexistent file. */)
3253 (filename)
3254 Lisp_Object filename;
3256 Lisp_Object handler;
3258 CHECK_STRING (filename);
3259 filename = Fexpand_file_name (filename, Qnil);
3261 /* If the file name has special constructs in it,
3262 call the corresponding file handler. */
3263 handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
3264 if (!NILP (handler))
3265 return call2 (handler, Qfile_symlink_p, filename);
3267 #ifdef S_IFLNK
3269 char *buf;
3270 int bufsize;
3271 int valsize;
3272 Lisp_Object val;
3274 filename = ENCODE_FILE (filename);
3276 bufsize = 50;
3277 buf = NULL;
3280 bufsize *= 2;
3281 buf = (char *) xrealloc (buf, bufsize);
3282 bzero (buf, bufsize);
3284 errno = 0;
3285 valsize = readlink (SDATA (filename), buf, bufsize);
3286 if (valsize == -1)
3288 #ifdef ERANGE
3289 /* HP-UX reports ERANGE if buffer is too small. */
3290 if (errno == ERANGE)
3291 valsize = bufsize;
3292 else
3293 #endif
3295 xfree (buf);
3296 return Qnil;
3300 while (valsize >= bufsize);
3302 val = make_string (buf, valsize);
3303 if (buf[0] == '/' && index (buf, ':'))
3304 val = concat2 (build_string ("/:"), val);
3305 xfree (buf);
3306 val = DECODE_FILE (val);
3307 return val;
3309 #else /* not S_IFLNK */
3310 return Qnil;
3311 #endif /* not S_IFLNK */
3314 DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
3315 doc: /* Return t if FILENAME names an existing directory.
3316 Symbolic links to directories count as directories.
3317 See `file-symlink-p' to distinguish symlinks. */)
3318 (filename)
3319 Lisp_Object filename;
3321 register Lisp_Object absname;
3322 struct stat st;
3323 Lisp_Object handler;
3325 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3327 /* If the file name has special constructs in it,
3328 call the corresponding file handler. */
3329 handler = Ffind_file_name_handler (absname, Qfile_directory_p);
3330 if (!NILP (handler))
3331 return call2 (handler, Qfile_directory_p, absname);
3333 absname = ENCODE_FILE (absname);
3335 if (stat (SDATA (absname), &st) < 0)
3336 return Qnil;
3337 return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
3340 DEFUN ("file-accessible-directory-p", Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
3341 doc: /* Return t if file FILENAME names a directory you can open.
3342 For the value to be t, FILENAME must specify the name of a directory as a file,
3343 and the directory must allow you to open files in it. In order to use a
3344 directory as a buffer's current directory, this predicate must return true.
3345 A directory name spec may be given instead; then the value is t
3346 if the directory so specified exists and really is a readable and
3347 searchable directory. */)
3348 (filename)
3349 Lisp_Object filename;
3351 Lisp_Object handler;
3352 int tem;
3353 struct gcpro gcpro1;
3355 /* If the file name has special constructs in it,
3356 call the corresponding file handler. */
3357 handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
3358 if (!NILP (handler))
3359 return call2 (handler, Qfile_accessible_directory_p, filename);
3361 GCPRO1 (filename);
3362 tem = (NILP (Ffile_directory_p (filename))
3363 || NILP (Ffile_executable_p (filename)));
3364 UNGCPRO;
3365 return tem ? Qnil : Qt;
3368 DEFUN ("file-regular-p", Ffile_regular_p, Sfile_regular_p, 1, 1, 0,
3369 doc: /* Return t if FILENAME names a regular file.
3370 This is the sort of file that holds an ordinary stream of data bytes.
3371 Symbolic links to regular files count as regular files.
3372 See `file-symlink-p' to distinguish symlinks. */)
3373 (filename)
3374 Lisp_Object filename;
3376 register Lisp_Object absname;
3377 struct stat st;
3378 Lisp_Object handler;
3380 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3382 /* If the file name has special constructs in it,
3383 call the corresponding file handler. */
3384 handler = Ffind_file_name_handler (absname, Qfile_regular_p);
3385 if (!NILP (handler))
3386 return call2 (handler, Qfile_regular_p, absname);
3388 absname = ENCODE_FILE (absname);
3390 #ifdef WINDOWSNT
3392 int result;
3393 Lisp_Object tem = Vw32_get_true_file_attributes;
3395 /* Tell stat to use expensive method to get accurate info. */
3396 Vw32_get_true_file_attributes = Qt;
3397 result = stat (SDATA (absname), &st);
3398 Vw32_get_true_file_attributes = tem;
3400 if (result < 0)
3401 return Qnil;
3402 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
3404 #else
3405 if (stat (SDATA (absname), &st) < 0)
3406 return Qnil;
3407 return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
3408 #endif
3411 DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
3412 doc: /* Return mode bits of file named FILENAME, as an integer.
3413 Return nil, if file does not exist or is not accessible. */)
3414 (filename)
3415 Lisp_Object filename;
3417 Lisp_Object absname;
3418 struct stat st;
3419 Lisp_Object handler;
3421 absname = expand_and_dir_to_file (filename, current_buffer->directory);
3423 /* If the file name has special constructs in it,
3424 call the corresponding file handler. */
3425 handler = Ffind_file_name_handler (absname, Qfile_modes);
3426 if (!NILP (handler))
3427 return call2 (handler, Qfile_modes, absname);
3429 absname = ENCODE_FILE (absname);
3431 if (stat (SDATA (absname), &st) < 0)
3432 return Qnil;
3433 #if defined (MSDOS) && __DJGPP__ < 2
3434 if (check_executable (SDATA (absname)))
3435 st.st_mode |= S_IEXEC;
3436 #endif /* MSDOS && __DJGPP__ < 2 */
3438 return make_number (st.st_mode & 07777);
3441 DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2, 0,
3442 doc: /* Set mode bits of file named FILENAME to MODE (an integer).
3443 Only the 12 low bits of MODE are used. */)
3444 (filename, mode)
3445 Lisp_Object filename, mode;
3447 Lisp_Object absname, encoded_absname;
3448 Lisp_Object handler;
3450 absname = Fexpand_file_name (filename, current_buffer->directory);
3451 CHECK_NUMBER (mode);
3453 /* If the file name has special constructs in it,
3454 call the corresponding file handler. */
3455 handler = Ffind_file_name_handler (absname, Qset_file_modes);
3456 if (!NILP (handler))
3457 return call3 (handler, Qset_file_modes, absname, mode);
3459 encoded_absname = ENCODE_FILE (absname);
3461 if (chmod (SDATA (encoded_absname), XINT (mode)) < 0)
3462 report_file_error ("Doing chmod", Fcons (absname, Qnil));
3464 return Qnil;
3467 DEFUN ("set-default-file-modes", Fset_default_file_modes, Sset_default_file_modes, 1, 1, 0,
3468 doc: /* Set the file permission bits for newly created files.
3469 The argument MODE should be an integer; only the low 9 bits are used.
3470 This setting is inherited by subprocesses. */)
3471 (mode)
3472 Lisp_Object mode;
3474 CHECK_NUMBER (mode);
3476 umask ((~ XINT (mode)) & 0777);
3478 return Qnil;
3481 DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
3482 doc: /* Return the default file protection for created files.
3483 The value is an integer. */)
3486 int realmask;
3487 Lisp_Object value;
3489 realmask = umask (0);
3490 umask (realmask);
3492 XSETINT (value, (~ realmask) & 0777);
3493 return value;
3496 extern int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
3498 DEFUN ("set-file-times", Fset_file_times, Sset_file_times, 1, 2, 0,
3499 doc: /* Set times of file FILENAME to TIME.
3500 Set both access and modification times.
3501 Return t on success, else nil.
3502 Use the current time if TIME is nil. TIME is in the format of
3503 `current-time'. */)
3504 (filename, time)
3505 Lisp_Object filename, time;
3507 Lisp_Object absname, encoded_absname;
3508 Lisp_Object handler;
3509 time_t sec;
3510 int usec;
3512 if (! lisp_time_argument (time, &sec, &usec))
3513 error ("Invalid time specification");
3515 absname = Fexpand_file_name (filename, current_buffer->directory);
3517 /* If the file name has special constructs in it,
3518 call the corresponding file handler. */
3519 handler = Ffind_file_name_handler (absname, Qset_file_times);
3520 if (!NILP (handler))
3521 return call3 (handler, Qset_file_times, absname, time);
3523 encoded_absname = ENCODE_FILE (absname);
3526 EMACS_TIME t;
3528 EMACS_SET_SECS (t, sec);
3529 EMACS_SET_USECS (t, usec);
3531 if (set_file_times (SDATA (encoded_absname), t, t))
3533 #ifdef DOS_NT
3534 struct stat st;
3536 /* Setting times on a directory always fails. */
3537 if (stat (SDATA (encoded_absname), &st) == 0
3538 && (st.st_mode & S_IFMT) == S_IFDIR)
3539 return Qnil;
3540 #endif
3541 report_file_error ("Setting file times", Fcons (absname, Qnil));
3542 return Qnil;
3546 return Qt;
3549 #ifdef HAVE_SYNC
3550 DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
3551 doc: /* Tell Unix to finish all pending disk updates. */)
3554 sync ();
3555 return Qnil;
3558 #endif /* HAVE_SYNC */
3560 DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p, Sfile_newer_than_file_p, 2, 2, 0,
3561 doc: /* Return t if file FILE1 is newer than file FILE2.
3562 If FILE1 does not exist, the answer is nil;
3563 otherwise, if FILE2 does not exist, the answer is t. */)
3564 (file1, file2)
3565 Lisp_Object file1, file2;
3567 Lisp_Object absname1, absname2;
3568 struct stat st;
3569 int mtime1;
3570 Lisp_Object handler;
3571 struct gcpro gcpro1, gcpro2;
3573 CHECK_STRING (file1);
3574 CHECK_STRING (file2);
3576 absname1 = Qnil;
3577 GCPRO2 (absname1, file2);
3578 absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
3579 absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
3580 UNGCPRO;
3582 /* If the file name has special constructs in it,
3583 call the corresponding file handler. */
3584 handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
3585 if (NILP (handler))
3586 handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
3587 if (!NILP (handler))
3588 return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
3590 GCPRO2 (absname1, absname2);
3591 absname1 = ENCODE_FILE (absname1);
3592 absname2 = ENCODE_FILE (absname2);
3593 UNGCPRO;
3595 if (stat (SDATA (absname1), &st) < 0)
3596 return Qnil;
3598 mtime1 = st.st_mtime;
3600 if (stat (SDATA (absname2), &st) < 0)
3601 return Qt;
3603 return (mtime1 > st.st_mtime) ? Qt : Qnil;
3606 #ifdef DOS_NT
3607 Lisp_Object Qfind_buffer_file_type;
3608 #endif /* DOS_NT */
3610 #ifndef READ_BUF_SIZE
3611 #define READ_BUF_SIZE (64 << 10)
3612 #endif
3614 extern void adjust_markers_for_delete P_ ((int, int, int, int));
3616 /* This function is called after Lisp functions to decide a coding
3617 system are called, or when they cause an error. Before they are
3618 called, the current buffer is set unibyte and it contains only a
3619 newly inserted text (thus the buffer was empty before the
3620 insertion).
3622 The functions may set markers, overlays, text properties, or even
3623 alter the buffer contents, change the current buffer.
3625 Here, we reset all those changes by:
3626 o set back the current buffer.
3627 o move all markers and overlays to BEG.
3628 o remove all text properties.
3629 o set back the buffer multibyteness. */
3631 static Lisp_Object
3632 decide_coding_unwind (unwind_data)
3633 Lisp_Object unwind_data;
3635 Lisp_Object multibyte, undo_list, buffer;
3637 multibyte = XCAR (unwind_data);
3638 unwind_data = XCDR (unwind_data);
3639 undo_list = XCAR (unwind_data);
3640 buffer = XCDR (unwind_data);
3642 if (current_buffer != XBUFFER (buffer))
3643 set_buffer_internal (XBUFFER (buffer));
3644 adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
3645 adjust_overlays_for_delete (BEG, Z - BEG);
3646 BUF_INTERVALS (current_buffer) = 0;
3647 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3649 /* Now we are safe to change the buffer's multibyteness directly. */
3650 current_buffer->enable_multibyte_characters = multibyte;
3651 current_buffer->undo_list = undo_list;
3653 return Qnil;
3657 /* Used to pass values from insert-file-contents to read_non_regular. */
3659 static int non_regular_fd;
3660 static int non_regular_inserted;
3661 static int non_regular_nbytes;
3664 /* Read from a non-regular file.
3665 Read non_regular_trytry bytes max from non_regular_fd.
3666 Non_regular_inserted specifies where to put the read bytes.
3667 Value is the number of bytes read. */
3669 static Lisp_Object
3670 read_non_regular ()
3672 int nbytes;
3674 immediate_quit = 1;
3675 QUIT;
3676 nbytes = emacs_read (non_regular_fd,
3677 BEG_ADDR + PT_BYTE - BEG_BYTE + non_regular_inserted,
3678 non_regular_nbytes);
3679 immediate_quit = 0;
3680 return make_number (nbytes);
3684 /* Condition-case handler used when reading from non-regular files
3685 in insert-file-contents. */
3687 static Lisp_Object
3688 read_non_regular_quit ()
3690 return Qnil;
3694 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
3695 1, 5, 0,
3696 doc: /* Insert contents of file FILENAME after point.
3697 Returns list of absolute file name and number of characters inserted.
3698 If second argument VISIT is non-nil, the buffer's visited filename
3699 and last save file modtime are set, and it is marked unmodified.
3700 If visiting and the file does not exist, visiting is completed
3701 before the error is signaled.
3702 The optional third and fourth arguments BEG and END
3703 specify what portion of the file to insert.
3704 These arguments count bytes in the file, not characters in the buffer.
3705 If VISIT is non-nil, BEG and END must be nil.
3707 If optional fifth argument REPLACE is non-nil,
3708 it means replace the current buffer contents (in the accessible portion)
3709 with the file contents. This is better than simply deleting and inserting
3710 the whole thing because (1) it preserves some marker positions
3711 and (2) it puts less data in the undo list.
3712 When REPLACE is non-nil, the value is the number of characters actually read,
3713 which is often less than the number of characters to be read.
3715 This does code conversion according to the value of
3716 `coding-system-for-read' or `file-coding-system-alist',
3717 and sets the variable `last-coding-system-used' to the coding system
3718 actually used. */)
3719 (filename, visit, beg, end, replace)
3720 Lisp_Object filename, visit, beg, end, replace;
3722 struct stat st;
3723 register int fd;
3724 int inserted = 0;
3725 register int how_much;
3726 register int unprocessed;
3727 int count = SPECPDL_INDEX ();
3728 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
3729 Lisp_Object handler, val, insval, orig_filename;
3730 Lisp_Object p;
3731 int total = 0;
3732 int not_regular = 0;
3733 unsigned char read_buf[READ_BUF_SIZE];
3734 struct coding_system coding;
3735 unsigned char buffer[1 << 14];
3736 int replace_handled = 0;
3737 int set_coding_system = 0;
3738 Lisp_Object coding_system;
3739 int read_quit = 0;
3740 Lisp_Object old_Vdeactivate_mark = Vdeactivate_mark;
3741 int we_locked_file = 0;
3743 if (current_buffer->base_buffer && ! NILP (visit))
3744 error ("Cannot do file visiting in an indirect buffer");
3746 if (!NILP (current_buffer->read_only))
3747 Fbarf_if_buffer_read_only ();
3749 val = Qnil;
3750 p = Qnil;
3751 orig_filename = Qnil;
3753 GCPRO4 (filename, val, p, orig_filename);
3755 CHECK_STRING (filename);
3756 filename = Fexpand_file_name (filename, Qnil);
3758 /* The value Qnil means that the coding system is not yet
3759 decided. */
3760 coding_system = Qnil;
3762 /* If the file name has special constructs in it,
3763 call the corresponding file handler. */
3764 handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
3765 if (!NILP (handler))
3767 val = call6 (handler, Qinsert_file_contents, filename,
3768 visit, beg, end, replace);
3769 if (CONSP (val) && CONSP (XCDR (val)))
3770 inserted = XINT (XCAR (XCDR (val)));
3771 goto handled;
3774 orig_filename = filename;
3775 filename = ENCODE_FILE (filename);
3777 fd = -1;
3779 #ifdef WINDOWSNT
3781 Lisp_Object tem = Vw32_get_true_file_attributes;
3783 /* Tell stat to use expensive method to get accurate info. */
3784 Vw32_get_true_file_attributes = Qt;
3785 total = stat (SDATA (filename), &st);
3786 Vw32_get_true_file_attributes = tem;
3788 if (total < 0)
3789 #else
3790 #ifndef APOLLO
3791 if (stat (SDATA (filename), &st) < 0)
3792 #else
3793 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0
3794 || fstat (fd, &st) < 0)
3795 #endif /* not APOLLO */
3796 #endif /* WINDOWSNT */
3798 if (fd >= 0) emacs_close (fd);
3799 badopen:
3800 if (NILP (visit))
3801 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
3802 st.st_mtime = -1;
3803 how_much = 0;
3804 if (!NILP (Vcoding_system_for_read))
3805 Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
3806 goto notfound;
3809 #ifdef S_IFREG
3810 /* This code will need to be changed in order to work on named
3811 pipes, and it's probably just not worth it. So we should at
3812 least signal an error. */
3813 if (!S_ISREG (st.st_mode))
3815 not_regular = 1;
3817 if (! NILP (visit))
3818 goto notfound;
3820 if (! NILP (replace) || ! NILP (beg) || ! NILP (end))
3821 xsignal2 (Qfile_error,
3822 build_string ("not a regular file"), orig_filename);
3824 #endif
3826 if (fd < 0)
3827 if ((fd = emacs_open (SDATA (filename), O_RDONLY, 0)) < 0)
3828 goto badopen;
3830 /* Replacement should preserve point as it preserves markers. */
3831 if (!NILP (replace))
3832 record_unwind_protect (restore_point_unwind, Fpoint_marker ());
3834 record_unwind_protect (close_file_unwind, make_number (fd));
3836 /* Supposedly happens on VMS. */
3837 /* Can happen on any platform that uses long as type of off_t, but allows
3838 file sizes to exceed 2Gb. VMS is no longer officially supported, so
3839 give a message suitable for the latter case. */
3840 if (! not_regular && st.st_size < 0)
3841 error ("Maximum buffer size exceeded");
3843 /* Prevent redisplay optimizations. */
3844 current_buffer->clip_changed = 1;
3846 if (!NILP (visit))
3848 if (!NILP (beg) || !NILP (end))
3849 error ("Attempt to visit less than an entire file");
3850 if (BEG < Z && NILP (replace))
3851 error ("Cannot do file visiting in a non-empty buffer");
3854 if (!NILP (beg))
3855 CHECK_NUMBER (beg);
3856 else
3857 XSETFASTINT (beg, 0);
3859 if (!NILP (end))
3860 CHECK_NUMBER (end);
3861 else
3863 if (! not_regular)
3865 XSETINT (end, st.st_size);
3867 /* Arithmetic overflow can occur if an Emacs integer cannot
3868 represent the file size, or if the calculations below
3869 overflow. The calculations below double the file size
3870 twice, so check that it can be multiplied by 4 safely. */
3871 if (XINT (end) != st.st_size
3872 || ((int) st.st_size * 4) / 4 != st.st_size)
3873 error ("Maximum buffer size exceeded");
3875 /* The file size returned from stat may be zero, but data
3876 may be readable nonetheless, for example when this is a
3877 file in the /proc filesystem. */
3878 if (st.st_size == 0)
3879 XSETINT (end, READ_BUF_SIZE);
3883 if (EQ (Vcoding_system_for_read, Qauto_save_coding))
3885 coding_system = coding_inherit_eol_type (Qutf_8_emacs, Qunix);
3886 setup_coding_system (coding_system, &coding);
3887 /* Ensure we set Vlast_coding_system_used. */
3888 set_coding_system = 1;
3890 else if (BEG < Z)
3892 /* Decide the coding system to use for reading the file now
3893 because we can't use an optimized method for handling
3894 `coding:' tag if the current buffer is not empty. */
3895 if (!NILP (Vcoding_system_for_read))
3896 coding_system = Vcoding_system_for_read;
3897 else
3899 /* Don't try looking inside a file for a coding system
3900 specification if it is not seekable. */
3901 if (! not_regular && ! NILP (Vset_auto_coding_function))
3903 /* Find a coding system specified in the heading two
3904 lines or in the tailing several lines of the file.
3905 We assume that the 1K-byte and 3K-byte for heading
3906 and tailing respectively are sufficient for this
3907 purpose. */
3908 int nread;
3910 if (st.st_size <= (1024 * 4))
3911 nread = emacs_read (fd, read_buf, 1024 * 4);
3912 else
3914 nread = emacs_read (fd, read_buf, 1024);
3915 if (nread >= 0)
3917 if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
3918 report_file_error ("Setting file position",
3919 Fcons (orig_filename, Qnil));
3920 nread += emacs_read (fd, read_buf + nread, 1024 * 3);
3924 if (nread < 0)
3925 error ("IO error reading %s: %s",
3926 SDATA (orig_filename), emacs_strerror (errno));
3927 else if (nread > 0)
3929 struct buffer *prev = current_buffer;
3930 Lisp_Object buffer;
3931 struct buffer *buf;
3933 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3935 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
3936 buf = XBUFFER (buffer);
3938 delete_all_overlays (buf);
3939 buf->directory = current_buffer->directory;
3940 buf->read_only = Qnil;
3941 buf->filename = Qnil;
3942 buf->undo_list = Qt;
3943 eassert (buf->overlays_before == NULL);
3944 eassert (buf->overlays_after == NULL);
3946 set_buffer_internal (buf);
3947 Ferase_buffer ();
3948 buf->enable_multibyte_characters = Qnil;
3950 insert_1_both (read_buf, nread, nread, 0, 0, 0);
3951 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
3952 coding_system = call2 (Vset_auto_coding_function,
3953 filename, make_number (nread));
3954 set_buffer_internal (prev);
3956 /* Discard the unwind protect for recovering the
3957 current buffer. */
3958 specpdl_ptr--;
3960 /* Rewind the file for the actual read done later. */
3961 if (lseek (fd, 0, 0) < 0)
3962 report_file_error ("Setting file position",
3963 Fcons (orig_filename, Qnil));
3967 if (NILP (coding_system))
3969 /* If we have not yet decided a coding system, check
3970 file-coding-system-alist. */
3971 Lisp_Object args[6];
3973 args[0] = Qinsert_file_contents, args[1] = orig_filename;
3974 args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
3975 coding_system = Ffind_operation_coding_system (6, args);
3976 if (CONSP (coding_system))
3977 coding_system = XCAR (coding_system);
3981 if (NILP (coding_system))
3982 coding_system = Qundecided;
3983 else
3984 CHECK_CODING_SYSTEM (coding_system);
3986 if (NILP (current_buffer->enable_multibyte_characters))
3987 /* We must suppress all character code conversion except for
3988 end-of-line conversion. */
3989 coding_system = raw_text_coding_system (coding_system);
3991 setup_coding_system (coding_system, &coding);
3992 /* Ensure we set Vlast_coding_system_used. */
3993 set_coding_system = 1;
3996 /* If requested, replace the accessible part of the buffer
3997 with the file contents. Avoid replacing text at the
3998 beginning or end of the buffer that matches the file contents;
3999 that preserves markers pointing to the unchanged parts.
4001 Here we implement this feature in an optimized way
4002 for the case where code conversion is NOT needed.
4003 The following if-statement handles the case of conversion
4004 in a less optimal way.
4006 If the code conversion is "automatic" then we try using this
4007 method and hope for the best.
4008 But if we discover the need for conversion, we give up on this method
4009 and let the following if-statement handle the replace job. */
4010 if (!NILP (replace)
4011 && BEGV < ZV
4012 && (NILP (coding_system)
4013 || ! CODING_REQUIRE_DECODING (&coding)))
4015 /* same_at_start and same_at_end count bytes,
4016 because file access counts bytes
4017 and BEG and END count bytes. */
4018 int same_at_start = BEGV_BYTE;
4019 int same_at_end = ZV_BYTE;
4020 int overlap;
4021 /* There is still a possibility we will find the need to do code
4022 conversion. If that happens, we set this variable to 1 to
4023 give up on handling REPLACE in the optimized way. */
4024 int giveup_match_end = 0;
4026 if (XINT (beg) != 0)
4028 if (lseek (fd, XINT (beg), 0) < 0)
4029 report_file_error ("Setting file position",
4030 Fcons (orig_filename, Qnil));
4033 immediate_quit = 1;
4034 QUIT;
4035 /* Count how many chars at the start of the file
4036 match the text at the beginning of the buffer. */
4037 while (1)
4039 int nread, bufpos;
4041 nread = emacs_read (fd, buffer, sizeof buffer);
4042 if (nread < 0)
4043 error ("IO error reading %s: %s",
4044 SDATA (orig_filename), emacs_strerror (errno));
4045 else if (nread == 0)
4046 break;
4048 if (CODING_REQUIRE_DETECTION (&coding))
4050 coding_system = detect_coding_system (buffer, nread, nread, 1, 0,
4051 coding_system);
4052 setup_coding_system (coding_system, &coding);
4055 if (CODING_REQUIRE_DECODING (&coding))
4056 /* We found that the file should be decoded somehow.
4057 Let's give up here. */
4059 giveup_match_end = 1;
4060 break;
4063 bufpos = 0;
4064 while (bufpos < nread && same_at_start < ZV_BYTE
4065 && FETCH_BYTE (same_at_start) == buffer[bufpos])
4066 same_at_start++, bufpos++;
4067 /* If we found a discrepancy, stop the scan.
4068 Otherwise loop around and scan the next bufferful. */
4069 if (bufpos != nread)
4070 break;
4072 immediate_quit = 0;
4073 /* If the file matches the buffer completely,
4074 there's no need to replace anything. */
4075 if (same_at_start - BEGV_BYTE == XINT (end))
4077 emacs_close (fd);
4078 specpdl_ptr--;
4079 /* Truncate the buffer to the size of the file. */
4080 del_range_1 (same_at_start, same_at_end, 0, 0);
4081 goto handled;
4083 immediate_quit = 1;
4084 QUIT;
4085 /* Count how many chars at the end of the file
4086 match the text at the end of the buffer. But, if we have
4087 already found that decoding is necessary, don't waste time. */
4088 while (!giveup_match_end)
4090 int total_read, nread, bufpos, curpos, trial;
4092 /* At what file position are we now scanning? */
4093 curpos = XINT (end) - (ZV_BYTE - same_at_end);
4094 /* If the entire file matches the buffer tail, stop the scan. */
4095 if (curpos == 0)
4096 break;
4097 /* How much can we scan in the next step? */
4098 trial = min (curpos, sizeof buffer);
4099 if (lseek (fd, curpos - trial, 0) < 0)
4100 report_file_error ("Setting file position",
4101 Fcons (orig_filename, Qnil));
4103 total_read = nread = 0;
4104 while (total_read < trial)
4106 nread = emacs_read (fd, buffer + total_read, trial - total_read);
4107 if (nread < 0)
4108 error ("IO error reading %s: %s",
4109 SDATA (orig_filename), emacs_strerror (errno));
4110 else if (nread == 0)
4111 break;
4112 total_read += nread;
4115 /* Scan this bufferful from the end, comparing with
4116 the Emacs buffer. */
4117 bufpos = total_read;
4119 /* Compare with same_at_start to avoid counting some buffer text
4120 as matching both at the file's beginning and at the end. */
4121 while (bufpos > 0 && same_at_end > same_at_start
4122 && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
4123 same_at_end--, bufpos--;
4125 /* If we found a discrepancy, stop the scan.
4126 Otherwise loop around and scan the preceding bufferful. */
4127 if (bufpos != 0)
4129 /* If this discrepancy is because of code conversion,
4130 we cannot use this method; giveup and try the other. */
4131 if (same_at_end > same_at_start
4132 && FETCH_BYTE (same_at_end - 1) >= 0200
4133 && ! NILP (current_buffer->enable_multibyte_characters)
4134 && (CODING_MAY_REQUIRE_DECODING (&coding)))
4135 giveup_match_end = 1;
4136 break;
4139 if (nread == 0)
4140 break;
4142 immediate_quit = 0;
4144 if (! giveup_match_end)
4146 int temp;
4148 /* We win! We can handle REPLACE the optimized way. */
4150 /* Extend the start of non-matching text area to multibyte
4151 character boundary. */
4152 if (! NILP (current_buffer->enable_multibyte_characters))
4153 while (same_at_start > BEGV_BYTE
4154 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4155 same_at_start--;
4157 /* Extend the end of non-matching text area to multibyte
4158 character boundary. */
4159 if (! NILP (current_buffer->enable_multibyte_characters))
4160 while (same_at_end < ZV_BYTE
4161 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4162 same_at_end++;
4164 /* Don't try to reuse the same piece of text twice. */
4165 overlap = (same_at_start - BEGV_BYTE
4166 - (same_at_end + st.st_size - ZV));
4167 if (overlap > 0)
4168 same_at_end += overlap;
4170 /* Arrange to read only the nonmatching middle part of the file. */
4171 XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV_BYTE));
4172 XSETFASTINT (end, XINT (end) - (ZV_BYTE - same_at_end));
4174 del_range_byte (same_at_start, same_at_end, 0);
4175 /* Insert from the file at the proper position. */
4176 temp = BYTE_TO_CHAR (same_at_start);
4177 SET_PT_BOTH (temp, same_at_start);
4179 /* If display currently starts at beginning of line,
4180 keep it that way. */
4181 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
4182 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
4184 replace_handled = 1;
4188 /* If requested, replace the accessible part of the buffer
4189 with the file contents. Avoid replacing text at the
4190 beginning or end of the buffer that matches the file contents;
4191 that preserves markers pointing to the unchanged parts.
4193 Here we implement this feature for the case where code conversion
4194 is needed, in a simple way that needs a lot of memory.
4195 The preceding if-statement handles the case of no conversion
4196 in a more optimized way. */
4197 if (!NILP (replace) && ! replace_handled && BEGV < ZV)
4199 int same_at_start = BEGV_BYTE;
4200 int same_at_end = ZV_BYTE;
4201 int same_at_start_charpos;
4202 int inserted_chars;
4203 int overlap;
4204 int bufpos;
4205 unsigned char *decoded;
4206 int temp;
4207 int this_count = SPECPDL_INDEX ();
4208 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
4209 Lisp_Object conversion_buffer;
4211 conversion_buffer = code_conversion_save (1, multibyte);
4213 /* First read the whole file, performing code conversion into
4214 CONVERSION_BUFFER. */
4216 if (lseek (fd, XINT (beg), 0) < 0)
4217 report_file_error ("Setting file position",
4218 Fcons (orig_filename, Qnil));
4220 total = st.st_size; /* Total bytes in the file. */
4221 how_much = 0; /* Bytes read from file so far. */
4222 inserted = 0; /* Bytes put into CONVERSION_BUFFER so far. */
4223 unprocessed = 0; /* Bytes not processed in previous loop. */
4225 GCPRO1 (conversion_buffer);
4226 while (how_much < total)
4228 /* We read one bunch by one (READ_BUF_SIZE bytes) to allow
4229 quitting while reading a huge while. */
4230 /* try is reserved in some compilers (Microsoft C) */
4231 int trytry = min (total - how_much, READ_BUF_SIZE - unprocessed);
4232 int this;
4234 /* Allow quitting out of the actual I/O. */
4235 immediate_quit = 1;
4236 QUIT;
4237 this = emacs_read (fd, read_buf + unprocessed, trytry);
4238 immediate_quit = 0;
4240 if (this <= 0)
4242 if (this < 0)
4243 how_much = this;
4244 break;
4247 how_much += this;
4249 BUF_SET_PT (XBUFFER (conversion_buffer),
4250 BUF_Z (XBUFFER (conversion_buffer)));
4251 decode_coding_c_string (&coding, read_buf, unprocessed + this,
4252 conversion_buffer);
4253 unprocessed = coding.carryover_bytes;
4254 if (coding.carryover_bytes > 0)
4255 bcopy (coding.carryover, read_buf, unprocessed);
4257 UNGCPRO;
4258 emacs_close (fd);
4260 /* At this point, HOW_MUCH should equal TOTAL, or should be <= 0
4261 if we couldn't read the file. */
4263 if (how_much < 0)
4264 error ("IO error reading %s: %s",
4265 SDATA (orig_filename), emacs_strerror (errno));
4267 if (unprocessed > 0)
4269 coding.mode |= CODING_MODE_LAST_BLOCK;
4270 decode_coding_c_string (&coding, read_buf, unprocessed,
4271 conversion_buffer);
4272 coding.mode &= ~CODING_MODE_LAST_BLOCK;
4275 decoded = BUF_BEG_ADDR (XBUFFER (conversion_buffer));
4276 inserted = (BUF_Z_BYTE (XBUFFER (conversion_buffer))
4277 - BUF_BEG_BYTE (XBUFFER (conversion_buffer)));
4279 /* Compare the beginning of the converted string with the buffer
4280 text. */
4282 bufpos = 0;
4283 while (bufpos < inserted && same_at_start < same_at_end
4284 && FETCH_BYTE (same_at_start) == decoded[bufpos])
4285 same_at_start++, bufpos++;
4287 /* If the file matches the head of buffer completely,
4288 there's no need to replace anything. */
4290 if (bufpos == inserted)
4292 specpdl_ptr--;
4293 /* Truncate the buffer to the size of the file. */
4294 del_range_byte (same_at_start, same_at_end, 0);
4295 inserted = 0;
4297 unbind_to (this_count, Qnil);
4298 goto handled;
4301 /* Extend the start of non-matching text area to the previous
4302 multibyte character boundary. */
4303 if (! NILP (current_buffer->enable_multibyte_characters))
4304 while (same_at_start > BEGV_BYTE
4305 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_start)))
4306 same_at_start--;
4308 /* Scan this bufferful from the end, comparing with
4309 the Emacs buffer. */
4310 bufpos = inserted;
4312 /* Compare with same_at_start to avoid counting some buffer text
4313 as matching both at the file's beginning and at the end. */
4314 while (bufpos > 0 && same_at_end > same_at_start
4315 && FETCH_BYTE (same_at_end - 1) == decoded[bufpos - 1])
4316 same_at_end--, bufpos--;
4318 /* Extend the end of non-matching text area to the next
4319 multibyte character boundary. */
4320 if (! NILP (current_buffer->enable_multibyte_characters))
4321 while (same_at_end < ZV_BYTE
4322 && ! CHAR_HEAD_P (FETCH_BYTE (same_at_end)))
4323 same_at_end++;
4325 /* Don't try to reuse the same piece of text twice. */
4326 overlap = same_at_start - BEGV_BYTE - (same_at_end + inserted - ZV_BYTE);
4327 if (overlap > 0)
4328 same_at_end += overlap;
4330 /* If display currently starts at beginning of line,
4331 keep it that way. */
4332 if (XBUFFER (XWINDOW (selected_window)->buffer) == current_buffer)
4333 XWINDOW (selected_window)->start_at_line_beg = Fbolp ();
4335 /* Replace the chars that we need to replace,
4336 and update INSERTED to equal the number of bytes
4337 we are taking from the decoded string. */
4338 inserted -= (ZV_BYTE - same_at_end) + (same_at_start - BEGV_BYTE);
4340 if (same_at_end != same_at_start)
4342 del_range_byte (same_at_start, same_at_end, 0);
4343 temp = GPT;
4344 same_at_start = GPT_BYTE;
4346 else
4348 temp = BYTE_TO_CHAR (same_at_start);
4350 /* Insert from the file at the proper position. */
4351 SET_PT_BOTH (temp, same_at_start);
4352 same_at_start_charpos
4353 = buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4354 same_at_start);
4355 inserted_chars
4356 = (buf_bytepos_to_charpos (XBUFFER (conversion_buffer),
4357 same_at_start + inserted)
4358 - same_at_start_charpos);
4359 /* This binding is to avoid ask-user-about-supersession-threat
4360 being called in insert_from_buffer (via in
4361 prepare_to_modify_buffer). */
4362 specbind (intern ("buffer-file-name"), Qnil);
4363 insert_from_buffer (XBUFFER (conversion_buffer),
4364 same_at_start_charpos, inserted_chars, 0);
4365 /* Set `inserted' to the number of inserted characters. */
4366 inserted = PT - temp;
4367 /* Set point before the inserted characters. */
4368 SET_PT_BOTH (temp, same_at_start);
4370 unbind_to (this_count, Qnil);
4372 goto handled;
4375 if (! not_regular)
4377 register Lisp_Object temp;
4379 total = XINT (end) - XINT (beg);
4381 /* Make sure point-max won't overflow after this insertion. */
4382 XSETINT (temp, total);
4383 if (total != XINT (temp))
4384 error ("Maximum buffer size exceeded");
4386 else
4387 /* For a special file, all we can do is guess. */
4388 total = READ_BUF_SIZE;
4390 if (NILP (visit) && inserted > 0)
4392 #ifdef CLASH_DETECTION
4393 if (!NILP (current_buffer->file_truename)
4394 /* Make binding buffer-file-name to nil effective. */
4395 && !NILP (current_buffer->filename)
4396 && SAVE_MODIFF >= MODIFF)
4397 we_locked_file = 1;
4398 #endif /* CLASH_DETECTION */
4399 prepare_to_modify_buffer (GPT, GPT, NULL);
4402 move_gap (PT);
4403 if (GAP_SIZE < total)
4404 make_gap (total - GAP_SIZE);
4406 if (XINT (beg) != 0 || !NILP (replace))
4408 if (lseek (fd, XINT (beg), 0) < 0)
4409 report_file_error ("Setting file position",
4410 Fcons (orig_filename, Qnil));
4413 /* In the following loop, HOW_MUCH contains the total bytes read so
4414 far for a regular file, and not changed for a special file. But,
4415 before exiting the loop, it is set to a negative value if I/O
4416 error occurs. */
4417 how_much = 0;
4419 /* Total bytes inserted. */
4420 inserted = 0;
4422 /* Here, we don't do code conversion in the loop. It is done by
4423 decode_coding_gap after all data are read into the buffer. */
4425 int gap_size = GAP_SIZE;
4427 while (how_much < total)
4429 /* try is reserved in some compilers (Microsoft C) */
4430 int trytry = min (total - how_much, READ_BUF_SIZE);
4431 int this;
4433 if (not_regular)
4435 Lisp_Object val;
4437 /* Maybe make more room. */
4438 if (gap_size < trytry)
4440 make_gap (total - gap_size);
4441 gap_size = GAP_SIZE;
4444 /* Read from the file, capturing `quit'. When an
4445 error occurs, end the loop, and arrange for a quit
4446 to be signaled after decoding the text we read. */
4447 non_regular_fd = fd;
4448 non_regular_inserted = inserted;
4449 non_regular_nbytes = trytry;
4450 val = internal_condition_case_1 (read_non_regular, Qnil, Qerror,
4451 read_non_regular_quit);
4452 if (NILP (val))
4454 read_quit = 1;
4455 break;
4458 this = XINT (val);
4460 else
4462 /* Allow quitting out of the actual I/O. We don't make text
4463 part of the buffer until all the reading is done, so a C-g
4464 here doesn't do any harm. */
4465 immediate_quit = 1;
4466 QUIT;
4467 this = emacs_read (fd, BEG_ADDR + PT_BYTE - BEG_BYTE + inserted, trytry);
4468 immediate_quit = 0;
4471 if (this <= 0)
4473 how_much = this;
4474 break;
4477 gap_size -= this;
4479 /* For a regular file, where TOTAL is the real size,
4480 count HOW_MUCH to compare with it.
4481 For a special file, where TOTAL is just a buffer size,
4482 so don't bother counting in HOW_MUCH.
4483 (INSERTED is where we count the number of characters inserted.) */
4484 if (! not_regular)
4485 how_much += this;
4486 inserted += this;
4490 /* Now we have read all the file data into the gap.
4491 If it was empty, undo marking the buffer modified. */
4493 if (inserted == 0)
4495 #ifdef CLASH_DETECTION
4496 if (we_locked_file)
4497 unlock_file (current_buffer->file_truename);
4498 #endif
4499 Vdeactivate_mark = old_Vdeactivate_mark;
4501 else
4502 Vdeactivate_mark = Qt;
4504 /* Make the text read part of the buffer. */
4505 GAP_SIZE -= inserted;
4506 GPT += inserted;
4507 GPT_BYTE += inserted;
4508 ZV += inserted;
4509 ZV_BYTE += inserted;
4510 Z += inserted;
4511 Z_BYTE += inserted;
4513 if (GAP_SIZE > 0)
4514 /* Put an anchor to ensure multi-byte form ends at gap. */
4515 *GPT_ADDR = 0;
4517 emacs_close (fd);
4519 /* Discard the unwind protect for closing the file. */
4520 specpdl_ptr--;
4522 if (how_much < 0)
4523 error ("IO error reading %s: %s",
4524 SDATA (orig_filename), emacs_strerror (errno));
4526 notfound:
4528 if (NILP (coding_system))
4530 /* The coding system is not yet decided. Decide it by an
4531 optimized method for handling `coding:' tag.
4533 Note that we can get here only if the buffer was empty
4534 before the insertion. */
4536 if (!NILP (Vcoding_system_for_read))
4537 coding_system = Vcoding_system_for_read;
4538 else
4540 /* Since we are sure that the current buffer was empty
4541 before the insertion, we can toggle
4542 enable-multibyte-characters directly here without taking
4543 care of marker adjustment. By this way, we can run Lisp
4544 program safely before decoding the inserted text. */
4545 Lisp_Object unwind_data;
4546 int count = SPECPDL_INDEX ();
4548 unwind_data = Fcons (current_buffer->enable_multibyte_characters,
4549 Fcons (current_buffer->undo_list,
4550 Fcurrent_buffer ()));
4551 current_buffer->enable_multibyte_characters = Qnil;
4552 current_buffer->undo_list = Qt;
4553 record_unwind_protect (decide_coding_unwind, unwind_data);
4555 if (inserted > 0 && ! NILP (Vset_auto_coding_function))
4557 coding_system = call2 (Vset_auto_coding_function,
4558 filename, make_number (inserted));
4561 if (NILP (coding_system))
4563 /* If the coding system is not yet decided, check
4564 file-coding-system-alist. */
4565 Lisp_Object args[6];
4567 args[0] = Qinsert_file_contents, args[1] = orig_filename;
4568 args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
4569 coding_system = Ffind_operation_coding_system (6, args);
4570 if (CONSP (coding_system))
4571 coding_system = XCAR (coding_system);
4573 unbind_to (count, Qnil);
4574 inserted = Z_BYTE - BEG_BYTE;
4577 if (NILP (coding_system))
4578 coding_system = Qundecided;
4579 else
4580 CHECK_CODING_SYSTEM (coding_system);
4582 if (NILP (current_buffer->enable_multibyte_characters))
4583 /* We must suppress all character code conversion except for
4584 end-of-line conversion. */
4585 coding_system = raw_text_coding_system (coding_system);
4586 setup_coding_system (coding_system, &coding);
4587 /* Ensure we set Vlast_coding_system_used. */
4588 set_coding_system = 1;
4591 if (!NILP (visit))
4593 /* When we visit a file by raw-text, we change the buffer to
4594 unibyte. */
4595 if (CODING_FOR_UNIBYTE (&coding)
4596 /* Can't do this if part of the buffer might be preserved. */
4597 && NILP (replace))
4598 /* Visiting a file with these coding system makes the buffer
4599 unibyte. */
4600 current_buffer->enable_multibyte_characters = Qnil;
4603 coding.dst_multibyte = ! NILP (current_buffer->enable_multibyte_characters);
4604 if (CODING_MAY_REQUIRE_DECODING (&coding)
4605 && (inserted > 0 || CODING_REQUIRE_FLUSHING (&coding)))
4607 move_gap_both (PT, PT_BYTE);
4608 GAP_SIZE += inserted;
4609 ZV_BYTE -= inserted;
4610 Z_BYTE -= inserted;
4611 ZV -= inserted;
4612 Z -= inserted;
4613 decode_coding_gap (&coding, inserted, inserted);
4614 inserted = coding.produced_char;
4615 coding_system = CODING_ID_NAME (coding.id);
4617 else if (inserted > 0)
4618 adjust_after_insert (PT, PT_BYTE, PT + inserted, PT_BYTE + inserted,
4619 inserted);
4621 /* Now INSERTED is measured in characters. */
4623 #ifdef DOS_NT
4624 /* Use the conversion type to determine buffer-file-type
4625 (find-buffer-file-type is now used to help determine the
4626 conversion). */
4627 if ((VECTORP (CODING_ID_EOL_TYPE (coding.id))
4628 || EQ (CODING_ID_EOL_TYPE (coding.id), Qunix))
4629 && ! CODING_REQUIRE_DECODING (&coding))
4630 current_buffer->buffer_file_type = Qt;
4631 else
4632 current_buffer->buffer_file_type = Qnil;
4633 #endif
4635 handled:
4637 if (!NILP (visit))
4639 if (!EQ (current_buffer->undo_list, Qt))
4640 current_buffer->undo_list = Qnil;
4641 #ifdef APOLLO
4642 stat (SDATA (filename), &st);
4643 #endif
4645 if (NILP (handler))
4647 current_buffer->modtime = st.st_mtime;
4648 current_buffer->filename = orig_filename;
4651 SAVE_MODIFF = MODIFF;
4652 current_buffer->auto_save_modified = MODIFF;
4653 XSETFASTINT (current_buffer->save_length, Z - BEG);
4654 #ifdef CLASH_DETECTION
4655 if (NILP (handler))
4657 if (!NILP (current_buffer->file_truename))
4658 unlock_file (current_buffer->file_truename);
4659 unlock_file (filename);
4661 #endif /* CLASH_DETECTION */
4662 if (not_regular)
4663 xsignal2 (Qfile_error,
4664 build_string ("not a regular file"), orig_filename);
4667 if (set_coding_system)
4668 Vlast_coding_system_used = coding_system;
4670 if (! NILP (Ffboundp (Qafter_insert_file_set_coding)))
4672 insval = call2 (Qafter_insert_file_set_coding, make_number (inserted),
4673 visit);
4674 if (! NILP (insval))
4676 CHECK_NUMBER (insval);
4677 inserted = XFASTINT (insval);
4681 /* Decode file format */
4682 if (inserted > 0)
4684 int empty_undo_list_p = 0;
4686 /* If we're anyway going to discard undo information, don't
4687 record it in the first place. The buffer's undo list at this
4688 point is either nil or t when visiting a file. */
4689 if (!NILP (visit))
4691 empty_undo_list_p = NILP (current_buffer->undo_list);
4692 current_buffer->undo_list = Qt;
4695 insval = call3 (Qformat_decode,
4696 Qnil, make_number (inserted), visit);
4697 CHECK_NUMBER (insval);
4698 inserted = XFASTINT (insval);
4700 if (!NILP (visit))
4701 current_buffer->undo_list = empty_undo_list_p ? Qnil : Qt;
4704 /* Call after-change hooks for the inserted text, aside from the case
4705 of normal visiting (not with REPLACE), which is done in a new buffer
4706 "before" the buffer is changed. */
4707 if (inserted > 0 && total > 0
4708 && (NILP (visit) || !NILP (replace)))
4710 signal_after_change (PT, 0, inserted);
4711 update_compositions (PT, PT, CHECK_BORDER);
4714 p = Vafter_insert_file_functions;
4715 while (CONSP (p))
4717 insval = call1 (XCAR (p), make_number (inserted));
4718 if (!NILP (insval))
4720 CHECK_NUMBER (insval);
4721 inserted = XFASTINT (insval);
4723 QUIT;
4724 p = XCDR (p);
4727 if (!NILP (visit)
4728 && current_buffer->modtime == -1)
4730 /* If visiting nonexistent file, return nil. */
4731 report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
4734 if (read_quit)
4735 Fsignal (Qquit, Qnil);
4737 /* ??? Retval needs to be dealt with in all cases consistently. */
4738 if (NILP (val))
4739 val = Fcons (orig_filename,
4740 Fcons (make_number (inserted),
4741 Qnil));
4743 RETURN_UNGCPRO (unbind_to (count, val));
4746 static Lisp_Object build_annotations P_ ((Lisp_Object, Lisp_Object));
4748 /* If build_annotations switched buffers, switch back to BUF.
4749 Kill the temporary buffer that was selected in the meantime.
4751 Since this kill only the last temporary buffer, some buffers remain
4752 not killed if build_annotations switched buffers more than once.
4753 -- K.Handa */
4755 static Lisp_Object
4756 build_annotations_unwind (buf)
4757 Lisp_Object buf;
4759 Lisp_Object tembuf;
4761 if (XBUFFER (buf) == current_buffer)
4762 return Qnil;
4763 tembuf = Fcurrent_buffer ();
4764 Fset_buffer (buf);
4765 Fkill_buffer (tembuf);
4766 return Qnil;
4769 /* Decide the coding-system to encode the data with. */
4771 static Lisp_Object
4772 choose_write_coding_system (start, end, filename,
4773 append, visit, lockname, coding)
4774 Lisp_Object start, end, filename, append, visit, lockname;
4775 struct coding_system *coding;
4777 Lisp_Object val;
4778 Lisp_Object eol_parent = Qnil;
4780 if (auto_saving
4781 && NILP (Fstring_equal (current_buffer->filename,
4782 current_buffer->auto_save_file_name)))
4784 val = Qutf_8_emacs;
4785 eol_parent = Qunix;
4787 else if (!NILP (Vcoding_system_for_write))
4789 val = Vcoding_system_for_write;
4790 if (coding_system_require_warning
4791 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4792 /* Confirm that VAL can surely encode the current region. */
4793 val = call5 (Vselect_safe_coding_system_function,
4794 start, end, Fcons (Qt, Fcons (val, Qnil)),
4795 Qnil, filename);
4797 else
4799 /* If the variable `buffer-file-coding-system' is set locally,
4800 it means that the file was read with some kind of code
4801 conversion or the variable is explicitly set by users. We
4802 had better write it out with the same coding system even if
4803 `enable-multibyte-characters' is nil.
4805 If it is not set locally, we anyway have to convert EOL
4806 format if the default value of `buffer-file-coding-system'
4807 tells that it is not Unix-like (LF only) format. */
4808 int using_default_coding = 0;
4809 int force_raw_text = 0;
4811 val = current_buffer->buffer_file_coding_system;
4812 if (NILP (val)
4813 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4815 val = Qnil;
4816 if (NILP (current_buffer->enable_multibyte_characters))
4817 force_raw_text = 1;
4820 if (NILP (val))
4822 /* Check file-coding-system-alist. */
4823 Lisp_Object args[7], coding_systems;
4825 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4826 args[3] = filename; args[4] = append; args[5] = visit;
4827 args[6] = lockname;
4828 coding_systems = Ffind_operation_coding_system (7, args);
4829 if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
4830 val = XCDR (coding_systems);
4833 if (NILP (val))
4835 /* If we still have not decided a coding system, use the
4836 default value of buffer-file-coding-system. */
4837 val = current_buffer->buffer_file_coding_system;
4838 using_default_coding = 1;
4841 if (! NILP (val) && ! force_raw_text)
4843 Lisp_Object spec, attrs;
4845 CHECK_CODING_SYSTEM_GET_SPEC (val, spec);
4846 attrs = AREF (spec, 0);
4847 if (EQ (CODING_ATTR_TYPE (attrs), Qraw_text))
4848 force_raw_text = 1;
4851 if (!force_raw_text
4852 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4853 /* Confirm that VAL can surely encode the current region. */
4854 val = call5 (Vselect_safe_coding_system_function,
4855 start, end, val, Qnil, filename);
4857 /* If the decided coding-system doesn't specify end-of-line
4858 format, we use that of
4859 `default-buffer-file-coding-system'. */
4860 if (! using_default_coding
4861 && ! NILP (buffer_defaults.buffer_file_coding_system))
4862 val = (coding_inherit_eol_type
4863 (val, buffer_defaults.buffer_file_coding_system));
4865 /* If we decide not to encode text, use `raw-text' or one of its
4866 subsidiaries. */
4867 if (force_raw_text)
4868 val = raw_text_coding_system (val);
4871 val = coding_inherit_eol_type (val, eol_parent);
4872 setup_coding_system (val, coding);
4874 if (!STRINGP (start) && !NILP (current_buffer->selective_display))
4875 coding->mode |= CODING_MODE_SELECTIVE_DISPLAY;
4876 return val;
4879 DEFUN ("write-region", Fwrite_region, Swrite_region, 3, 7,
4880 "r\nFWrite region to file: \ni\ni\ni\np",
4881 doc: /* Write current region into specified file.
4882 When called from a program, requires three arguments:
4883 START, END and FILENAME. START and END are normally buffer positions
4884 specifying the part of the buffer to write.
4885 If START is nil, that means to use the entire buffer contents.
4886 If START is a string, then output that string to the file
4887 instead of any buffer contents; END is ignored.
4889 Optional fourth argument APPEND if non-nil means
4890 append to existing file contents (if any). If it is an integer,
4891 seek to that offset in the file before writing.
4892 Optional fifth argument VISIT, if t or a string, means
4893 set the last-save-file-modtime of buffer to this file's modtime
4894 and mark buffer not modified.
4895 If VISIT is a string, it is a second file name;
4896 the output goes to FILENAME, but the buffer is marked as visiting VISIT.
4897 VISIT is also the file name to lock and unlock for clash detection.
4898 If VISIT is neither t nor nil nor a string,
4899 that means do not display the \"Wrote file\" message.
4900 The optional sixth arg LOCKNAME, if non-nil, specifies the name to
4901 use for locking and unlocking, overriding FILENAME and VISIT.
4902 The optional seventh arg MUSTBENEW, if non-nil, insists on a check
4903 for an existing file with the same name. If MUSTBENEW is `excl',
4904 that means to get an error if the file already exists; never overwrite.
4905 If MUSTBENEW is neither nil nor `excl', that means ask for
4906 confirmation before overwriting, but do go ahead and overwrite the file
4907 if the user confirms.
4909 This does code conversion according to the value of
4910 `coding-system-for-write', `buffer-file-coding-system', or
4911 `file-coding-system-alist', and sets the variable
4912 `last-coding-system-used' to the coding system actually used. */)
4913 (start, end, filename, append, visit, lockname, mustbenew)
4914 Lisp_Object start, end, filename, append, visit, lockname, mustbenew;
4916 register int desc;
4917 int failure;
4918 int save_errno = 0;
4919 const unsigned char *fn;
4920 struct stat st;
4921 int count = SPECPDL_INDEX ();
4922 int count1;
4923 #ifdef VMS
4924 unsigned char *fname = 0; /* If non-0, original filename (must rename) */
4925 #endif /* VMS */
4926 Lisp_Object handler;
4927 Lisp_Object visit_file;
4928 Lisp_Object annotations;
4929 Lisp_Object encoded_filename;
4930 int visiting = (EQ (visit, Qt) || STRINGP (visit));
4931 int quietly = !NILP (visit);
4932 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4933 struct buffer *given_buffer;
4934 #ifdef DOS_NT
4935 int buffer_file_type = O_BINARY;
4936 #endif /* DOS_NT */
4937 struct coding_system coding;
4939 if (current_buffer->base_buffer && visiting)
4940 error ("Cannot do file visiting in an indirect buffer");
4942 if (!NILP (start) && !STRINGP (start))
4943 validate_region (&start, &end);
4945 visit_file = Qnil;
4946 GCPRO5 (start, filename, visit, visit_file, lockname);
4948 filename = Fexpand_file_name (filename, Qnil);
4950 if (!NILP (mustbenew) && !EQ (mustbenew, Qexcl))
4951 barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
4953 if (STRINGP (visit))
4954 visit_file = Fexpand_file_name (visit, Qnil);
4955 else
4956 visit_file = filename;
4958 if (NILP (lockname))
4959 lockname = visit_file;
4961 annotations = Qnil;
4963 /* If the file name has special constructs in it,
4964 call the corresponding file handler. */
4965 handler = Ffind_file_name_handler (filename, Qwrite_region);
4966 /* If FILENAME has no handler, see if VISIT has one. */
4967 if (NILP (handler) && STRINGP (visit))
4968 handler = Ffind_file_name_handler (visit, Qwrite_region);
4970 if (!NILP (handler))
4972 Lisp_Object val;
4973 val = call6 (handler, Qwrite_region, start, end,
4974 filename, append, visit);
4976 if (visiting)
4978 SAVE_MODIFF = MODIFF;
4979 XSETFASTINT (current_buffer->save_length, Z - BEG);
4980 current_buffer->filename = visit_file;
4982 UNGCPRO;
4983 return val;
4986 record_unwind_protect (save_restriction_restore, save_restriction_save ());
4988 /* Special kludge to simplify auto-saving. */
4989 if (NILP (start))
4991 XSETFASTINT (start, BEG);
4992 XSETFASTINT (end, Z);
4993 Fwiden ();
4996 record_unwind_protect (build_annotations_unwind, Fcurrent_buffer ());
4997 count1 = SPECPDL_INDEX ();
4999 given_buffer = current_buffer;
5001 if (!STRINGP (start))
5003 annotations = build_annotations (start, end);
5005 if (current_buffer != given_buffer)
5007 XSETFASTINT (start, BEGV);
5008 XSETFASTINT (end, ZV);
5012 UNGCPRO;
5014 GCPRO5 (start, filename, annotations, visit_file, lockname);
5016 /* Decide the coding-system to encode the data with.
5017 We used to make this choice before calling build_annotations, but that
5018 leads to problems when a write-annotate-function takes care of
5019 unsavable chars (as was the case with X-Symbol). */
5020 Vlast_coding_system_used
5021 = choose_write_coding_system (start, end, filename,
5022 append, visit, lockname, &coding);
5024 #ifdef CLASH_DETECTION
5025 if (!auto_saving)
5027 #if 0 /* This causes trouble for GNUS. */
5028 /* If we've locked this file for some other buffer,
5029 query before proceeding. */
5030 if (!visiting && EQ (Ffile_locked_p (lockname), Qt))
5031 call2 (intern ("ask-user-about-lock"), filename, Vuser_login_name);
5032 #endif
5034 lock_file (lockname);
5036 #endif /* CLASH_DETECTION */
5038 encoded_filename = ENCODE_FILE (filename);
5040 fn = SDATA (encoded_filename);
5041 desc = -1;
5042 if (!NILP (append))
5043 #ifdef DOS_NT
5044 desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
5045 #else /* not DOS_NT */
5046 desc = emacs_open (fn, O_WRONLY, 0);
5047 #endif /* not DOS_NT */
5049 if (desc < 0 && (NILP (append) || errno == ENOENT))
5050 #ifdef VMS
5051 if (auto_saving) /* Overwrite any previous version of autosave file */
5053 vms_truncate (fn); /* if fn exists, truncate to zero length */
5054 desc = emacs_open (fn, O_RDWR, 0);
5055 if (desc < 0)
5056 desc = creat_copy_attrs (STRINGP (current_buffer->filename)
5057 ? SDATA (current_buffer->filename) : 0,
5058 fn);
5060 else /* Write to temporary name and rename if no errors */
5062 Lisp_Object temp_name;
5063 temp_name = Ffile_name_directory (filename);
5065 if (!NILP (temp_name))
5067 temp_name = Fmake_temp_name (concat2 (temp_name,
5068 build_string ("$$SAVE$$")));
5069 fname = SDATA (filename);
5070 fn = SDATA (temp_name);
5071 desc = creat_copy_attrs (fname, fn);
5072 if (desc < 0)
5074 /* If we can't open the temporary file, try creating a new
5075 version of the original file. VMS "creat" creates a
5076 new version rather than truncating an existing file. */
5077 fn = fname;
5078 fname = 0;
5079 desc = creat (fn, 0666);
5080 #if 0 /* This can clobber an existing file and fail to replace it,
5081 if the user runs out of space. */
5082 if (desc < 0)
5084 /* We can't make a new version;
5085 try to truncate and rewrite existing version if any. */
5086 vms_truncate (fn);
5087 desc = emacs_open (fn, O_RDWR, 0);
5089 #endif
5092 else
5093 desc = creat (fn, 0666);
5095 #else /* not VMS */
5096 #ifdef DOS_NT
5097 desc = emacs_open (fn,
5098 O_WRONLY | O_CREAT | buffer_file_type
5099 | (EQ (mustbenew, Qexcl) ? O_EXCL : O_TRUNC),
5100 S_IREAD | S_IWRITE);
5101 #else /* not DOS_NT */
5102 desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
5103 | (EQ (mustbenew, Qexcl) ? O_EXCL : 0),
5104 auto_saving ? auto_save_mode_bits : 0666);
5105 #endif /* not DOS_NT */
5106 #endif /* not VMS */
5108 if (desc < 0)
5110 #ifdef CLASH_DETECTION
5111 save_errno = errno;
5112 if (!auto_saving) unlock_file (lockname);
5113 errno = save_errno;
5114 #endif /* CLASH_DETECTION */
5115 UNGCPRO;
5116 report_file_error ("Opening output file", Fcons (filename, Qnil));
5119 record_unwind_protect (close_file_unwind, make_number (desc));
5121 if (!NILP (append) && !NILP (Ffile_regular_p (filename)))
5123 long ret;
5125 if (NUMBERP (append))
5126 ret = lseek (desc, XINT (append), 1);
5127 else
5128 ret = lseek (desc, 0, 2);
5129 if (ret < 0)
5131 #ifdef CLASH_DETECTION
5132 if (!auto_saving) unlock_file (lockname);
5133 #endif /* CLASH_DETECTION */
5134 UNGCPRO;
5135 report_file_error ("Lseek error", Fcons (filename, Qnil));
5139 UNGCPRO;
5141 #ifdef VMS
5143 * Kludge Warning: The VMS C RTL likes to insert carriage returns
5144 * if we do writes that don't end with a carriage return. Furthermore
5145 * it cannot handle writes of more then 16K. The modified
5146 * version of "sys_write" in SYSDEP.C (see comment there) copes with
5147 * this EXCEPT for the last record (iff it doesn't end with a carriage
5148 * return). This implies that if your buffer doesn't end with a carriage
5149 * return, you get one free... tough. However it also means that if
5150 * we make two calls to sys_write (a la the following code) you can
5151 * get one at the gap as well. The easiest way to fix this (honest)
5152 * is to move the gap to the next newline (or the end of the buffer).
5153 * Thus this change.
5155 * Yech!
5157 if (GPT > BEG && GPT_ADDR[-1] != '\n')
5158 move_gap (find_next_newline (GPT, 1));
5159 #else
5160 #if 0
5161 /* The new encoding routine doesn't require the following. */
5163 /* Whether VMS or not, we must move the gap to the next of newline
5164 when we must put designation sequences at beginning of line. */
5165 if (INTEGERP (start)
5166 && coding.type == coding_type_iso2022
5167 && coding.flags & CODING_FLAG_ISO_DESIGNATE_AT_BOL
5168 && GPT > BEG && GPT_ADDR[-1] != '\n')
5170 int opoint = PT, opoint_byte = PT_BYTE;
5171 scan_newline (PT, PT_BYTE, ZV, ZV_BYTE, 1, 0);
5172 move_gap_both (PT, PT_BYTE);
5173 SET_PT_BOTH (opoint, opoint_byte);
5175 #endif
5176 #endif
5178 failure = 0;
5179 immediate_quit = 1;
5181 if (STRINGP (start))
5183 failure = 0 > a_write (desc, start, 0, SCHARS (start),
5184 &annotations, &coding);
5185 save_errno = errno;
5187 else if (XINT (start) != XINT (end))
5189 failure = 0 > a_write (desc, Qnil,
5190 XINT (start), XINT (end) - XINT (start),
5191 &annotations, &coding);
5192 save_errno = errno;
5194 else
5196 /* If file was empty, still need to write the annotations */
5197 coding.mode |= CODING_MODE_LAST_BLOCK;
5198 failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
5199 save_errno = errno;
5202 if (CODING_REQUIRE_FLUSHING (&coding)
5203 && !(coding.mode & CODING_MODE_LAST_BLOCK)
5204 && ! failure)
5206 /* We have to flush out a data. */
5207 coding.mode |= CODING_MODE_LAST_BLOCK;
5208 failure = 0 > e_write (desc, Qnil, 1, 1, &coding);
5209 save_errno = errno;
5212 immediate_quit = 0;
5214 #ifdef HAVE_FSYNC
5215 /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
5216 Disk full in NFS may be reported here. */
5217 /* mib says that closing the file will try to write as fast as NFS can do
5218 it, and that means the fsync here is not crucial for autosave files. */
5219 if (!auto_saving && !write_region_inhibit_fsync && fsync (desc) < 0)
5221 /* If fsync fails with EINTR, don't treat that as serious. */
5222 if (errno != EINTR)
5223 failure = 1, save_errno = errno;
5225 #endif
5227 /* Spurious "file has changed on disk" warnings have been
5228 observed on Suns as well.
5229 It seems that `close' can change the modtime, under nfs.
5231 (This has supposedly been fixed in Sunos 4,
5232 but who knows about all the other machines with NFS?) */
5233 #if 0
5235 /* On VMS and APOLLO, must do the stat after the close
5236 since closing changes the modtime. */
5237 #ifndef VMS
5238 #ifndef APOLLO
5239 /* Recall that #if defined does not work on VMS. */
5240 #define FOO
5241 fstat (desc, &st);
5242 #endif
5243 #endif
5244 #endif
5246 /* NFS can report a write failure now. */
5247 if (emacs_close (desc) < 0)
5248 failure = 1, save_errno = errno;
5250 #ifdef VMS
5251 /* If we wrote to a temporary name and had no errors, rename to real name. */
5252 if (fname)
5254 if (!failure)
5255 failure = (rename (fn, fname) != 0), save_errno = errno;
5256 fn = fname;
5258 #endif /* VMS */
5260 #ifndef FOO
5261 stat (fn, &st);
5262 #endif
5263 /* Discard the unwind protect for close_file_unwind. */
5264 specpdl_ptr = specpdl + count1;
5265 /* Restore the original current buffer. */
5266 visit_file = unbind_to (count, visit_file);
5268 #ifdef CLASH_DETECTION
5269 if (!auto_saving)
5270 unlock_file (lockname);
5271 #endif /* CLASH_DETECTION */
5273 /* Do this before reporting IO error
5274 to avoid a "file has changed on disk" warning on
5275 next attempt to save. */
5276 if (visiting)
5277 current_buffer->modtime = st.st_mtime;
5279 if (failure)
5280 error ("IO error writing %s: %s", SDATA (filename),
5281 emacs_strerror (save_errno));
5283 if (visiting)
5285 SAVE_MODIFF = MODIFF;
5286 XSETFASTINT (current_buffer->save_length, Z - BEG);
5287 current_buffer->filename = visit_file;
5288 update_mode_lines++;
5290 else if (quietly)
5292 if (auto_saving
5293 && ! NILP (Fstring_equal (current_buffer->filename,
5294 current_buffer->auto_save_file_name)))
5295 SAVE_MODIFF = MODIFF;
5297 return Qnil;
5300 if (!auto_saving)
5301 message_with_string ((INTEGERP (append)
5302 ? "Updated %s"
5303 : ! NILP (append)
5304 ? "Added to %s"
5305 : "Wrote %s"),
5306 visit_file, 1);
5308 return Qnil;
5311 Lisp_Object merge ();
5313 DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
5314 doc: /* Return t if (car A) is numerically less than (car B). */)
5315 (a, b)
5316 Lisp_Object a, b;
5318 return Flss (Fcar (a), Fcar (b));
5321 /* Build the complete list of annotations appropriate for writing out
5322 the text between START and END, by calling all the functions in
5323 write-region-annotate-functions and merging the lists they return.
5324 If one of these functions switches to a different buffer, we assume
5325 that buffer contains altered text. Therefore, the caller must
5326 make sure to restore the current buffer in all cases,
5327 as save-excursion would do. */
5329 static Lisp_Object
5330 build_annotations (start, end)
5331 Lisp_Object start, end;
5333 Lisp_Object annotations;
5334 Lisp_Object p, res;
5335 struct gcpro gcpro1, gcpro2;
5336 Lisp_Object original_buffer;
5337 int i, used_global = 0;
5339 XSETBUFFER (original_buffer, current_buffer);
5341 annotations = Qnil;
5342 p = Vwrite_region_annotate_functions;
5343 GCPRO2 (annotations, p);
5344 while (CONSP (p))
5346 struct buffer *given_buffer = current_buffer;
5347 if (EQ (Qt, XCAR (p)) && !used_global)
5348 { /* Use the global value of the hook. */
5349 Lisp_Object arg[2];
5350 used_global = 1;
5351 arg[0] = Fdefault_value (Qwrite_region_annotate_functions);
5352 arg[1] = XCDR (p);
5353 p = Fappend (2, arg);
5354 continue;
5356 Vwrite_region_annotations_so_far = annotations;
5357 res = call2 (XCAR (p), start, end);
5358 /* If the function makes a different buffer current,
5359 assume that means this buffer contains altered text to be output.
5360 Reset START and END from the buffer bounds
5361 and discard all previous annotations because they should have
5362 been dealt with by this function. */
5363 if (current_buffer != given_buffer)
5365 XSETFASTINT (start, BEGV);
5366 XSETFASTINT (end, ZV);
5367 annotations = Qnil;
5369 Flength (res); /* Check basic validity of return value */
5370 annotations = merge (annotations, res, Qcar_less_than_car);
5371 p = XCDR (p);
5374 /* Now do the same for annotation functions implied by the file-format */
5375 if (auto_saving && (!EQ (current_buffer->auto_save_file_format, Qt)))
5376 p = current_buffer->auto_save_file_format;
5377 else
5378 p = current_buffer->file_format;
5379 for (i = 0; CONSP (p); p = XCDR (p), ++i)
5381 struct buffer *given_buffer = current_buffer;
5383 Vwrite_region_annotations_so_far = annotations;
5385 /* Value is either a list of annotations or nil if the function
5386 has written annotations to a temporary buffer, which is now
5387 current. */
5388 res = call5 (Qformat_annotate_function, XCAR (p), start, end,
5389 original_buffer, make_number (i));
5390 if (current_buffer != given_buffer)
5392 XSETFASTINT (start, BEGV);
5393 XSETFASTINT (end, ZV);
5394 annotations = Qnil;
5397 if (CONSP (res))
5398 annotations = merge (annotations, res, Qcar_less_than_car);
5401 UNGCPRO;
5402 return annotations;
5406 /* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
5407 If STRING is nil, POS is the character position in the current buffer.
5408 Intersperse with them the annotations from *ANNOT
5409 which fall within the range of POS to POS + NCHARS,
5410 each at its appropriate position.
5412 We modify *ANNOT by discarding elements as we use them up.
5414 The return value is negative in case of system call failure. */
5416 static int
5417 a_write (desc, string, pos, nchars, annot, coding)
5418 int desc;
5419 Lisp_Object string;
5420 register int nchars;
5421 int pos;
5422 Lisp_Object *annot;
5423 struct coding_system *coding;
5425 Lisp_Object tem;
5426 int nextpos;
5427 int lastpos = pos + nchars;
5429 while (NILP (*annot) || CONSP (*annot))
5431 tem = Fcar_safe (Fcar (*annot));
5432 nextpos = pos - 1;
5433 if (INTEGERP (tem))
5434 nextpos = XFASTINT (tem);
5436 /* If there are no more annotations in this range,
5437 output the rest of the range all at once. */
5438 if (! (nextpos >= pos && nextpos <= lastpos))
5439 return e_write (desc, string, pos, lastpos, coding);
5441 /* Output buffer text up to the next annotation's position. */
5442 if (nextpos > pos)
5444 if (0 > e_write (desc, string, pos, nextpos, coding))
5445 return -1;
5446 pos = nextpos;
5448 /* Output the annotation. */
5449 tem = Fcdr (Fcar (*annot));
5450 if (STRINGP (tem))
5452 if (0 > e_write (desc, tem, 0, SCHARS (tem), coding))
5453 return -1;
5455 *annot = Fcdr (*annot);
5457 return 0;
5461 /* Write text in the range START and END into descriptor DESC,
5462 encoding them with coding system CODING. If STRING is nil, START
5463 and END are character positions of the current buffer, else they
5464 are indexes to the string STRING. */
5466 static int
5467 e_write (desc, string, start, end, coding)
5468 int desc;
5469 Lisp_Object string;
5470 int start, end;
5471 struct coding_system *coding;
5473 if (STRINGP (string))
5475 start = 0;
5476 end = SCHARS (string);
5479 /* We used to have a code for handling selective display here. But,
5480 now it is handled within encode_coding. */
5482 while (start < end)
5484 if (STRINGP (string))
5486 coding->src_multibyte = SCHARS (string) < SBYTES (string);
5487 if (CODING_REQUIRE_ENCODING (coding))
5489 encode_coding_object (coding, string,
5490 start, string_char_to_byte (string, start),
5491 end, string_char_to_byte (string, end), Qt);
5493 else
5495 coding->dst_object = string;
5496 coding->consumed_char = SCHARS (string);
5497 coding->produced = SBYTES (string);
5500 else
5502 int start_byte = CHAR_TO_BYTE (start);
5503 int end_byte = CHAR_TO_BYTE (end);
5505 coding->src_multibyte = (end - start) < (end_byte - start_byte);
5506 if (CODING_REQUIRE_ENCODING (coding))
5508 encode_coding_object (coding, Fcurrent_buffer (),
5509 start, start_byte, end, end_byte, Qt);
5511 else
5513 coding->dst_object = Qnil;
5514 coding->dst_pos_byte = start_byte;
5515 if (start >= GPT || end <= GPT)
5517 coding->consumed_char = end - start;
5518 coding->produced = end_byte - start_byte;
5520 else
5522 coding->consumed_char = GPT - start;
5523 coding->produced = GPT_BYTE - start_byte;
5528 if (coding->produced > 0)
5530 coding->produced -=
5531 emacs_write (desc,
5532 STRINGP (coding->dst_object)
5533 ? SDATA (coding->dst_object)
5534 : BYTE_POS_ADDR (coding->dst_pos_byte),
5535 coding->produced);
5537 if (coding->produced)
5538 return -1;
5540 start += coding->consumed_char;
5543 return 0;
5546 DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
5547 Sverify_visited_file_modtime, 1, 1, 0,
5548 doc: /* Return t if last mod time of BUF's visited file matches what BUF records.
5549 This means that the file has not been changed since it was visited or saved.
5550 See Info node `(elisp)Modification Time' for more details. */)
5551 (buf)
5552 Lisp_Object buf;
5554 struct buffer *b;
5555 struct stat st;
5556 Lisp_Object handler;
5557 Lisp_Object filename;
5559 CHECK_BUFFER (buf);
5560 b = XBUFFER (buf);
5562 if (!STRINGP (b->filename)) return Qt;
5563 if (b->modtime == 0) return Qt;
5565 /* If the file name has special constructs in it,
5566 call the corresponding file handler. */
5567 handler = Ffind_file_name_handler (b->filename,
5568 Qverify_visited_file_modtime);
5569 if (!NILP (handler))
5570 return call2 (handler, Qverify_visited_file_modtime, buf);
5572 filename = ENCODE_FILE (b->filename);
5574 if (stat (SDATA (filename), &st) < 0)
5576 /* If the file doesn't exist now and didn't exist before,
5577 we say that it isn't modified, provided the error is a tame one. */
5578 if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
5579 st.st_mtime = -1;
5580 else
5581 st.st_mtime = 0;
5583 if (st.st_mtime == b->modtime
5584 /* If both are positive, accept them if they are off by one second. */
5585 || (st.st_mtime > 0 && b->modtime > 0
5586 && (st.st_mtime == b->modtime + 1
5587 || st.st_mtime == b->modtime - 1)))
5588 return Qt;
5589 return Qnil;
5592 DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
5593 Sclear_visited_file_modtime, 0, 0, 0,
5594 doc: /* Clear out records of last mod time of visited file.
5595 Next attempt to save will certainly not complain of a discrepancy. */)
5598 current_buffer->modtime = 0;
5599 return Qnil;
5602 DEFUN ("visited-file-modtime", Fvisited_file_modtime,
5603 Svisited_file_modtime, 0, 0, 0,
5604 doc: /* Return the current buffer's recorded visited file modification time.
5605 The value is a list of the form (HIGH LOW), like the time values
5606 that `file-attributes' returns. If the current buffer has no recorded
5607 file modification time, this function returns 0.
5608 See Info node `(elisp)Modification Time' for more details. */)
5611 Lisp_Object tcons;
5612 tcons = long_to_cons ((unsigned long) current_buffer->modtime);
5613 if (CONSP (tcons))
5614 return list2 (XCAR (tcons), XCDR (tcons));
5615 return tcons;
5618 DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
5619 Sset_visited_file_modtime, 0, 1, 0,
5620 doc: /* Update buffer's recorded modification time from the visited file's time.
5621 Useful if the buffer was not read from the file normally
5622 or if the file itself has been changed for some known benign reason.
5623 An argument specifies the modification time value to use
5624 \(instead of that of the visited file), in the form of a list
5625 \(HIGH . LOW) or (HIGH LOW). */)
5626 (time_list)
5627 Lisp_Object time_list;
5629 if (!NILP (time_list))
5630 current_buffer->modtime = cons_to_long (time_list);
5631 else
5633 register Lisp_Object filename;
5634 struct stat st;
5635 Lisp_Object handler;
5637 filename = Fexpand_file_name (current_buffer->filename, Qnil);
5639 /* If the file name has special constructs in it,
5640 call the corresponding file handler. */
5641 handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
5642 if (!NILP (handler))
5643 /* The handler can find the file name the same way we did. */
5644 return call2 (handler, Qset_visited_file_modtime, Qnil);
5646 filename = ENCODE_FILE (filename);
5648 if (stat (SDATA (filename), &st) >= 0)
5649 current_buffer->modtime = st.st_mtime;
5652 return Qnil;
5655 Lisp_Object
5656 auto_save_error (error)
5657 Lisp_Object error;
5659 Lisp_Object args[3], msg;
5660 int i, nbytes;
5661 struct gcpro gcpro1;
5662 char *msgbuf;
5663 USE_SAFE_ALLOCA;
5665 ring_bell ();
5667 args[0] = build_string ("Auto-saving %s: %s");
5668 args[1] = current_buffer->name;
5669 args[2] = Ferror_message_string (error);
5670 msg = Fformat (3, args);
5671 GCPRO1 (msg);
5672 nbytes = SBYTES (msg);
5673 SAFE_ALLOCA (msgbuf, char *, nbytes);
5674 bcopy (SDATA (msg), msgbuf, nbytes);
5676 for (i = 0; i < 3; ++i)
5678 if (i == 0)
5679 message2 (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5680 else
5681 message2_nolog (msgbuf, nbytes, STRING_MULTIBYTE (msg));
5682 Fsleep_for (make_number (1), Qnil);
5685 SAFE_FREE ();
5686 UNGCPRO;
5687 return Qnil;
5690 Lisp_Object
5691 auto_save_1 ()
5693 struct stat st;
5694 Lisp_Object modes;
5696 auto_save_mode_bits = 0666;
5698 /* Get visited file's mode to become the auto save file's mode. */
5699 if (! NILP (current_buffer->filename))
5701 if (stat (SDATA (current_buffer->filename), &st) >= 0)
5702 /* But make sure we can overwrite it later! */
5703 auto_save_mode_bits = st.st_mode | 0600;
5704 else if ((modes = Ffile_modes (current_buffer->filename),
5705 INTEGERP (modes)))
5706 /* Remote files don't cooperate with stat. */
5707 auto_save_mode_bits = XINT (modes) | 0600;
5710 return
5711 Fwrite_region (Qnil, Qnil,
5712 current_buffer->auto_save_file_name,
5713 Qnil, Qlambda, Qnil, Qnil);
5716 static Lisp_Object
5717 do_auto_save_unwind (arg) /* used as unwind-protect function */
5718 Lisp_Object arg;
5720 FILE *stream = (FILE *) XSAVE_VALUE (arg)->pointer;
5721 auto_saving = 0;
5722 if (stream != NULL)
5724 BLOCK_INPUT;
5725 fclose (stream);
5726 UNBLOCK_INPUT;
5728 return Qnil;
5731 static Lisp_Object
5732 do_auto_save_unwind_1 (value) /* used as unwind-protect function */
5733 Lisp_Object value;
5735 minibuffer_auto_raise = XINT (value);
5736 return Qnil;
5739 static Lisp_Object
5740 do_auto_save_make_dir (dir)
5741 Lisp_Object dir;
5743 Lisp_Object mode;
5745 call2 (Qmake_directory, dir, Qt);
5746 XSETFASTINT (mode, 0700);
5747 return Fset_file_modes (dir, mode);
5750 static Lisp_Object
5751 do_auto_save_eh (ignore)
5752 Lisp_Object ignore;
5754 return Qnil;
5757 DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
5758 doc: /* Auto-save all buffers that need it.
5759 This is all buffers that have auto-saving enabled
5760 and are changed since last auto-saved.
5761 Auto-saving writes the buffer into a file
5762 so that your editing is not lost if the system crashes.
5763 This file is not the file you visited; that changes only when you save.
5764 Normally we run the normal hook `auto-save-hook' before saving.
5766 A non-nil NO-MESSAGE argument means do not print any message if successful.
5767 A non-nil CURRENT-ONLY argument means save only current buffer. */)
5768 (no_message, current_only)
5769 Lisp_Object no_message, current_only;
5771 struct buffer *old = current_buffer, *b;
5772 Lisp_Object tail, buf;
5773 int auto_saved = 0;
5774 int do_handled_files;
5775 Lisp_Object oquit;
5776 FILE *stream = NULL;
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");
5830 record_unwind_protect (do_auto_save_unwind,
5831 make_save_value (stream, 0));
5832 record_unwind_protect (do_auto_save_unwind_1,
5833 make_number (minibuffer_auto_raise));
5834 minibuffer_auto_raise = 0;
5835 auto_saving = 1;
5837 /* On first pass, save all files that don't have handlers.
5838 On second pass, save all files that do have handlers.
5840 If Emacs is crashing, the handlers may tweak what is causing
5841 Emacs to crash in the first place, and it would be a shame if
5842 Emacs failed to autosave perfectly ordinary files because it
5843 couldn't handle some ange-ftp'd file. */
5845 for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
5846 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5848 buf = XCDR (XCAR (tail));
5849 b = XBUFFER (buf);
5851 /* Record all the buffers that have auto save mode
5852 in the special file that lists them. For each of these buffers,
5853 Record visited name (if any) and auto save name. */
5854 if (STRINGP (b->auto_save_file_name)
5855 && stream != NULL && do_handled_files == 0)
5857 BLOCK_INPUT;
5858 if (!NILP (b->filename))
5860 fwrite (SDATA (b->filename), 1,
5861 SBYTES (b->filename), stream);
5863 putc ('\n', stream);
5864 fwrite (SDATA (b->auto_save_file_name), 1,
5865 SBYTES (b->auto_save_file_name), stream);
5866 putc ('\n', stream);
5867 UNBLOCK_INPUT;
5870 if (!NILP (current_only)
5871 && b != current_buffer)
5872 continue;
5874 /* Don't auto-save indirect buffers.
5875 The base buffer takes care of it. */
5876 if (b->base_buffer)
5877 continue;
5879 /* Check for auto save enabled
5880 and file changed since last auto save
5881 and file changed since last real save. */
5882 if (STRINGP (b->auto_save_file_name)
5883 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
5884 && b->auto_save_modified < BUF_MODIFF (b)
5885 /* -1 means we've turned off autosaving for a while--see below. */
5886 && XINT (b->save_length) >= 0
5887 && (do_handled_files
5888 || NILP (Ffind_file_name_handler (b->auto_save_file_name,
5889 Qwrite_region))))
5891 EMACS_TIME before_time, after_time;
5893 EMACS_GET_TIME (before_time);
5895 /* If we had a failure, don't try again for 20 minutes. */
5896 if (b->auto_save_failure_time >= 0
5897 && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
5898 continue;
5900 if ((XFASTINT (b->save_length) * 10
5901 > (BUF_Z (b) - BUF_BEG (b)) * 13)
5902 /* A short file is likely to change a large fraction;
5903 spare the user annoying messages. */
5904 && XFASTINT (b->save_length) > 5000
5905 /* These messages are frequent and annoying for `*mail*'. */
5906 && !EQ (b->filename, Qnil)
5907 && NILP (no_message))
5909 /* It has shrunk too much; turn off auto-saving here. */
5910 minibuffer_auto_raise = orig_minibuffer_auto_raise;
5911 message_with_string ("Buffer %s has shrunk a lot; auto save disabled in that buffer until next real save",
5912 b->name, 1);
5913 minibuffer_auto_raise = 0;
5914 /* Turn off auto-saving until there's a real save,
5915 and prevent any more warnings. */
5916 XSETINT (b->save_length, -1);
5917 Fsleep_for (make_number (1), Qnil);
5918 continue;
5920 set_buffer_internal (b);
5921 if (!auto_saved && NILP (no_message))
5922 message1 ("Auto-saving...");
5923 internal_condition_case (auto_save_1, Qt, auto_save_error);
5924 auto_saved++;
5925 b->auto_save_modified = BUF_MODIFF (b);
5926 XSETFASTINT (current_buffer->save_length, Z - BEG);
5927 set_buffer_internal (old);
5929 EMACS_GET_TIME (after_time);
5931 /* If auto-save took more than 60 seconds,
5932 assume it was an NFS failure that got a timeout. */
5933 if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
5934 b->auto_save_failure_time = EMACS_SECS (after_time);
5938 /* Prevent another auto save till enough input events come in. */
5939 record_auto_save ();
5941 if (auto_saved && NILP (no_message))
5943 if (old_message_p)
5945 /* If we are going to restore an old message,
5946 give time to read ours. */
5947 sit_for (make_number (1), 0, 0);
5948 restore_message ();
5950 else
5951 /* If we displayed a message and then restored a state
5952 with no message, leave a "done" message on the screen. */
5953 message1 ("Auto-saving...done");
5956 Vquit_flag = oquit;
5958 /* This restores the message-stack status. */
5959 unbind_to (count, Qnil);
5960 return Qnil;
5963 DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
5964 Sset_buffer_auto_saved, 0, 0, 0,
5965 doc: /* Mark current buffer as auto-saved with its current text.
5966 No auto-save file will be written until the buffer changes again. */)
5969 current_buffer->auto_save_modified = MODIFF;
5970 XSETFASTINT (current_buffer->save_length, Z - BEG);
5971 current_buffer->auto_save_failure_time = -1;
5972 return Qnil;
5975 DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
5976 Sclear_buffer_auto_save_failure, 0, 0, 0,
5977 doc: /* Clear any record of a recent auto-save failure in the current buffer. */)
5980 current_buffer->auto_save_failure_time = -1;
5981 return Qnil;
5984 DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
5985 0, 0, 0,
5986 doc: /* Return t if current buffer has been auto-saved recently.
5987 More precisely, if it has been auto-saved since last read from or saved
5988 in the visited file. If the buffer has no visited file,
5989 then any auto-save counts as "recent". */)
5992 return (SAVE_MODIFF < current_buffer->auto_save_modified) ? Qt : Qnil;
5995 /* Reading and completing file names */
5996 extern Lisp_Object Ffile_name_completion (), Ffile_name_all_completions ();
5998 /* In the string VAL, change each $ to $$ and return the result. */
6000 static Lisp_Object
6001 double_dollars (val)
6002 Lisp_Object val;
6004 register const unsigned char *old;
6005 register unsigned char *new;
6006 register int n;
6007 int osize, count;
6009 osize = SBYTES (val);
6011 /* Count the number of $ characters. */
6012 for (n = osize, count = 0, old = SDATA (val); n > 0; n--)
6013 if (*old++ == '$') count++;
6014 if (count > 0)
6016 old = SDATA (val);
6017 val = make_uninit_multibyte_string (SCHARS (val) + count,
6018 osize + count);
6019 new = SDATA (val);
6020 for (n = osize; n > 0; n--)
6021 if (*old != '$')
6022 *new++ = *old++;
6023 else
6025 *new++ = '$';
6026 *new++ = '$';
6027 old++;
6030 return val;
6033 static Lisp_Object
6034 read_file_name_cleanup (arg)
6035 Lisp_Object arg;
6037 return (current_buffer->directory = arg);
6040 DEFUN ("read-file-name-internal", Fread_file_name_internal, Sread_file_name_internal,
6041 3, 3, 0,
6042 doc: /* Internal subroutine for read-file-name. Do not call this. */)
6043 (string, dir, action)
6044 Lisp_Object string, dir, action;
6045 /* action is nil for complete, t for return list of completions,
6046 lambda for verify final value */
6048 Lisp_Object name, specdir, realdir, val, orig_string;
6049 int changed;
6050 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
6052 CHECK_STRING (string);
6054 realdir = dir;
6055 name = string;
6056 orig_string = Qnil;
6057 specdir = Qnil;
6058 changed = 0;
6059 /* No need to protect ACTION--we only compare it with t and nil. */
6060 GCPRO5 (string, realdir, name, specdir, orig_string);
6062 if (SCHARS (string) == 0)
6064 if (EQ (action, Qlambda))
6066 UNGCPRO;
6067 return Qnil;
6070 else
6072 orig_string = string;
6073 string = Fsubstitute_in_file_name (string);
6074 changed = NILP (Fstring_equal (string, orig_string));
6075 name = Ffile_name_nondirectory (string);
6076 val = Ffile_name_directory (string);
6077 if (! NILP (val))
6078 realdir = Fexpand_file_name (val, realdir);
6081 if (NILP (action))
6083 specdir = Ffile_name_directory (string);
6084 val = Ffile_name_completion (name, realdir, Vread_file_name_predicate);
6085 UNGCPRO;
6086 if (!STRINGP (val))
6088 if (changed)
6089 return double_dollars (string);
6090 return val;
6093 if (!NILP (specdir))
6094 val = concat2 (specdir, val);
6095 #ifndef VMS
6096 return double_dollars (val);
6097 #else /* not VMS */
6098 return val;
6099 #endif /* not VMS */
6101 UNGCPRO;
6103 if (EQ (action, Qt))
6105 Lisp_Object all = Ffile_name_all_completions (name, realdir);
6106 Lisp_Object comp;
6107 int count;
6109 if (NILP (Vread_file_name_predicate)
6110 || EQ (Vread_file_name_predicate, Qfile_exists_p))
6111 return all;
6113 #ifndef VMS
6114 if (EQ (Vread_file_name_predicate, Qfile_directory_p))
6116 /* Brute-force speed up for directory checking:
6117 Discard strings which don't end in a slash. */
6118 for (comp = Qnil; CONSP (all); all = XCDR (all))
6120 Lisp_Object tem = XCAR (all);
6121 int len;
6122 if (STRINGP (tem) &&
6123 (len = SBYTES (tem), len > 0) &&
6124 IS_DIRECTORY_SEP (SREF (tem, len-1)))
6125 comp = Fcons (tem, comp);
6128 else
6129 #endif
6131 /* Must do it the hard (and slow) way. */
6132 Lisp_Object tem;
6133 GCPRO3 (all, comp, specdir);
6134 count = SPECPDL_INDEX ();
6135 record_unwind_protect (read_file_name_cleanup, current_buffer->directory);
6136 current_buffer->directory = realdir;
6137 for (comp = Qnil; CONSP (all); all = XCDR (all))
6139 tem = call1 (Vread_file_name_predicate, XCAR (all));
6140 if (!NILP (tem))
6141 comp = Fcons (XCAR (all), comp);
6143 unbind_to (count, Qnil);
6144 UNGCPRO;
6146 return Fnreverse (comp);
6149 /* Only other case actually used is ACTION = lambda */
6150 #ifdef VMS
6151 /* Supposedly this helps commands such as `cd' that read directory names,
6152 but can someone explain how it helps them? -- RMS */
6153 if (SCHARS (name) == 0)
6154 return Qt;
6155 #endif /* VMS */
6156 string = Fexpand_file_name (string, dir);
6157 if (!NILP (Vread_file_name_predicate))
6158 return call1 (Vread_file_name_predicate, string);
6159 return Ffile_exists_p (string);
6162 DEFUN ("next-read-file-uses-dialog-p", Fnext_read_file_uses_dialog_p,
6163 Snext_read_file_uses_dialog_p, 0, 0, 0,
6164 doc: /* Return t if a call to `read-file-name' will use a dialog.
6165 The return value is only relevant for a call to `read-file-name' that happens
6166 before any other event (mouse or keypress) is handeled. */)
6169 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) || defined (HAVE_CARBON)
6170 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
6171 && use_dialog_box
6172 && use_file_dialog
6173 && have_menus_p ())
6174 return Qt;
6175 #endif
6176 return Qnil;
6179 DEFUN ("read-file-name", Fread_file_name, Sread_file_name, 1, 6, 0,
6180 doc: /* Read file name, prompting with PROMPT and completing in directory DIR.
6181 Value is not expanded---you must call `expand-file-name' yourself.
6182 Default name to DEFAULT-FILENAME if user exits the minibuffer with
6183 the same non-empty string that was inserted by this function.
6184 (If DEFAULT-FILENAME is omitted, the visited file name is used,
6185 except that if INITIAL is specified, that combined with DIR is used.)
6186 If the user exits with an empty minibuffer, this function returns
6187 an empty string. (This can only happen if the user erased the
6188 pre-inserted contents or if `insert-default-directory' is nil.)
6189 Fourth arg MUSTMATCH non-nil means require existing file's name.
6190 Non-nil and non-t means also require confirmation after completion.
6191 Fifth arg INITIAL specifies text to start with.
6192 If optional sixth arg PREDICATE is non-nil, possible completions and
6193 the resulting file name must satisfy (funcall PREDICATE NAME).
6194 DIR should be an absolute directory name. It defaults to the value of
6195 `default-directory'.
6197 If this command was invoked with the mouse, use a file dialog box if
6198 `use-dialog-box' is non-nil, and the window system or X toolkit in use
6199 provides a file dialog box.
6201 See also `read-file-name-completion-ignore-case'
6202 and `read-file-name-function'. */)
6203 (prompt, dir, default_filename, mustmatch, initial, predicate)
6204 Lisp_Object prompt, dir, default_filename, mustmatch, initial, predicate;
6206 Lisp_Object val, insdef, tem;
6207 struct gcpro gcpro1, gcpro2;
6208 register char *homedir;
6209 Lisp_Object decoded_homedir;
6210 int replace_in_history = 0;
6211 int add_to_history = 0;
6212 int count;
6214 if (NILP (dir))
6215 dir = current_buffer->directory;
6216 if (NILP (Ffile_name_absolute_p (dir)))
6217 dir = Fexpand_file_name (dir, Qnil);
6218 if (NILP (default_filename))
6219 default_filename
6220 = (!NILP (initial)
6221 ? Fexpand_file_name (initial, dir)
6222 : current_buffer->filename);
6224 /* If dir starts with user's homedir, change that to ~. */
6225 homedir = (char *) egetenv ("HOME");
6226 #ifdef DOS_NT
6227 /* homedir can be NULL in temacs, since Vprocess_environment is not
6228 yet set up. We shouldn't crash in that case. */
6229 if (homedir != 0)
6231 homedir = strcpy (alloca (strlen (homedir) + 1), homedir);
6232 CORRECT_DIR_SEPS (homedir);
6234 #endif
6235 if (homedir != 0)
6236 decoded_homedir
6237 = DECODE_FILE (make_unibyte_string (homedir, strlen (homedir)));
6238 if (homedir != 0
6239 && STRINGP (dir)
6240 && !strncmp (SDATA (decoded_homedir), SDATA (dir),
6241 SBYTES (decoded_homedir))
6242 && IS_DIRECTORY_SEP (SREF (dir, SBYTES (decoded_homedir))))
6244 dir = Fsubstring (dir, make_number (SCHARS (decoded_homedir)), Qnil);
6245 dir = concat2 (build_string ("~"), dir);
6247 /* Likewise for default_filename. */
6248 if (homedir != 0
6249 && STRINGP (default_filename)
6250 && !strncmp (SDATA (decoded_homedir), SDATA (default_filename),
6251 SBYTES (decoded_homedir))
6252 && IS_DIRECTORY_SEP (SREF (default_filename, SBYTES (decoded_homedir))))
6254 default_filename
6255 = Fsubstring (default_filename,
6256 make_number (SCHARS (decoded_homedir)), Qnil);
6257 default_filename = concat2 (build_string ("~"), default_filename);
6259 if (!NILP (default_filename))
6261 CHECK_STRING (default_filename);
6262 default_filename = double_dollars (default_filename);
6265 if (insert_default_directory && STRINGP (dir))
6267 insdef = dir;
6268 if (!NILP (initial))
6270 Lisp_Object args[2], pos;
6272 args[0] = insdef;
6273 args[1] = initial;
6274 insdef = Fconcat (2, args);
6275 pos = make_number (SCHARS (double_dollars (dir)));
6276 insdef = Fcons (double_dollars (insdef), pos);
6278 else
6279 insdef = double_dollars (insdef);
6281 else if (STRINGP (initial))
6282 insdef = Fcons (double_dollars (initial), make_number (0));
6283 else
6284 insdef = Qnil;
6286 if (!NILP (Vread_file_name_function))
6288 Lisp_Object args[7];
6290 GCPRO2 (insdef, default_filename);
6291 args[0] = Vread_file_name_function;
6292 args[1] = prompt;
6293 args[2] = dir;
6294 args[3] = default_filename;
6295 args[4] = mustmatch;
6296 args[5] = initial;
6297 args[6] = predicate;
6298 RETURN_UNGCPRO (Ffuncall (7, args));
6301 count = SPECPDL_INDEX ();
6302 specbind (intern ("completion-ignore-case"),
6303 read_file_name_completion_ignore_case ? Qt : Qnil);
6304 specbind (intern ("minibuffer-completing-file-name"), Qt);
6305 specbind (intern ("read-file-name-predicate"),
6306 (NILP (predicate) ? Qfile_exists_p : predicate));
6308 GCPRO2 (insdef, default_filename);
6310 #if defined (USE_MOTIF) || defined (HAVE_NTGUI) || defined (USE_GTK) || defined (HAVE_CARBON)
6311 if (! NILP (Fnext_read_file_uses_dialog_p ()))
6313 /* If DIR contains a file name, split it. */
6314 Lisp_Object file;
6315 file = Ffile_name_nondirectory (dir);
6316 if (SCHARS (file) && NILP (default_filename))
6318 default_filename = file;
6319 dir = Ffile_name_directory (dir);
6321 if (!NILP(default_filename))
6322 default_filename = Fexpand_file_name (default_filename, dir);
6323 val = Fx_file_dialog (prompt, dir, default_filename, mustmatch,
6324 EQ (predicate, Qfile_directory_p) ? Qt : Qnil);
6325 add_to_history = 1;
6327 else
6328 #endif
6329 val = Fcompleting_read (prompt, intern ("read-file-name-internal"),
6330 dir, mustmatch, insdef,
6331 Qfile_name_history, default_filename, Qnil);
6333 tem = Fsymbol_value (Qfile_name_history);
6334 if (CONSP (tem) && EQ (XCAR (tem), val))
6335 replace_in_history = 1;
6337 /* If Fcompleting_read returned the inserted default string itself
6338 (rather than a new string with the same contents),
6339 it has to mean that the user typed RET with the minibuffer empty.
6340 In that case, we really want to return ""
6341 so that commands such as set-visited-file-name can distinguish. */
6342 if (EQ (val, default_filename))
6344 /* In this case, Fcompleting_read has not added an element
6345 to the history. Maybe we should. */
6346 if (! replace_in_history)
6347 add_to_history = 1;
6349 val = empty_unibyte_string;
6352 unbind_to (count, Qnil);
6353 UNGCPRO;
6354 if (NILP (val))
6355 error ("No file name specified");
6357 tem = Fstring_equal (val, CONSP (insdef) ? XCAR (insdef) : insdef);
6359 if (!NILP (tem) && !NILP (default_filename))
6360 val = default_filename;
6361 val = Fsubstitute_in_file_name (val);
6363 if (replace_in_history)
6364 /* Replace what Fcompleting_read added to the history
6365 with what we will actually return. */
6367 Lisp_Object val1 = double_dollars (val);
6368 tem = Fsymbol_value (Qfile_name_history);
6369 if (history_delete_duplicates)
6370 XSETCDR (tem, Fdelete (val1, XCDR(tem)));
6371 XSETCAR (tem, val1);
6373 else if (add_to_history)
6375 /* Add the value to the history--but not if it matches
6376 the last value already there. */
6377 Lisp_Object val1 = double_dollars (val);
6378 tem = Fsymbol_value (Qfile_name_history);
6379 if (! CONSP (tem) || NILP (Fequal (XCAR (tem), val1)))
6381 if (history_delete_duplicates) tem = Fdelete (val1, tem);
6382 Fset (Qfile_name_history, Fcons (val1, tem));
6386 return val;
6390 void
6391 init_fileio_once ()
6393 /* Must be set before any path manipulation is performed. */
6394 XSETFASTINT (Vdirectory_sep_char, '/');
6398 void
6399 syms_of_fileio ()
6401 Qoperations = intern ("operations");
6402 Qexpand_file_name = intern ("expand-file-name");
6403 Qsubstitute_in_file_name = intern ("substitute-in-file-name");
6404 Qdirectory_file_name = intern ("directory-file-name");
6405 Qfile_name_directory = intern ("file-name-directory");
6406 Qfile_name_nondirectory = intern ("file-name-nondirectory");
6407 Qunhandled_file_name_directory = intern ("unhandled-file-name-directory");
6408 Qfile_name_as_directory = intern ("file-name-as-directory");
6409 Qcopy_file = intern ("copy-file");
6410 Qmake_directory_internal = intern ("make-directory-internal");
6411 Qmake_directory = intern ("make-directory");
6412 Qdelete_directory = intern ("delete-directory");
6413 Qdelete_file = intern ("delete-file");
6414 Qrename_file = intern ("rename-file");
6415 Qadd_name_to_file = intern ("add-name-to-file");
6416 Qmake_symbolic_link = intern ("make-symbolic-link");
6417 Qfile_exists_p = intern ("file-exists-p");
6418 Qfile_executable_p = intern ("file-executable-p");
6419 Qfile_readable_p = intern ("file-readable-p");
6420 Qfile_writable_p = intern ("file-writable-p");
6421 Qfile_symlink_p = intern ("file-symlink-p");
6422 Qaccess_file = intern ("access-file");
6423 Qfile_directory_p = intern ("file-directory-p");
6424 Qfile_regular_p = intern ("file-regular-p");
6425 Qfile_accessible_directory_p = intern ("file-accessible-directory-p");
6426 Qfile_modes = intern ("file-modes");
6427 Qset_file_modes = intern ("set-file-modes");
6428 Qset_file_times = intern ("set-file-times");
6429 Qfile_newer_than_file_p = intern ("file-newer-than-file-p");
6430 Qinsert_file_contents = intern ("insert-file-contents");
6431 Qwrite_region = intern ("write-region");
6432 Qverify_visited_file_modtime = intern ("verify-visited-file-modtime");
6433 Qset_visited_file_modtime = intern ("set-visited-file-modtime");
6434 Qauto_save_coding = intern ("auto-save-coding");
6436 staticpro (&Qoperations);
6437 staticpro (&Qexpand_file_name);
6438 staticpro (&Qsubstitute_in_file_name);
6439 staticpro (&Qdirectory_file_name);
6440 staticpro (&Qfile_name_directory);
6441 staticpro (&Qfile_name_nondirectory);
6442 staticpro (&Qunhandled_file_name_directory);
6443 staticpro (&Qfile_name_as_directory);
6444 staticpro (&Qcopy_file);
6445 staticpro (&Qmake_directory_internal);
6446 staticpro (&Qmake_directory);
6447 staticpro (&Qdelete_directory);
6448 staticpro (&Qdelete_file);
6449 staticpro (&Qrename_file);
6450 staticpro (&Qadd_name_to_file);
6451 staticpro (&Qmake_symbolic_link);
6452 staticpro (&Qfile_exists_p);
6453 staticpro (&Qfile_executable_p);
6454 staticpro (&Qfile_readable_p);
6455 staticpro (&Qfile_writable_p);
6456 staticpro (&Qaccess_file);
6457 staticpro (&Qfile_symlink_p);
6458 staticpro (&Qfile_directory_p);
6459 staticpro (&Qfile_regular_p);
6460 staticpro (&Qfile_accessible_directory_p);
6461 staticpro (&Qfile_modes);
6462 staticpro (&Qset_file_modes);
6463 staticpro (&Qset_file_times);
6464 staticpro (&Qfile_newer_than_file_p);
6465 staticpro (&Qinsert_file_contents);
6466 staticpro (&Qwrite_region);
6467 staticpro (&Qverify_visited_file_modtime);
6468 staticpro (&Qset_visited_file_modtime);
6469 staticpro (&Qauto_save_coding);
6471 Qfile_name_history = intern ("file-name-history");
6472 Fset (Qfile_name_history, Qnil);
6473 staticpro (&Qfile_name_history);
6475 Qfile_error = intern ("file-error");
6476 staticpro (&Qfile_error);
6477 Qfile_already_exists = intern ("file-already-exists");
6478 staticpro (&Qfile_already_exists);
6479 Qfile_date_error = intern ("file-date-error");
6480 staticpro (&Qfile_date_error);
6481 Qexcl = intern ("excl");
6482 staticpro (&Qexcl);
6484 #ifdef DOS_NT
6485 Qfind_buffer_file_type = intern ("find-buffer-file-type");
6486 staticpro (&Qfind_buffer_file_type);
6487 #endif /* DOS_NT */
6489 DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system,
6490 doc: /* *Coding system for encoding file names.
6491 If it is nil, `default-file-name-coding-system' (which see) is used. */);
6492 Vfile_name_coding_system = Qnil;
6494 DEFVAR_LISP ("default-file-name-coding-system",
6495 &Vdefault_file_name_coding_system,
6496 doc: /* Default coding system for encoding file names.
6497 This variable is used only when `file-name-coding-system' is nil.
6499 This variable is set/changed by the command `set-language-environment'.
6500 User should not set this variable manually,
6501 instead use `file-name-coding-system' to get a constant encoding
6502 of file names regardless of the current language environment. */);
6503 Vdefault_file_name_coding_system = Qnil;
6505 Qformat_decode = intern ("format-decode");
6506 staticpro (&Qformat_decode);
6507 Qformat_annotate_function = intern ("format-annotate-function");
6508 staticpro (&Qformat_annotate_function);
6509 Qafter_insert_file_set_coding = intern ("after-insert-file-set-coding");
6510 staticpro (&Qafter_insert_file_set_coding);
6512 Qcar_less_than_car = intern ("car-less-than-car");
6513 staticpro (&Qcar_less_than_car);
6515 Fput (Qfile_error, Qerror_conditions,
6516 list2 (Qfile_error, Qerror));
6517 Fput (Qfile_error, Qerror_message,
6518 build_string ("File error"));
6520 Fput (Qfile_already_exists, Qerror_conditions,
6521 list3 (Qfile_already_exists, Qfile_error, Qerror));
6522 Fput (Qfile_already_exists, Qerror_message,
6523 build_string ("File already exists"));
6525 Fput (Qfile_date_error, Qerror_conditions,
6526 list3 (Qfile_date_error, Qfile_error, Qerror));
6527 Fput (Qfile_date_error, Qerror_message,
6528 build_string ("Cannot set file date"));
6530 DEFVAR_LISP ("read-file-name-function", &Vread_file_name_function,
6531 doc: /* If this is non-nil, `read-file-name' does its work by calling this function. */);
6532 Vread_file_name_function = Qnil;
6534 DEFVAR_LISP ("read-file-name-predicate", &Vread_file_name_predicate,
6535 doc: /* Current predicate used by `read-file-name-internal'. */);
6536 Vread_file_name_predicate = Qnil;
6538 DEFVAR_BOOL ("read-file-name-completion-ignore-case", &read_file_name_completion_ignore_case,
6539 doc: /* *Non-nil means when reading a file name completion ignores case. */);
6540 #if defined VMS || defined DOS_NT || defined MAC_OS
6541 read_file_name_completion_ignore_case = 1;
6542 #else
6543 read_file_name_completion_ignore_case = 0;
6544 #endif
6546 DEFVAR_BOOL ("insert-default-directory", &insert_default_directory,
6547 doc: /* *Non-nil means when reading a filename start with default dir in minibuffer.
6548 If the initial minibuffer contents are non-empty, you can usually
6549 request a default filename by typing RETURN without editing. For some
6550 commands, exiting with an empty minibuffer has a special meaning,
6551 such as making the current buffer visit no file in the case of
6552 `set-visited-file-name'.
6553 If this variable is non-nil, the minibuffer contents are always
6554 initially non-empty and typing RETURN without editing will fetch the
6555 default name, if one is provided. Note however that this default name
6556 is not necessarily the name originally inserted in the minibuffer, if
6557 that is just the default directory.
6558 If this variable is nil, the minibuffer often starts out empty. In
6559 that case you may have to explicitly fetch the next history element to
6560 request the default name. */);
6561 insert_default_directory = 1;
6563 DEFVAR_BOOL ("vms-stmlf-recfm", &vms_stmlf_recfm,
6564 doc: /* *Non-nil means write new files with record format `stmlf'.
6565 nil means use format `var'. This variable is meaningful only on VMS. */);
6566 vms_stmlf_recfm = 0;
6568 DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char,
6569 doc: /* Directory separator character for built-in functions that return file names.
6570 The value is always ?/. Don't use this variable, just use `/'. */);
6572 DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
6573 doc: /* *Alist of elements (REGEXP . HANDLER) for file names handled specially.
6574 If a file name matches REGEXP, then all I/O on that file is done by calling
6575 HANDLER.
6577 The first argument given to HANDLER is the name of the I/O primitive
6578 to be handled; the remaining arguments are the arguments that were
6579 passed to that primitive. For example, if you do
6580 (file-exists-p FILENAME)
6581 and FILENAME is handled by HANDLER, then HANDLER is called like this:
6582 (funcall HANDLER 'file-exists-p FILENAME)
6583 The function `find-file-name-handler' checks this list for a handler
6584 for its argument. */);
6585 Vfile_name_handler_alist = Qnil;
6587 DEFVAR_LISP ("set-auto-coding-function",
6588 &Vset_auto_coding_function,
6589 doc: /* If non-nil, a function to call to decide a coding system of file.
6590 Two arguments are passed to this function: the file name
6591 and the length of a file contents following the point.
6592 This function should return a coding system to decode the file contents.
6593 It should check the file name against `auto-coding-alist'.
6594 If no coding system is decided, it should check a coding system
6595 specified in the heading lines with the format:
6596 -*- ... coding: CODING-SYSTEM; ... -*-
6597 or local variable spec of the tailing lines with `coding:' tag. */);
6598 Vset_auto_coding_function = Qnil;
6600 DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
6601 doc: /* A list of functions to be called at the end of `insert-file-contents'.
6602 Each is passed one argument, the number of characters inserted,
6603 with point at the start of the inserted text. Each function
6604 should leave point the same, and return the new character count.
6605 If `insert-file-contents' is intercepted by a handler from
6606 `file-name-handler-alist', that handler is responsible for calling the
6607 functions in `after-insert-file-functions' if appropriate. */);
6608 Vafter_insert_file_functions = Qnil;
6610 DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
6611 doc: /* A list of functions to be called at the start of `write-region'.
6612 Each is passed two arguments, START and END as for `write-region'.
6613 These are usually two numbers but not always; see the documentation
6614 for `write-region'. The function should return a list of pairs
6615 of the form (POSITION . STRING), consisting of strings to be effectively
6616 inserted at the specified positions of the file being written (1 means to
6617 insert before the first byte written). The POSITIONs must be sorted into
6618 increasing order. If there are several functions in the list, the several
6619 lists are merged destructively. Alternatively, the function can return
6620 with a different buffer current; in that case it should pay attention
6621 to the annotations returned by previous functions and listed in
6622 `write-region-annotations-so-far'.*/);
6623 Vwrite_region_annotate_functions = Qnil;
6624 staticpro (&Qwrite_region_annotate_functions);
6625 Qwrite_region_annotate_functions
6626 = intern ("write-region-annotate-functions");
6628 DEFVAR_LISP ("write-region-annotations-so-far",
6629 &Vwrite_region_annotations_so_far,
6630 doc: /* When an annotation function is called, this holds the previous annotations.
6631 These are the annotations made by other annotation functions
6632 that were already called. See also `write-region-annotate-functions'. */);
6633 Vwrite_region_annotations_so_far = Qnil;
6635 DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
6636 doc: /* A list of file name handlers that temporarily should not be used.
6637 This applies only to the operation `inhibit-file-name-operation'. */);
6638 Vinhibit_file_name_handlers = Qnil;
6640 DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
6641 doc: /* The operation for which `inhibit-file-name-handlers' is applicable. */);
6642 Vinhibit_file_name_operation = Qnil;
6644 DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
6645 doc: /* File name in which we write a list of all auto save file names.
6646 This variable is initialized automatically from `auto-save-list-file-prefix'
6647 shortly after Emacs reads your `.emacs' file, if you have not yet given it
6648 a non-nil value. */);
6649 Vauto_save_list_file_name = Qnil;
6651 #ifdef HAVE_FSYNC
6652 DEFVAR_BOOL ("write-region-inhibit-fsync", &write_region_inhibit_fsync,
6653 doc: /* *Non-nil means don't call fsync in `write-region'.
6654 This variable affects calls to `write-region' as well as save commands.
6655 A non-nil value may result in data loss! */);
6656 write_region_inhibit_fsync = 0;
6657 #endif
6659 defsubr (&Sfind_file_name_handler);
6660 defsubr (&Sfile_name_directory);
6661 defsubr (&Sfile_name_nondirectory);
6662 defsubr (&Sunhandled_file_name_directory);
6663 defsubr (&Sfile_name_as_directory);
6664 defsubr (&Sdirectory_file_name);
6665 defsubr (&Smake_temp_name);
6666 defsubr (&Sexpand_file_name);
6667 defsubr (&Ssubstitute_in_file_name);
6668 defsubr (&Scopy_file);
6669 defsubr (&Smake_directory_internal);
6670 defsubr (&Sdelete_directory);
6671 defsubr (&Sdelete_file);
6672 defsubr (&Srename_file);
6673 defsubr (&Sadd_name_to_file);
6674 #ifdef S_IFLNK
6675 defsubr (&Smake_symbolic_link);
6676 #endif /* S_IFLNK */
6677 #ifdef VMS
6678 defsubr (&Sdefine_logical_name);
6679 #endif /* VMS */
6680 #ifdef HPUX_NET
6681 defsubr (&Ssysnetunam);
6682 #endif /* HPUX_NET */
6683 defsubr (&Sfile_name_absolute_p);
6684 defsubr (&Sfile_exists_p);
6685 defsubr (&Sfile_executable_p);
6686 defsubr (&Sfile_readable_p);
6687 defsubr (&Sfile_writable_p);
6688 defsubr (&Saccess_file);
6689 defsubr (&Sfile_symlink_p);
6690 defsubr (&Sfile_directory_p);
6691 defsubr (&Sfile_accessible_directory_p);
6692 defsubr (&Sfile_regular_p);
6693 defsubr (&Sfile_modes);
6694 defsubr (&Sset_file_modes);
6695 defsubr (&Sset_file_times);
6696 defsubr (&Sset_default_file_modes);
6697 defsubr (&Sdefault_file_modes);
6698 defsubr (&Sfile_newer_than_file_p);
6699 defsubr (&Sinsert_file_contents);
6700 defsubr (&Swrite_region);
6701 defsubr (&Scar_less_than_car);
6702 defsubr (&Sverify_visited_file_modtime);
6703 defsubr (&Sclear_visited_file_modtime);
6704 defsubr (&Svisited_file_modtime);
6705 defsubr (&Sset_visited_file_modtime);
6706 defsubr (&Sdo_auto_save);
6707 defsubr (&Sset_buffer_auto_saved);
6708 defsubr (&Sclear_buffer_auto_save_failure);
6709 defsubr (&Srecent_auto_save_p);
6711 defsubr (&Sread_file_name_internal);
6712 defsubr (&Sread_file_name);
6713 defsubr (&Snext_read_file_uses_dialog_p);
6715 #ifdef HAVE_SYNC
6716 defsubr (&Sunix_sync);
6717 #endif
6720 /* arch-tag: 64ba3fd7-f844-4fb2-ba4b-427eb928786c
6721 (do not change this comment) */